diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 6bbbbacb70..47eb6c216f 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -8,6 +8,7 @@ body: value: > Before creating a **bug report**, please check the following: * If the issue likely only affects your car model or make, go back and open a **car bug report** instead. + * If the issue is related to the driving or driver monitoring models, you should open a [discussion](https://github.com/commaai/openpilot/discussions/categories/model-feedback) instead. * Ensure you're running the latest openpilot release. * Ensure you're using officially supported hardware. Issues running on PCs have a different issue template. * Ensure there isn't an existing issue for your bug. If there is, leave a comment on the existing issue. @@ -22,23 +23,11 @@ body: validations: required: true - - type: dropdown - id: hw - attributes: - label: What hardware does this issue affect? - multiple: true - options: - - comma three - - comma two - - EON Gold - validations: - required: true - - type: input id: route attributes: label: Provide a route where the issue occurs - description: Ensure the route is fully uploaded at https://useradmin.comma.ai + description: Ensure the route is fully uploaded at https://useradmin.comma.ai. We cannot look into issues without routes, or at least a Dongle ID. placeholder: 77611a1fac303767|2020-05-11--16-37-07 validations: required: true diff --git a/.github/ISSUE_TEMPLATE/car_bug_report.yml b/.github/ISSUE_TEMPLATE/car_bug_report.yml index a48f984192..7f368f11b4 100644 --- a/.github/ISSUE_TEMPLATE/car_bug_report.yml +++ b/.github/ISSUE_TEMPLATE/car_bug_report.yml @@ -1,6 +1,6 @@ name: Car bug report description: For issues with a particular car make or model -labels: ["car bug"] +labels: ["car", "bug"] body: - type: markdown @@ -21,18 +21,6 @@ body: validations: required: true - - type: dropdown - id: hw - attributes: - label: What hardware does this issue affect? - multiple: true - options: - - comma three - - comma two - - EON Gold - validations: - required: true - - type: input id: car attributes: diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 2c2deb17ba..45a8af0aaf 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,8 +1,11 @@ blank_issues_enabled: false contact_links: + - name: Report model bugs + url: https://github.com/commaai/openpilot/discussions/categories/model-feedback + about: Provide feedback for the driving or driver monitoring models - name: Discussions url: https://github.com/commaai/openpilot/discussions - about: For questions and discussion about openpilot + about: For questions and general discussion about openpilot - name: Community Wiki url: https://github.com/commaai/openpilot/wiki about: Check out our community wiki diff --git a/.github/PULL_REQUEST_TEMPLATE/car_bugfix.md b/.github/PULL_REQUEST_TEMPLATE/car_bugfix.md index d0c8bc58e4..76c86346c8 100644 --- a/.github/PULL_REQUEST_TEMPLATE/car_bugfix.md +++ b/.github/PULL_REQUEST_TEMPLATE/car_bugfix.md @@ -1,6 +1,6 @@ --- name: Car Bug fix -about: For vehicle/brand specifc bug fixes +about: For vehicle/brand specific bug fixes title: '' labels: 'car bug fix' assignees: '' diff --git a/.github/PULL_REQUEST_TEMPLATE/car_port.md b/.github/PULL_REQUEST_TEMPLATE/car_port.md index d275468395..4264363ba2 100644 --- a/.github/PULL_REQUEST_TEMPLATE/car_port.md +++ b/.github/PULL_REQUEST_TEMPLATE/car_port.md @@ -9,7 +9,7 @@ assignees: '' **Checklist** - [ ] added to README -- [ ] test route added to [test_routes.py](https://github.com/commaai/openpilot/blob/master/selfdrive/test/test_models.py) +- [ ] test route added to [routes.py](https://github.com/commaai/openpilot/blob/master/selfdrive/car/tests/routes.py) - [ ] route with openpilot: - [ ] route with stock system: - [ ] car harness used (if comma doesn't sell it, put N/A): diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 38a6c78643..efa947a91a 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -22,8 +22,8 @@ Route: [a route with the bug fix] + # Supported Cars -## comma.ai supported cars - -| Make | Model (US Market Reference) | Supported Package | ACC | No ACC accel below | No ALC below | -| ----------| ------------------------------| ------------------| -----------------| -------------------| ------------------| -| Acura | ILX 2016-19 | AcuraWatch Plus | openpilot | 25mph1 | 25mph | -| Acura | RDX 2016-18 | AcuraWatch Plus | openpilot | 25mph1 | 12mph | -| Acura | RDX 2019-21 | All | Stock | 0mph | 3mph | -| Honda | Accord 2018-21 | All | Stock | 0mph | 3mph | -| Honda | Accord Hybrid 2018-21 | All | Stock | 0mph | 3mph | -| Honda | Civic Hatchback 2017-21 | Honda Sensing | Stock | 0mph | 12mph | -| Honda | Civic Coupe 2016-18 | Honda Sensing | openpilot | 0mph | 12mph | -| Honda | Civic Coupe 2019-20 | All | Stock | 0mph | 2mph2 | -| Honda | Civic Sedan 2016-18 | Honda Sensing | openpilot | 0mph | 12mph | -| Honda | Civic Sedan 2019-20 | All | Stock | 0mph | 2mph2 | -| Honda | CR-V 2015-16 | Touring | openpilot | 25mph1 | 12mph | -| Honda | CR-V 2017-21 | Honda Sensing | Stock | 0mph | 12mph | -| Honda | CR-V Hybrid 2017-2019 | Honda Sensing | Stock | 0mph | 12mph | -| Honda | e 2020 | All | Stock | 0mph | 3mph | -| Honda | Fit 2018-19 | Honda Sensing | openpilot | 25mph1 | 12mph | -| Honda | Freed 2020 | Honda Sensing | openpilot | 25mph1 | 12mph | -| Honda | HR-V 2019-20 | Honda Sensing | openpilot | 25mph1 | 12mph | -| Honda | Insight 2019-21 | All | Stock | 0mph | 3mph | -| Honda | Inspire 2018 | All | Stock | 0mph | 3mph | -| Honda | Odyssey 2018-20 | Honda Sensing | openpilot | 25mph1 | 0mph | -| Honda | Passport 2019-21 | All | openpilot | 25mph1 | 12mph | -| Honda | Pilot 2016-21 | Honda Sensing | openpilot | 25mph1 | 12mph | -| Honda | Ridgeline 2017-21 | Honda Sensing | openpilot | 25mph1 | 12mph | -| Hyundai | Palisade 2020-21 | All | Stock | 0mph | 0mph | -| Hyundai | Sonata 2020-22 | All | Stock | 0mph | 0mph | -| Lexus | CT Hybrid 2017-18 | LSS | Stock3| 0mph | 0mph | -| Lexus | ES 2019-21 | All | openpilot | 0mph | 0mph | -| Lexus | ES Hybrid 2017-18 | LSS | Stock3| 0mph | 0mph | -| Lexus | ES Hybrid 2019-21 | All | openpilot | 0mph | 0mph | -| Lexus | IS 2017-2019 | All | Stock | 22mph | 0mph | -| Lexus | NX 2018-2019 | All | Stock3| 0mph | 0mph | -| Lexus | NX 2020 | All | openpilot | 0mph | 0mph | -| Lexus | NX Hybrid 2018-19 | All | Stock3| 0mph | 0mph | -| Lexus | RC 2020 | All | Stock | 22mph | 0mph | -| Lexus | RX 2016-18 | All | Stock3| 0mph | 0mph | -| Lexus | RX 2020-21 | All | openpilot | 0mph | 0mph | -| Lexus | RX Hybrid 2016-19 | All | Stock3| 0mph | 0mph | -| Lexus | RX Hybrid 2020-21 | All | openpilot | 0mph | 0mph | -| Lexus | UX Hybrid 2019-21 | All | openpilot | 0mph | 0mph | -| Toyota | Alphard 2019-20 | All | openpilot | 0mph | 0mph | -| Toyota | Avalon 2016-21 | TSS-P | Stock3| 20mph1 | 0mph | -| Toyota | Avalon 2022 | All | openpilot | 0mph | 0mph | -| Toyota | Avalon Hybrid 2019-21 | TSS-P | Stock3| 20mph1 | 0mph | -| Toyota | Camry 2018-20 | All | Stock | 0mph4 | 0mph | -| Toyota | Camry 2021-22 | All | openpilot | 0mph4 | 0mph | -| Toyota | Camry Hybrid 2018-20 | All | Stock | 0mph4 | 0mph | -| Toyota | Camry Hybrid 2021-22 | All | openpilot | 0mph | 0mph | -| Toyota | C-HR 2017-21 | All | Stock | 0mph | 0mph | -| Toyota | C-HR Hybrid 2017-19 | All | Stock | 0mph | 0mph | -| Toyota | Corolla 2017-19 | All | Stock3| 20mph1 | 0mph | -| Toyota | Corolla 2020-22 | All | openpilot | 0mph | 0mph | -| Toyota | Corolla Hatchback 2019-22 | All | openpilot | 0mph | 0mph | -| Toyota | Corolla Hybrid 2020-22 | All | openpilot | 0mph | 0mph | -| Toyota | Highlander 2017-19 | All | Stock3| 0mph | 0mph | -| Toyota | Highlander 2020-22 | All | openpilot | 0mph | 0mph | -| Toyota | Highlander Hybrid 2017-19 | All | Stock3| 0mph | 0mph | -| Toyota | Highlander Hybrid 2020-22 | All | openpilot | 0mph | 0mph | -| Toyota | Mirai 2021 | All | openpilot | 0mph | 0mph | -| Toyota | Prius 2016-20 | TSS-P | Stock3| 0mph | 0mph | -| Toyota | Prius 2021-22 | All | openpilot | 0mph | 0mph | -| Toyota | Prius v 2017 | TSS-P | Stock3| 20mph1 | 0mph | -| Toyota | Prius Prime 2017-20 | All | Stock3| 0mph | 0mph | -| Toyota | Prius Prime 2021-22 | All | openpilot | 0mph | 0mph | -| Toyota | Rav4 2016-18 | TSS-P | Stock3| 20mph1 | 0mph | -| Toyota | Rav4 2019-21 | All | openpilot | 0mph | 0mph | -| Toyota | Rav4 Hybrid 2016-18 | TSS-P | Stock3| 0mph | 0mph | -| Toyota | Rav4 Hybrid 2019-21 | All | openpilot | 0mph | 0mph | -| Toyota | Sienna 2018-20 | All | Stock3| 0mph | 0mph | - -1[Comma Pedal](https://github.com/commaai/openpilot/wiki/comma-pedal) is used to provide stop-and-go capability to some of the openpilot-supported cars that don't currently support stop-and-go. ***NOTE: The Comma Pedal is not officially supported by [comma](https://comma.ai).***
-22019 Honda Civic 1.6L Diesel Sedan does not have ALC below 12mph.
-3When disconnecting the Driver Support Unit (DSU), openpilot ACC will replace stock ACC. ***NOTE: disconnecting the DSU disables Automatic Emergency Braking (AEB).***
-428mph for Camry 4CYL L, 4CYL LE and 4CYL SE which don't have Full-Speed Range Dynamic Radar Cruise Control.
- -## Community Maintained Cars and Features - -| Make | Model (US Market Reference) | Supported Package | ACC | No ACC accel below | No ALC below | -| ----------| --------------------------------| ------------------| -----------------| -------------------| -------------| -| Audi | A3 2014-19 | ACC + Lane Assist | Stock | 0mph | 0mph | -| Audi | A3 Sportback e-tron 2017-18 | ACC + Lane Assist | Stock | 0mph | 0mph | -| Audi | Q2 2018 | ACC + Lane Assist | Stock | 0mph | 0mph | -| Audi | Q3 2020-21 | ACC + Lane Assist | Stock | 0mph | 0mph | -| Audi | S3 2015 | ACC + Lane Assist | Stock | 0mph | 0mph | -| Cadillac | Escalade ESV 20161 | ACC + LKAS | openpilot | 0mph | 7mph | -| Chevrolet | Volt 2017-181 | Adaptive Cruise | openpilot | 0mph | 7mph | -| Chrysler | Pacifica 2017-18 | Adaptive Cruise | Stock | 0mph | 9mph | -| Chrysler | Pacifica 2020 | Adaptive Cruise | Stock | 0mph | 39mph | -| Chrysler | Pacifica Hybrid 2017-18 | Adaptive Cruise | Stock | 0mph | 9mph | -| Chrysler | Pacifica Hybrid 2019-21 | Adaptive Cruise | Stock | 0mph | 39mph | -| Genesis | G70 2018 | All | Stock | 0mph | 0mph | -| Genesis | G70 2020 | All | Stock | 0mph | 0mph | -| Genesis | G80 2018 | All | Stock | 0mph | 0mph | -| Genesis | G90 2018 | All | Stock | 0mph | 0mph | -| GMC | Acadia 20181 | Adaptive Cruise | openpilot | 0mph | 7mph | -| Hyundai | Elantra 2017-19 | SCC + LKAS | Stock | 19mph | 34mph | -| Hyundai | Elantra 2021-22 | SCC + LKAS | Stock | 0mph | 0mph | -| Hyundai | Elantra Hybrid 2021 | SCC + LKAS | Stock | 0mph | 0mph | -| Hyundai | Genesis 2015-16 | SCC + LKAS | Stock | 19mph | 37mph | -| Hyundai | Ioniq Electric 2019 | SCC + LKAS | Stock | 0mph | 32mph | -| Hyundai | Ioniq Electric 2020 | SCC + LKAS | Stock | 0mph | 0mph | -| Hyundai | Ioniq Hybrid 2017-19 | SCC + LKAS | Stock | 0mph | 32mph | -| Hyundai | Ioniq Hybrid 2020-22 | SCC + LFA | Stock | 0mph | 0mph | -| Hyundai | Ioniq PHEV 2020-21 | SCC + LKAS | Stock | 0mph | 0mph | -| Hyundai | Kona 2020 | SCC + LKAS | Stock | 0mph | 0mph | -| Hyundai | Kona EV 2018-19 | SCC + LKAS | Stock | 0mph | 0mph | -| Hyundai | Kona Hybrid 2020 | SCC + LKAS | Stock | 0mph | 0mph | -| Hyundai | Santa Fe 2019-20 | All | Stock | 0mph | 0mph | -| Hyundai | Santa Fe 2021-22 | All | Stock | 0mph | 0mph | -| Hyundai | Santa Fe Hybrid 2022 | All | Stock | 0mph | 0mph | -| Hyundai | Santa Fe Plug-in Hybrid 2022 | All | Stock | 0mph | 0mph | -| Hyundai | Sonata 2018-2019 | SCC + LKAS | Stock | 0mph | 0mph | -| Hyundai | Sonata Hybrid 2021-22 | All | Stock | 0mph | 0mph | -| Hyundai | Veloster 2019-20 | SCC + LKAS | Stock | 5mph | 0mph | -| Jeep | Grand Cherokee 2016-18 | Adaptive Cruise | Stock | 0mph | 9mph | -| Jeep | Grand Cherokee 2019-20 | Adaptive Cruise | Stock | 0mph | 39mph | -| Kia | Ceed 2019 | SCC + LKAS | Stock | 0mph | 0mph | -| Kia | Forte 2018-21 | SCC + LKAS | Stock | 0mph | 0mph | -| Kia | K5 2021-22 | SCC + LFA | Stock | 0mph | 0mph | -| Kia | Niro EV 2019-22 | All | Stock | 0mph | 0mph | -| Kia | Niro Hybrid 2021 | SCC + LKAS | Stock | 0mph | 0mph | -| Kia | Niro PHEV 2019 | SCC + LKAS | Stock | 10mph | 32mph | -| Kia | Optima 2017 | SCC + LKAS | Stock | 0mph | 32mph | -| Kia | Optima 2019 | SCC + LKAS | Stock | 0mph | 0mph | -| Kia | Seltos 2021 | SCC + LKAS | Stock | 0mph | 0mph | -| Kia | Sorento 2018-19 | SCC + LKAS | Stock | 0mph | 0mph | -| Kia | Stinger 2018 | SCC + LKAS | Stock | 0mph | 0mph | -| Kia | Telluride 2020 | SCC + LKAS | Stock | 0mph | 0mph | -| Mazda | CX-5 2022 | All | Stock | 0mph | 0mph | -| Mazda | CX-9 2021 | All | Stock | 0mph | 28mph | -| Nissan | Altima 2019-20 | ProPILOT | Stock | 0mph | 0mph | -| Nissan | Leaf 2018-22 | ProPILOT | Stock | 0mph | 0mph | -| Nissan | Rogue 2018-20 | ProPILOT | Stock | 0mph | 0mph | -| Nissan | X-Trail 2017 | ProPILOT | Stock | 0mph | 0mph | -| SEAT | Ateca 2018 | Driver Assistance | Stock | 0mph | 0mph | -| SEAT | Leon 2014-2020 | Driver Assistance | Stock | 0mph | 0mph | -| Subaru | Ascent 2019 | EyeSight | Stock | 0mph | 0mph | -| Subaru | Crosstrek 2018-20 | EyeSight | Stock | 0mph | 0mph | -| Subaru | Forester 2019-21 | EyeSight | Stock | 0mph | 0mph | -| Subaru | Impreza 2017-19 | EyeSight | Stock | 0mph | 0mph | -| Škoda | Kamiq 20212 | Driver Assistance | Stock | 0mph | 0mph | -| Škoda | Karoq 2019 | Driver Assistance | Stock | 0mph | 0mph | -| Škoda | Kodiaq 2018-19 | Driver Assistance | Stock | 0mph | 0mph | -| Škoda | Octavia 2015, 2018-19 | Driver Assistance | Stock | 0mph | 0mph | -| Škoda | Octavia RS 2016 | Driver Assistance | Stock | 0mph | 0mph | -| Škoda | Scala 2020 | Driver Assistance | Stock | 0mph | 0mph | -| Škoda | Superb 2015-18 | Driver Assistance | Stock | 0mph | 0mph | -| Volkswagen| Arteon 2018, 20214 | Driver Assistance | Stock | 0mph | 0mph | -| Volkswagen| Atlas 2018-19, 20224 | Driver Assistance | Stock | 0mph | 0mph | -| Volkswagen| Caravelle 20204 | Driver Assistance | Stock | 0mph | 32mph | -| Volkswagen| California 20214 | Driver Assistance | Stock | 0mph | 32mph | -| Volkswagen| e-Golf 2014, 2019-20 | Driver Assistance | Stock | 0mph | 0mph | -| Volkswagen| Golf 2015-20 | Driver Assistance | Stock | 0mph | 0mph | -| Volkswagen| Golf Alltrack 2017-18 | Driver Assistance | Stock | 0mph | 0mph | -| Volkswagen| Golf GTE 2016 | Driver Assistance | Stock | 0mph | 0mph | -| Volkswagen| Golf GTI 2018-20 | Driver Assistance | Stock | 0mph | 0mph | -| Volkswagen| Golf R 2016-19 | Driver Assistance | Stock | 0mph | 0mph | -| Volkswagen| Golf SportsVan 2016 | Driver Assistance | Stock | 0mph | 0mph | -| Volkswagen| Golf SportWagen 2015 | Driver Assistance | Stock | 0mph | 0mph | -| Volkswagen| Jetta 2018-20 | Driver Assistance | Stock | 0mph | 0mph | -| Volkswagen| Jetta GLI 2021 | Driver Assistance | Stock | 0mph | 0mph | -| Volkswagen| Passat 2016-183 | Driver Assistance | Stock | 0mph | 0mph | -| Volkswagen| Polo 2020 | Driver Assistance | Stock | 0mph | 0mph | -| Volkswagen| T-Cross 20214 | Driver Assistance | Stock | 0mph | 0mph | -| Volkswagen| T-Roc 20214 | Driver Assistance | Stock | 0mph | 0mph | -| Volkswagen| Taos 20224 | Driver Assistance | Stock | 0mph | 0mph | -| Volkswagen| Tiguan 2020 | Driver Assistance | Stock | 0mph | 0mph | -| Volkswagen| Touran 2017 | Driver Assistance | Stock | 0mph | 0mph | - -1Requires an [OBD-II car harness](https://comma.ai/shop/products/comma-car-harness) and [community built ASCM harness](https://github.com/commaai/openpilot/wiki/GM#hardware). ***NOTE: disconnecting the ASCM disables Automatic Emergency Braking (AEB).***
-2Not including the China market Kamiq, which is based on the (currently) unsupported PQ34 platform.
-3Not including the USA/China market Passat, which is based on the (currently) unsupported PQ35/NMS platform.
-4Model-years 2021 and beyond may have a new camera harness design, which isn't yet available from the comma store. Before ordering, -remove the Lane Assist camera cover and check to see if the connector is black (older design) or light brown (newer design). For the newer design, -in the interim, choose "VW J533 Development" from the vehicle drop-down for a harness that integrates at the CAN gateway inside the dashboard.
-Community Maintained Cars and Features are not verified by comma to meet our [safety model](SAFETY.md). Be extra cautious using them. - -To promote a car from community maintained, it must meet a few requirements. We must own one from the brand, we must sell the harness for it, has full ISO26262 in both panda and openpilot, there must be a path forward for longitudinal control, it must have AEB still enabled, and it must support fingerprinting 2.0 +A supported vehicle is one that just works when you install a comma three. All supported cars provide a better experience than any stock system. + +# 219 Supported Cars + +|Make|Model|Supported Package|ACC|No ACC accel below|No ALC below|Steering Torque|Resume from stop|Harness| +|---|---|---|:---:|:---:|:---:|:---:|:---:|:---:| +|Acura|ILX 2016-19|AcuraWatch Plus|openpilot|25 mph|25 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Honda Nidec| +|Acura|RDX 2016-18|AcuraWatch Plus|openpilot|25 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Honda Nidec| +|Acura|RDX 2019-22|All|openpilot available[1](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Honda Bosch A| +|Audi|A3 2014-19|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Audi|A3 Sportback e-tron 2017-18|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Audi|Q2 2018|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Audi|Q3 2019-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Audi|RS3 2018|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Audi|S3 2015-17|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Cadillac|Escalade ESV 2016[3](#footnotes)|Adaptive Cruise Control (ACC) & LKAS|openpilot|0 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|OBD-II| +|Chevrolet|Bolt EUV 2022-23|Premier or Premier Redline Trim without Super Cruise Package|openpilot available[1](#footnotes)|3 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|GM| +|Chevrolet|Bolt EV 2022-23|2LT Trim with Adaptive Cruise Control Package|openpilot available[1](#footnotes)|3 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|GM| +|Chevrolet|Silverado 1500 2020-21|Safety Package II|openpilot available[1](#footnotes)|3 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|GM| +|Chevrolet|Volt 2017-18[3](#footnotes)|Adaptive Cruise Control (ACC)|openpilot|0 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|OBD-II| +|Chrysler|Pacifica 2017-18|Adaptive Cruise Control (ACC)|Stock|0 mph|9 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|FCA| +|Chrysler|Pacifica 2019-20|Adaptive Cruise Control (ACC)|Stock|0 mph|39 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|FCA| +|Chrysler|Pacifica 2021|All|Stock|0 mph|39 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|FCA| +|Chrysler|Pacifica Hybrid 2017-18|Adaptive Cruise Control (ACC)|Stock|0 mph|9 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|FCA| +|Chrysler|Pacifica Hybrid 2019-22|Adaptive Cruise Control (ACC)|Stock|0 mph|39 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|FCA| +|comma|body|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|None| +|Genesis|G70 2018-19|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai F| +|Genesis|G70 2020|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai F| +|Genesis|G80 2017-19|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai H| +|Genesis|G90 2017-18|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai C| +|Genesis|GV70 2022-23[5](#footnotes)|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai L| +|GMC|Acadia 2018[3](#footnotes)|Adaptive Cruise Control (ACC)|openpilot|0 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|OBD-II| +|GMC|Sierra 1500 2020-21|Driver Alert Package II|openpilot available[1](#footnotes)|3 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|GM| +|Honda|Accord 2018-22|All|openpilot available[1](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Honda Bosch A| +|Honda|Accord Hybrid 2018-22|All|openpilot available[1](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Honda Bosch A| +|Honda|Civic 2016-18|Honda Sensing|openpilot|0 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Honda Nidec| +|Honda|Civic 2019-21|All|openpilot available[1](#footnotes)|0 mph|2 mph[4](#footnotes)|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Honda Bosch A| +|Honda|Civic 2022|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Honda Bosch B| +|Honda|Civic Hatchback 2017-21|Honda Sensing|openpilot available[1](#footnotes)|0 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Honda Bosch A| +|Honda|Civic Hatchback 2022|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Honda Bosch B| +|Honda|CR-V 2015-16|Touring Trim|openpilot|25 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Honda Nidec| +|Honda|CR-V 2017-22|Honda Sensing|openpilot available[1](#footnotes)|0 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Honda Bosch A| +|Honda|CR-V Hybrid 2017-19|Honda Sensing|openpilot available[1](#footnotes)|0 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Honda Bosch A| +|Honda|e 2020|All|openpilot available[1](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Honda Bosch A| +|Honda|Fit 2018-20|Honda Sensing|openpilot|25 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Honda Nidec| +|Honda|Freed 2020|Honda Sensing|openpilot|25 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Honda Nidec| +|Honda|HR-V 2019-22|Honda Sensing|openpilot|25 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Honda Nidec| +|Honda|Insight 2019-22|All|openpilot available[1](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Honda Bosch A| +|Honda|Inspire 2018|All|openpilot available[1](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Honda Bosch A| +|Honda|Odyssey 2018-20|Honda Sensing|openpilot|25 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Honda Nidec| +|Honda|Passport 2019-21|All|openpilot|25 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Honda Nidec| +|Honda|Pilot 2016-22|Honda Sensing|openpilot|25 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Honda Nidec| +|Honda|Ridgeline 2017-22|Honda Sensing|openpilot|25 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Honda Nidec| +|Hyundai|Elantra 2017-19|Smart Cruise Control (SCC)|Stock|19 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai B| +|Hyundai|Elantra 2021-22|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai K| +|Hyundai|Elantra GT 2017-19|Smart Cruise Control (SCC)|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai E| +|Hyundai|Elantra Hybrid 2021-23|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai K| +|Hyundai|Genesis 2015-16|Smart Cruise Control (SCC)|Stock|19 mph|37 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai J| +|Hyundai|i30 2019|Smart Cruise Control (SCC)|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai E| +|Hyundai|Ioniq 5 (with HDA II) 2022-23[5](#footnotes)|Highway Driving Assist II|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai Q| +|Hyundai|Ioniq 5 (without HDA II) 2022-23[5](#footnotes)|Highway Driving Assist|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai K| +|Hyundai|Ioniq Electric 2019|Smart Cruise Control (SCC)|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai C| +|Hyundai|Ioniq Electric 2020|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai H| +|Hyundai|Ioniq Hybrid 2017-19|Smart Cruise Control (SCC)|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai C| +|Hyundai|Ioniq Hybrid 2020-22|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai H| +|Hyundai|Ioniq Plug-in Hybrid 2019|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai C| +|Hyundai|Ioniq Plug-in Hybrid 2020-21|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai H| +|Hyundai|Kona 2020|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai B| +|Hyundai|Kona Electric 2018-21|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai G| +|Hyundai|Kona Electric 2022|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai O| +|Hyundai|Kona Hybrid 2020|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai I| +|Hyundai|Palisade 2020-22|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai H| +|Hyundai|Santa Cruz 2021-22[5](#footnotes)|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai N| +|Hyundai|Santa Fe 2019-20|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai D| +|Hyundai|Santa Fe 2021-22|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai L| +|Hyundai|Santa Fe Hybrid 2022|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai L| +|Hyundai|Santa Fe Plug-in Hybrid 2022|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai L| +|Hyundai|Sonata 2018-19|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai E| +|Hyundai|Sonata 2020-22|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai A| +|Hyundai|Sonata Hybrid 2020-22|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai A| +|Hyundai|Tucson 2021|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai L| +|Hyundai|Tucson 2022[5](#footnotes)|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai N| +|Hyundai|Tucson 2023[5](#footnotes)|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai N| +|Hyundai|Tucson Diesel 2019|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai L| +|Hyundai|Tucson Hybrid 2022[5](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai N| +|Hyundai|Veloster 2019-20|Smart Cruise Control (SCC)|Stock|5 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai E| +|Jeep|Grand Cherokee 2016-18|Adaptive Cruise Control (ACC)|Stock|0 mph|9 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|FCA| +|Jeep|Grand Cherokee 2019-21|Adaptive Cruise Control (ACC)|Stock|0 mph|39 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|FCA| +|Kia|Ceed 2019|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai E| +|Kia|EV6 (with HDA II) 2022[5](#footnotes)|Highway Driving Assist II|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai P| +|Kia|EV6 (without HDA II) 2022[5](#footnotes)|Highway Driving Assist|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai L| +|Kia|Forte 2019-21|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai G| +|Kia|K5 2021-22|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai A| +|Kia|Niro EV 2019|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai H| +|Kia|Niro EV 2020|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai F| +|Kia|Niro EV 2021|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai C| +|Kia|Niro EV 2022|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai H| +|Kia|Niro Hybrid 2021|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai F| +|Kia|Niro Hybrid 2022|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai H| +|Kia|Niro Plug-in Hybrid 2018-19|All|openpilot available[1](#footnotes)|10 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai C| +|Kia|Optima 2017|Advanced Smart Cruise Control|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai B| +|Kia|Optima 2019-20|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai G| +|Kia|Seltos 2021|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai A| +|Kia|Sorento 2018|Advanced Smart Cruise Control|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai C| +|Kia|Sorento 2019|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai E| +|Kia|Sorento Plug-in Hybrid 2022-23[5](#footnotes)|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai A| +|Kia|Sportage 2023[5](#footnotes)|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai N| +|Kia|Sportage Hybrid 2023[5](#footnotes)|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai N| +|Kia|Stinger 2018-20|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai C| +|Kia|Stinger 2022|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai K| +|Kia|Telluride 2020-22|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Hyundai H| +|Lexus|CT Hybrid 2017-18|Lexus Safety System+|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Toyota| +|Lexus|ES 2019-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Lexus|ES Hybrid 2017-18|Lexus Safety System+|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Lexus|ES Hybrid 2019-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Lexus|IS 2017-19|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Toyota| +|Lexus|NX 2018-19|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Toyota| +|Lexus|NX 2020-21|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Lexus|NX Hybrid 2018-19|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Toyota| +|Lexus|NX Hybrid 2020-21|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Lexus|RC 2017-20|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Toyota| +|Lexus|RX 2016|Lexus Safety System+|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Toyota| +|Lexus|RX 2017-19|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Toyota| +|Lexus|RX 2020-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Lexus|RX Hybrid 2016|Lexus Safety System+|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Toyota| +|Lexus|RX Hybrid 2017-19|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Toyota| +|Lexus|RX Hybrid 2020-21|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Lexus|UX Hybrid 2019-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Mazda|CX-5 2022-23|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Mazda| +|Mazda|CX-9 2021-23|All|Stock|0 mph|28 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Mazda| +|Nissan|Altima 2019-20|ProPILOT Assist|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Nissan B| +|Nissan|Leaf 2018-22|ProPILOT Assist|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Nissan A| +|Nissan|Rogue 2018-20|ProPILOT Assist|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Nissan A| +|Nissan|X-Trail 2017|ProPILOT Assist|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Nissan A| +|Ram|1500 2019-22|Adaptive Cruise Control (ACC)|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Ram| +|SEAT|Ateca 2018|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|SEAT|Leon 2014-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Subaru|Ascent 2019-21|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Subaru A| +|Subaru|Crosstrek 2018-19|EyeSight Driver Assistance|Stock|0 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Subaru A| +|Subaru|Crosstrek 2020-23|EyeSight Driver Assistance|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Subaru A| +|Subaru|Forester 2019-21|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Subaru A| +|Subaru|Impreza 2017-19|EyeSight Driver Assistance|Stock|0 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Subaru A| +|Subaru|Impreza 2020-22|EyeSight Driver Assistance|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Subaru A| +|Subaru|Legacy 2020-22|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Subaru B| +|Subaru|Outback 2020-22|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Subaru B| +|Subaru|XV 2018-19|EyeSight Driver Assistance|Stock|0 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Subaru A| +|Subaru|XV 2020-21|EyeSight Driver Assistance|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Subaru A| +|Škoda|Kamiq 2021[7](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533[10](#footnotes)| +|Škoda|Karoq 2019-21|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Škoda|Kodiaq 2018-19|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Škoda|Octavia 2015, 2018-19|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Škoda|Octavia RS 2016|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Škoda|Scala 2020|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533[10](#footnotes)| +|Škoda|Superb 2015-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Toyota|Alphard 2019-20|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Toyota|Alphard Hybrid 2021|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Toyota|Avalon 2016|Toyota Safety Sense P|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Toyota| +|Toyota|Avalon 2017-18|All|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Toyota| +|Toyota|Avalon 2019-21|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Toyota| +|Toyota|Avalon 2022|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Toyota|Avalon Hybrid 2019-21|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Toyota| +|Toyota|Avalon Hybrid 2022|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Toyota|C-HR 2017-21|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Toyota| +|Toyota|C-HR Hybrid 2017-19|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Toyota| +|Toyota|Camry 2018-20|All|Stock|0 mph[6](#footnotes)|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Toyota| +|Toyota|Camry 2021-22|All|openpilot|0 mph[6](#footnotes)|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Toyota|Camry Hybrid 2018-20|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Toyota| +|Toyota|Camry Hybrid 2021-23|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Toyota|Corolla 2017-19|All|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Toyota| +|Toyota|Corolla 2020-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Toyota|Corolla Cross (Non-US only) 2020-23|All|openpilot|17 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Toyota|Corolla Cross Hybrid (Non-US only) 2020-22|All|openpilot|17 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Toyota|Corolla Hatchback 2019-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Toyota|Corolla Hybrid 2020-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Toyota|Highlander 2017-19|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Toyota|Highlander 2020-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Toyota|Highlander Hybrid 2017-19|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Toyota|Highlander Hybrid 2020-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Toyota|Mirai 2021|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Toyota|Prius 2016|Toyota Safety Sense P|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Toyota| +|Toyota|Prius 2017-20|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Toyota| +|Toyota|Prius 2021-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Toyota|Prius Prime 2017-20|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Toyota| +|Toyota|Prius Prime 2021-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Toyota|Prius v 2017|Toyota Safety Sense P|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Toyota|RAV4 2016|Toyota Safety Sense P|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Toyota| +|Toyota|RAV4 2017-18|All|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Toyota| +|Toyota|RAV4 2019-21|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Toyota|RAV4 2022|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Toyota| +|Toyota|RAV4 Hybrid 2016|Toyota Safety Sense P|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Toyota|RAV4 Hybrid 2017-18|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Toyota|RAV4 Hybrid 2019-21|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Toyota|RAV4 Hybrid 2022|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|Toyota| +|Toyota|Sienna 2018-20|All|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|Toyota| +|Volkswagen|Arteon 2018-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Volkswagen|Arteon eHybrid 2020-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Volkswagen|Arteon R 2020-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Volkswagen|Atlas 2018-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Volkswagen|Atlas Cross Sport 2021-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Volkswagen|California 2021|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Volkswagen|Caravelle 2020|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Volkswagen|CC 2018-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Volkswagen|e-Golf 2014-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Volkswagen|Golf 2015-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Volkswagen|Golf Alltrack 2015-19|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Volkswagen|Golf GTD 2015-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Volkswagen|Golf GTE 2015-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Volkswagen|Golf GTI 2015-21|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Volkswagen|Golf R 2015-19|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Volkswagen|Golf SportsVan 2015-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Volkswagen|Jetta 2018-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Volkswagen|Jetta GLI 2021-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Volkswagen|Passat 2015-22[8](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Volkswagen|Passat Alltrack 2015-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Volkswagen|Passat GTE 2015-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Volkswagen|Polo 2020-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533[10](#footnotes)| +|Volkswagen|Polo GTI 2020-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533[10](#footnotes)| +|Volkswagen|T-Cross 2021|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533[10](#footnotes)| +|Volkswagen|T-Roc 2021|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533[10](#footnotes)| +|Volkswagen|Taos 2022|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Volkswagen|Teramont 2018-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Volkswagen|Teramont Cross Sport 2021-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Volkswagen|Teramont X 2021-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Volkswagen|Tiguan 2019-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| +|Volkswagen|Touran 2017|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|J533| + + +1Experimental openpilot longitudinal control is available behind a toggle; the toggle is only available in non-release branches such as `devel` or `master-ci`.
+2By default, this car will use the stock Adaptive Cruise Control (ACC) for longitudinal control. If the Driver Support Unit (DSU) is disconnected, openpilot ACC will replace stock ACC. NOTE: disconnecting the DSU disables Automatic Emergency Braking (AEB).
+3Requires a community built ASCM harness. NOTE: disconnecting the ASCM disables Automatic Emergency Braking (AEB).
+42019 Honda Civic 1.6L Diesel Sedan does not have ALC below 12mph.
+5Requires a red panda, additional harness box, additional OBD-C cable, USB-A to USB-A cable, and a USB-A to USB-C OTG dongle.
+6openpilot operates above 28mph for Camry 4CYL L, 4CYL LE and 4CYL SE which don't have Full-Speed Range Dynamic Radar Cruise Control.
+7Not including the China market Kamiq, which is based on the (currently) unsupported PQ34 platform.
+8Refers only to the MQB-based European B8 Passat, not the NMS Passat in the USA/China/Mideast markets.
+9Only available for vehicles using a gateway (J533) harness. At this time, vehicles using a camera harness are limited to using stock ACC.
+10Model-years 2022 and beyond may have a combined CAN gateway and BCM, which is supported by openpilot in software, but doesn't yet have a harness available from the comma store.
+## Community Maintained Cars Although they're not upstream, the community has openpilot running on other makes and models. See the 'Community Supported Models' section of each make [on our wiki](https://wiki.comma.ai/). + +# Don't see your car here? + +**openpilot can support many more cars than it currently does.** There are a few reasons your car may not be supported. +If your car doesn't fit into any of the incompatibility criteria here, then there's a good chance it can be supported! We're adding support for new cars all the time. **We don't have a roadmap for car support**, and in fact, most car support comes from users like you! + +### Which cars are able to be supported? + +openpilot uses the existing steering, gas, and brake interfaces in your car. If your car lacks any one of these interfaces, openpilot will not be able to control the car. If your car has [ACC](https://en.wikipedia.org/wiki/Adaptive_cruise_control) and any form of [LKAS](https://en.wikipedia.org/wiki/Automated_Lane_Keeping_Systems)/[LCA](https://en.wikipedia.org/wiki/Lane_centering), then it almost certainly has these interfaces. These features generally started shipping on cars around 2016. Note that manufacturers will often make their own [marketing terms](https://en.wikipedia.org/wiki/Adaptive_cruise_control#Vehicle_models_supporting_adaptive_cruise_control) for these features, such as Hyundai's "Smart Cruise Control" branding of Adaptive Cruise Control. + +If your car has the following packages or features, then it's a good candidate for support. + +| Make | Required Package/Features | +| ---- | ------------------------- | +| Acura | Any car with AcuraWatch Plus will work. AcuraWatch Plus comes standard on many newer models. | +| Honda | Any car with Honda Sensing will work. Honda Sensing comes standard on many newer models. | +| Subaru | Any car with EyeSight will work. EyeSight comes standard on many newer models. | +| Nissan | Any car with ProPILOT will likely work. | +| Toyota & Lexus | Any car that has Toyota/Lexus Safety Sense with "Lane Departure Alert with Steering Assist (LDA w/SA)" and/or "Lane Tracing Assist (LTA)" will work. Note that LDA without Steering Assist will not work. These features come standard on most newer models. | +| Hyundai, Kia, & Genesis | Any car with Smart Cruise Control (SCC) and Lane Following Assist (LFA) or Lane Keeping Assist (LKAS) will work. LKAS/LFA comes standard on most newer models. Any form of SCC will work, such as NSCC. | +| Chrysler, Jeep, & Ram | Any car with LaneSense and Adaptive Cruise Control will likely work. These come standard on many newer models. | + +### FlexRay + +All the cars that openpilot supports use a [CAN bus](https://en.wikipedia.org/wiki/CAN_bus) for communication between all the car's computers, however a CAN bus isn't the only way that the cars in your computer can communicate. Most, if not all, vehicles from the following manufacturers use [FlexRay](https://en.wikipedia.org/wiki/FlexRay) instead of a CAN bus: **BMW, Mercedes, Audi, Land Rover, and some Volvo**. These cars may one day be supported, but we have no immediate plans to support FlexRay. + +### Toyota Security + +openpilot does not yet support these Toyota models due to a new message authentication method. +[Vote](https://comma.ai/shop/products/vote) if you'd like to see openpilot support on these models. + +* Toyota RAV4 Prime 2021+ +* Toyota Sienna 2021+ +* Toyota Venza 2021+ +* Toyota Sequoia 2023+ +* Toyota Tundra 2022+ +* Toyota Corolla Cross 2022+ (only US model) +* Lexus NX 2022+ +* Toyota bZ4x 2023+ +* Subaru Solterra 2023+ diff --git a/docs/INTEGRATION.md b/docs/INTEGRATION.md index 97b72e39d3..ba6291c1e3 100644 --- a/docs/INTEGRATION.md +++ b/docs/INTEGRATION.md @@ -8,4 +8,4 @@ Additionally, on specific supported cars (see ACC column in [supported cars](CAR * Stock ACC is replaced by openpilot ACC. * openpilot FCW operates in addition to stock FCW. -openpilot should preserve all other vehicle's stock features, including, but are not limited to: FCW, Automatic Emergency Braking (AEB), auto high-beam, blind spot warning, and side collision warning. +openpilot should preserve all other vehicle's stock features, including, but not limited to: FCW, Automatic Emergency Braking (AEB), auto high-beam, blind spot warning, and side collision warning. diff --git a/docs/Makefile b/docs/Makefile index 02db7db2d3..d0aa841c4d 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -32,7 +32,7 @@ clean: @echo "Copying docs & config to build folder..." cp -a "$(DOCSDIR)" "$(BUILDDIR)" cd "$(OPENPILOT_ROOT)" && \ - find . -type f \( -name "*.md" -o -name "*.rst" -o -name "*.png" -o -name "*.jpg" \) \ + find . -type f \( -name "*.md" -o -name "*.rst" -o -name "*.png" -o -name "*.jpg" -o -name "*.svg" \) \ -not -path "*/.*" \ -not -path "./build/*" \ -not -path "./docs/*" \ diff --git a/docs/SAFETY.md b/docs/SAFETY.md index 23ee251af4..49f88df8c0 100644 --- a/docs/SAFETY.md +++ b/docs/SAFETY.md @@ -22,7 +22,7 @@ Following Hazard and Risk Analysis and FMEA, at a very high level, we have desig ensuring two main safety requirements. 1. The driver must always be capable to immediately retake manual control of the vehicle, - by stepping on either pedal or by pressing the cancel button. + by stepping on the brake pedal or by pressing the cancel button. 2. The vehicle must not alter its trajectory too quickly for the driver to safely react. This means that while the system is engaged, the actuators are constrained to operate within reasonable limits. diff --git a/docs/assets/icon-star-empty.svg b/docs/assets/icon-star-empty.svg new file mode 100644 index 0000000000..5d3c32d671 --- /dev/null +++ b/docs/assets/icon-star-empty.svg @@ -0,0 +1,56 @@ + + + + + + image/svg+xml + + + + + + + + diff --git a/docs/assets/icon-star-full.svg b/docs/assets/icon-star-full.svg new file mode 100644 index 0000000000..294db2b7f2 --- /dev/null +++ b/docs/assets/icon-star-full.svg @@ -0,0 +1,56 @@ + + + + + + image/svg+xml + + + + + + + + diff --git a/docs/assets/icon-star-half.svg b/docs/assets/icon-star-half.svg new file mode 100644 index 0000000000..ab905fddcb --- /dev/null +++ b/docs/assets/icon-star-half.svg @@ -0,0 +1,66 @@ + + + + + + image/svg+xml + + + + + + + + + + diff --git a/docs/c_docs.rst b/docs/c_docs.rst index 6cf5f268c5..77be7e51d8 100644 --- a/docs/c_docs.rst +++ b/docs/c_docs.rst @@ -28,11 +28,9 @@ selfdrive camerad ^^^^^^^ .. autodoxygenindex:: - :project: selfdrive_camerad_cameras + :project: system_camerad_cameras .. autodoxygenindex:: - :project: selfdrive_camerad_transforms -.. autodoxygenindex:: - :project: selfdrive_camerad_imgproc + :project: system_camerad_imgproc locationd ^^^^^^^^^ @@ -50,15 +48,11 @@ soundd .. autodoxygenindex:: :project: selfdrive_ui_soundd -navd -"""" -.. autodoxygenindex:: - :project: selfdrive_ui_navd replay """""" .. autodoxygenindex:: - :project: selfdrive_ui_replay + :project: tools_replay qt "" @@ -70,7 +64,7 @@ qt proclogd ^^^^^^^^ .. autodoxygenindex:: - :project: selfdrive_proclogd + :project: system_proclogd modeld ^^^^^^ @@ -78,15 +72,13 @@ modeld :project: selfdrive_modeld_transforms .. autodoxygenindex:: :project: selfdrive_modeld_models -.. autodoxygenindex:: - :project: selfdrive_modeld_thneed .. autodoxygenindex:: :project: selfdrive_modeld_runners common ^^^^^^ .. autodoxygenindex:: - :project: selfdrive_common + :project: common sensorsd ^^^^^^^^ diff --git a/docs/conf.py b/docs/conf.py index c11d17455d..fea921de1f 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -14,10 +14,12 @@ # documentation root, use os.path.abspath to make it absolute, like shown here. # import os -from os.path import exists import sys -from selfdrive.version import get_version +from os.path import exists + from common.basedir import BASEDIR +from system.version import get_version + sys.path.insert(0, os.path.abspath('.')) sys.path.insert(0, os.path.abspath('..')) diff --git a/docs/docker/Dockerfile b/docs/docker/Dockerfile index 124feb1bfc..0d5883f566 100644 --- a/docs/docker/Dockerfile +++ b/docs/docker/Dockerfile @@ -4,16 +4,11 @@ ENV PYTHONUNBUFFERED 1 ENV OPENPILOT_PATH /home/batman/openpilot/ ENV PYTHONPATH ${OPENPILOT_PATH}:${PYTHONPATH} +ENV POETRY_VIRUALENVS_CREATE false RUN mkdir -p ${OPENPILOT_PATH} WORKDIR ${OPENPILOT_PATH} -COPY Pipfile Pipfile.lock $OPENPILOT_PATH -RUN pip install --no-cache-dir pipenv==2021.5.29 pip==21.3.1 && \ - pipenv install --system --deploy --dev --clear && \ - pip uninstall -y pipenv - - COPY SConstruct ${OPENPILOT_PATH} COPY ./pyextra ${OPENPILOT_PATH}/pyextra @@ -30,6 +25,7 @@ COPY ./opendbc ${OPENPILOT_PATH}/opendbc COPY ./cereal ${OPENPILOT_PATH}/cereal COPY ./panda ${OPENPILOT_PATH}/panda COPY ./selfdrive ${OPENPILOT_PATH}/selfdrive +COPY ./system ${OPENPILOT_PATH}/system COPY ./*.md ${OPENPILOT_PATH}/ RUN scons -j$(nproc) diff --git a/installer/updater/updater b/installer/updater/updater deleted file mode 100755 index 8bf40708a6..0000000000 --- a/installer/updater/updater +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/bash -echo "this is a compatability shim for old updaters" diff --git a/laika_repo b/laika_repo index dec99a0f77..e1049cde0a 160000 --- a/laika_repo +++ b/laika_repo @@ -1 +1 @@ -Subproject commit dec99a0f77328f7a9f104020d98d7227345d1288 +Subproject commit e1049cde0a68f7d4a70b1ebd76befdc0e163ad55 diff --git a/launch_chffrplus.sh b/launch_chffrplus.sh index 7ef671c265..911774a4eb 100755 --- a/launch_chffrplus.sh +++ b/launch_chffrplus.sh @@ -8,110 +8,13 @@ source "$BASEDIR/launch_env.sh" DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" -function two_init { - - # set IO scheduler - setprop sys.io.scheduler noop - for f in /sys/block/*/queue/scheduler; do - echo noop > $f - done - - # *** shield cores 2-3 *** - - # TODO: should we enable this? - # offline cores 2-3 to force recurring timers onto the other cores - #echo 0 > /sys/devices/system/cpu/cpu2/online - #echo 0 > /sys/devices/system/cpu/cpu3/online - #echo 1 > /sys/devices/system/cpu/cpu2/online - #echo 1 > /sys/devices/system/cpu/cpu3/online - - # android gets two cores - echo 0-1 > /dev/cpuset/background/cpus - echo 0-1 > /dev/cpuset/system-background/cpus - echo 0-1 > /dev/cpuset/foreground/cpus - echo 0-1 > /dev/cpuset/foreground/boost/cpus - echo 0-1 > /dev/cpuset/android/cpus - - # openpilot gets all the cores - echo 0-3 > /dev/cpuset/app/cpus - - # mask off 2-3 from RPS and XPS - Receive/Transmit Packet Steering - echo 3 | tee /sys/class/net/*/queues/*/rps_cpus - echo 3 | tee /sys/class/net/*/queues/*/xps_cpus - - # *** set up governors *** - - # +50mW offroad, +500mW onroad for 30% more RAM bandwidth - echo "performance" > /sys/class/devfreq/soc:qcom,cpubw/governor - echo 1056000 > /sys/class/devfreq/soc:qcom,m4m/max_freq - echo "performance" > /sys/class/devfreq/soc:qcom,m4m/governor - - # unclear if these help, but they don't seem to hurt - echo "performance" > /sys/class/devfreq/soc:qcom,memlat-cpu0/governor - echo "performance" > /sys/class/devfreq/soc:qcom,memlat-cpu2/governor - - # GPU - echo "performance" > /sys/class/devfreq/b00000.qcom,kgsl-3d0/governor - - # /sys/class/devfreq/soc:qcom,mincpubw is the only one left at "powersave" - # it seems to gain nothing but a wasted 500mW - - # *** set up IRQ affinities *** - - # Collect RIL and other possibly long-running I/O interrupts onto CPU 1 - echo 1 > /proc/irq/78/smp_affinity_list # qcom,smd-modem (LTE radio) - echo 1 > /proc/irq/33/smp_affinity_list # ufshcd (flash storage) - echo 1 > /proc/irq/35/smp_affinity_list # wifi (wlan_pci) - echo 1 > /proc/irq/6/smp_affinity_list # MDSS - - # USB traffic needs realtime handling on cpu 3 - [ -d "/proc/irq/733" ] && echo 3 > /proc/irq/733/smp_affinity_list - - # GPU and camera get cpu 2 - CAM_IRQS="177 178 179 180 181 182 183 184 185 186 192" - for irq in $CAM_IRQS; do - echo 2 > /proc/irq/$irq/smp_affinity_list - done - echo 2 > /proc/irq/193/smp_affinity_list # GPU - - # give GPU threads RT priority - for pid in $(pgrep "kgsl"); do - chrt -f -p 52 $pid - done - - # the flippening! - LD_LIBRARY_PATH="" content insert --uri content://settings/system --bind name:s:user_rotation --bind value:i:1 - - # disable bluetooth - service call bluetooth_manager 8 - - # wifi scan - wpa_cli IFNAME=wlan0 SCAN - - # Check for NEOS update - if [ $(< /VERSION) != "$REQUIRED_NEOS_VERSION" ]; then - echo "Installing NEOS update" - NEOS_PY="$DIR/selfdrive/hardware/eon/neos.py" - MANIFEST="$DIR/selfdrive/hardware/eon/neos.json" - $NEOS_PY --swap-if-ready $MANIFEST - $DIR/selfdrive/hardware/eon/updater $NEOS_PY $MANIFEST - fi -} - -function tici_init { +function agnos_init { # wait longer for weston to come up if [ -f "$BASEDIR/prebuilt" ]; then sleep 3 fi - # setup governors - sudo su -c 'echo "performance" > /sys/class/devfreq/soc:qcom,memlat-cpu0/governor' - sudo su -c 'echo "performance" > /sys/class/devfreq/soc:qcom,memlat-cpu4/governor' - # TODO: move this to agnos - # network manager config - nmcli connection modify --temporary lte gsm.auto-config yes - nmcli connection modify --temporary lte gsm.home-only yes sudo rm -f /data/etc/NetworkManager/system-connections/*.nmmeta # set success flag for current boot slot @@ -119,12 +22,12 @@ function tici_init { # Check if AGNOS update is required if [ $(< /VERSION) != "$AGNOS_VERSION" ]; then - AGNOS_PY="$DIR/selfdrive/hardware/tici/agnos.py" - MANIFEST="$DIR/selfdrive/hardware/tici/agnos.json" + AGNOS_PY="$DIR/system/hardware/tici/agnos.py" + MANIFEST="$DIR/system/hardware/tici/agnos.json" if $AGNOS_PY --verify $MANIFEST; then sudo reboot fi - $DIR/selfdrive/hardware/tici/updater $AGNOS_PY $MANIFEST + $DIR/system/hardware/tici/updater $AGNOS_PY $MANIFEST fi } @@ -159,7 +62,6 @@ function launch { cd $BASEDIR echo "Restarting launch script ${LAUNCHER_LOCATION}" - unset REQUIRED_NEOS_VERSION unset AGNOS_VERSION exec "${LAUNCHER_LOCATION}" else @@ -175,11 +77,7 @@ function launch { export PYTHONPATH="$PWD:$PWD/pyextra" # hardware specific init - if [ -f /EON ]; then - two_init - elif [ -f /TICI ]; then - tici_init - fi + agnos_init # write tmux scrollback to a file tmux capture-pane -pq -S-1000 > /tmp/launch_log diff --git a/launch_env.sh b/launch_env.sh index cd0c27f643..3059ec268e 100755 --- a/launch_env.sh +++ b/launch_env.sh @@ -6,12 +6,8 @@ export NUMEXPR_NUM_THREADS=1 export OPENBLAS_NUM_THREADS=1 export VECLIB_MAXIMUM_THREADS=1 -if [ -z "$REQUIRED_NEOS_VERSION" ]; then - export REQUIRED_NEOS_VERSION="19.1" -fi - if [ -z "$AGNOS_VERSION" ]; then - export AGNOS_VERSION="4" + export AGNOS_VERSION="6.2" fi if [ -z "$PASSIVE" ]; then diff --git a/models/README.md b/models/README.md deleted file mode 100644 index 9f1bfdba02..0000000000 --- a/models/README.md +++ /dev/null @@ -1,109 +0,0 @@ -## Neural networks in openpilot -To view the architecture of the ONNX networks, you can use [netron](https://netron.app/) - -## Supercombo -### Supercombo input format (Full size: 393738 x float32) -* **image stream** - * Two consecutive images (256 * 512 * 3 in RGB) recorded at 20 Hz : 393216 = 2 * 6 * 128 * 256 - * Each 256 * 512 image is represented in YUV420 with 6 channels : 6 * 128 * 256 - * Channels 0,1,2,3 represent the full-res Y channel and are represented in numpy as Y[::2, ::2], Y[::2, 1::2], Y[1::2, ::2], and Y[1::2, 1::2] - * Channel 4 represents the half-res U channel - * Channel 5 represents the half-res V channel -* **desire** - * one-hot encoded vector to command model to execute certain actions, bit only needs to be sent for 1 frame : 8 -* **traffic convention** - * one-hot encoded vector to tell model whether traffic is right-hand or left-hand traffic : 2 -* **recurrent state** - * The recurrent state vector that is fed back into the GRU for temporal context : 512 - - -### Supercombo output format (Full size: 6472 x float32) -* **plan** - * 5 potential desired plan predictions : 4955 = 5 * 991 - * predicted mean and standard deviation of the following values at 33 timesteps : 990 = 2 * 33 * 15 - * x,y,z position in current frame (meters) - * x,y,z velocity in local frame (meters/s) - * x,y,z acceleration local frame (meters/(s*s)) - * roll, pitch , yaw in current frame (radians) - * roll, pitch , yaw rates in local frame (radians/s) - * probability[^1] of this plan hypothesis being the most likely: 1 -* **lanelines** - * 4 lanelines (outer left, left, right, and outer right): 528 = 4 * 132 - * predicted mean and standard deviation for the following values at 33 x positions : 132 = 2 * 33 * 2 - * y position in current frame (meters) - * z position in current frame (meters) -* **laneline probabilties** - * 2 probabilities[^1] that each of the 4 lanelines exists : 8 = 4 * 2 - * deprecated probability - * used probability -* **road-edges** - * 2 road-edges (left and right): 264 = 2 * 132 - * predicted mean and standard deviation for the following values at 33 x positions : 132 = 2 * 33 * 2 - * y position in current frame (meters) - * z position in current frame (meters) -* **leads** - * 2 hypotheses for potential lead cars : 102 = 2 * 51 - * predicted mean and stadard deviation for the following values at 0,2,4,6,8,10s : 48 = 2 * 6 * 4 - * x position of lead in current frame (meters) - * y position of lead in current frame (meters) - * speed of lead (meters/s) - * acceleration of lead(meters/(s*s)) - * probabilities[^1] this hypothesis is the most likely hypothesis at 0s, 2s or 4s from now : 3 -* **lead probabilities** - * probability[^1] that there is a lead car at 0s, 2s, 4s from now : 3 = 1 * 3 -* **desire state** - * probability[^1] that the model thinks it is executing each of the 8 potential desire actions : 8 -* **meta** [^2] - * Various metadata about the scene : 80 = 1 + 35 + 12 + 32 - * Probability[^1] that openpilot is engaged : 1 - * Probabilities[^1] of various things happening between now and 2,4,6,8,10s : 35 = 5 * 7 - * Disengage of openpilot with gas pedal - * Disengage of openpilot with brake pedal - * Override of openpilot steering - * 3m/(s*s) of deceleration - * 4m/(s*s) of deceleration - * 5m/(s*s) of deceleration - * Probabilities[^1] of left or right blinker being active at 0,2,4,6,8,10s : 12 = 6 * 2 - * Probabilities[^1] that each of the 8 desires is being executed at 0,2,4,6s : 32 = 4 * 8 - -* **pose** [^2] - * predicted mean and standard deviation of current translation and rotation rates : 12 = 2 * 6 - * x,y,z velocity in current frame (meters/s) - * roll, pitch , yaw rates in current frame (radians/s) -* **recurrent state** - * The recurrent state vector that is fed back into the GRU for temporal context : 512 - -[^1]: All probabilities are in logits, so you need to apply sigmoid or softmax functions to get actual probabilities -[^2]: These outputs come directly from the vision blocks, they do not have access to temporal state or the desire input - - -## Driver Monitoring Model -* .onnx model can be run with onnx runtimes -* .dlc file is a pre-quantized model and only runs on qualcomm DSPs - -### input format -* single image (640 * 320 * 3 in RGB): - * full input size is 6 * 640/2 * 320/2 = 307200 - * represented in YUV420 with 6 channels: - * Channels 0,1,2,3 represent the full-res Y channel and are represented in numpy as Y[::2, ::2], Y[::2, 1::2], Y[1::2, ::2], and Y[1::2, 1::2] - * Channel 4 represents the half-res U channel - * Channel 5 represents the half-res V channel - * normalized, ranging from -1.0 to 1.0 - -### output format -* 39 x float32 outputs ([parsing example](https://github.com/commaai/openpilot/blob/master/selfdrive/modeld/models/dmonitoring.cc#L165)) - * face pose: 12 = 6 + 6 - * face orientation [pitch, yaw, roll] in camera frame: 3 - * face position [dx, dy] relative to image center: 2 - * normalized face size: 1 - * standard deviations for above outputs: 6 - * face visible probability: 1 - * eyes: 20 = (8 + 1) + (8 + 1) + 1 + 1 - * eye position and size, and their standard deviations: 8 - * eye visible probability: 1 - * eye closed probability: 1 - * wearing sunglasses probability: 1 - * poor camera vision probability: 1 - * face partially out-of-frame probability: 1 - * (deprecated) distracted probabilities: 2 - * face covered probability: 1 diff --git a/models/big_supercombo.dlc b/models/big_supercombo.dlc deleted file mode 100644 index a27e3d1180..0000000000 --- a/models/big_supercombo.dlc +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ba3fe3e61853cc1434e3e220f40c8e9d1f1b9bab8458196ba3bea6a10b82c6ed -size 72718099 diff --git a/models/big_supercombo.onnx b/models/big_supercombo.onnx deleted file mode 100644 index 3039035fbc..0000000000 --- a/models/big_supercombo.onnx +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:bda57c1a66944f5a633ecd739a24d62702c717a234f2fdcc499dfa1d61c3c19e -size 73147489 diff --git a/models/dmonitoring_model.current b/models/dmonitoring_model.current deleted file mode 100644 index b9e0c24751..0000000000 --- a/models/dmonitoring_model.current +++ /dev/null @@ -1,2 +0,0 @@ -4e19be90-bd5b-485d-b79a-2462f7f1b49e -08f7ec37b78228cd1cb750b6ddb9c6ba1769e911 \ No newline at end of file diff --git a/models/dmonitoring_model.onnx b/models/dmonitoring_model.onnx deleted file mode 100644 index 9fe743334d..0000000000 --- a/models/dmonitoring_model.onnx +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:895ee32e2a1c77496e015270db475eef65034b25331f2859bac0ccf702f64298 -size 3294407 diff --git a/models/dmonitoring_model_q.dlc b/models/dmonitoring_model_q.dlc deleted file mode 100644 index 1e34e0de3f..0000000000 --- a/models/dmonitoring_model_q.dlc +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6e4ac870984d11cd8e86cda4a63e3321fde837bacf4a055a27b7c8ba34facfe2 -size 916079 diff --git a/models/supercombo.dlc b/models/supercombo.dlc deleted file mode 100644 index 2ebf4fa828..0000000000 --- a/models/supercombo.dlc +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:209e9544e456dbc2a7d60490da65154e129bc84830909d8d931f97b3df93949b -size 56684955 diff --git a/models/supercombo.onnx b/models/supercombo.onnx deleted file mode 100644 index 17d233dad7..0000000000 --- a/models/supercombo.onnx +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2365bae967cce21ce68707c30bf2981bb7081ee5c3e6a3dff793e660f23ff622 -size 57554657 diff --git a/mypy.ini b/mypy.ini index 66b82bd5df..39b1b007a7 100644 --- a/mypy.ini +++ b/mypy.ini @@ -1,4 +1,16 @@ [mypy] python_version = 3.8 +plugins = numpy.typing.mypy_plugin +files = body, common, docs, scripts, selfdrive, site_scons, system, tools +exclude = ^(pyextra/)|(cereal/)|(opendbc/)|(panda/)|(laika/)|(laika_repo/)|(rednose/)|(rednose_repo/)|(tinygrad/)|(tinygrad_repo/)|(xx/) + +; third-party packages ignore_missing_imports = True +; helpful warnings +warn_redundant_casts = True +warn_unreachable = True +warn_unused_ignores = True + +; restrict dynamic typing +warn_return_any = True diff --git a/opendbc b/opendbc index 46a942d679..94fff4782b 160000 --- a/opendbc +++ b/opendbc @@ -1 +1 @@ -Subproject commit 46a942d6790531cf5b94b14266140e43afcfda3e +Subproject commit 94fff4782be263efad10032a612b3c96a120c0b7 diff --git a/panda b/panda index cb88a1756b..4edd1a6021 160000 --- a/panda +++ b/panda @@ -1 +1 @@ -Subproject commit cb88a1756ba2b8b06e06102691c75f8aa87f687b +Subproject commit 4edd1a602131ec2f09a604a4bd28e7d00e334458 diff --git a/poetry.lock b/poetry.lock new file mode 100644 index 0000000000..39fb78cf2a --- /dev/null +++ b/poetry.lock @@ -0,0 +1,8030 @@ +[[package]] +name = "adal" +version = "1.2.7" +description = "Note: This library is already replaced by MSAL Python, available here: https://pypi.org/project/msal/ .ADAL Python remains available here as a legacy. The ADAL for Python library makes it easy for python application to authenticate to Azure Active Directory (AAD) in order to access AAD protected web resources." +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +cryptography = ">=1.1.0" +PyJWT = ">=1.0.0,<3" +python-dateutil = ">=2.1.0,<3" +requests = ">=2.0.0,<3" + +[[package]] +name = "aenum" +version = "3.1.11" +description = "Advanced Enumerations (compatible with Python's stdlib Enum), NamedTuples, and NamedConstants" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "aiohttp" +version = "3.8.3" +description = "Async http client/server framework (asyncio)" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +aiosignal = ">=1.1.2" +async-timeout = ">=4.0.0a3,<5.0" +attrs = ">=17.3.0" +charset-normalizer = ">=2.0,<3.0" +frozenlist = ">=1.1.1" +multidict = ">=4.5,<7.0" +yarl = ">=1.0,<2.0" + +[package.extras] +speedups = ["Brotli", "aiodns", "cchardet"] + +[[package]] +name = "aiosignal" +version = "1.2.0" +description = "aiosignal: a list of registered asynchronous callbacks" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +frozenlist = ">=1.1.0" + +[[package]] +name = "alabaster" +version = "0.7.12" +description = "A configurable sidebar-enabled Sphinx theme" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "albumentations" +version = "1.3.0" +description = "Fast image augmentation library and easy to use wrapper around other libraries" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +numpy = ">=1.11.1" +opencv-python-headless = ">=4.1.1" +PyYAML = "*" +qudida = ">=0.0.4" +scikit-image = ">=0.16.1" +scipy = "*" + +[package.extras] +develop = ["imgaug (>=0.4.0)", "pytest"] +imgaug = ["imgaug (>=0.4.0)"] +tests = ["pytest"] + +[[package]] +name = "anyio" +version = "3.6.2" +description = "High level compatibility layer for multiple asynchronous event loop implementations" +category = "dev" +optional = false +python-versions = ">=3.6.2" + +[package.dependencies] +idna = ">=2.8" +sniffio = ">=1.1" + +[package.extras] +doc = ["packaging", "sphinx-autodoc-typehints (>=1.2.0)", "sphinx-rtd-theme"] +test = ["contextlib2", "coverage[toml] (>=4.5)", "hypothesis (>=4.0)", "mock (>=4)", "pytest (>=7.0)", "pytest-mock (>=3.6.1)", "trustme", "uvloop (<0.15)", "uvloop (>=0.15)"] +trio = ["trio (>=0.16,<0.22)"] + +[[package]] +name = "apex" +version = "0.1" +description = "PyTorch Extensions written by NVIDIA" +category = "dev" +optional = false +python-versions = "*" + +[package.source] +type = "url" +url = "https://github.com/commaai/apex/releases/download/pytorch1.10.0%2Bcu11.1/apex-0.1-cp38-cp38-linux_x86_64.whl" + +[[package]] +name = "appdirs" +version = "1.4.4" +description = "A small Python module for determining appropriate platform-specific dirs, e.g. a \"user data dir\"." +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "applicationinsights" +version = "0.11.10" +description = "This project extends the Application Insights API surface to support Python." +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "appnope" +version = "0.1.3" +description = "Disable App Nap on macOS >= 10.9" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "argcomplete" +version = "1.12.3" +description = "Bash tab completion for argparse" +category = "dev" +optional = false +python-versions = "*" + +[package.extras] +test = ["coverage", "flake8", "pexpect", "wheel"] + +[[package]] +name = "argon2-cffi" +version = "21.3.0" +description = "The secure Argon2 password hashing algorithm." +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +argon2-cffi-bindings = "*" + +[package.extras] +dev = ["cogapp", "coverage[toml] (>=5.0.2)", "furo", "hypothesis", "pre-commit", "pytest", "sphinx", "sphinx-notfound-page", "tomli"] +docs = ["furo", "sphinx", "sphinx-notfound-page"] +tests = ["coverage[toml] (>=5.0.2)", "hypothesis", "pytest"] + +[[package]] +name = "argon2-cffi-bindings" +version = "21.2.0" +description = "Low-level CFFI bindings for Argon2" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +cffi = ">=1.0.1" + +[package.extras] +dev = ["cogapp", "pre-commit", "pytest", "wheel"] +tests = ["pytest"] + +[[package]] +name = "astroid" +version = "2.12.12" +description = "An abstract syntax tree for Python with inference support." +category = "main" +optional = false +python-versions = ">=3.7.2" + +[package.dependencies] +lazy-object-proxy = ">=1.4.0" +typing-extensions = {version = ">=3.10", markers = "python_version < \"3.10\""} +wrapt = {version = ">=1.11,<2", markers = "python_version < \"3.11\""} + +[[package]] +name = "asttokens" +version = "2.0.8" +description = "Annotate AST trees with source code positions" +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +six = "*" + +[package.extras] +test = ["astroid (<=2.5.3)", "pytest"] + +[[package]] +name = "async-timeout" +version = "4.0.2" +description = "Timeout context manager for asyncio programs" +category = "dev" +optional = false +python-versions = ">=3.6" + +[[package]] +name = "atomicwrites" +version = "1.4.1" +description = "Atomic file writes." +category = "main" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" + +[[package]] +name = "attrs" +version = "22.1.0" +description = "Classes Without Boilerplate" +category = "main" +optional = false +python-versions = ">=3.5" + +[package.extras] +dev = ["cloudpickle", "coverage[toml] (>=5.0.2)", "furo", "hypothesis", "mypy (>=0.900,!=0.940)", "pre-commit", "pympler", "pytest (>=4.3.0)", "pytest-mypy-plugins", "sphinx", "sphinx-notfound-page", "zope.interface"] +docs = ["furo", "sphinx", "sphinx-notfound-page", "zope.interface"] +tests = ["cloudpickle", "coverage[toml] (>=5.0.2)", "hypothesis", "mypy (>=0.900,!=0.940)", "pympler", "pytest (>=4.3.0)", "pytest-mypy-plugins", "zope.interface"] +tests-no-zope = ["cloudpickle", "coverage[toml] (>=5.0.2)", "hypothesis", "mypy (>=0.900,!=0.940)", "pympler", "pytest (>=4.3.0)", "pytest-mypy-plugins"] + +[[package]] +name = "av" +version = "9.2.0" +description = "Pythonic bindings for FFmpeg's libraries." +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "azure-cli-core" +version = "2.41.0" +description = "Microsoft Azure Command-Line Tools Core Module" +category = "dev" +optional = false +python-versions = ">=3.7.0" + +[package.dependencies] +argcomplete = ">=1.8,<2.0" +azure-cli-telemetry = ">=1.0.0,<1.1.0" +azure-mgmt-core = ">=1.2.0,<2" +cryptography = "*" +humanfriendly = ">=10.0,<11.0" +jmespath = "*" +knack = ">=0.10.0,<0.11.0" +msal = {version = "1.20.0b1", extras = ["broker"]} +msal-extensions = ">=1.0.0,<1.1.0" +msrestazure = ">=0.6.4,<0.7.0" +packaging = ">=20.9,<22.0" +paramiko = ">=2.0.8,<3.0.0" +pkginfo = ">=1.5.0.1" +psutil = {version = ">=5.9,<6.0", markers = "sys_platform != \"cygwin\""} +PyJWT = ">=2.1.0" +pyopenssl = ">=17.1.0" +requests = {version = "*", extras = ["socks"]} + +[[package]] +name = "azure-cli-telemetry" +version = "1.0.8" +description = "Microsoft Azure CLI Telemetry Package" +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +applicationinsights = ">=0.11.1,<0.12" +portalocker = ">=1.6,<3" + +[[package]] +name = "azure-common" +version = "1.1.28" +description = "Microsoft Azure Client Library for Python (Common)" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "azure-core" +version = "1.26.0" +description = "Microsoft Azure Core Library for Python" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +requests = ">=2.18.4" +six = ">=1.11.0" +typing-extensions = ">=4.0.1" + +[package.extras] +aio = ["aiohttp (>=3.0)"] + +[[package]] +name = "azure-mgmt-core" +version = "1.3.2" +description = "Microsoft Azure Management Core Library for Python" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +azure-core = ">=1.24.0,<2.0.0" + +[[package]] +name = "azure-nspkg" +version = "3.0.2" +description = "Microsoft Azure Namespace Package [Internal]" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "azure-storage-blob" +version = "2.1.0" +description = "Microsoft Azure Storage Blob Client Library for Python" +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +azure-common = ">=1.1.5" +azure-storage-common = ">=2.1,<3.0" + +[[package]] +name = "azure-storage-common" +version = "2.1.0" +description = "Microsoft Azure Storage Common Client Library for Python" +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +azure-common = ">=1.1.5" +cryptography = "*" +python-dateutil = "*" +requests = "*" + +[[package]] +name = "azure-storage-nspkg" +version = "3.1.0" +description = "Microsoft Azure Storage Namespace Package [Internal]" +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +azure-nspkg = ">=2.0.0" + +[[package]] +name = "babel" +version = "2.10.3" +description = "Internationalization utilities" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +pytz = ">=2015.7" + +[[package]] +name = "backcall" +version = "0.2.0" +description = "Specifications for callback functions passed in to an API" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "bcrypt" +version = "4.0.1" +description = "Modern password hashing for your software and your servers" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.extras] +tests = ["pytest (>=3.2.1,!=3.3.0)"] +typecheck = ["mypy"] + +[[package]] +name = "beautifulsoup4" +version = "4.11.1" +description = "Screen-scraping library" +category = "dev" +optional = false +python-versions = ">=3.6.0" + +[package.dependencies] +soupsieve = ">1.2" + +[package.extras] +html5lib = ["html5lib"] +lxml = ["lxml"] + +[[package]] +name = "bidict" +version = "0.22.0" +description = "The bidirectional mapping library for Python." +category = "dev" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "bleach" +version = "5.0.1" +description = "An easy safelist-based HTML-sanitizing tool." +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +six = ">=1.9.0" +webencodings = "*" + +[package.extras] +css = ["tinycss2 (>=1.1.0,<1.2)"] +dev = ["Sphinx (==4.3.2)", "black (==22.3.0)", "build (==0.8.0)", "flake8 (==4.0.1)", "hashin (==0.17.0)", "mypy (==0.961)", "pip-tools (==6.6.2)", "pytest (==7.1.2)", "tox (==3.25.0)", "twine (==4.0.1)", "wheel (==0.37.1)"] + +[[package]] +name = "blosc" +version = "1.9.2" +description = "Blosc data compressor" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "breathe" +version = "4.34.0" +description = "Sphinx Doxygen renderer" +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +docutils = ">=0.12" +Sphinx = ">=4.0,<5.0.0 || >5.0.0,<6" + +[[package]] +name = "cachecontrol" +version = "0.12.11" +description = "httplib2 caching for requests" +category = "main" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +lockfile = {version = ">=0.9", optional = true, markers = "extra == \"filecache\""} +msgpack = ">=0.5.2" +requests = "*" + +[package.extras] +filecache = ["lockfile (>=0.9)"] +redis = ["redis (>=2.10.5)"] + +[[package]] +name = "cachy" +version = "0.3.0" +description = "Cachy provides a simple yet effective caching library." +category = "main" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" + +[package.extras] +memcached = ["python-memcached (>=1.59,<2.0)"] +msgpack = ["msgpack-python (>=0.5,<0.6)"] +redis = ["redis (>=3.3.6,<4.0.0)"] + +[[package]] +name = "carla" +version = "0.9.13" +description = "Python API for communicating with the CARLA server." +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "casadi" +version = "3.5.5" +description = "CasADi -- framework for algorithmic differentiation and numeric optimization" +category = "main" +optional = false +python-versions = "*" + +[[package]] +name = "certifi" +version = "2022.9.24" +description = "Python package for providing Mozilla's CA Bundle." +category = "main" +optional = false +python-versions = ">=3.6" + +[[package]] +name = "cffi" +version = "1.15.1" +description = "Foreign Function Interface for Python calling C code." +category = "main" +optional = false +python-versions = "*" + +[package.dependencies] +pycparser = "*" + +[[package]] +name = "cfgv" +version = "3.3.1" +description = "Validate configuration and produce human readable error messages." +category = "dev" +optional = false +python-versions = ">=3.6.1" + +[[package]] +name = "charset-normalizer" +version = "2.1.1" +description = "The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet." +category = "main" +optional = false +python-versions = ">=3.6.0" + +[package.extras] +unicode-backport = ["unicodedata2"] + +[[package]] +name = "cleo" +version = "1.0.0a5" +description = "Cleo allows you to create beautiful and testable command-line interfaces." +category = "main" +optional = false +python-versions = ">=3.7,<4.0" + +[package.dependencies] +crashtest = ">=0.3.1,<0.4.0" +pylev = ">=1.3.0,<2.0.0" + +[[package]] +name = "click" +version = "8.1.3" +description = "Composable command line interface toolkit" +category = "main" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +colorama = {version = "*", markers = "platform_system == \"Windows\""} + +[[package]] +name = "cloudpickle" +version = "2.2.0" +description = "Extended pickling support for Python objects" +category = "dev" +optional = false +python-versions = ">=3.6" + +[[package]] +name = "colorama" +version = "0.4.5" +description = "Cross-platform colored terminal text." +category = "main" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" + +[[package]] +name = "coloredlogs" +version = "15.0.1" +description = "Colored terminal output for Python's logging module" +category = "main" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" + +[package.dependencies] +humanfriendly = ">=9.1" + +[package.extras] +cron = ["capturer (>=2.4)"] + +[[package]] +name = "configargparse" +version = "1.5.3" +description = "A drop-in replacement for argparse that allows options to also be set via config files and/or environment variables." +category = "dev" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" + +[package.extras] +test = ["PyYAML", "mock", "pytest"] +yaml = ["PyYAML"] + +[[package]] +name = "contourpy" +version = "1.0.5" +description = "Python library for calculating contours of 2D quadrilateral grids" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +numpy = ">=1.16" + +[package.extras] +bokeh = ["bokeh", "selenium"] +docs = ["docutils (<0.18)", "sphinx", "sphinx-rtd-theme"] +test = ["Pillow", "flake8", "isort", "matplotlib", "pytest"] +test-minimal = ["pytest"] +test-no-codebase = ["Pillow", "matplotlib", "pytest"] + +[[package]] +name = "control" +version = "0.9.2" +description = "Python Control Systems Library" +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +matplotlib = "*" +numpy = "*" +scipy = "*" + +[package.extras] +slycot = ["slycot (>=0.4.0)"] +test = ["pytest", "pytest-timeout"] + +[[package]] +name = "coverage" +version = "6.5.0" +description = "Code coverage measurement for Python" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.extras] +toml = ["tomli"] + +[[package]] +name = "crashtest" +version = "0.3.1" +description = "Manage Python errors with ease" +category = "main" +optional = false +python-versions = ">=3.6,<4.0" + +[[package]] +name = "crcmod" +version = "1.7" +description = "CRC Generator" +category = "main" +optional = false +python-versions = "*" + +[[package]] +name = "cryptography" +version = "37.0.4" +description = "cryptography is a package which provides cryptographic recipes and primitives to Python developers." +category = "main" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +cffi = ">=1.12" + +[package.extras] +docs = ["sphinx (>=1.6.5,!=1.8.0,!=3.1.0,!=3.1.1)", "sphinx_rtd_theme"] +docstest = ["pyenchant (>=1.6.11)", "sphinxcontrib-spelling (>=4.0.1)", "twine (>=1.12.0)"] +pep8test = ["black", "flake8", "flake8-import-order", "pep8-naming"] +sdist = ["setuptools_rust (>=0.11.4)"] +ssh = ["bcrypt (>=3.1.5)"] +test = ["hypothesis (>=1.11.4,!=3.79.2)", "iso8601", "pretend", "pytest (>=6.2.0)", "pytest-benchmark", "pytest-cov", "pytest-subtests", "pytest-xdist", "pytz"] + +[[package]] +name = "cupy-cuda113" +version = "10.6.0" +description = "CuPy: NumPy & SciPy for GPU" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +fastrlock = ">=0.5" +numpy = ">=1.18,<1.25" + +[package.extras] +all = ["Cython (>=0.29.22,<3)", "optuna (>=2.0)", "scipy (>=1.4,<1.11)"] +stylecheck = ["autopep8 (==1.5.5)", "flake8 (==3.8.4)", "mypy (==0.950)", "pbr (==5.5.1)", "pycodestyle (==2.6.0)", "types-setuptools (==57.4.14)"] +test = ["hypothesis (>=6.37.2)", "pytest (>=6.2)"] + +[[package]] +name = "cycler" +version = "0.11.0" +description = "Composable style cycles" +category = "dev" +optional = false +python-versions = ">=3.6" + +[[package]] +name = "cython" +version = "0.29.32" +description = "The Cython compiler for writing C extensions for the Python language." +category = "main" +optional = false +python-versions = ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*" + +[[package]] +name = "datadog" +version = "0.44.0" +description = "The Datadog Python library" +category = "dev" +optional = false +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7" + +[package.dependencies] +requests = ">=2.6.0" + +[[package]] +name = "debugpy" +version = "1.6.3" +description = "An implementation of the Debug Adapter Protocol for Python" +category = "dev" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "decorator" +version = "5.1.1" +description = "Decorators for Humans" +category = "dev" +optional = false +python-versions = ">=3.5" + +[[package]] +name = "defusedxml" +version = "0.7.1" +description = "XML bomb protection for Python stdlib modules" +category = "dev" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" + +[[package]] +name = "deprecated" +version = "1.2.13" +description = "Python @deprecated decorator to deprecate old python classes, functions or methods." +category = "dev" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" + +[package.dependencies] +wrapt = ">=1.10,<2" + +[package.extras] +dev = ["PyTest", "PyTest (<5)", "PyTest-Cov", "PyTest-Cov (<2.6)", "bump2version (<1)", "configparser (<5)", "importlib-metadata (<3)", "importlib-resources (<4)", "sphinx (<2)", "sphinxcontrib-websupport (<2)", "tox", "zipp (<2)"] + +[[package]] +name = "dictdiffer" +version = "0.9.0" +description = "Dictdiffer is a library that helps you to diff and patch dictionaries." +category = "dev" +optional = false +python-versions = "*" + +[package.extras] +all = ["Sphinx (>=3)", "check-manifest (>=0.42)", "mock (>=1.3.0)", "numpy (>=1.13.0)", "numpy (>=1.15.0)", "numpy (>=1.18.0)", "numpy (>=1.20.0)", "pytest (==5.4.3)", "pytest (>=6)", "pytest-cov (>=2.10.1)", "pytest-isort (>=1.2.0)", "pytest-pycodestyle (>=2)", "pytest-pycodestyle (>=2.2.0)", "pytest-pydocstyle (>=2)", "pytest-pydocstyle (>=2.2.0)", "sphinx (>=3)", "sphinx-rtd-theme (>=0.2)", "tox (>=3.7.0)"] +docs = ["Sphinx (>=3)", "sphinx-rtd-theme (>=0.2)"] +numpy = ["numpy (>=1.13.0)", "numpy (>=1.15.0)", "numpy (>=1.18.0)", "numpy (>=1.20.0)"] +tests = ["check-manifest (>=0.42)", "mock (>=1.3.0)", "pytest (==5.4.3)", "pytest (>=6)", "pytest-cov (>=2.10.1)", "pytest-isort (>=1.2.0)", "pytest-pycodestyle (>=2)", "pytest-pycodestyle (>=2.2.0)", "pytest-pydocstyle (>=2)", "pytest-pydocstyle (>=2.2.0)", "sphinx (>=3)", "tox (>=3.7.0)"] + +[[package]] +name = "dill" +version = "0.3.5.1" +description = "serialize all of python" +category = "main" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, !=3.6.*" + +[package.extras] +graph = ["objgraph (>=1.7.2)"] + +[[package]] +name = "distlib" +version = "0.3.6" +description = "Distribution utilities" +category = "main" +optional = false +python-versions = "*" + +[[package]] +name = "docutils" +version = "0.17.1" +description = "Docutils -- Python Documentation Utilities" +category = "dev" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" + +[[package]] +name = "dotmap" +version = "1.3.30" +description = "ordered, dynamically-expandable dot-access dictionary" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "dulwich" +version = "0.20.46" +description = "Python Git Library" +category = "main" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +urllib3 = ">=1.25" + +[package.extras] +fastimport = ["fastimport"] +https = ["urllib3 (>=1.24.1)"] +paramiko = ["paramiko"] +pgp = ["gpg"] + +[[package]] +name = "efficientnet-pytorch" +version = "0.6.3" +description = "EfficientNet implemented in PyTorch." +category = "dev" +optional = false +python-versions = ">=3.5.0" + +[package.dependencies] +torch = "*" + +[[package]] +name = "einops" +version = "0.5.0" +description = "A new flavour of deep learning operations" +category = "dev" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "elastic-transport" +version = "8.4.0" +description = "Transport classes and utilities shared among Python Elastic client libraries" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +certifi = "*" +urllib3 = ">=1.26.2,<2" + +[package.extras] +develop = ["aiohttp", "mock", "pytest", "pytest-asyncio", "pytest-cov", "pytest-httpserver", "pytest-mock", "requests", "trustme"] + +[[package]] +name = "elasticsearch" +version = "8.4.3" +description = "Python client for Elasticsearch" +category = "dev" +optional = false +python-versions = ">=3.6, <4" + +[package.dependencies] +elastic-transport = ">=8,<9" + +[package.extras] +async = ["aiohttp (>=3,<4)"] +requests = ["requests (>=2.4.0,<3.0.0)"] + +[[package]] +name = "entrypoints" +version = "0.4" +description = "Discover and load entry points from installed packages." +category = "dev" +optional = false +python-versions = ">=3.6" + +[[package]] +name = "execnet" +version = "1.9.0" +description = "execnet: rapid multi-Python deployment" +category = "dev" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" + +[package.extras] +testing = ["pre-commit"] + +[[package]] +name = "executing" +version = "1.1.1" +description = "Get the currently executing AST node of a frame, and other information" +category = "dev" +optional = false +python-versions = "*" + +[package.extras] +tests = ["asttokens", "littleutils", "pytest", "rich"] + +[[package]] +name = "fastcluster" +version = "1.2.6" +description = "Fast hierarchical clustering routines for R and Python." +category = "dev" +optional = false +python-versions = ">=3" + +[package.dependencies] +numpy = ">=1.9" + +[package.extras] +test = ["scipy (>=1.6.3)"] + +[[package]] +name = "fastjsonschema" +version = "2.16.2" +description = "Fastest Python implementation of JSON schema" +category = "dev" +optional = false +python-versions = "*" + +[package.extras] +devel = ["colorama", "json-spec", "jsonschema", "pylint", "pytest", "pytest-benchmark", "pytest-cache", "validictory"] + +[[package]] +name = "fastrlock" +version = "0.8" +description = "Fast, re-entrant optimistic lock implemented in Cython" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "filelock" +version = "3.8.0" +description = "A platform independent file lock." +category = "main" +optional = false +python-versions = ">=3.7" + +[package.extras] +docs = ["furo (>=2022.6.21)", "sphinx (>=5.1.1)", "sphinx-autodoc-typehints (>=1.19.1)"] +testing = ["covdefaults (>=2.2)", "coverage (>=6.4.2)", "pytest (>=7.1.2)", "pytest-cov (>=3)", "pytest-timeout (>=2.1)"] + +[[package]] +name = "flake8" +version = "4.0.1" +description = "the modular source code checker: pep8 pyflakes and co" +category = "main" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +mccabe = ">=0.6.0,<0.7.0" +pycodestyle = ">=2.8.0,<2.9.0" +pyflakes = ">=2.4.0,<2.5.0" + +[[package]] +name = "flask" +version = "2.2.2" +description = "A simple framework for building complex web applications." +category = "main" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +click = ">=8.0" +importlib-metadata = {version = ">=3.6.0", markers = "python_version < \"3.10\""} +itsdangerous = ">=2.0" +Jinja2 = ">=3.0" +Werkzeug = ">=2.2.2" + +[package.extras] +async = ["asgiref (>=3.2)"] +dotenv = ["python-dotenv"] + +[[package]] +name = "flask-cors" +version = "3.0.10" +description = "A Flask extension adding a decorator for CORS support" +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +Flask = ">=0.9" +Six = "*" + +[[package]] +name = "flask-socketio" +version = "5.3.1" +description = "Socket.IO integration for Flask applications" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +Flask = ">=0.9" +python-socketio = ">=5.0.2" + +[[package]] +name = "flatbuffers" +version = "22.9.24" +description = "The FlatBuffers serialization format for Python" +category = "main" +optional = false +python-versions = "*" + +[[package]] +name = "fonttools" +version = "4.37.4" +description = "Tools to manipulate font files" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.extras] +all = ["brotli (>=1.0.1)", "brotlicffi (>=0.8.0)", "fs (>=2.2.0,<3)", "lxml (>=4.0,<5)", "lz4 (>=1.7.4.2)", "matplotlib", "munkres", "scipy", "skia-pathops (>=0.5.0)", "sympy", "uharfbuzz (>=0.23.0)", "unicodedata2 (>=14.0.0)", "xattr", "zopfli (>=0.1.4)"] +graphite = ["lz4 (>=1.7.4.2)"] +interpolatable = ["munkres", "scipy"] +lxml = ["lxml (>=4.0,<5)"] +pathops = ["skia-pathops (>=0.5.0)"] +plot = ["matplotlib"] +repacker = ["uharfbuzz (>=0.23.0)"] +symfont = ["sympy"] +type1 = ["xattr"] +ufo = ["fs (>=2.2.0,<3)"] +unicode = ["unicodedata2 (>=14.0.0)"] +woff = ["brotli (>=1.0.1)", "brotlicffi (>=0.8.0)", "zopfli (>=0.1.4)"] + +[[package]] +name = "frozenlist" +version = "1.3.1" +description = "A list-like structure which implements collections.abc.MutableSequence" +category = "dev" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "ft4222" +version = "1.6.0" +description = "Python wrapper around libFT4222." +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "future" +version = "0.18.2" +description = "Clean single-source support for Python 3 and 2" +category = "dev" +optional = false +python-versions = ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*" + +[[package]] +name = "future-fstrings" +version = "1.2.0" +description = "A backport of fstrings to python<3.6" +category = "main" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" + +[package.extras] +rewrite = ["tokenize-rt (>=3)"] + +[[package]] +name = "geoalchemy2" +version = "0.12.5" +description = "Using SQLAlchemy with Spatial Databases" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +packaging = "*" +SQLAlchemy = ">=1.4" + +[[package]] +name = "gevent" +version = "22.10.1" +description = "Coroutine-based network library" +category = "dev" +optional = false +python-versions = ">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5" + +[package.dependencies] +cffi = {version = ">=1.12.2", markers = "platform_python_implementation == \"CPython\" and sys_platform == \"win32\""} +greenlet = {version = ">=1.1.3,<2.0", markers = "platform_python_implementation == \"CPython\""} +setuptools = "*" +"zope.event" = "*" +"zope.interface" = "*" + +[package.extras] +dnspython = ["dnspython (>=1.16.0,<2.0)", "idna"] +docs = ["repoze.sphinx.autointerface", "sphinxcontrib-programoutput", "zope.schema"] +monitor = ["psutil (>=5.7.0)"] +recommended = ["backports.socketpair", "cffi (>=1.12.2)", "dnspython (>=1.16.0,<2.0)", "idna", "psutil (>=5.7.0)", "selectors2"] +test = ["backports.socketpair", "cffi (>=1.12.2)", "contextvars (==2.4)", "coverage (>=5.0)", "coveralls (>=1.7.0)", "dnspython (>=1.16.0,<2.0)", "futures", "idna", "mock", "objgraph", "psutil (>=5.7.0)", "requests", "selectors2"] + +[[package]] +name = "greenlet" +version = "1.1.3.post0" +description = "Lightweight in-process concurrent programming" +category = "dev" +optional = false +python-versions = ">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*" + +[package.extras] +docs = ["Sphinx"] + +[[package]] +name = "gunicorn" +version = "20.1.0" +description = "WSGI HTTP Server for UNIX" +category = "main" +optional = false +python-versions = ">=3.5" + +[package.dependencies] +setuptools = ">=3.0" + +[package.extras] +eventlet = ["eventlet (>=0.24.1)"] +gevent = ["gevent (>=1.4.0)"] +setproctitle = ["setproctitle"] +tornado = ["tornado (>=0.2)"] + +[[package]] +name = "h3" +version = "3.7.4" +description = "Hierarchical hexagonal geospatial indexing system" +category = "main" +optional = false +python-versions = "*" + +[package.extras] +all = ["flake8", "numpy", "pylint", "pytest", "pytest-cov"] +numpy = ["numpy"] +test = ["flake8", "pylint", "pytest", "pytest-cov"] + +[[package]] +name = "hatanaka" +version = "2.4.0" +description = "Effortlessly compress / decompress any RINEX file" +category = "main" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +importlib-resources = "*" +ncompress = "*" + +[package.extras] +dev = ["pytest"] +tests = ["pytest"] + +[[package]] +name = "hexdump" +version = "3.3" +description = "dump binary data to hex format and restore from there" +category = "main" +optional = false +python-versions = "*" + +[[package]] +name = "html5lib" +version = "1.1" +description = "HTML parser based on the WHATWG HTML specification" +category = "main" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" + +[package.dependencies] +six = ">=1.9" +webencodings = "*" + +[package.extras] +all = ["chardet (>=2.2)", "genshi", "lxml"] +chardet = ["chardet (>=2.2)"] +genshi = ["genshi"] +lxml = ["lxml"] + +[[package]] +name = "humanfriendly" +version = "10.0" +description = "Human friendly output for text interfaces using Python" +category = "main" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" + +[package.dependencies] +pyreadline3 = {version = "*", markers = "sys_platform == \"win32\" and python_version >= \"3.8\""} + +[[package]] +name = "hypothesis" +version = "6.46.7" +description = "A library for property-based testing" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +attrs = ">=19.2.0" +sortedcontainers = ">=2.1.0,<3.0.0" + +[package.extras] +all = ["backports.zoneinfo (>=0.2.1)", "black (>=19.10b0)", "click (>=7.0)", "django (>=2.2)", "dpcontracts (>=0.4)", "importlib-metadata (>=3.6)", "lark-parser (>=0.6.5)", "libcst (>=0.3.16)", "numpy (>=1.9.0)", "pandas (>=0.25)", "pytest (>=4.6)", "python-dateutil (>=1.4)", "pytz (>=2014.1)", "redis (>=3.0.0)", "rich (>=9.0.0)", "tzdata (>=2022.1)"] +cli = ["black (>=19.10b0)", "click (>=7.0)", "rich (>=9.0.0)"] +codemods = ["libcst (>=0.3.16)"] +dateutil = ["python-dateutil (>=1.4)"] +django = ["django (>=2.2)"] +dpcontracts = ["dpcontracts (>=0.4)"] +ghostwriter = ["black (>=19.10b0)"] +lark = ["lark-parser (>=0.6.5)"] +numpy = ["numpy (>=1.9.0)"] +pandas = ["pandas (>=0.25)"] +pytest = ["pytest (>=4.6)"] +pytz = ["pytz (>=2014.1)"] +redis = ["redis (>=3.0.0)"] +zoneinfo = ["backports.zoneinfo (>=0.2.1)", "tzdata (>=2022.1)"] + +[[package]] +name = "identify" +version = "2.5.6" +description = "File identification library for Python" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.extras] +license = ["ukkonen"] + +[[package]] +name = "idna" +version = "3.4" +description = "Internationalized Domain Names in Applications (IDNA)" +category = "main" +optional = false +python-versions = ">=3.5" + +[[package]] +name = "imageio" +version = "2.22.2" +description = "Library for reading and writing a wide range of image, video, scientific, and volumetric data formats." +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +numpy = "*" +pillow = ">=8.3.2" + +[package.extras] +all-plugins = ["astropy", "av", "imageio-ffmpeg", "opencv-python", "psutil", "tifffile"] +all-plugins-pypy = ["av", "imageio-ffmpeg", "psutil", "tifffile"] +build = ["wheel"] +dev = ["black", "flake8", "fsspec[github]", "invoke", "pytest", "pytest-cov"] +docs = ["numpydoc", "pydata-sphinx-theme", "sphinx"] +ffmpeg = ["imageio-ffmpeg", "psutil"] +fits = ["astropy"] +full = ["astropy", "av", "black", "flake8", "fsspec[github]", "gdal", "imageio-ffmpeg", "invoke", "itk", "numpydoc", "opencv-python", "psutil", "pydata-sphinx-theme", "pytest", "pytest-cov", "sphinx", "tifffile", "wheel"] +gdal = ["gdal"] +itk = ["itk"] +linting = ["black", "flake8"] +opencv = ["opencv-python"] +pyav = ["av"] +test = ["fsspec[github]", "invoke", "pytest", "pytest-cov"] +tifffile = ["tifffile"] + +[[package]] +name = "imagesize" +version = "1.4.1" +description = "Getting image size from png/jpeg/jpeg2000/gif file" +category = "dev" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" + +[[package]] +name = "importlib-metadata" +version = "4.13.0" +description = "Read metadata from Python packages" +category = "main" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +zipp = ">=0.5" + +[package.extras] +docs = ["furo", "jaraco.packaging (>=9)", "jaraco.tidelift (>=1.4)", "rst.linker (>=1.9)", "sphinx (>=3.5)"] +perf = ["ipython"] +testing = ["flake8 (<5)", "flufl.flake8", "importlib-resources (>=1.3)", "packaging", "pyfakefs", "pytest (>=6)", "pytest-black (>=0.3.7)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=1.3)", "pytest-flake8", "pytest-mypy (>=0.9.1)", "pytest-perf (>=0.9.2)"] + +[[package]] +name = "importlib-resources" +version = "5.10.0" +description = "Read resources from Python packages" +category = "main" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +zipp = {version = ">=3.1.0", markers = "python_version < \"3.10\""} + +[package.extras] +docs = ["furo", "jaraco.packaging (>=9)", "jaraco.tidelift (>=1.4)", "rst.linker (>=1.9)", "sphinx (>=3.5)"] +testing = ["flake8 (<5)", "pytest (>=6)", "pytest-black (>=0.3.7)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=1.3)", "pytest-flake8", "pytest-mypy (>=0.9.1)"] + +[[package]] +name = "influxdb-client" +version = "1.33.0" +description = "InfluxDB 2.0 Python client library" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +certifi = ">=14.05.14" +python-dateutil = ">=2.5.3" +reactivex = ">=4.0.4" +setuptools = ">=21.0.0" +urllib3 = ">=1.26.0" + +[package.extras] +async = ["aiocsv (>=1.2.2)", "aiohttp (>=3.8.1)"] +ciso = ["ciso8601 (>=2.1.1)"] +extra = ["numpy", "pandas (>=0.25.3)"] +test = ["aioresponses (>=0.7.3)", "coverage (>=4.0.3)", "flake8 (>=5.0.3)", "httpretty (==1.0.5)", "jinja2 (==3.1.2)", "nose (>=1.3.7)", "pluggy (>=0.3.1)", "psutil (>=5.6.3)", "py (>=1.4.31)", "pytest (>=5.0.0)", "pytest-cov (>=3.0.0)", "randomize (>=0.13)", "sphinx (==1.8.5)", "sphinx-rtd-theme"] + +[[package]] +name = "iniconfig" +version = "1.1.1" +description = "iniconfig: brain-dead simple config-ini parsing" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "inputs" +version = "0.5" +description = "Cross-platform Python support for keyboards, mice and gamepads." +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "ipykernel" +version = "6.16.1" +description = "IPython Kernel for Jupyter" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +appnope = {version = "*", markers = "platform_system == \"Darwin\""} +debugpy = ">=1.0" +ipython = ">=7.23.1" +jupyter-client = ">=6.1.12" +matplotlib-inline = ">=0.1" +nest-asyncio = "*" +packaging = "*" +psutil = "*" +pyzmq = ">=17" +tornado = ">=6.1" +traitlets = ">=5.1.0" + +[package.extras] +docs = ["myst-parser", "pydata-sphinx-theme", "sphinx", "sphinxcontrib-github-alt"] +test = ["flaky", "ipyparallel", "pre-commit", "pytest (>=7.0)", "pytest-cov", "pytest-timeout"] + +[[package]] +name = "ipython" +version = "8.5.0" +description = "IPython: Productive Interactive Computing" +category = "dev" +optional = false +python-versions = ">=3.8" + +[package.dependencies] +appnope = {version = "*", markers = "sys_platform == \"darwin\""} +backcall = "*" +colorama = {version = "*", markers = "sys_platform == \"win32\""} +decorator = "*" +jedi = ">=0.16" +matplotlib-inline = "*" +pexpect = {version = ">4.3", markers = "sys_platform != \"win32\""} +pickleshare = "*" +prompt-toolkit = ">3.0.1,<3.1.0" +pygments = ">=2.4.0" +stack-data = "*" +traitlets = ">=5" + +[package.extras] +all = ["Sphinx (>=1.3)", "black", "curio", "ipykernel", "ipyparallel", "ipywidgets", "matplotlib (!=3.2.0)", "nbconvert", "nbformat", "notebook", "numpy (>=1.19)", "pandas", "pytest (<7.1)", "pytest-asyncio", "qtconsole", "testpath", "trio"] +black = ["black"] +doc = ["Sphinx (>=1.3)"] +kernel = ["ipykernel"] +nbconvert = ["nbconvert"] +nbformat = ["nbformat"] +notebook = ["ipywidgets", "notebook"] +parallel = ["ipyparallel"] +qtconsole = ["qtconsole"] +test = ["pytest (<7.1)", "pytest-asyncio", "testpath"] +test-extra = ["curio", "matplotlib (!=3.2.0)", "nbformat", "numpy (>=1.19)", "pandas", "pytest (<7.1)", "pytest-asyncio", "testpath", "trio"] + +[[package]] +name = "ipython-genutils" +version = "0.2.0" +description = "Vestigial utilities from IPython" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "ipywidgets" +version = "8.0.2" +description = "Jupyter interactive widgets" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +ipykernel = ">=4.5.1" +ipython = ">=6.1.0" +jupyterlab-widgets = ">=3.0,<4.0" +traitlets = ">=4.3.1" +widgetsnbextension = ">=4.0,<5.0" + +[package.extras] +test = ["jsonschema", "pytest (>=3.6.0)", "pytest-cov", "pytz"] + +[[package]] +name = "isodate" +version = "0.6.1" +description = "An ISO 8601 date/time/duration parser and formatter" +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +six = "*" + +[[package]] +name = "isort" +version = "5.10.1" +description = "A Python utility / library to sort Python imports." +category = "main" +optional = false +python-versions = ">=3.6.1,<4.0" + +[package.extras] +colors = ["colorama (>=0.4.3,<0.5.0)"] +pipfile-deprecated-finder = ["pipreqs", "requirementslib"] +plugins = ["setuptools"] +requirements-deprecated-finder = ["pip-api", "pipreqs"] + +[[package]] +name = "itsdangerous" +version = "2.1.2" +description = "Safely pass data to untrusted environments and back." +category = "main" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "jaraco-classes" +version = "3.2.3" +description = "Utility functions for Python class constructs" +category = "main" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +more-itertools = "*" + +[package.extras] +docs = ["jaraco.packaging (>=9)", "jaraco.tidelift (>=1.4)", "rst.linker (>=1.9)", "sphinx (>=3.5)"] +testing = ["flake8 (<5)", "pytest (>=6)", "pytest-black (>=0.3.7)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=1.3)", "pytest-flake8", "pytest-mypy (>=0.9.1)"] + +[[package]] +name = "jedi" +version = "0.18.1" +description = "An autocompletion tool for Python that can be used for text editors." +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +parso = ">=0.8.0,<0.9.0" + +[package.extras] +qa = ["flake8 (==3.8.3)", "mypy (==0.782)"] +testing = ["Django (<3.1)", "colorama", "docopt", "pytest (<7.0.0)"] + +[[package]] +name = "jeepney" +version = "0.8.0" +description = "Low-level, pure Python DBus protocol wrapper." +category = "main" +optional = false +python-versions = ">=3.7" + +[package.extras] +test = ["async-timeout", "pytest", "pytest-asyncio (>=0.17)", "pytest-trio", "testpath", "trio"] +trio = ["async_generator", "trio"] + +[[package]] +name = "jinja2" +version = "3.1.2" +description = "A very fast and expressive template engine." +category = "main" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +MarkupSafe = ">=2.0" + +[package.extras] +i18n = ["Babel (>=2.7)"] + +[[package]] +name = "jmespath" +version = "1.0.1" +description = "JSON Matching Expressions" +category = "dev" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "joblib" +version = "1.2.0" +description = "Lightweight pipelining with Python functions" +category = "dev" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "json-logging-py" +version = "0.2" +description = "JSON / Logstash formatters for Python logging" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "json-rpc" +version = "1.13.0" +description = "JSON-RPC transport implementation" +category = "main" +optional = false +python-versions = "*" + +[[package]] +name = "json5" +version = "0.9.10" +description = "A Python implementation of the JSON5 data format." +category = "dev" +optional = false +python-versions = "*" + +[package.extras] +dev = ["hypothesis"] + +[[package]] +name = "jsonschema" +version = "4.16.0" +description = "An implementation of JSON Schema validation for Python" +category = "main" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +attrs = ">=17.4.0" +importlib-resources = {version = ">=1.4.0", markers = "python_version < \"3.9\""} +pkgutil-resolve-name = {version = ">=1.3.10", markers = "python_version < \"3.9\""} +pyrsistent = ">=0.14.0,<0.17.0 || >0.17.0,<0.17.1 || >0.17.1,<0.17.2 || >0.17.2" + +[package.extras] +format = ["fqdn", "idna", "isoduration", "jsonpointer (>1.13)", "rfc3339-validator", "rfc3987", "uri-template", "webcolors (>=1.11)"] +format-nongpl = ["fqdn", "idna", "isoduration", "jsonpointer (>1.13)", "rfc3339-validator", "rfc3986-validator (>0.1.0)", "uri-template", "webcolors (>=1.11)"] + +[[package]] +name = "jupyter" +version = "1.0.0" +description = "Jupyter metapackage. Install all the Jupyter components in one go." +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +ipykernel = "*" +ipywidgets = "*" +jupyter-console = "*" +nbconvert = "*" +notebook = "*" +qtconsole = "*" + +[[package]] +name = "jupyter-client" +version = "7.4.3" +description = "Jupyter protocol implementation and client libraries" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +entrypoints = "*" +jupyter-core = ">=4.9.2" +nest-asyncio = ">=1.5.4" +python-dateutil = ">=2.8.2" +pyzmq = ">=23.0" +tornado = ">=6.2" +traitlets = "*" + +[package.extras] +doc = ["ipykernel", "myst-parser", "sphinx (>=1.3.6)", "sphinx-rtd-theme", "sphinxcontrib-github-alt"] +test = ["codecov", "coverage", "ipykernel (>=6.12)", "ipython", "mypy", "pre-commit", "pytest", "pytest-asyncio (>=0.18)", "pytest-cov", "pytest-timeout"] + +[[package]] +name = "jupyter-console" +version = "6.4.4" +description = "Jupyter terminal console" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +ipykernel = "*" +ipython = "*" +jupyter-client = ">=7.0.0" +prompt-toolkit = ">=2.0.0,<3.0.0 || >3.0.0,<3.0.1 || >3.0.1,<3.1.0" +pygments = "*" + +[package.extras] +test = ["pexpect"] + +[[package]] +name = "jupyter-core" +version = "4.11.2" +description = "Jupyter core package. A base package on which Jupyter projects rely." +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +pywin32 = {version = ">=1.0", markers = "sys_platform == \"win32\" and platform_python_implementation != \"PyPy\""} +traitlets = "*" + +[package.extras] +test = ["ipykernel", "pre-commit", "pytest", "pytest-cov", "pytest-timeout"] + +[[package]] +name = "jupyter-server" +version = "1.21.0" +description = "The backend—i.e. core services, APIs, and REST endpoints—to Jupyter web applications." +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +anyio = ">=3.1.0,<4" +argon2-cffi = "*" +jinja2 = "*" +jupyter-client = ">=6.1.12" +jupyter-core = ">=4.7.0" +nbconvert = ">=6.4.4" +nbformat = ">=5.2.0" +packaging = "*" +prometheus-client = "*" +pywinpty = {version = "*", markers = "os_name == \"nt\""} +pyzmq = ">=17" +Send2Trash = "*" +terminado = ">=0.8.3" +tornado = ">=6.1.0" +traitlets = ">=5.1" +websocket-client = "*" + +[package.extras] +test = ["coverage", "ipykernel", "pre-commit", "pytest (>=7.0)", "pytest-console-scripts", "pytest-cov", "pytest-mock", "pytest-timeout", "pytest-tornasync", "requests"] + +[[package]] +name = "jupyterlab" +version = "3.4.8" +description = "JupyterLab computational environment" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +ipython = "*" +jinja2 = ">=2.1" +jupyter-core = "*" +jupyter-server = ">=1.16,<2.0" +jupyterlab-server = ">=2.10,<3.0" +nbclassic = "*" +notebook = "<7" +packaging = "*" +tomli = "*" +tornado = ">=6.1.0" + +[package.extras] +test = ["check-manifest", "coverage", "jupyterlab-server[test]", "pre-commit", "pytest (>=6.0)", "pytest-check-links (>=0.5)", "pytest-console-scripts", "pytest-cov", "requests", "requests-cache", "virtualenv"] +ui-tests = ["build"] + +[[package]] +name = "jupyterlab-pygments" +version = "0.2.2" +description = "Pygments theme using JupyterLab CSS variables" +category = "dev" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "jupyterlab-server" +version = "2.16.1" +description = "A set of server components for JupyterLab and JupyterLab like applications." +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +babel = "*" +importlib-metadata = {version = ">=4.8.3", markers = "python_version < \"3.10\""} +jinja2 = ">=3.0.3" +json5 = "*" +jsonschema = ">=3.0.1" +jupyter-server = ">=1.8,<3" +packaging = "*" +requests = "*" + +[package.extras] +docs = ["autodoc-traits", "docutils (<0.19)", "jinja2 (<3.1.0)", "mistune (<1)", "myst-parser", "pydata-sphinx-theme", "sphinx", "sphinx-copybutton", "sphinxcontrib-openapi"] +openapi = ["openapi-core (>=0.14.2)", "ruamel-yaml"] +test = ["codecov", "ipykernel", "jupyter-server[test]", "openapi-core (>=0.14.2,<0.15.0)", "openapi-spec-validator (<0.5)", "pytest (>=7.0)", "pytest-console-scripts", "pytest-cov", "ruamel-yaml", "strict-rfc3339"] + +[[package]] +name = "jupyterlab-vim" +version = "0.15.1" +description = "Code cell vim bindings" +category = "dev" +optional = false +python-versions = ">=3.6" + +[[package]] +name = "jupyterlab-widgets" +version = "3.0.3" +description = "Jupyter interactive widgets for JupyterLab" +category = "dev" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "keyring" +version = "23.9.3" +description = "Store and access your passwords safely." +category = "main" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +importlib-metadata = {version = ">=3.6", markers = "python_version < \"3.10\""} +"jaraco.classes" = "*" +jeepney = {version = ">=0.4.2", markers = "sys_platform == \"linux\""} +pywin32-ctypes = {version = "<0.1.0 || >0.1.0,<0.1.1 || >0.1.1", markers = "sys_platform == \"win32\""} +SecretStorage = {version = ">=3.2", markers = "sys_platform == \"linux\""} + +[package.extras] +docs = ["jaraco.packaging (>=9)", "jaraco.tidelift (>=1.4)", "rst.linker (>=1.9)", "sphinx"] +testing = ["flake8 (<5)", "pytest (>=6)", "pytest-black (>=0.3.7)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=1.3)", "pytest-flake8", "pytest-mypy (>=0.9.1)"] + +[[package]] +name = "kiwisolver" +version = "1.4.4" +description = "A fast implementation of the Cassowary constraint solver" +category = "dev" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "knack" +version = "0.10.0" +description = "A Command-Line Interface framework" +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +argcomplete = "*" +jmespath = "*" +pygments = "*" +pyyaml = "*" +tabulate = "*" + +[[package]] +name = "lazy-object-proxy" +version = "1.7.1" +description = "A fast and thorough lazy object proxy." +category = "main" +optional = false +python-versions = ">=3.6" + +[[package]] +name = "libusb1" +version = "3.0.0" +description = "Pure-python wrapper for libusb-1.0" +category = "main" +optional = false +python-versions = "*" + +[[package]] +name = "lockfile" +version = "0.12.2" +description = "Platform-independent file locking module" +category = "main" +optional = false +python-versions = "*" + +[[package]] +name = "lru-dict" +version = "1.1.8" +description = "An Dict like LRU container." +category = "dev" +optional = false +python-versions = "*" + +[package.extras] +test = ["pytest"] + +[[package]] +name = "lxml" +version = "4.9.1" +description = "Powerful and Pythonic XML processing library combining libxml2/libxslt with the ElementTree API." +category = "dev" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, != 3.4.*" + +[package.extras] +cssselect = ["cssselect (>=0.7)"] +html5 = ["html5lib"] +htmlsoup = ["BeautifulSoup4"] +source = ["Cython (>=0.29.7)"] + +[[package]] +name = "mako" +version = "1.2.3" +description = "A super-fast templating language that borrows the best ideas from the existing templating languages." +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +MarkupSafe = ">=0.9.2" + +[package.extras] +babel = ["Babel"] +lingua = ["lingua"] +testing = ["pytest"] + +[[package]] +name = "markdown" +version = "3.4.1" +description = "Python implementation of Markdown." +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +importlib-metadata = {version = ">=4.4", markers = "python_version < \"3.10\""} + +[package.extras] +testing = ["coverage", "pyyaml"] + +[[package]] +name = "markdown-it-py" +version = "2.1.0" +description = "Python port of markdown-it. Markdown parsing, done right!" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +mdurl = ">=0.1,<1.0" + +[package.extras] +benchmarking = ["psutil", "pytest", "pytest-benchmark (>=3.2,<4.0)"] +code-style = ["pre-commit (==2.6)"] +compare = ["commonmark (>=0.9.1,<0.10.0)", "markdown (>=3.3.6,<3.4.0)", "mistletoe (>=0.8.1,<0.9.0)", "mistune (>=2.0.2,<2.1.0)", "panflute (>=2.1.3,<2.2.0)"] +linkify = ["linkify-it-py (>=1.0,<2.0)"] +plugins = ["mdit-py-plugins"] +profiling = ["gprof2dot"] +rtd = ["attrs", "myst-parser", "pyyaml", "sphinx", "sphinx-copybutton", "sphinx-design", "sphinx_book_theme"] +testing = ["coverage", "pytest", "pytest-cov", "pytest-regressions"] + +[[package]] +name = "markupsafe" +version = "2.1.1" +description = "Safely add untrusted strings to HTML/XML markup." +category = "main" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "matplotlib" +version = "3.6.1" +description = "Python plotting package" +category = "dev" +optional = false +python-versions = ">=3.8" + +[package.dependencies] +contourpy = ">=1.0.1" +cycler = ">=0.10" +fonttools = ">=4.22.0" +kiwisolver = ">=1.0.1" +numpy = ">=1.19" +packaging = ">=20.0" +pillow = ">=6.2.0" +pyparsing = ">=2.2.1" +python-dateutil = ">=2.7" +setuptools_scm = ">=7" + +[[package]] +name = "matplotlib-inline" +version = "0.1.6" +description = "Inline Matplotlib backend for Jupyter" +category = "dev" +optional = false +python-versions = ">=3.5" + +[package.dependencies] +traitlets = "*" + +[[package]] +name = "mccabe" +version = "0.6.1" +description = "McCabe checker, plugin for flake8" +category = "main" +optional = false +python-versions = "*" + +[[package]] +name = "mdit-py-plugins" +version = "0.3.1" +description = "Collection of plugins for markdown-it-py" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +markdown-it-py = ">=1.0.0,<3.0.0" + +[package.extras] +code-style = ["pre-commit"] +rtd = ["attrs", "myst-parser (>=0.16.1,<0.17.0)", "sphinx-book-theme (>=0.1.0,<0.2.0)"] +testing = ["coverage", "pytest", "pytest-cov", "pytest-regressions"] + +[[package]] +name = "mdurl" +version = "0.1.2" +description = "Markdown URL utilities" +category = "dev" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "mistune" +version = "2.0.4" +description = "A sane Markdown parser with useful plugins and renderers" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "more-itertools" +version = "9.0.0" +description = "More routines for operating on iterables, beyond itertools" +category = "main" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "mpld3" +version = "0.5.8" +description = "D3 Viewer for Matplotlib" +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +jinja2 = "*" +matplotlib = "*" + +[[package]] +name = "mpmath" +version = "1.2.1" +description = "Python library for arbitrary-precision floating-point arithmetic" +category = "main" +optional = false +python-versions = "*" + +[package.extras] +develop = ["codecov", "pycodestyle", "pytest (>=4.6)", "pytest-cov", "wheel"] +tests = ["pytest (>=4.6)"] + +[[package]] +name = "msal" +version = "1.20.0b1" +description = "The Microsoft Authentication Library (MSAL) for Python library enables your app to access the Microsoft Cloud by supporting authentication of users with Microsoft Azure Active Directory accounts (AAD) and Microsoft Accounts (MSA) using industry standard OAuth2 and OpenID Connect." +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +cryptography = ">=0.6,<40" +PyJWT = {version = ">=1.0.0,<3", extras = ["crypto"]} +pymsalruntime = {version = ">=0.11.2,<0.12", optional = true, markers = "python_version >= \"3.6\" and platform_system == \"Windows\" and extra == \"broker\""} +requests = ">=2.0.0,<3" + +[package.extras] +broker = ["pymsalruntime (>=0.11.2,<0.12)"] + +[[package]] +name = "msal-extensions" +version = "1.0.0" +description = "Microsoft Authentication Library extensions (MSAL EX) provides a persistence API that can save your data on disk, encrypted on Windows, macOS and Linux. Concurrent data access will be coordinated by a file lock mechanism." +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +msal = ">=0.4.1,<2.0.0" +portalocker = [ + {version = ">=1.0,<3", markers = "python_version >= \"3.5\" and platform_system != \"Windows\""}, + {version = ">=1.6,<3", markers = "python_version >= \"3.5\" and platform_system == \"Windows\""}, +] + +[[package]] +name = "msgpack" +version = "1.0.4" +description = "MessagePack serializer" +category = "main" +optional = false +python-versions = "*" + +[[package]] +name = "msgpack-numpy" +version = "0.4.8" +description = "Numpy data serialization using msgpack" +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +msgpack = ">=0.5.2" +numpy = ">=1.9.0" + +[[package]] +name = "msgpack-python" +version = "0.5.6" +description = "MessagePack (de)serializer." +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "msrest" +version = "0.7.1" +description = "AutoRest swagger generator Python client runtime." +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +azure-core = ">=1.24.0" +certifi = ">=2017.4.17" +isodate = ">=0.6.0" +requests = ">=2.16,<3.0" +requests-oauthlib = ">=0.5.0" + +[package.extras] +async = ["aiodns", "aiohttp (>=3.0)"] + +[[package]] +name = "msrestazure" +version = "0.6.4" +description = "AutoRest swagger generator Python client runtime. Azure-specific module." +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +adal = ">=0.6.0,<2.0.0" +msrest = ">=0.6.0,<2.0.0" +six = "*" + +[[package]] +name = "multidict" +version = "6.0.2" +description = "multidict implementation" +category = "dev" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "munch" +version = "2.5.0" +description = "A dot-accessible dictionary (a la JavaScript objects)" +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +six = "*" + +[package.extras] +testing = ["astroid (>=1.5.3,<1.6.0)", "astroid (>=2.0)", "coverage", "pylint (>=1.7.2,<1.8.0)", "pylint (>=2.3.1,<2.4.0)", "pytest"] +yaml = ["PyYAML (>=5.1.0)"] + +[[package]] +name = "mypy" +version = "0.961" +description = "Optional static typing for Python" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +mypy-extensions = ">=0.4.3" +tomli = {version = ">=1.1.0", markers = "python_version < \"3.11\""} +typing-extensions = ">=3.10" + +[package.extras] +dmypy = ["psutil (>=4.0)"] +python2 = ["typed-ast (>=1.4.0,<2)"] +reports = ["lxml"] + +[[package]] +name = "mypy-extensions" +version = "0.4.3" +description = "Experimental type system extensions for programs checked with the mypy typechecker." +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "myst-parser" +version = "0.18.1" +description = "An extended commonmark compliant parser, with bridges to docutils & sphinx." +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +docutils = ">=0.15,<0.20" +jinja2 = "*" +markdown-it-py = ">=1.0.0,<3.0.0" +mdit-py-plugins = ">=0.3.1,<0.4.0" +pyyaml = "*" +sphinx = ">=4,<6" +typing-extensions = "*" + +[package.extras] +code-style = ["pre-commit (>=2.12,<3.0)"] +linkify = ["linkify-it-py (>=1.0,<2.0)"] +rtd = ["ipython", "sphinx-book-theme", "sphinx-design", "sphinxcontrib.mermaid (>=0.7.1,<0.8.0)", "sphinxext-opengraph (>=0.6.3,<0.7.0)", "sphinxext-rediraffe (>=0.2.7,<0.3.0)"] +testing = ["beautifulsoup4", "coverage[toml]", "pytest (>=6,<7)", "pytest-cov", "pytest-param-files (>=0.3.4,<0.4.0)", "pytest-regressions", "sphinx (<5.2)", "sphinx-pytest"] + +[[package]] +name = "natsort" +version = "8.2.0" +description = "Simple yet flexible natural sorting in Python." +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.extras] +fast = ["fastnumbers (>=2.0.0)"] +icu = ["PyICU (>=1.0.0)"] + +[[package]] +name = "nbclassic" +version = "0.4.7" +description = "A web-based notebook environment for interactive computing" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +argon2-cffi = "*" +ipykernel = "*" +ipython-genutils = "*" +jinja2 = "*" +jupyter-client = ">=6.1.1" +jupyter-core = ">=4.6.1" +jupyter-server = ">=1.8" +nbconvert = ">=5" +nbformat = "*" +nest-asyncio = ">=1.5" +notebook-shim = ">=0.1.0" +prometheus-client = "*" +pyzmq = ">=17" +Send2Trash = ">=1.8.0" +terminado = ">=0.8.3" +tornado = ">=6.1" +traitlets = ">=4.2.1" + +[package.extras] +docs = ["myst-parser", "nbsphinx", "sphinx", "sphinx-rtd-theme", "sphinxcontrib-github-alt"] +json-logging = ["json-logging"] +test = ["coverage", "nbval", "pytest", "pytest-cov", "pytest-tornasync", "requests", "requests-unixsocket", "selenium (==4.1.5)", "testpath"] + +[[package]] +name = "nbclient" +version = "0.7.0" +description = "A client library for executing notebooks. Formerly nbconvert's ExecutePreprocessor." +category = "dev" +optional = false +python-versions = ">=3.7.0" + +[package.dependencies] +jupyter-client = ">=6.1.5" +nbformat = ">=5.0" +nest-asyncio = "*" +traitlets = ">=5.2.2" + +[package.extras] +sphinx = ["Sphinx (>=1.7)", "autodoc-traits", "mock", "moto", "myst-parser", "sphinx-book-theme"] +test = ["black", "check-manifest", "flake8", "ipykernel", "ipython", "ipywidgets", "mypy", "nbconvert", "pip (>=18.1)", "pre-commit", "pytest (>=4.1)", "pytest-asyncio", "pytest-cov (>=2.6.1)", "setuptools (>=60.0)", "testpath", "twine (>=1.11.0)", "xmltodict"] + +[[package]] +name = "nbconvert" +version = "7.2.2" +description = "Converting Jupyter Notebooks" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +beautifulsoup4 = "*" +bleach = "*" +defusedxml = "*" +importlib-metadata = {version = ">=3.6", markers = "python_version < \"3.10\""} +jinja2 = ">=3.0" +jupyter-core = ">=4.7" +jupyterlab-pygments = "*" +markupsafe = ">=2.0" +mistune = ">=2.0.3,<3" +nbclient = ">=0.5.0" +nbformat = ">=5.1" +packaging = "*" +pandocfilters = ">=1.4.1" +pygments = ">=2.4.1" +tinycss2 = "*" +traitlets = ">=5.0" + +[package.extras] +all = ["ipykernel", "ipython", "ipywidgets (>=7)", "myst-parser", "nbsphinx (>=0.2.12)", "pre-commit", "pyppeteer (>=1,<1.1)", "pyqtwebengine (>=5.15)", "pytest", "pytest-cov", "pytest-dependency", "sphinx (==5.0.2)", "sphinx-rtd-theme", "tornado (>=6.1)"] +docs = ["ipython", "myst-parser", "nbsphinx (>=0.2.12)", "sphinx (==5.0.2)", "sphinx-rtd-theme"] +qtpdf = ["pyqtwebengine (>=5.15)"] +qtpng = ["pyqtwebengine (>=5.15)"] +serve = ["tornado (>=6.1)"] +test = ["ipykernel", "ipywidgets (>=7)", "pre-commit", "pyppeteer (>=1,<1.1)", "pytest", "pytest-cov", "pytest-dependency"] +webpdf = ["pyppeteer (>=1,<1.1)"] + +[[package]] +name = "nbformat" +version = "5.7.0" +description = "The Jupyter Notebook format" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +fastjsonschema = "*" +jsonschema = ">=2.6" +jupyter-core = "*" +traitlets = ">=5.1" + +[package.extras] +test = ["check-manifest", "pep440", "pre-commit", "pytest", "testpath"] + +[[package]] +name = "ncompress" +version = "1.0.0" +description = "LZW compression and decompression" +category = "main" +optional = false +python-versions = "*" + +[package.extras] +tests = ["pytest"] + +[[package]] +name = "nest-asyncio" +version = "1.5.6" +description = "Patch asyncio to allow nested event loops" +category = "dev" +optional = false +python-versions = ">=3.5" + +[[package]] +name = "networkx" +version = "2.3" +description = "Python package for creating and manipulating graphs and networks" +category = "dev" +optional = false +python-versions = ">=3.5" + +[package.dependencies] +decorator = ">=4.3.0" + +[package.extras] +all = ["gdal", "lxml", "matplotlib", "nose", "numpy", "pandas", "pydot", "pygraphviz", "pyyaml", "scipy"] +gdal = ["gdal"] +lxml = ["lxml"] +matplotlib = ["matplotlib"] +nose = ["nose"] +numpy = ["numpy"] +pandas = ["pandas"] +pydot = ["pydot"] +pygraphviz = ["pygraphviz"] +pyyaml = ["pyyaml"] +scipy = ["scipy"] + +[[package]] +name = "nodeenv" +version = "1.7.0" +description = "Node.js virtual environment builder" +category = "dev" +optional = false +python-versions = ">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*" + +[package.dependencies] +setuptools = "*" + +[[package]] +name = "nose" +version = "1.3.7" +description = "nose extends unittest to make testing easier" +category = "main" +optional = false +python-versions = "*" + +[[package]] +name = "notebook" +version = "6.4.12" +description = "A web-based notebook environment for interactive computing" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +argon2-cffi = "*" +ipykernel = "*" +ipython-genutils = "*" +jinja2 = "*" +jupyter-client = ">=5.3.4" +jupyter-core = ">=4.6.1" +nbconvert = ">=5" +nbformat = "*" +nest-asyncio = ">=1.5" +prometheus-client = "*" +pyzmq = ">=17" +Send2Trash = ">=1.8.0" +terminado = ">=0.8.3" +tornado = ">=6.1" +traitlets = ">=4.2.1" + +[package.extras] +docs = ["myst-parser", "nbsphinx", "sphinx", "sphinx-rtd-theme", "sphinxcontrib-github-alt"] +json-logging = ["json-logging"] +test = ["coverage", "nbval", "pytest", "pytest-cov", "requests", "requests-unixsocket", "selenium", "testpath"] + +[[package]] +name = "notebook-shim" +version = "0.2.0" +description = "A shim layer for notebook traits and config" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +jupyter-server = ">=1.8,<3" + +[package.extras] +test = ["pytest", "pytest-console-scripts", "pytest-tornasync"] + +[[package]] +name = "numpy" +version = "1.23.4" +description = "NumPy is the fundamental package for array computing with Python." +category = "main" +optional = false +python-versions = ">=3.8" + +[[package]] +name = "nvidia-ml-py3" +version = "7.352.0" +description = "Python Bindings for the NVIDIA Management Library" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "oauthlib" +version = "3.2.2" +description = "A generic, spec-compliant, thorough implementation of the OAuth request-signing logic" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.extras] +rsa = ["cryptography (>=3.0.0)"] +signals = ["blinker (>=1.4.0)"] +signedtoken = ["cryptography (>=3.0.0)", "pyjwt (>=2.0.0,<3)"] + +[[package]] +name = "onnx" +version = "1.12.0" +description = "Open Neural Network Exchange" +category = "main" +optional = false +python-versions = "*" + +[package.dependencies] +numpy = ">=1.16.6" +protobuf = ">=3.12.2,<=3.20.1" +typing-extensions = ">=3.6.2.1" + +[package.extras] +lint = ["clang-format (==13.0.0)", "flake8", "mypy (==0.782)", "types-protobuf (==3.18.4)"] + +[[package]] +name = "onnx2torch" +version = "1.5.4" +description = "Nice Onnx to Pytorch converter" +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +numpy = ">=1.16.4" +onnx = ">=1.9.0" +torch = ">=1.8.0" +torchvision = ">=0.9.0" + +[[package]] +name = "onnxoptimizer" +version = "0.3.1" +description = "Open Neural Network Exchange" +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +onnx = "*" + +[package.extras] +mypy = ["mypy (==0.600)"] + +[[package]] +name = "onnxruntime-gpu" +version = "1.12.1" +description = "ONNX Runtime is a runtime accelerator for Machine Learning models" +category = "main" +optional = false +python-versions = "*" + +[package.dependencies] +coloredlogs = "*" +flatbuffers = "*" +numpy = ">=1.21.0" +packaging = "*" +protobuf = "*" +sympy = "*" + +[[package]] +name = "opencv-python-headless" +version = "4.5.5.64" +description = "Wrapper package for OpenCV python bindings." +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +numpy = [ + {version = ">=1.21.2", markers = "python_version >= \"3.6\" and platform_system == \"Darwin\" and platform_machine == \"arm64\""}, + {version = ">=1.19.3", markers = "python_version >= \"3.6\" and platform_system == \"Linux\" and platform_machine == \"aarch64\""}, + {version = ">=1.14.5", markers = "python_version >= \"3.7\""}, + {version = ">=1.17.3", markers = "python_version >= \"3.8\""}, +] + +[package.source] +type = "url" +url = "https://github.com/commaai/opencv-python-builder/releases/download/4.5.5.64%2Bcu113/opencv_python_headless-4.5.5.64-cp38-cp38-manylinux_2_31_x86_64.whl" + +[[package]] +name = "osmium" +version = "3.4.1" +description = "Python bindings for libosmium, the data processing library for OSM data" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +requests = "*" + +[[package]] +name = "packaging" +version = "21.3" +description = "Core utilities for Python packages" +category = "main" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +pyparsing = ">=2.0.2,<3.0.5 || >3.0.5" + +[[package]] +name = "pandas" +version = "1.5.1" +description = "Powerful data structures for data analysis, time series, and statistics" +category = "dev" +optional = false +python-versions = ">=3.8" + +[package.dependencies] +numpy = {version = ">=1.20.3", markers = "python_version < \"3.10\""} +python-dateutil = ">=2.8.1" +pytz = ">=2020.1" + +[package.extras] +test = ["hypothesis (>=5.5.3)", "pytest (>=6.0)", "pytest-xdist (>=1.31)"] + +[[package]] +name = "pandocfilters" +version = "1.5.0" +description = "Utilities for writing pandoc filters in python" +category = "dev" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" + +[[package]] +name = "parameterized" +version = "0.8.1" +description = "Parameterized testing with any Python test framework" +category = "dev" +optional = false +python-versions = "*" + +[package.extras] +dev = ["jinja2"] + +[[package]] +name = "paramiko" +version = "2.11.0" +description = "SSH2 protocol library" +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +bcrypt = ">=3.1.3" +cryptography = ">=2.5" +pynacl = ">=1.0.1" +six = "*" + +[package.extras] +all = ["bcrypt (>=3.1.3)", "gssapi (>=1.4.1)", "invoke (>=1.3)", "pyasn1 (>=0.1.7)", "pynacl (>=1.0.1)", "pywin32 (>=2.1.8)"] +ed25519 = ["bcrypt (>=3.1.3)", "pynacl (>=1.0.1)"] +gssapi = ["gssapi (>=1.4.1)", "pyasn1 (>=0.1.7)", "pywin32 (>=2.1.8)"] +invoke = ["invoke (>=1.3)"] + +[[package]] +name = "parso" +version = "0.8.3" +description = "A Python Parser" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.extras] +qa = ["flake8 (==3.8.3)", "mypy (==0.782)"] +testing = ["docopt", "pytest (<6.0.0)"] + +[[package]] +name = "pexpect" +version = "4.8.0" +description = "Pexpect allows easy control of interactive console applications." +category = "main" +optional = false +python-versions = "*" + +[package.dependencies] +ptyprocess = ">=0.5" + +[[package]] +name = "pickleshare" +version = "0.7.5" +description = "Tiny 'shelve'-like database with concurrency support" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "pillow" +version = "9.2.0" +description = "Python Imaging Library (Fork)" +category = "main" +optional = false +python-versions = ">=3.7" + +[package.extras] +docs = ["furo", "olefile", "sphinx (>=2.4)", "sphinx-copybutton", "sphinx-issues (>=3.0.1)", "sphinx-removed-in", "sphinxext-opengraph"] +tests = ["check-manifest", "coverage", "defusedxml", "markdown2", "olefile", "packaging", "pyroma", "pytest", "pytest-cov", "pytest-timeout"] + +[[package]] +name = "pillow-avif-plugin" +version = "1.2.2" +description = "A pillow plugin that adds avif support via libavif" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "pipenv" +version = "2022.10.12" +description = "Python Development Workflow for Humans." +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +certifi = "*" +setuptools = ">=36.2.1" +virtualenv = "*" +virtualenv-clone = ">=0.2.5" + +[package.extras] +dev = ["black", "bs4", "flake8 (>=3.3.0,<4.0)", "invoke", "parver", "sphinx", "towncrier"] +tests = ["flaky", "mock", "pytest (>=5.0)", "pytest-timeout", "pytest-xdist"] + +[[package]] +name = "pkginfo" +version = "1.8.3" +description = "Query metadatdata from sdists / bdists / installed packages." +category = "main" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*" + +[package.extras] +testing = ["coverage", "nose"] + +[[package]] +name = "pkgutil-resolve-name" +version = "1.3.10" +description = "Resolve a name to an object." +category = "main" +optional = false +python-versions = ">=3.6" + +[[package]] +name = "platformdirs" +version = "2.5.2" +description = "A small Python module for determining appropriate platform-specific dirs, e.g. a \"user data dir\"." +category = "main" +optional = false +python-versions = ">=3.7" + +[package.extras] +docs = ["furo (>=2021.7.5b38)", "proselint (>=0.10.2)", "sphinx (>=4)", "sphinx-autodoc-typehints (>=1.12)"] +test = ["appdirs (==1.4.4)", "pytest (>=6)", "pytest-cov (>=2.7)", "pytest-mock (>=3.6)"] + +[[package]] +name = "plotly" +version = "5.10.0" +description = "An open-source, interactive data visualization library for Python" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +tenacity = ">=6.2.0" + +[[package]] +name = "pluggy" +version = "1.0.0" +description = "plugin and hook calling mechanisms for python" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.extras] +dev = ["pre-commit", "tox"] +testing = ["pytest", "pytest-benchmark"] + +[[package]] +name = "poetry" +version = "1.2.2" +description = "Python dependency management and packaging made easy." +category = "main" +optional = false +python-versions = ">=3.7,<4.0" + +[package.dependencies] +cachecontrol = {version = ">=0.12.9,<0.13.0", extras = ["filecache"]} +cachy = ">=0.3.0,<0.4.0" +cleo = ">=1.0.0a5,<2.0.0" +crashtest = ">=0.3.0,<0.4.0" +dulwich = ">=0.20.46,<0.21.0" +html5lib = ">=1.0,<2.0" +importlib-metadata = {version = ">=4.4,<5.0", markers = "python_version < \"3.10\""} +jsonschema = ">=4.10.0,<5.0.0" +keyring = ">=21.2.0" +packaging = ">=20.4" +pexpect = ">=4.7.0,<5.0.0" +pkginfo = ">=1.5,<2.0" +platformdirs = ">=2.5.2,<3.0.0" +poetry-core = "1.3.2" +poetry-plugin-export = ">=1.1.2,<2.0.0" +requests = ">=2.18,<3.0" +requests-toolbelt = ">=0.9.1,<0.10.0" +shellingham = ">=1.5,<2.0" +tomlkit = ">=0.11.1,<0.11.2 || >0.11.2,<0.11.3 || >0.11.3,<1.0.0" +urllib3 = ">=1.26.0,<2.0.0" +virtualenv = ">=20.4.3,<20.4.5 || >20.4.5,<20.4.6 || >20.4.6" +xattr = {version = ">=0.9.7,<0.10.0", markers = "sys_platform == \"darwin\""} + +[[package]] +name = "poetry-core" +version = "1.3.2" +description = "Poetry PEP 517 Build Backend" +category = "main" +optional = false +python-versions = ">=3.7,<4.0" + +[[package]] +name = "poetry-plugin-export" +version = "1.1.2" +description = "Poetry plugin to export the dependencies to various formats" +category = "main" +optional = false +python-versions = ">=3.7,<4.0" + +[package.dependencies] +poetry = ">=1.2.0,<2.0.0" +poetry-core = ">=1.1.0,<2.0.0" + +[[package]] +name = "portalocker" +version = "2.6.0" +description = "Wraps the portalocker recipe for easy usage" +category = "dev" +optional = false +python-versions = ">=3.5" + +[package.dependencies] +pywin32 = {version = ">=226", markers = "platform_system == \"Windows\""} + +[package.extras] +docs = ["sphinx (>=1.7.1)"] +redis = ["redis"] +tests = ["pytest (>=5.4.1)", "pytest-cov (>=2.8.1)", "pytest-mypy (>=0.8.0)", "pytest-timeout (>=2.1.0)", "redis", "sphinx (>=3.0.3)"] + +[[package]] +name = "pprofile" +version = "2.1.0" +description = "Line-granularity, thread-aware deterministic and statistic pure-python profiler" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "pre-commit" +version = "2.20.0" +description = "A framework for managing and maintaining multi-language pre-commit hooks." +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +cfgv = ">=2.0.0" +identify = ">=1.0.0" +nodeenv = ">=0.11.1" +pyyaml = ">=5.1" +toml = "*" +virtualenv = ">=20.0.8" + +[[package]] +name = "pretrainedmodels" +version = "0.7.4" +description = "Pretrained models for Pytorch" +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +munch = "*" +torch = "*" +torchvision = "*" +tqdm = "*" + +[[package]] +name = "prometheus-client" +version = "0.15.0" +description = "Python client for the Prometheus monitoring system." +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.extras] +twisted = ["twisted"] + +[[package]] +name = "prompt-toolkit" +version = "3.0.31" +description = "Library for building powerful interactive command lines in Python" +category = "dev" +optional = false +python-versions = ">=3.6.2" + +[package.dependencies] +wcwidth = "*" + +[[package]] +name = "protobuf" +version = "3.20.1" +description = "Protocol Buffers" +category = "main" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "psutil" +version = "5.9.3" +description = "Cross-platform lib for process and system monitoring in Python." +category = "main" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" + +[package.extras] +test = ["enum34", "ipaddress", "mock", "pywin32", "wmi"] + +[[package]] +name = "ptyprocess" +version = "0.7.0" +description = "Run a subprocess in a pseudo terminal" +category = "main" +optional = false +python-versions = "*" + +[[package]] +name = "pure-eval" +version = "0.2.2" +description = "Safely evaluate AST nodes without side effects" +category = "dev" +optional = false +python-versions = "*" + +[package.extras] +tests = ["pytest"] + +[[package]] +name = "py" +version = "1.11.0" +description = "library with cross-python path, ini-parsing, io, code, log facilities" +category = "main" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" + +[[package]] +name = "pycapnp" +version = "1.1.0" +description = "A cython wrapping of the C++ Cap'n Proto library" +category = "main" +optional = false +python-versions = "*" + +[[package]] +name = "pycodestyle" +version = "2.8.0" +description = "Python style guide checker" +category = "main" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" + +[[package]] +name = "pycparser" +version = "2.21" +description = "C parser in Python" +category = "main" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" + +[[package]] +name = "pycryptodome" +version = "3.15.0" +description = "Cryptographic library for Python" +category = "main" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" + +[[package]] +name = "pycuda" +version = "2022.1" +description = "Python wrapper for Nvidia CUDA" +category = "dev" +optional = false +python-versions = "~=3.6" + +[package.dependencies] +appdirs = ">=1.4.0" +mako = "*" +pytools = ">=2011.2" + +[[package]] +name = "pycurl" +version = "7.45.1" +description = "PycURL -- A Python Interface To The cURL library" +category = "dev" +optional = false +python-versions = ">=3.5" + +[[package]] +name = "pyflakes" +version = "2.4.0" +description = "passive checker of Python programs" +category = "main" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" + +[[package]] +name = "pygame" +version = "2.1.2" +description = "Python Game Development" +category = "dev" +optional = false +python-versions = ">=3.6" + +[[package]] +name = "pygments" +version = "2.13.0" +description = "Pygments is a syntax highlighting package written in Python." +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.extras] +plugins = ["importlib-metadata"] + +[[package]] +name = "pyjwt" +version = "2.6.0" +description = "JSON Web Token implementation in Python" +category = "main" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +cryptography = {version = ">=3.4.0", optional = true, markers = "extra == \"crypto\""} + +[package.extras] +crypto = ["cryptography (>=3.4.0)"] +dev = ["coverage[toml] (==5.0.4)", "cryptography (>=3.4.0)", "pre-commit", "pytest (>=6.0.0,<7.0.0)", "sphinx (>=4.5.0,<5.0.0)", "sphinx-rtd-theme", "zope.interface"] +docs = ["sphinx (>=4.5.0,<5.0.0)", "sphinx-rtd-theme", "zope.interface"] +tests = ["coverage[toml] (==5.0.4)", "pytest (>=6.0.0,<7.0.0)"] + +[[package]] +name = "pylev" +version = "1.4.0" +description = "A pure Python Levenshtein implementation that's not freaking GPL'd." +category = "main" +optional = false +python-versions = "*" + +[[package]] +name = "pylint" +version = "2.15.4" +description = "python code static checker" +category = "main" +optional = false +python-versions = ">=3.7.2" + +[package.dependencies] +astroid = ">=2.12.11,<=2.14.0-dev0" +colorama = {version = ">=0.4.5", markers = "sys_platform == \"win32\""} +dill = ">=0.2" +isort = ">=4.2.5,<6" +mccabe = ">=0.6,<0.8" +platformdirs = ">=2.2.0" +tomli = {version = ">=1.1.0", markers = "python_version < \"3.11\""} +tomlkit = ">=0.10.1" +typing-extensions = {version = ">=3.10.0", markers = "python_version < \"3.10\""} + +[package.extras] +spelling = ["pyenchant (>=3.2,<4.0)"] +testutils = ["gitpython (>3)"] + +[[package]] +name = "pymsalruntime" +version = "0.11.2" +description = "The MSALRuntime Python Interop Package" +category = "dev" +optional = false +python-versions = ">=3.6" + +[[package]] +name = "pymysql" +version = "0.9.3" +description = "Pure Python MySQL Driver" +category = "dev" +optional = false +python-versions = "*" + +[package.extras] +rsa = ["cryptography"] + +[[package]] +name = "pynacl" +version = "1.5.0" +description = "Python binding to the Networking and Cryptography (NaCl) library" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +cffi = ">=1.4.1" + +[package.extras] +docs = ["sphinx (>=1.6.5)", "sphinx_rtd_theme"] +tests = ["hypothesis (>=3.27.0)", "pytest (>=3.2.1,!=3.3.0)"] + +[[package]] +name = "pyopencl" +version = "2022.2.4" +description = "Python wrapper for OpenCL" +category = "main" +optional = false +python-versions = "~=3.6" + +[package.dependencies] +numpy = "*" +platformdirs = ">=2.2.0" +pytools = ">=2021.2.7" + +[package.extras] +oclgrind = ["oclgrind-binary-distribution (>=18.3)"] +pocl = ["pocl-binary-distribution (>=1.2)"] +test = ["Mako", "pytest (>=7.0.0)"] + +[[package]] +name = "pyopenssl" +version = "22.0.0" +description = "Python wrapper module around the OpenSSL library" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +cryptography = ">=35.0" + +[package.extras] +docs = ["sphinx", "sphinx-rtd-theme"] +test = ["flaky", "pretend", "pytest (>=3.0.1)"] + +[[package]] +name = "pyparsing" +version = "3.0.9" +description = "pyparsing module - Classes and methods to define and execute parsing grammars" +category = "main" +optional = false +python-versions = ">=3.6.8" + +[package.extras] +diagrams = ["jinja2", "railroad-diagrams"] + +[[package]] +name = "pyprof2calltree" +version = "1.4.5" +description = "Help visualize profiling data from cProfile with kcachegrind and qcachegrind" +category = "dev" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" + +[[package]] +name = "pyproj" +version = "3.4.0" +description = "Python interface to PROJ (cartographic projections and coordinate transformations library)" +category = "dev" +optional = false +python-versions = ">=3.8" + +[package.dependencies] +certifi = "*" + +[[package]] +name = "pyreadline3" +version = "3.4.1" +description = "A python implementation of GNU readline." +category = "main" +optional = false +python-versions = "*" + +[[package]] +name = "pyrsistent" +version = "0.18.1" +description = "Persistent/Functional/Immutable data structures" +category = "main" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "pyserial" +version = "3.5" +description = "Python Serial Port Extension" +category = "main" +optional = false +python-versions = "*" + +[package.extras] +cp2110 = ["hidapi"] + +[[package]] +name = "pysocks" +version = "1.7.1" +description = "A Python SOCKS client module. See https://github.com/Anorov/PySocks for more information." +category = "dev" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" + +[[package]] +name = "pytest" +version = "7.1.3" +description = "pytest: simple powerful testing with Python" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +attrs = ">=19.2.0" +colorama = {version = "*", markers = "sys_platform == \"win32\""} +iniconfig = "*" +packaging = "*" +pluggy = ">=0.12,<2.0" +py = ">=1.8.2" +tomli = ">=1.0.0" + +[package.extras] +testing = ["argcomplete", "hypothesis (>=3.56)", "mock", "nose", "pygments (>=2.7.2)", "requests", "xmlschema"] + +[[package]] +name = "pytest-forked" +version = "1.4.0" +description = "run tests in isolated forked subprocesses" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +py = "*" +pytest = ">=3.10" + +[[package]] +name = "pytest-xdist" +version = "2.5.0" +description = "pytest xdist plugin for distributed testing and loop-on-failing modes" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +execnet = ">=1.1" +pytest = ">=6.2.0" +pytest-forked = "*" + +[package.extras] +psutil = ["psutil (>=3.0)"] +setproctitle = ["setproctitle"] +testing = ["filelock"] + +[[package]] +name = "python-dateutil" +version = "2.8.2" +description = "Extensions to the standard Python datetime module" +category = "main" +optional = false +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,>=2.7" + +[package.dependencies] +six = ">=1.5" + +[[package]] +name = "python-engineio" +version = "4.3.4" +description = "Engine.IO server and client for Python" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.extras] +asyncio-client = ["aiohttp (>=3.4)"] +client = ["requests (>=2.21.0)", "websocket-client (>=0.54.0)"] + +[[package]] +name = "python-logstash" +version = "0.4.8" +description = "Python logging handler for Logstash." +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "python-socketio" +version = "5.7.2" +description = "Socket.IO server and client for Python" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +bidict = ">=0.21.0" +python-engineio = ">=4.3.0" + +[package.extras] +asyncio-client = ["aiohttp (>=3.4)"] +client = ["requests (>=2.21.0)", "websocket-client (>=0.54.0)"] + +[[package]] +name = "pytools" +version = "2022.1.12" +description = "A collection of tools for Python" +category = "main" +optional = false +python-versions = "~=3.6" + +[package.dependencies] +platformdirs = ">=2.2.0" +typing_extensions = {version = ">=4.0", markers = "python_version < \"3.11\""} + +[package.extras] +numpy = ["numpy (>=1.6.0)"] + +[[package]] +name = "pytz" +version = "2022.5" +description = "World timezone definitions, modern and historical" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "pywavelets" +version = "1.4.1" +description = "PyWavelets, wavelet transform module" +category = "dev" +optional = false +python-versions = ">=3.8" + +[package.dependencies] +numpy = ">=1.17.3" + +[[package]] +name = "pywin32" +version = "304" +description = "Python for Window Extensions" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "pywin32-ctypes" +version = "0.2.0" +description = "" +category = "main" +optional = false +python-versions = "*" + +[[package]] +name = "pywinpty" +version = "2.0.8" +description = "Pseudo terminal support for Windows from Python." +category = "dev" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "pyyaml" +version = "6.0" +description = "YAML parser and emitter for Python" +category = "main" +optional = false +python-versions = ">=3.6" + +[[package]] +name = "pyzmq" +version = "23.2.1" +description = "Python bindings for 0MQ" +category = "main" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +cffi = {version = "*", markers = "implementation_name == \"pypy\""} +py = {version = "*", markers = "implementation_name == \"pypy\""} + +[[package]] +name = "qtconsole" +version = "5.3.2" +description = "Jupyter Qt console" +category = "dev" +optional = false +python-versions = ">= 3.7" + +[package.dependencies] +ipykernel = ">=4.1" +ipython-genutils = "*" +jupyter-client = ">=4.1" +jupyter-core = "*" +pygments = "*" +pyzmq = ">=17.1" +qtpy = ">=2.0.1" +traitlets = "<5.2.1 || >5.2.1,<5.2.2 || >5.2.2" + +[package.extras] +doc = ["Sphinx (>=1.3)"] +test = ["flaky", "pytest", "pytest-qt"] + +[[package]] +name = "qtpy" +version = "2.2.1" +description = "Provides an abstraction layer on top of the various Qt bindings (PyQt5/6 and PySide2/6)." +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +packaging = "*" + +[package.extras] +test = ["pytest (>=6,!=7.0.0,!=7.0.1)", "pytest-cov (>=3.0.0)", "pytest-qt"] + +[[package]] +name = "qudida" +version = "0.0.4" +description = "QUick and DIrty Domain Adaptation" +category = "dev" +optional = false +python-versions = ">=3.5.0" + +[package.dependencies] +numpy = ">=0.18.0" +opencv-python-headless = ">=4.0.1" +scikit-learn = ">=0.19.1" +typing-extensions = "*" + +[[package]] +name = "reactivex" +version = "4.0.4" +description = "ReactiveX (Rx) for Python" +category = "dev" +optional = false +python-versions = ">=3.7,<4.0" + +[package.dependencies] +typing-extensions = ">=4.1.1,<5.0.0" + +[[package]] +name = "redis" +version = "4.3.4" +description = "Python client for Redis database and key-value store" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +async-timeout = ">=4.0.2" +deprecated = ">=1.2.3" +packaging = ">=20.4" + +[package.extras] +hiredis = ["hiredis (>=1.0.0)"] +ocsp = ["cryptography (>=36.0.1)", "pyopenssl (==20.0.1)", "requests (>=2.26.0)"] + +[[package]] +name = "requests" +version = "2.28.1" +description = "Python HTTP for Humans." +category = "main" +optional = false +python-versions = ">=3.7, <4" + +[package.dependencies] +certifi = ">=2017.4.17" +charset-normalizer = ">=2,<3" +idna = ">=2.5,<4" +PySocks = {version = ">=1.5.6,<1.5.7 || >1.5.7", optional = true, markers = "extra == \"socks\""} +urllib3 = ">=1.21.1,<1.27" + +[package.extras] +socks = ["PySocks (>=1.5.6,!=1.5.7)"] +use-chardet-on-py3 = ["chardet (>=3.0.2,<6)"] + +[[package]] +name = "requests-oauthlib" +version = "1.3.1" +description = "OAuthlib authentication support for Requests." +category = "dev" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" + +[package.dependencies] +oauthlib = ">=3.0.0" +requests = ">=2.0.0" + +[package.extras] +rsa = ["oauthlib[signedtoken] (>=3.0.0)"] + +[[package]] +name = "requests-toolbelt" +version = "0.9.1" +description = "A utility belt for advanced users of python-requests" +category = "main" +optional = false +python-versions = "*" + +[package.dependencies] +requests = ">=2.0.1,<3.0.0" + +[[package]] +name = "reverse-geocoder" +version = "1.5.1" +description = "Fast, offline reverse geocoder" +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +numpy = ">=1.11.0" +scipy = ">=0.17.1" + +[[package]] +name = "s2sphere" +version = "0.2.5" +description = "Python implementation of the S2 Geometry Library" +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +future = ">=0.15" + +[package.extras] +docs = ["Sphinx (>=1.6.5)", "sphinx-rtd-theme (>=0.1.9)"] +tests = ["flake8 (>=2.5.4)", "hacking (>=0.11.0)", "nose (>=1.3.4)", "numpy (>=1.11.0)"] + +[[package]] +name = "scikit-image" +version = "0.19.3" +description = "Image processing in Python" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +imageio = ">=2.4.1" +networkx = ">=2.2" +numpy = ">=1.17.0" +packaging = ">=20.0" +pillow = ">=6.1.0,<7.1.0 || >7.1.0,<7.1.1 || >7.1.1,<8.3.0 || >8.3.0" +PyWavelets = ">=1.1.1" +scipy = ">=1.4.1" +tifffile = ">=2019.7.26" + +[package.extras] +data = ["pooch (>=1.3.0)"] +docs = ["cloudpickle (>=0.2.1)", "dask[array] (>=0.15.0,!=2.17.0)", "ipywidgets", "kaleido", "matplotlib (>=3.3)", "myst-parser", "numpydoc (>=1.0)", "pandas (>=0.23.0)", "plotly (>=4.14.0)", "pooch (>=1.3.0)", "pytest-runner", "scikit-learn", "seaborn (>=0.7.1)", "sphinx (>=1.8)", "sphinx-copybutton", "sphinx-gallery (>=0.10.1)", "tifffile (>=2020.5.30)"] +optional = ["SimpleITK", "astropy (>=3.1.2)", "cloudpickle (>=0.2.1)", "dask[array] (>=1.0.0,!=2.17.0)", "matplotlib (>=3.0.3)", "pooch (>=1.3.0)", "pyamg", "qtpy"] +test = ["asv", "codecov", "flake8", "matplotlib (>=3.0.3)", "pooch (>=1.3.0)", "pytest (>=5.2.0)", "pytest-cov (>=2.7.0)", "pytest-faulthandler", "pytest-localserver"] + +[[package]] +name = "scikit-learn" +version = "1.1.2" +description = "A set of python modules for machine learning and data mining" +category = "dev" +optional = false +python-versions = ">=3.8" + +[package.dependencies] +joblib = ">=1.0.0" +numpy = ">=1.17.3" +scipy = ">=1.3.2" +threadpoolctl = ">=2.0.0" + +[package.extras] +benchmark = ["matplotlib (>=3.1.2)", "memory-profiler (>=0.57.0)", "pandas (>=1.0.5)"] +docs = ["Pillow (>=7.1.2)", "matplotlib (>=3.1.2)", "memory-profiler (>=0.57.0)", "numpydoc (>=1.2.0)", "pandas (>=1.0.5)", "scikit-image (>=0.16.2)", "seaborn (>=0.9.0)", "sphinx (>=4.0.1)", "sphinx-gallery (>=0.7.0)", "sphinx-prompt (>=1.3.0)", "sphinxext-opengraph (>=0.4.2)"] +examples = ["matplotlib (>=3.1.2)", "pandas (>=1.0.5)", "scikit-image (>=0.16.2)", "seaborn (>=0.9.0)"] +tests = ["black (>=22.3.0)", "flake8 (>=3.8.2)", "matplotlib (>=3.1.2)", "mypy (>=0.961)", "numpydoc (>=1.2.0)", "pandas (>=1.0.5)", "pyamg (>=4.0.0)", "pytest (>=5.0.1)", "pytest-cov (>=2.9.0)", "scikit-image (>=0.16.2)"] + +[[package]] +name = "scipy" +version = "1.9.3" +description = "Fundamental algorithms for scientific computing in Python" +category = "dev" +optional = false +python-versions = ">=3.8" + +[package.dependencies] +numpy = ">=1.18.5,<1.26.0" + +[package.extras] +dev = ["flake8", "mypy", "pycodestyle", "typing_extensions"] +doc = ["matplotlib (>2)", "numpydoc", "pydata-sphinx-theme (==0.9.0)", "sphinx (!=4.1.0)", "sphinx-panels (>=0.5.2)", "sphinx-tabs"] +test = ["asv", "gmpy2", "mpmath", "pytest", "pytest-cov", "pytest-xdist", "scikit-umfpack", "threadpoolctl"] + +[[package]] +name = "scons" +version = "4.4.0" +description = "Open Source next-generation build tool." +category = "main" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +setuptools = "*" + +[[package]] +name = "secretstorage" +version = "3.3.3" +description = "Python bindings to FreeDesktop.org Secret Service API" +category = "main" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +cryptography = ">=2.0" +jeepney = ">=0.6" + +[[package]] +name = "segmentation-models-pytorch" +version = "0.2.1" +description = "Image segmentation models with pre-trained backbones. PyTorch." +category = "dev" +optional = false +python-versions = ">=3.0.0" + +[package.dependencies] +efficientnet-pytorch = "0.6.3" +pretrainedmodels = "0.7.4" +timm = "0.4.12" +torchvision = ">=0.5.0" + +[package.extras] +test = ["pytest"] + +[[package]] +name = "send2trash" +version = "1.8.0" +description = "Send file to trash natively under Mac OS X, Windows and Linux." +category = "dev" +optional = false +python-versions = "*" + +[package.extras] +nativelib = ["pyobjc-framework-Cocoa", "pywin32"] +objc = ["pyobjc-framework-Cocoa"] +win32 = ["pywin32"] + +[[package]] +name = "sentry-sdk" +version = "1.10.0" +description = "Python client for Sentry (https://sentry.io)" +category = "main" +optional = false +python-versions = "*" + +[package.dependencies] +certifi = "*" +urllib3 = {version = ">=1.26.11", markers = "python_version >= \"3.6\""} + +[package.extras] +aiohttp = ["aiohttp (>=3.5)"] +beam = ["apache-beam (>=2.12)"] +bottle = ["bottle (>=0.12.13)"] +celery = ["celery (>=3)"] +chalice = ["chalice (>=1.16.0)"] +django = ["django (>=1.8)"] +falcon = ["falcon (>=1.4)"] +fastapi = ["fastapi (>=0.79.0)"] +flask = ["blinker (>=1.1)", "flask (>=0.11)"] +httpx = ["httpx (>=0.16.0)"] +pure-eval = ["asttokens", "executing", "pure-eval"] +pyspark = ["pyspark (>=2.4.4)"] +quart = ["blinker (>=1.1)", "quart (>=0.16.1)"] +rq = ["rq (>=0.6)"] +sanic = ["sanic (>=0.8)"] +sqlalchemy = ["sqlalchemy (>=1.2)"] +starlette = ["starlette (>=0.19.1)"] +tornado = ["tornado (>=5)"] + +[[package]] +name = "setproctitle" +version = "1.3.2" +description = "A Python module to customize the process title" +category = "main" +optional = false +python-versions = ">=3.7" + +[package.extras] +test = ["pytest"] + +[[package]] +name = "setuptools" +version = "65.5.0" +description = "Easily download, build, install, upgrade, and uninstall Python packages" +category = "main" +optional = false +python-versions = ">=3.7" + +[package.extras] +docs = ["furo", "jaraco.packaging (>=9)", "jaraco.tidelift (>=1.4)", "pygments-github-lexers (==0.0.5)", "rst.linker (>=1.9)", "sphinx (>=3.5)", "sphinx-favicon", "sphinx-hoverxref (<2)", "sphinx-inline-tabs", "sphinx-notfound-page (==0.8.3)", "sphinx-reredirects", "sphinxcontrib-towncrier"] +testing = ["build[virtualenv]", "filelock (>=3.4.0)", "flake8 (<5)", "flake8-2020", "ini2toml[lite] (>=0.9)", "jaraco.envs (>=2.2)", "jaraco.path (>=3.2.0)", "mock", "pip (>=19.1)", "pip-run (>=8.8)", "pytest (>=6)", "pytest-black (>=0.3.7)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=1.3)", "pytest-flake8", "pytest-mypy (>=0.9.1)", "pytest-perf", "pytest-xdist", "tomli-w (>=1.0.0)", "virtualenv (>=13.0.0)", "wheel"] +testing-integration = ["build[virtualenv]", "filelock (>=3.4.0)", "jaraco.envs (>=2.2)", "jaraco.path (>=3.2.0)", "pytest", "pytest-enabler", "pytest-xdist", "tomli", "virtualenv (>=13.0.0)", "wheel"] + +[[package]] +name = "setuptools-scm" +version = "7.0.5" +description = "the blessed package to manage your versions by scm tags" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +packaging = ">=20.0" +setuptools = "*" +tomli = ">=1.0.0" +typing-extensions = "*" + +[package.extras] +test = ["pytest (>=6.2)", "virtualenv (>20)"] +toml = ["setuptools (>=42)"] + +[[package]] +name = "shellingham" +version = "1.5.0" +description = "Tool to Detect Surrounding Shell" +category = "main" +optional = false +python-versions = ">=3.4" + +[[package]] +name = "simplejson" +version = "3.17.6" +description = "Simple, fast, extensible JSON encoder/decoder for Python" +category = "dev" +optional = false +python-versions = ">=2.5, !=3.0.*, !=3.1.*, !=3.2.*" + +[[package]] +name = "six" +version = "1.16.0" +description = "Python 2 and 3 compatibility utilities" +category = "main" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*" + +[[package]] +name = "smbus2" +version = "0.4.2" +description = "smbus2 is a drop-in replacement for smbus-cffi/smbus-python in pure Python" +category = "main" +optional = false +python-versions = "*" + +[package.extras] +docs = ["sphinx (>=1.5.3)"] +qa = ["flake8"] +test = ["mock", "nose"] + +[[package]] +name = "sniffio" +version = "1.3.0" +description = "Sniff out which async library your code is running under" +category = "dev" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "snowballstemmer" +version = "2.2.0" +description = "This package provides 29 stemmers for 28 languages generated from Snowball algorithms." +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "sortedcontainers" +version = "2.4.0" +description = "Sorted Containers -- Sorted List, Sorted Dict, Sorted Set" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "sounddevice" +version = "0.4.5" +description = "Play and Record Sound with Python" +category = "main" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +CFFI = ">=1.0" + +[package.extras] +numpy = ["NumPy"] + +[[package]] +name = "soupsieve" +version = "2.3.2.post1" +description = "A modern CSS selector implementation for Beautiful Soup." +category = "dev" +optional = false +python-versions = ">=3.6" + +[[package]] +name = "sphinx" +version = "5.3.0" +description = "Python documentation generator" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +alabaster = ">=0.7,<0.8" +babel = ">=2.9" +colorama = {version = ">=0.4.5", markers = "sys_platform == \"win32\""} +docutils = ">=0.14,<0.20" +imagesize = ">=1.3" +importlib-metadata = {version = ">=4.8", markers = "python_version < \"3.10\""} +Jinja2 = ">=3.0" +packaging = ">=21.0" +Pygments = ">=2.12" +requests = ">=2.5.0" +snowballstemmer = ">=2.0" +sphinxcontrib-applehelp = "*" +sphinxcontrib-devhelp = "*" +sphinxcontrib-htmlhelp = ">=2.0.0" +sphinxcontrib-jsmath = "*" +sphinxcontrib-qthelp = "*" +sphinxcontrib-serializinghtml = ">=1.1.5" + +[package.extras] +docs = ["sphinxcontrib-websupport"] +lint = ["docutils-stubs", "flake8 (>=3.5.0)", "flake8-bugbear", "flake8-comprehensions", "flake8-simplify", "isort", "mypy (>=0.981)", "sphinx-lint", "types-requests", "types-typed-ast"] +test = ["cython", "html5lib", "pytest (>=4.6)", "typed_ast"] + +[[package]] +name = "sphinx-rtd-theme" +version = "1.0.0" +description = "Read the Docs theme for Sphinx" +category = "dev" +optional = false +python-versions = ">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*" + +[package.dependencies] +docutils = "<0.18" +sphinx = ">=1.6" + +[package.extras] +dev = ["bump2version", "sphinxcontrib-httpdomain", "transifex-client"] + +[[package]] +name = "sphinx-sitemap" +version = "2.2.0" +description = "Sitemap generator for Sphinx" +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +six = "*" +sphinx = ">=1.2" + +[[package]] +name = "sphinxcontrib-applehelp" +version = "1.0.2" +description = "sphinxcontrib-applehelp is a sphinx extension which outputs Apple help books" +category = "dev" +optional = false +python-versions = ">=3.5" + +[package.extras] +lint = ["docutils-stubs", "flake8", "mypy"] +test = ["pytest"] + +[[package]] +name = "sphinxcontrib-devhelp" +version = "1.0.2" +description = "sphinxcontrib-devhelp is a sphinx extension which outputs Devhelp document." +category = "dev" +optional = false +python-versions = ">=3.5" + +[package.extras] +lint = ["docutils-stubs", "flake8", "mypy"] +test = ["pytest"] + +[[package]] +name = "sphinxcontrib-htmlhelp" +version = "2.0.0" +description = "sphinxcontrib-htmlhelp is a sphinx extension which renders HTML help files" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.extras] +lint = ["docutils-stubs", "flake8", "mypy"] +test = ["html5lib", "pytest"] + +[[package]] +name = "sphinxcontrib-jsmath" +version = "1.0.1" +description = "A sphinx extension which renders display math in HTML via JavaScript" +category = "dev" +optional = false +python-versions = ">=3.5" + +[package.extras] +test = ["flake8", "mypy", "pytest"] + +[[package]] +name = "sphinxcontrib-qthelp" +version = "1.0.3" +description = "sphinxcontrib-qthelp is a sphinx extension which outputs QtHelp document." +category = "dev" +optional = false +python-versions = ">=3.5" + +[package.extras] +lint = ["docutils-stubs", "flake8", "mypy"] +test = ["pytest"] + +[[package]] +name = "sphinxcontrib-serializinghtml" +version = "1.1.5" +description = "sphinxcontrib-serializinghtml is a sphinx extension which outputs \"serialized\" HTML files (json and pickle)." +category = "dev" +optional = false +python-versions = ">=3.5" + +[package.extras] +lint = ["docutils-stubs", "flake8", "mypy"] +test = ["pytest"] + +[[package]] +name = "spidev" +version = "3.6" +description = "Python bindings for Linux SPI access through spidev" +category = "main" +optional = false +python-versions = "*" + +[[package]] +name = "sqlalchemy" +version = "1.4.42" +description = "Database Abstraction Library" +category = "dev" +optional = false +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,>=2.7" + +[package.dependencies] +greenlet = {version = "!=0.4.17", markers = "python_version >= \"3\" and (platform_machine == \"aarch64\" or platform_machine == \"ppc64le\" or platform_machine == \"x86_64\" or platform_machine == \"amd64\" or platform_machine == \"AMD64\" or platform_machine == \"win32\" or platform_machine == \"WIN32\")"} + +[package.extras] +aiomysql = ["aiomysql", "greenlet (!=0.4.17)"] +aiosqlite = ["aiosqlite", "greenlet (!=0.4.17)", "typing_extensions (!=3.10.0.1)"] +asyncio = ["greenlet (!=0.4.17)"] +asyncmy = ["asyncmy (>=0.2.3,!=0.2.4)", "greenlet (!=0.4.17)"] +mariadb-connector = ["mariadb (>=1.0.1,!=1.1.2)"] +mssql = ["pyodbc"] +mssql-pymssql = ["pymssql"] +mssql-pyodbc = ["pyodbc"] +mypy = ["mypy (>=0.910)", "sqlalchemy2-stubs"] +mysql = ["mysqlclient (>=1.4.0)", "mysqlclient (>=1.4.0,<2)"] +mysql-connector = ["mysql-connector-python"] +oracle = ["cx_oracle (>=7)", "cx_oracle (>=7,<8)"] +postgresql = ["psycopg2 (>=2.7)"] +postgresql-asyncpg = ["asyncpg", "greenlet (!=0.4.17)"] +postgresql-pg8000 = ["pg8000 (>=1.16.6,!=1.29.0)"] +postgresql-psycopg2binary = ["psycopg2-binary"] +postgresql-psycopg2cffi = ["psycopg2cffi"] +pymysql = ["pymysql", "pymysql (<1)"] +sqlcipher = ["sqlcipher3_binary"] + +[[package]] +name = "stack-data" +version = "0.5.1" +description = "Extract data from python stack frames and tracebacks for informative displays" +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +asttokens = "*" +executing = "*" +pure-eval = "*" + +[package.extras] +tests = ["cython", "littleutils", "pygments", "pytest", "typeguard"] + +[[package]] +name = "subprocess32" +version = "3.5.4" +description = "A backport of the subprocess module from Python 3 for use on 2.x." +category = "dev" +optional = false +python-versions = ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*, <4" + +[[package]] +name = "sympy" +version = "1.11.1" +description = "Computer algebra system (CAS) in Python" +category = "main" +optional = false +python-versions = ">=3.8" + +[package.dependencies] +mpmath = ">=0.19" + +[[package]] +name = "tabulate" +version = "0.8.10" +description = "Pretty-print tabular data" +category = "dev" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" + +[package.extras] +widechars = ["wcwidth"] + +[[package]] +name = "tenacity" +version = "8.1.0" +description = "Retry code until it succeeds" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.extras] +doc = ["reno", "sphinx", "tornado (>=4.5)"] + +[[package]] +name = "terminado" +version = "0.16.0" +description = "Tornado websocket backend for the Xterm.js Javascript terminal emulator library." +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +ptyprocess = {version = "*", markers = "os_name != \"nt\""} +pywinpty = {version = ">=1.1.0", markers = "os_name == \"nt\""} +tornado = ">=6.1.0" + +[package.extras] +test = ["pre-commit", "pytest (>=6.0)", "pytest-timeout"] + +[[package]] +name = "threadpoolctl" +version = "3.1.0" +description = "threadpoolctl" +category = "dev" +optional = false +python-versions = ">=3.6" + +[[package]] +name = "tifffile" +version = "2022.10.10" +description = "Read and write TIFF files" +category = "dev" +optional = false +python-versions = ">=3.8" + +[package.dependencies] +numpy = ">=1.19.2" + +[package.extras] +all = ["fsspec", "imagecodecs (>=2022.2.22)", "lxml", "matplotlib (>=3.3)", "zarr"] + +[[package]] +name = "timezonefinder" +version = "6.1.3" +description = "fast python package for finding the timezone of any point on earth (coordinates) offline" +category = "main" +optional = false +python-versions = ">=3.8,<3.11" + +[package.dependencies] +cffi = ">=1.15.1,<2.0.0" +h3 = ">=3.7.3,<4.0.0" +numpy = ">=1.22,<2.0" +setuptools = ">=65.3.0,<66.0.0" + +[package.extras] +numba = ["numba (>=0.55.2,<0.56.0)"] + +[[package]] +name = "timm" +version = "0.4.12" +description = "(Unofficial) PyTorch Image Models" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +torch = ">=1.4" +torchvision = "*" + +[[package]] +name = "tinycss2" +version = "1.2.1" +description = "A tiny CSS parser" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +webencodings = ">=0.4" + +[package.extras] +doc = ["sphinx", "sphinx_rtd_theme"] +test = ["flake8", "isort", "pytest"] + +[[package]] +name = "toml" +version = "0.10.2" +description = "Python Library for Tom's Obvious, Minimal Language" +category = "dev" +optional = false +python-versions = ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*" + +[[package]] +name = "tomli" +version = "2.0.1" +description = "A lil' TOML parser" +category = "main" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "tomlkit" +version = "0.11.5" +description = "Style preserving TOML library" +category = "main" +optional = false +python-versions = ">=3.6,<4.0" + +[[package]] +name = "torch" +version = "1.11.0+cu113" +description = "Tensors and Dynamic neural networks in Python with strong GPU acceleration" +category = "dev" +optional = false +python-versions = ">=3.7.0" + +[package.dependencies] +typing-extensions = "*" + +[package.source] +type = "url" +url = "https://download.pytorch.org/whl/cu113/torch-1.11.0%2Bcu113-cp38-cp38-linux_x86_64.whl" + +[[package]] +name = "torchsummary" +version = "1.5.1" +description = "Model summary in PyTorch similar to `model.summary()` in Keras" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "torchvision" +version = "0.12.0+cu113" +description = "image and video datasets and models for torch deep learning" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +numpy = "*" +pillow = ">=5.3.0,<8.3.0 || >=8.4.0" +requests = "*" +torch = "1.11.0" +typing-extensions = "*" + +[package.extras] +scipy = ["scipy"] + +[package.source] +type = "url" +url = "https://download.pytorch.org/whl/cu113/torchvision-0.12.0%2Bcu113-cp38-cp38-linux_x86_64.whl" + +[[package]] +name = "tornado" +version = "6.2" +description = "Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed." +category = "dev" +optional = false +python-versions = ">= 3.7" + +[[package]] +name = "tqdm" +version = "4.64.1" +description = "Fast, Extensible Progress Meter" +category = "main" +optional = false +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,>=2.7" + +[package.dependencies] +colorama = {version = "*", markers = "platform_system == \"Windows\""} + +[package.extras] +dev = ["py-make (>=0.1.0)", "twine", "wheel"] +notebook = ["ipywidgets (>=6)"] +slack = ["slack-sdk"] +telegram = ["requests"] + +[[package]] +name = "traitlets" +version = "5.5.0" +description = "" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.extras] +docs = ["myst-parser", "pydata-sphinx-theme", "sphinx"] +test = ["pre-commit", "pytest"] + +[[package]] +name = "triton" +version = "1.1.1" +description = "A language and compiler for custom Deep Learning operations" +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +filelock = "*" +torch = "*" + +[[package]] +name = "types-atomicwrites" +version = "1.4.5.1" +description = "Typing stubs for atomicwrites" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "types-certifi" +version = "2021.10.8.3" +description = "Typing stubs for certifi" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "types-pycurl" +version = "7.45.1" +description = "Typing stubs for pycurl" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "types-pyyaml" +version = "6.0.12" +description = "Typing stubs for PyYAML" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "types-requests" +version = "2.28.11.2" +description = "Typing stubs for requests" +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +types-urllib3 = "<1.27" + +[[package]] +name = "types-urllib3" +version = "1.26.25.1" +description = "Typing stubs for urllib3" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "typing-extensions" +version = "4.4.0" +description = "Backported and Experimental Type Hints for Python 3.7+" +category = "main" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "urllib3" +version = "1.26.12" +description = "HTTP library with thread-safe connection pooling, file post, and more." +category = "main" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, <4" + +[package.extras] +brotli = ["brotli (>=1.0.9)", "brotlicffi (>=0.8.0)", "brotlipy (>=0.6.0)"] +secure = ["certifi", "cryptography (>=1.3.4)", "idna (>=2.0.0)", "ipaddress", "pyOpenSSL (>=0.14)", "urllib3-secure-extra"] +socks = ["PySocks (>=1.5.6,!=1.5.7,<2.0)"] + +[[package]] +name = "utm" +version = "0.7.0" +description = "Bidirectional UTM-WGS84 converter for python" +category = "main" +optional = false +python-versions = "*" + +[[package]] +name = "virtualenv" +version = "20.16.5" +description = "Virtual Python Environment builder" +category = "main" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +distlib = ">=0.3.5,<1" +filelock = ">=3.4.1,<4" +platformdirs = ">=2.4,<3" + +[package.extras] +docs = ["proselint (>=0.13)", "sphinx (>=5.1.1)", "sphinx-argparse (>=0.3.1)", "sphinx-rtd-theme (>=1)", "towncrier (>=21.9)"] +testing = ["coverage (>=6.2)", "coverage-enable-subprocess (>=1)", "flaky (>=3.7)", "packaging (>=21.3)", "pytest (>=7.0.1)", "pytest-env (>=0.6.2)", "pytest-freezegun (>=0.4.2)", "pytest-mock (>=3.6.1)", "pytest-randomly (>=3.10.3)", "pytest-timeout (>=2.1)"] + +[[package]] +name = "virtualenv-clone" +version = "0.5.7" +description = "script to clone virtualenvs." +category = "dev" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" + +[[package]] +name = "wcwidth" +version = "0.2.5" +description = "Measures the displayed width of unicode strings in a terminal" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "webencodings" +version = "0.5.1" +description = "Character encoding aliases for legacy web content" +category = "main" +optional = false +python-versions = "*" + +[[package]] +name = "websocket-client" +version = "1.4.1" +description = "WebSocket client for Python with low level API options" +category = "main" +optional = false +python-versions = ">=3.7" + +[package.extras] +docs = ["Sphinx (>=3.4)", "sphinx-rtd-theme (>=0.5)"] +optional = ["python-socks", "wsaccel"] +test = ["websockets"] + +[[package]] +name = "werkzeug" +version = "2.2.2" +description = "The comprehensive WSGI web application library." +category = "main" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +MarkupSafe = ">=2.1.1" + +[package.extras] +watchdog = ["watchdog"] + +[[package]] +name = "widgetsnbextension" +version = "4.0.3" +description = "Jupyter interactive widgets for Jupyter Notebook" +category = "dev" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "wrapt" +version = "1.14.1" +description = "Module for decorators, wrappers and monkey patching." +category = "main" +optional = false +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,>=2.7" + +[[package]] +name = "xattr" +version = "0.9.9" +description = "Python wrapper for extended filesystem attributes" +category = "main" +optional = false +python-versions = "*" + +[package.dependencies] +cffi = ">=1.0" + +[[package]] +name = "yarl" +version = "1.8.1" +description = "Yet another URL library" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +idna = ">=2.0" +multidict = ">=4.0" + +[[package]] +name = "zerorpc" +version = "0.6.3" +description = "zerorpc is a flexible RPC based on zeromq." +category = "dev" +optional = false +python-versions = "*" +develop = false + +[package.dependencies] +future = "*" +gevent = ">=1.1" +msgpack = ">=0.5.2" +msgpack-numpy = ">=0.4.3" +pyzmq = ">=13.1.0" + +[package.source] +type = "git" +url = "https://github.com/commaai/zerorpc-python.git" +reference = "master" +resolved_reference = "0e27fd795bb9a7ec9cab81a771a2e35a91e397c9" + +[[package]] +name = "zipp" +version = "3.9.0" +description = "Backport of pathlib-compatible object wrapper for zip files" +category = "main" +optional = false +python-versions = ">=3.7" + +[package.extras] +docs = ["furo", "jaraco.packaging (>=9)", "jaraco.tidelift (>=1.4)", "rst.linker (>=1.9)", "sphinx (>=3.5)"] +testing = ["flake8 (<5)", "func-timeout", "jaraco.functools", "jaraco.itertools", "more-itertools", "pytest (>=6)", "pytest-black (>=0.3.7)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=1.3)", "pytest-flake8", "pytest-mypy (>=0.9.1)"] + +[[package]] +name = "zope-event" +version = "4.5.0" +description = "Very basic event publishing system" +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +setuptools = "*" + +[package.extras] +docs = ["Sphinx"] +test = ["zope.testrunner"] + +[[package]] +name = "zope-interface" +version = "5.5.0" +description = "Interfaces for Python" +category = "dev" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" + +[package.dependencies] +setuptools = "*" + +[package.extras] +docs = ["Sphinx", "repoze.sphinx.autointerface"] +test = ["coverage (>=5.0.3)", "zope.event", "zope.testing"] +testing = ["coverage (>=5.0.3)", "zope.event", "zope.testing"] + +[metadata] +lock-version = "1.1" +python-versions = "~3.8" +content-hash = "331a7b700c17c618a4f0fa7d0ec3e5b585c1dc467f6f03261c3778f729058f55" + +[metadata.files] +adal = [ + {file = "adal-1.2.7-py2.py3-none-any.whl", hash = "sha256:2a7451ed7441ddbc57703042204a3e30ef747478eea022c70f789fc7f084bc3d"}, + {file = "adal-1.2.7.tar.gz", hash = "sha256:d74f45b81317454d96e982fd1c50e6fb5c99ac2223728aea8764433a39f566f1"}, +] +aenum = [ + {file = "aenum-3.1.11-py2-none-any.whl", hash = "sha256:525b4870a27d0b471c265bda692bc657f1e0dd7597ad4186d072c59f9db666f6"}, + {file = "aenum-3.1.11-py3-none-any.whl", hash = "sha256:12ae89967f2e25c0ce28c293955d643f891603488bc3d9946158ba2b35203638"}, + {file = "aenum-3.1.11.tar.gz", hash = "sha256:aed2c273547ae72a0d5ee869719c02a643da16bf507c80958faadc7e038e3f73"}, +] +aiohttp = [ + {file = "aiohttp-3.8.3-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:ba71c9b4dcbb16212f334126cc3d8beb6af377f6703d9dc2d9fb3874fd667ee9"}, + {file = "aiohttp-3.8.3-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:d24b8bb40d5c61ef2d9b6a8f4528c2f17f1c5d2d31fed62ec860f6006142e83e"}, + {file = "aiohttp-3.8.3-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:f88df3a83cf9df566f171adba39d5bd52814ac0b94778d2448652fc77f9eb491"}, + {file = "aiohttp-3.8.3-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b97decbb3372d4b69e4d4c8117f44632551c692bb1361b356a02b97b69e18a62"}, + {file = "aiohttp-3.8.3-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:309aa21c1d54b8ef0723181d430347d7452daaff93e8e2363db8e75c72c2fb2d"}, + {file = "aiohttp-3.8.3-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ad5383a67514e8e76906a06741febd9126fc7c7ff0f599d6fcce3e82b80d026f"}, + {file = "aiohttp-3.8.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:20acae4f268317bb975671e375493dbdbc67cddb5f6c71eebdb85b34444ac46b"}, + {file = "aiohttp-3.8.3-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:05a3c31c6d7cd08c149e50dc7aa2568317f5844acd745621983380597f027a18"}, + {file = "aiohttp-3.8.3-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:d6f76310355e9fae637c3162936e9504b4767d5c52ca268331e2756e54fd4ca5"}, + {file = "aiohttp-3.8.3-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:256deb4b29fe5e47893fa32e1de2d73c3afe7407738bd3c63829874661d4822d"}, + {file = "aiohttp-3.8.3-cp310-cp310-musllinux_1_1_ppc64le.whl", hash = "sha256:5c59fcd80b9049b49acd29bd3598cada4afc8d8d69bd4160cd613246912535d7"}, + {file = "aiohttp-3.8.3-cp310-cp310-musllinux_1_1_s390x.whl", hash = "sha256:059a91e88f2c00fe40aed9031b3606c3f311414f86a90d696dd982e7aec48142"}, + {file = "aiohttp-3.8.3-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:2feebbb6074cdbd1ac276dbd737b40e890a1361b3cc30b74ac2f5e24aab41f7b"}, + {file = "aiohttp-3.8.3-cp310-cp310-win32.whl", hash = "sha256:5bf651afd22d5f0c4be16cf39d0482ea494f5c88f03e75e5fef3a85177fecdeb"}, + {file = "aiohttp-3.8.3-cp310-cp310-win_amd64.whl", hash = "sha256:653acc3880459f82a65e27bd6526e47ddf19e643457d36a2250b85b41a564715"}, + {file = "aiohttp-3.8.3-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:86fc24e58ecb32aee09f864cb11bb91bc4c1086615001647dbfc4dc8c32f4008"}, + {file = "aiohttp-3.8.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:75e14eac916f024305db517e00a9252714fce0abcb10ad327fb6dcdc0d060f1d"}, + {file = "aiohttp-3.8.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:d1fde0f44029e02d02d3993ad55ce93ead9bb9b15c6b7ccd580f90bd7e3de476"}, + {file = "aiohttp-3.8.3-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4ab94426ddb1ecc6a0b601d832d5d9d421820989b8caa929114811369673235c"}, + {file = "aiohttp-3.8.3-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:89d2e02167fa95172c017732ed7725bc8523c598757f08d13c5acca308e1a061"}, + {file = "aiohttp-3.8.3-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:02f9a2c72fc95d59b881cf38a4b2be9381b9527f9d328771e90f72ac76f31ad8"}, + {file = "aiohttp-3.8.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9c7149272fb5834fc186328e2c1fa01dda3e1fa940ce18fded6d412e8f2cf76d"}, + {file = "aiohttp-3.8.3-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:512bd5ab136b8dc0ffe3fdf2dfb0c4b4f49c8577f6cae55dca862cd37a4564e2"}, + {file = "aiohttp-3.8.3-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:7018ecc5fe97027214556afbc7c502fbd718d0740e87eb1217b17efd05b3d276"}, + {file = "aiohttp-3.8.3-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:88c70ed9da9963d5496d38320160e8eb7e5f1886f9290475a881db12f351ab5d"}, + {file = "aiohttp-3.8.3-cp311-cp311-musllinux_1_1_ppc64le.whl", hash = "sha256:da22885266bbfb3f78218dc40205fed2671909fbd0720aedba39b4515c038091"}, + {file = "aiohttp-3.8.3-cp311-cp311-musllinux_1_1_s390x.whl", hash = "sha256:e65bc19919c910127c06759a63747ebe14f386cda573d95bcc62b427ca1afc73"}, + {file = "aiohttp-3.8.3-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:08c78317e950e0762c2983f4dd58dc5e6c9ff75c8a0efeae299d363d439c8e34"}, + {file = "aiohttp-3.8.3-cp311-cp311-win32.whl", hash = "sha256:45d88b016c849d74ebc6f2b6e8bc17cabf26e7e40c0661ddd8fae4c00f015697"}, + {file = "aiohttp-3.8.3-cp311-cp311-win_amd64.whl", hash = "sha256:96372fc29471646b9b106ee918c8eeb4cca423fcbf9a34daa1b93767a88a2290"}, + {file = "aiohttp-3.8.3-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:c971bf3786b5fad82ce5ad570dc6ee420f5b12527157929e830f51c55dc8af77"}, + {file = "aiohttp-3.8.3-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ff25f48fc8e623d95eca0670b8cc1469a83783c924a602e0fbd47363bb54aaca"}, + {file = "aiohttp-3.8.3-cp36-cp36m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e381581b37db1db7597b62a2e6b8b57c3deec95d93b6d6407c5b61ddc98aca6d"}, + {file = "aiohttp-3.8.3-cp36-cp36m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:db19d60d846283ee275d0416e2a23493f4e6b6028825b51290ac05afc87a6f97"}, + {file = "aiohttp-3.8.3-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:25892c92bee6d9449ffac82c2fe257f3a6f297792cdb18ad784737d61e7a9a85"}, + {file = "aiohttp-3.8.3-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:398701865e7a9565d49189f6c90868efaca21be65c725fc87fc305906be915da"}, + {file = "aiohttp-3.8.3-cp36-cp36m-musllinux_1_1_aarch64.whl", hash = "sha256:4a4fbc769ea9b6bd97f4ad0b430a6807f92f0e5eb020f1e42ece59f3ecfc4585"}, + {file = "aiohttp-3.8.3-cp36-cp36m-musllinux_1_1_i686.whl", hash = "sha256:b29bfd650ed8e148f9c515474a6ef0ba1090b7a8faeee26b74a8ff3b33617502"}, + {file = "aiohttp-3.8.3-cp36-cp36m-musllinux_1_1_ppc64le.whl", hash = "sha256:1e56b9cafcd6531bab5d9b2e890bb4937f4165109fe98e2b98ef0dcfcb06ee9d"}, + {file = "aiohttp-3.8.3-cp36-cp36m-musllinux_1_1_s390x.whl", hash = "sha256:ec40170327d4a404b0d91855d41bfe1fe4b699222b2b93e3d833a27330a87a6d"}, + {file = "aiohttp-3.8.3-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:2df5f139233060578d8c2c975128fb231a89ca0a462b35d4b5fcf7c501ebdbe1"}, + {file = "aiohttp-3.8.3-cp36-cp36m-win32.whl", hash = "sha256:f973157ffeab5459eefe7b97a804987876dd0a55570b8fa56b4e1954bf11329b"}, + {file = "aiohttp-3.8.3-cp36-cp36m-win_amd64.whl", hash = "sha256:437399385f2abcd634865705bdc180c8314124b98299d54fe1d4c8990f2f9494"}, + {file = "aiohttp-3.8.3-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:09e28f572b21642128ef31f4e8372adb6888846f32fecb288c8b0457597ba61a"}, + {file = "aiohttp-3.8.3-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6f3553510abdbec67c043ca85727396ceed1272eef029b050677046d3387be8d"}, + {file = "aiohttp-3.8.3-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e168a7560b7c61342ae0412997b069753f27ac4862ec7867eff74f0fe4ea2ad9"}, + {file = "aiohttp-3.8.3-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:db4c979b0b3e0fa7e9e69ecd11b2b3174c6963cebadeecfb7ad24532ffcdd11a"}, + {file = "aiohttp-3.8.3-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e164e0a98e92d06da343d17d4e9c4da4654f4a4588a20d6c73548a29f176abe2"}, + {file = "aiohttp-3.8.3-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e8a78079d9a39ca9ca99a8b0ac2fdc0c4d25fc80c8a8a82e5c8211509c523363"}, + {file = "aiohttp-3.8.3-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:21b30885a63c3f4ff5b77a5d6caf008b037cb521a5f33eab445dc566f6d092cc"}, + {file = "aiohttp-3.8.3-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:4b0f30372cef3fdc262f33d06e7b411cd59058ce9174ef159ad938c4a34a89da"}, + {file = "aiohttp-3.8.3-cp37-cp37m-musllinux_1_1_ppc64le.whl", hash = "sha256:8135fa153a20d82ffb64f70a1b5c2738684afa197839b34cc3e3c72fa88d302c"}, + {file = "aiohttp-3.8.3-cp37-cp37m-musllinux_1_1_s390x.whl", hash = "sha256:ad61a9639792fd790523ba072c0555cd6be5a0baf03a49a5dd8cfcf20d56df48"}, + {file = "aiohttp-3.8.3-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:978b046ca728073070e9abc074b6299ebf3501e8dee5e26efacb13cec2b2dea0"}, + {file = "aiohttp-3.8.3-cp37-cp37m-win32.whl", hash = "sha256:0d2c6d8c6872df4a6ec37d2ede71eff62395b9e337b4e18efd2177de883a5033"}, + {file = "aiohttp-3.8.3-cp37-cp37m-win_amd64.whl", hash = "sha256:21d69797eb951f155026651f7e9362877334508d39c2fc37bd04ff55b2007091"}, + {file = "aiohttp-3.8.3-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:2ca9af5f8f5812d475c5259393f52d712f6d5f0d7fdad9acdb1107dd9e3cb7eb"}, + {file = "aiohttp-3.8.3-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:1d90043c1882067f1bd26196d5d2db9aa6d268def3293ed5fb317e13c9413ea4"}, + {file = "aiohttp-3.8.3-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:d737fc67b9a970f3234754974531dc9afeea11c70791dcb7db53b0cf81b79784"}, + {file = "aiohttp-3.8.3-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ebf909ea0a3fc9596e40d55d8000702a85e27fd578ff41a5500f68f20fd32e6c"}, + {file = "aiohttp-3.8.3-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5835f258ca9f7c455493a57ee707b76d2d9634d84d5d7f62e77be984ea80b849"}, + {file = "aiohttp-3.8.3-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:da37dcfbf4b7f45d80ee386a5f81122501ec75672f475da34784196690762f4b"}, + {file = "aiohttp-3.8.3-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:87f44875f2804bc0511a69ce44a9595d5944837a62caecc8490bbdb0e18b1342"}, + {file = "aiohttp-3.8.3-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:527b3b87b24844ea7865284aabfab08eb0faf599b385b03c2aa91fc6edd6e4b6"}, + {file = "aiohttp-3.8.3-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:d5ba88df9aa5e2f806650fcbeedbe4f6e8736e92fc0e73b0400538fd25a4dd96"}, + {file = "aiohttp-3.8.3-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:e7b8813be97cab8cb52b1375f41f8e6804f6507fe4660152e8ca5c48f0436017"}, + {file = "aiohttp-3.8.3-cp38-cp38-musllinux_1_1_ppc64le.whl", hash = "sha256:2dea10edfa1a54098703cb7acaa665c07b4e7568472a47f4e64e6319d3821ccf"}, + {file = "aiohttp-3.8.3-cp38-cp38-musllinux_1_1_s390x.whl", hash = "sha256:713d22cd9643ba9025d33c4af43943c7a1eb8547729228de18d3e02e278472b6"}, + {file = "aiohttp-3.8.3-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:2d252771fc85e0cf8da0b823157962d70639e63cb9b578b1dec9868dd1f4f937"}, + {file = "aiohttp-3.8.3-cp38-cp38-win32.whl", hash = "sha256:66bd5f950344fb2b3dbdd421aaa4e84f4411a1a13fca3aeb2bcbe667f80c9f76"}, + {file = "aiohttp-3.8.3-cp38-cp38-win_amd64.whl", hash = "sha256:84b14f36e85295fe69c6b9789b51a0903b774046d5f7df538176516c3e422446"}, + {file = "aiohttp-3.8.3-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:16c121ba0b1ec2b44b73e3a8a171c4f999b33929cd2397124a8c7fcfc8cd9e06"}, + {file = "aiohttp-3.8.3-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:8d6aaa4e7155afaf994d7924eb290abbe81a6905b303d8cb61310a2aba1c68ba"}, + {file = "aiohttp-3.8.3-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:43046a319664a04b146f81b40e1545d4c8ac7b7dd04c47e40bf09f65f2437346"}, + {file = "aiohttp-3.8.3-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:599418aaaf88a6d02a8c515e656f6faf3d10618d3dd95866eb4436520096c84b"}, + {file = "aiohttp-3.8.3-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:92a2964319d359f494f16011e23434f6f8ef0434acd3cf154a6b7bec511e2fb7"}, + {file = "aiohttp-3.8.3-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:73a4131962e6d91109bca6536416aa067cf6c4efb871975df734f8d2fd821b37"}, + {file = "aiohttp-3.8.3-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:598adde339d2cf7d67beaccda3f2ce7c57b3b412702f29c946708f69cf8222aa"}, + {file = "aiohttp-3.8.3-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:75880ed07be39beff1881d81e4a907cafb802f306efd6d2d15f2b3c69935f6fb"}, + {file = "aiohttp-3.8.3-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:a0239da9fbafd9ff82fd67c16704a7d1bccf0d107a300e790587ad05547681c8"}, + {file = "aiohttp-3.8.3-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:4e3a23ec214e95c9fe85a58470b660efe6534b83e6cbe38b3ed52b053d7cb6ad"}, + {file = "aiohttp-3.8.3-cp39-cp39-musllinux_1_1_ppc64le.whl", hash = "sha256:47841407cc89a4b80b0c52276f3cc8138bbbfba4b179ee3acbd7d77ae33f7ac4"}, + {file = "aiohttp-3.8.3-cp39-cp39-musllinux_1_1_s390x.whl", hash = "sha256:54d107c89a3ebcd13228278d68f1436d3f33f2dd2af5415e3feaeb1156e1a62c"}, + {file = "aiohttp-3.8.3-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:c37c5cce780349d4d51739ae682dec63573847a2a8dcb44381b174c3d9c8d403"}, + {file = "aiohttp-3.8.3-cp39-cp39-win32.whl", hash = "sha256:f178d2aadf0166be4df834c4953da2d7eef24719e8aec9a65289483eeea9d618"}, + {file = "aiohttp-3.8.3-cp39-cp39-win_amd64.whl", hash = "sha256:88e5be56c231981428f4f506c68b6a46fa25c4123a2e86d156c58a8369d31ab7"}, + {file = "aiohttp-3.8.3.tar.gz", hash = "sha256:3828fb41b7203176b82fe5d699e0d845435f2374750a44b480ea6b930f6be269"}, +] +aiosignal = [ + {file = "aiosignal-1.2.0-py3-none-any.whl", hash = "sha256:26e62109036cd181df6e6ad646f91f0dcfd05fe16d0cb924138ff2ab75d64e3a"}, + {file = "aiosignal-1.2.0.tar.gz", hash = "sha256:78ed67db6c7b7ced4f98e495e572106d5c432a93e1ddd1bf475e1dc05f5b7df2"}, +] +alabaster = [ + {file = "alabaster-0.7.12-py2.py3-none-any.whl", hash = "sha256:446438bdcca0e05bd45ea2de1668c1d9b032e1a9154c2c259092d77031ddd359"}, + {file = "alabaster-0.7.12.tar.gz", hash = "sha256:a661d72d58e6ea8a57f7a86e37d86716863ee5e92788398526d58b26a4e4dc02"}, +] +albumentations = [ + {file = "albumentations-1.3.0-py3-none-any.whl", hash = "sha256:294165d87d03bc8323e484927f0a5c1a3c64b0e7b9c32a979582a6c93c363bdf"}, + {file = "albumentations-1.3.0.tar.gz", hash = "sha256:be1af36832c8893314f2a5550e8ac19801e04770734c1b70fa3c996b41f37bed"}, +] +anyio = [ + {file = "anyio-3.6.2-py3-none-any.whl", hash = "sha256:fbbe32bd270d2a2ef3ed1c5d45041250284e31fc0a4df4a5a6071842051a51e3"}, + {file = "anyio-3.6.2.tar.gz", hash = "sha256:25ea0d673ae30af41a0c442f81cf3b38c7e79fdc7b60335a4c14e05eb0947421"}, +] +apex = [] +appdirs = [ + {file = "appdirs-1.4.4-py2.py3-none-any.whl", hash = "sha256:a841dacd6b99318a741b166adb07e19ee71a274450e68237b4650ca1055ab128"}, + {file = "appdirs-1.4.4.tar.gz", hash = "sha256:7d5d0167b2b1ba821647616af46a749d1c653740dd0d2415100fe26e27afdf41"}, +] +applicationinsights = [ + {file = "applicationinsights-0.11.10-py2.py3-none-any.whl", hash = "sha256:e89a890db1c6906b6a7d0bcfd617dac83974773c64573147c8d6654f9cf2a6ea"}, + {file = "applicationinsights-0.11.10.tar.gz", hash = "sha256:0b761f3ef0680acf4731906dfc1807faa6f2a57168ae74592db0084a6099f7b3"}, +] +appnope = [ + {file = "appnope-0.1.3-py2.py3-none-any.whl", hash = "sha256:265a455292d0bd8a72453494fa24df5a11eb18373a60c7c0430889f22548605e"}, + {file = "appnope-0.1.3.tar.gz", hash = "sha256:02bd91c4de869fbb1e1c50aafc4098827a7a54ab2f39d9dcba6c9547ed920e24"}, +] +argcomplete = [ + {file = "argcomplete-1.12.3-py2.py3-none-any.whl", hash = "sha256:291f0beca7fd49ce285d2f10e4c1c77e9460cf823eef2de54df0c0fec88b0d81"}, + {file = "argcomplete-1.12.3.tar.gz", hash = "sha256:2c7dbffd8c045ea534921e63b0be6fe65e88599990d8dc408ac8c542b72a5445"}, +] +argon2-cffi = [ + {file = "argon2-cffi-21.3.0.tar.gz", hash = "sha256:d384164d944190a7dd7ef22c6aa3ff197da12962bd04b17f64d4e93d934dba5b"}, + {file = "argon2_cffi-21.3.0-py3-none-any.whl", hash = "sha256:8c976986f2c5c0e5000919e6de187906cfd81fb1c72bf9d88c01177e77da7f80"}, +] +argon2-cffi-bindings = [ + {file = "argon2-cffi-bindings-21.2.0.tar.gz", hash = "sha256:bb89ceffa6c791807d1305ceb77dbfacc5aa499891d2c55661c6459651fc39e3"}, + {file = "argon2_cffi_bindings-21.2.0-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:ccb949252cb2ab3a08c02024acb77cfb179492d5701c7cbdbfd776124d4d2367"}, + {file = "argon2_cffi_bindings-21.2.0-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9524464572e12979364b7d600abf96181d3541da11e23ddf565a32e70bd4dc0d"}, + {file = "argon2_cffi_bindings-21.2.0-cp36-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b746dba803a79238e925d9046a63aa26bf86ab2a2fe74ce6b009a1c3f5c8f2ae"}, + {file = "argon2_cffi_bindings-21.2.0-cp36-abi3-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:58ed19212051f49a523abb1dbe954337dc82d947fb6e5a0da60f7c8471a8476c"}, + {file = "argon2_cffi_bindings-21.2.0-cp36-abi3-musllinux_1_1_aarch64.whl", hash = "sha256:bd46088725ef7f58b5a1ef7ca06647ebaf0eb4baff7d1d0d177c6cc8744abd86"}, + {file = "argon2_cffi_bindings-21.2.0-cp36-abi3-musllinux_1_1_i686.whl", hash = "sha256:8cd69c07dd875537a824deec19f978e0f2078fdda07fd5c42ac29668dda5f40f"}, + {file = "argon2_cffi_bindings-21.2.0-cp36-abi3-musllinux_1_1_x86_64.whl", hash = "sha256:f1152ac548bd5b8bcecfb0b0371f082037e47128653df2e8ba6e914d384f3c3e"}, + {file = "argon2_cffi_bindings-21.2.0-cp36-abi3-win32.whl", hash = "sha256:603ca0aba86b1349b147cab91ae970c63118a0f30444d4bc80355937c950c082"}, + {file = "argon2_cffi_bindings-21.2.0-cp36-abi3-win_amd64.whl", hash = "sha256:b2ef1c30440dbbcba7a5dc3e319408b59676e2e039e2ae11a8775ecf482b192f"}, + {file = "argon2_cffi_bindings-21.2.0-cp38-abi3-macosx_10_9_universal2.whl", hash = "sha256:e415e3f62c8d124ee16018e491a009937f8cf7ebf5eb430ffc5de21b900dad93"}, + {file = "argon2_cffi_bindings-21.2.0-pp37-pypy37_pp73-macosx_10_9_x86_64.whl", hash = "sha256:3e385d1c39c520c08b53d63300c3ecc28622f076f4c2b0e6d7e796e9f6502194"}, + {file = "argon2_cffi_bindings-21.2.0-pp37-pypy37_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2c3e3cc67fdb7d82c4718f19b4e7a87123caf8a93fde7e23cf66ac0337d3cb3f"}, + {file = "argon2_cffi_bindings-21.2.0-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6a22ad9800121b71099d0fb0a65323810a15f2e292f2ba450810a7316e128ee5"}, + {file = "argon2_cffi_bindings-21.2.0-pp37-pypy37_pp73-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f9f8b450ed0547e3d473fdc8612083fd08dd2120d6ac8f73828df9b7d45bb351"}, + {file = "argon2_cffi_bindings-21.2.0-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:93f9bf70084f97245ba10ee36575f0c3f1e7d7724d67d8e5b08e61787c320ed7"}, + {file = "argon2_cffi_bindings-21.2.0-pp38-pypy38_pp73-macosx_10_9_x86_64.whl", hash = "sha256:3b9ef65804859d335dc6b31582cad2c5166f0c3e7975f324d9ffaa34ee7e6583"}, + {file = "argon2_cffi_bindings-21.2.0-pp38-pypy38_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d4966ef5848d820776f5f562a7d45fdd70c2f330c961d0d745b784034bd9f48d"}, + {file = "argon2_cffi_bindings-21.2.0-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:20ef543a89dee4db46a1a6e206cd015360e5a75822f76df533845c3cbaf72670"}, + {file = "argon2_cffi_bindings-21.2.0-pp38-pypy38_pp73-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ed2937d286e2ad0cc79a7087d3c272832865f779430e0cc2b4f3718d3159b0cb"}, + {file = "argon2_cffi_bindings-21.2.0-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:5e00316dabdaea0b2dd82d141cc66889ced0cdcbfa599e8b471cf22c620c329a"}, +] +astroid = [ + {file = "astroid-2.12.12-py3-none-any.whl", hash = "sha256:72702205200b2a638358369d90c222d74ebc376787af8fb2f7f2a86f7b5cc85f"}, + {file = "astroid-2.12.12.tar.gz", hash = "sha256:1c00a14f5a3ed0339d38d2e2e5b74ea2591df5861c0936bb292b84ccf3a78d83"}, +] +asttokens = [ + {file = "asttokens-2.0.8-py2.py3-none-any.whl", hash = "sha256:e3305297c744ae53ffa032c45dc347286165e4ffce6875dc662b205db0623d86"}, + {file = "asttokens-2.0.8.tar.gz", hash = "sha256:c61e16246ecfb2cde2958406b4c8ebc043c9e6d73aaa83c941673b35e5d3a76b"}, +] +async-timeout = [ + {file = "async-timeout-4.0.2.tar.gz", hash = "sha256:2163e1640ddb52b7a8c80d0a67a08587e5d245cc9c553a74a847056bc2976b15"}, + {file = "async_timeout-4.0.2-py3-none-any.whl", hash = "sha256:8ca1e4fcf50d07413d66d1a5e416e42cfdf5851c981d679a09851a6853383b3c"}, +] +atomicwrites = [ + {file = "atomicwrites-1.4.1.tar.gz", hash = "sha256:81b2c9071a49367a7f770170e5eec8cb66567cfbbc8c73d20ce5ca4a8d71cf11"}, +] +attrs = [ + {file = "attrs-22.1.0-py2.py3-none-any.whl", hash = "sha256:86efa402f67bf2df34f51a335487cf46b1ec130d02b8d39fd248abfd30da551c"}, + {file = "attrs-22.1.0.tar.gz", hash = "sha256:29adc2665447e5191d0e7c568fde78b21f9672d344281d0c6e1ab085429b22b6"}, +] +av = [ + {file = "av-9.2.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:29373aa86a055a07eebb14d253cb202033f63ba98c5a4b0233d6d4c07fc7a292"}, + {file = "av-9.2.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:343b11d9b03e71da29f3ce56bc0a6c2d40aba448225dcf8296ab53c10527fff0"}, + {file = "av-9.2.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3ea180bfd89bc0a9e392c32de204cf4e51648aefe2f375d430ce39c04e3ed625"}, + {file = "av-9.2.0-cp310-cp310-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b07b91f534ee7a096068149404c67c3c0e5b4c373580b016151de0fcb440cd3f"}, + {file = "av-9.2.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a9983bc45dab65d2416d2f8a63785caa076a751590823fc8c199617d0dbad390"}, + {file = "av-9.2.0-cp310-cp310-win_amd64.whl", hash = "sha256:0340cc68f3d222bc9438b4fde12e3d68f949eeb5de9e090db182f2cb06e23d53"}, + {file = "av-9.2.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:e3e4a28fa0eabd3ab5b0915e9c005e9155039f9e1a4466212434c40eb69a33fb"}, + {file = "av-9.2.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d6a3c9126d658029b151484b48c656b73af1b145b143c50de5b8b983ac60e095"}, + {file = "av-9.2.0-cp37-cp37m-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3facfe8dc5ba7f9ec7fd7e4c0466e577b84d5f2a1671428f7e28ebcd2cb0ccd3"}, + {file = "av-9.2.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:af951271d998f736a20e54fbc0d944f263db7b17592f11cd489947957bf46aa8"}, + {file = "av-9.2.0-cp37-cp37m-win_amd64.whl", hash = "sha256:109526152e658921731018c50a05db802e7c9f3eb04a7a5fcbd8321fb3b73134"}, + {file = "av-9.2.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:587dd492a2ef3eb20324a0a8d67e6a2e686845d8c1dfdcad058377ac84268d67"}, + {file = "av-9.2.0-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:28d85b8476f7d8fb18e3af9bd6d22bb292f1d810a20f8910fe481f648372e798"}, + {file = "av-9.2.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a6a35e6028dec677caed97d19bfab3b66182690d43b0ec3c355778d740ce0509"}, + {file = "av-9.2.0-cp38-cp38-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a616a6eb46b62f41ff69569cafe12b0005a6dd14389f597dee115340336a910f"}, + {file = "av-9.2.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d730f3ed30eda46d06849bd71ad87d480cf0cad9fd064f33a0386dee95461e31"}, + {file = "av-9.2.0-cp38-cp38-win_amd64.whl", hash = "sha256:6b01fbe8047da81892f8bd2aee5690f00465bf5215e3f6b6372863ac9408d75f"}, + {file = "av-9.2.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:ba3d9e3fe23fd8a14e810f291386225acbdef1c7e5376cc10c8e85c2d4280771"}, + {file = "av-9.2.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:b6be9388618af978304b56d1cf6b74c811db4f220dd320da5bd79640aa443358"}, + {file = "av-9.2.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e59e4ab0e8832bf87707e5024283b3a24cc01784604f0b0e96fbfbadbd8d9fc0"}, + {file = "av-9.2.0-cp39-cp39-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:9b0f124e335561cf4de6b7cdc461283c5eba5f05cccb1a5e1b8ceb1cd15393d8"}, + {file = "av-9.2.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:49481c2d5bc296f451ccd3f93b1cb692d7f58a804b794b99c8b7743e058cae71"}, + {file = "av-9.2.0-cp39-cp39-win_amd64.whl", hash = "sha256:1cbf031f650f89943023eef80e8b2c99588bf9ba26ffef8b3b54bef7102ea3dc"}, + {file = "av-9.2.0-pp37-pypy37_pp73-macosx_10_9_x86_64.whl", hash = "sha256:48819e401cea5be57bd03299d8e5f700082c411746d1ac23eb5e5a931d3d3ced"}, + {file = "av-9.2.0-pp37-pypy37_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0d9cad890e6eccf2697b1c932761bee6f5e1e7faf9b8c03cf10f18f697d29ba3"}, + {file = "av-9.2.0-pp37-pypy37_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d080f34ddfde551de3a5f2d0d06d7518718e3115af81e56182e158cc03111662"}, + {file = "av-9.2.0-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2b46b54ddf64409d4455f408b5970f8494c27c0273181b81c2f7d5072c9afb55"}, + {file = "av-9.2.0-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:bf941896b4c800ee707211c802f94c6e0b4642d3000e25d1974d0b6032af4f66"}, + {file = "av-9.2.0-pp38-pypy38_pp73-macosx_10_9_x86_64.whl", hash = "sha256:d380925732e7497c1c11545107eabe1f498cab214f49f32d1b5d6abe01a2b36b"}, + {file = "av-9.2.0-pp38-pypy38_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6a1c2c1dcc1947473ea1e2cbbf50549e2655e49e08bdd2a6427a97276d7a92c8"}, + {file = "av-9.2.0-pp38-pypy38_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1e2a50a146b3f33a24ea059af913ad368dbb61ed494234debe140a09f1076950"}, + {file = "av-9.2.0-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:45816a39255b39e514a72125e0b6e29eb24fe0994bef3f4f87f3b9d9960b3fa8"}, + {file = "av-9.2.0-pp39-pypy39_pp73-macosx_10_9_x86_64.whl", hash = "sha256:ab90aa3ac2cbdf1f22087fc0fa439f643e96979f169ecfa1d496e114c3c3a8b3"}, + {file = "av-9.2.0-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:24dac414eafcc20423f2ec7e873706489433648f0e9af08a537996880aa55979"}, + {file = "av-9.2.0-pp39-pypy39_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:17a7b6617d4201214f3dd5f628041b4fe56f4244dcd48399ed8d0cf324ca24d1"}, + {file = "av-9.2.0-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8671fa01648ce7aac76e71816c2421ddb1939bf706e2e14684608ab1ce9dbbbb"}, + {file = "av-9.2.0-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:7a5dc26b9df656bed5e1bdeaf8bcc4ff4a2e009ee90b3b3024a86cf8476b2cbf"}, + {file = "av-9.2.0.tar.gz", hash = "sha256:f2a7c226724d7f7745b376b459c500d9d17bd8d0473b7ea6bf8ddb4f7957c69d"}, +] +azure-cli-core = [ + {file = "azure-cli-core-2.41.0.tar.gz", hash = "sha256:f76fa9a44fd1e858397ba2951d260309e70710f367dd609eea03d6c0d8b05d3e"}, + {file = "azure_cli_core-2.41.0-py3-none-any.whl", hash = "sha256:b4cdf765106ff481361d6d84ae0403c46ea6c414ea511b38a316241c03f69252"}, +] +azure-cli-telemetry = [ + {file = "azure-cli-telemetry-1.0.8.tar.gz", hash = "sha256:ca996d162ab689c865f6b60be23b9757c26c3d97928e3319858eea83462df08d"}, + {file = "azure_cli_telemetry-1.0.8-py3-none-any.whl", hash = "sha256:502cbd90723a16603822909befd096ca0b1707de1e70cf730e7b4700ddd7a456"}, +] +azure-common = [ + {file = "azure-common-1.1.28.zip", hash = "sha256:4ac0cd3214e36b6a1b6a442686722a5d8cc449603aa833f3f0f40bda836704a3"}, + {file = "azure_common-1.1.28-py2.py3-none-any.whl", hash = "sha256:5c12d3dcf4ec20599ca6b0d3e09e86e146353d443e7fcc050c9a19c1f9df20ad"}, +] +azure-core = [ + {file = "azure-core-1.26.0.zip", hash = "sha256:b0036a0d256329e08d1278dff7df36be30031d2ec9b16c691bc61e4732f71fe0"}, + {file = "azure_core-1.26.0-py3-none-any.whl", hash = "sha256:578ea3ae56bca48880c96797871b6c954b5ae78d10d54360182c7604dc837f25"}, +] +azure-mgmt-core = [ + {file = "azure-mgmt-core-1.3.2.zip", hash = "sha256:07f4afe823a55d704b048d61edfdc1318c051ed59f244032126350be95e9d501"}, + {file = "azure_mgmt_core-1.3.2-py3-none-any.whl", hash = "sha256:fd829f67086e5cf6f7eb016c9e80bb0fb293cbbbd4d8738dc90af9aa1055fb7b"}, +] +azure-nspkg = [ + {file = "azure-nspkg-3.0.2.zip", hash = "sha256:e7d3cea6af63e667d87ba1ca4f8cd7cb4dfca678e4c55fc1cedb320760e39dd0"}, + {file = "azure_nspkg-3.0.2-py2-none-any.whl", hash = "sha256:1d0bbb2157cf57b1bef6c8c8e5b41133957364456c43b0a43599890023cca0a8"}, + {file = "azure_nspkg-3.0.2-py3-none-any.whl", hash = "sha256:31a060caca00ed1ebd369fc7fe01a56768c927e404ebc92268f4d9d636435e28"}, +] +azure-storage-blob = [ + {file = "azure-storage-blob-2.1.0.tar.gz", hash = "sha256:b90323aad60f207f9f90a0c4cf94c10acc313c20b39403398dfba51f25f7b454"}, + {file = "azure_storage_blob-2.1.0-py2.py3-none-any.whl", hash = "sha256:a8e91a51d4f62d11127c7fd8ba0077385c5b11022f0269f8a2a71b9fc36bef31"}, +] +azure-storage-common = [ + {file = "azure-storage-common-2.1.0.tar.gz", hash = "sha256:ccedef5c67227bc4d6670ffd37cec18fb529a1b7c3a5e53e4096eb0cf23dc73f"}, + {file = "azure_storage_common-2.1.0-py2.py3-none-any.whl", hash = "sha256:b01a491a18839b9d05a4fe3421458a0ddb5ab9443c14e487f40d16f9a1dc2fbe"}, +] +azure-storage-nspkg = [ + {file = "azure-storage-nspkg-3.1.0.tar.gz", hash = "sha256:6f3bbe8652d5f542767d8433e7f96b8df7f518774055ac7c92ed7ca85f653811"}, + {file = "azure_storage_nspkg-3.1.0-py2.py3-none-any.whl", hash = "sha256:7da3bd6c73b8c464a57f53ae9af8328490d2267c66430d8a7621997e52a9703e"}, +] +babel = [ + {file = "Babel-2.10.3-py3-none-any.whl", hash = "sha256:ff56f4892c1c4bf0d814575ea23471c230d544203c7748e8c68f0089478d48eb"}, + {file = "Babel-2.10.3.tar.gz", hash = "sha256:7614553711ee97490f732126dc077f8d0ae084ebc6a96e23db1482afabdb2c51"}, +] +backcall = [ + {file = "backcall-0.2.0-py2.py3-none-any.whl", hash = "sha256:fbbce6a29f263178a1f7915c1940bde0ec2b2a967566fe1c65c1dfb7422bd255"}, + {file = "backcall-0.2.0.tar.gz", hash = "sha256:5cbdbf27be5e7cfadb448baf0aa95508f91f2bbc6c6437cd9cd06e2a4c215e1e"}, +] +bcrypt = [ + {file = "bcrypt-4.0.1-cp36-abi3-macosx_10_10_universal2.whl", hash = "sha256:b1023030aec778185a6c16cf70f359cbb6e0c289fd564a7cfa29e727a1c38f8f"}, + {file = "bcrypt-4.0.1-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:08d2947c490093a11416df18043c27abe3921558d2c03e2076ccb28a116cb6d0"}, + {file = "bcrypt-4.0.1-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0eaa47d4661c326bfc9d08d16debbc4edf78778e6aaba29c1bc7ce67214d4410"}, + {file = "bcrypt-4.0.1-cp36-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ae88eca3024bb34bb3430f964beab71226e761f51b912de5133470b649d82344"}, + {file = "bcrypt-4.0.1-cp36-abi3-manylinux_2_24_x86_64.whl", hash = "sha256:a522427293d77e1c29e303fc282e2d71864579527a04ddcfda6d4f8396c6c36a"}, + {file = "bcrypt-4.0.1-cp36-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:fbdaec13c5105f0c4e5c52614d04f0bca5f5af007910daa8b6b12095edaa67b3"}, + {file = "bcrypt-4.0.1-cp36-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:ca3204d00d3cb2dfed07f2d74a25f12fc12f73e606fcaa6975d1f7ae69cacbb2"}, + {file = "bcrypt-4.0.1-cp36-abi3-musllinux_1_1_aarch64.whl", hash = "sha256:089098effa1bc35dc055366740a067a2fc76987e8ec75349eb9484061c54f535"}, + {file = "bcrypt-4.0.1-cp36-abi3-musllinux_1_1_x86_64.whl", hash = "sha256:e9a51bbfe7e9802b5f3508687758b564069ba937748ad7b9e890086290d2f79e"}, + {file = "bcrypt-4.0.1-cp36-abi3-win32.whl", hash = "sha256:2caffdae059e06ac23fce178d31b4a702f2a3264c20bfb5ff541b338194d8fab"}, + {file = "bcrypt-4.0.1-cp36-abi3-win_amd64.whl", hash = "sha256:8a68f4341daf7522fe8d73874de8906f3a339048ba406be6ddc1b3ccb16fc0d9"}, + {file = "bcrypt-4.0.1-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bf4fa8b2ca74381bb5442c089350f09a3f17797829d958fad058d6e44d9eb83c"}, + {file = "bcrypt-4.0.1-pp37-pypy37_pp73-manylinux_2_24_x86_64.whl", hash = "sha256:67a97e1c405b24f19d08890e7ae0c4f7ce1e56a712a016746c8b2d7732d65d4b"}, + {file = "bcrypt-4.0.1-pp37-pypy37_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:b3b85202d95dd568efcb35b53936c5e3b3600c7cdcc6115ba461df3a8e89f38d"}, + {file = "bcrypt-4.0.1-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cbb03eec97496166b704ed663a53680ab57c5084b2fc98ef23291987b525cb7d"}, + {file = "bcrypt-4.0.1-pp38-pypy38_pp73-manylinux_2_24_x86_64.whl", hash = "sha256:5ad4d32a28b80c5fa6671ccfb43676e8c1cc232887759d1cd7b6f56ea4355215"}, + {file = "bcrypt-4.0.1-pp38-pypy38_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:b57adba8a1444faf784394de3436233728a1ecaeb6e07e8c22c8848f179b893c"}, + {file = "bcrypt-4.0.1-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:705b2cea8a9ed3d55b4491887ceadb0106acf7c6387699fca771af56b1cdeeda"}, + {file = "bcrypt-4.0.1-pp39-pypy39_pp73-manylinux_2_24_x86_64.whl", hash = "sha256:2b3ac11cf45161628f1f3733263e63194f22664bf4d0c0f3ab34099c02134665"}, + {file = "bcrypt-4.0.1-pp39-pypy39_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:3100851841186c25f127731b9fa11909ab7b1df6fc4b9f8353f4f1fd952fbf71"}, + {file = "bcrypt-4.0.1.tar.gz", hash = "sha256:27d375903ac8261cfe4047f6709d16f7d18d39b1ec92aaf72af989552a650ebd"}, +] +beautifulsoup4 = [ + {file = "beautifulsoup4-4.11.1-py3-none-any.whl", hash = "sha256:58d5c3d29f5a36ffeb94f02f0d786cd53014cf9b3b3951d42e0080d8a9498d30"}, + {file = "beautifulsoup4-4.11.1.tar.gz", hash = "sha256:ad9aa55b65ef2808eb405f46cf74df7fcb7044d5cbc26487f96eb2ef2e436693"}, +] +bidict = [ + {file = "bidict-0.22.0-py3-none-any.whl", hash = "sha256:415126d23a0c81e1a8c584a8fb1f6905ea090c772571803aeee0a2242e8e7ba0"}, + {file = "bidict-0.22.0.tar.gz", hash = "sha256:5c826b3e15e97cc6e615de295756847c282a79b79c5430d3bfc909b1ac9f5bd8"}, +] +bleach = [ + {file = "bleach-5.0.1-py3-none-any.whl", hash = "sha256:085f7f33c15bd408dd9b17a4ad77c577db66d76203e5984b1bd59baeee948b2a"}, + {file = "bleach-5.0.1.tar.gz", hash = "sha256:0d03255c47eb9bd2f26aa9bb7f2107732e7e8fe195ca2f64709fcf3b0a4a085c"}, +] +blosc = [ + {file = "blosc-1.9.2.tar.gz", hash = "sha256:89196a2112035836f027a29835ee247b0c7a45cece4cd9e4b740a1428aa174bf"}, +] +breathe = [ + {file = "breathe-4.34.0-py3-none-any.whl", hash = "sha256:48804dcf0e607a89fb6ad88c729ef12743a42db03ae9489be4ef8f7c4011774a"}, + {file = "breathe-4.34.0.tar.gz", hash = "sha256:ac0768a5e84addad3e632028fe67749c567aba2b29088493b64c2c1634bcdba1"}, +] +cachecontrol = [ + {file = "CacheControl-0.12.11-py2.py3-none-any.whl", hash = "sha256:2c75d6a8938cb1933c75c50184549ad42728a27e9f6b92fd677c3151aa72555b"}, + {file = "CacheControl-0.12.11.tar.gz", hash = "sha256:a5b9fcc986b184db101aa280b42ecdcdfc524892596f606858e0b7a8b4d9e144"}, +] +cachy = [ + {file = "cachy-0.3.0-py2.py3-none-any.whl", hash = "sha256:338ca09c8860e76b275aff52374330efedc4d5a5e45dc1c5b539c1ead0786fe7"}, + {file = "cachy-0.3.0.tar.gz", hash = "sha256:186581f4ceb42a0bbe040c407da73c14092379b1e4c0e327fdb72ae4a9b269b1"}, +] +carla = [ + {file = "carla-0.9.13-cp27-cp27mu-manylinux_2_27_x86_64.whl", hash = "sha256:339fcb1e392f3ade1be82b7258de19c533e2efae111e954a6eb174efb296903d"}, + {file = "carla-0.9.13-cp36-cp36m-manylinux_2_27_x86_64.whl", hash = "sha256:5f065825ce812343bf27a80a19d647b3200b31b44a9e80cea0340e3bd20cdf81"}, + {file = "carla-0.9.13-cp36-cp36m-win_amd64.whl", hash = "sha256:1210cce213e968a644effd4e2e48458a072481459d073424b05725056ba3d77d"}, + {file = "carla-0.9.13-cp37-cp37m-manylinux_2_27_x86_64.whl", hash = "sha256:a95d2d4218ea388c863c66b7c2ab3fe49ffefe53999305cfcb6a8107042f79af"}, + {file = "carla-0.9.13-cp37-cp37m-win_amd64.whl", hash = "sha256:954ca34d5bdd4516ceca353db907fee8cec6630d6b31a732b17dd1554e0f0f94"}, + {file = "carla-0.9.13-cp38-cp38-manylinux_2_27_x86_64.whl", hash = "sha256:d2bfaea2d6824a2d758cbe813856c69420494f5c97d2a2dfb45653ccf976f1ce"}, + {file = "carla-0.9.13-cp38-cp38-win_amd64.whl", hash = "sha256:a64ee78fe91137fa7d4828c7fc06d5824bd7312e29e4ea4f31a5d74dd28bff40"}, +] +casadi = [ + {file = "casadi-3.5.5-cp27-none-macosx_10_13_x86_64.macosx_10_13_intel.whl", hash = "sha256:d4e49cb46404cef61f83b30bb20ec9597c50ae7f55cfd6b89c17facc74675437"}, + {file = "casadi-3.5.5-cp27-none-manylinux1_i686.whl", hash = "sha256:f08a99e98b0a15083f06b1e221f064a29b3ed9e20617dc55aa8e823f2f732ace"}, + {file = "casadi-3.5.5-cp27-none-manylinux1_x86_64.whl", hash = "sha256:09e103bb597d46aa338fc57bc49270068a1f07be35f9494c9f796dea4b801aeb"}, + {file = "casadi-3.5.5-cp27-none-win32.whl", hash = "sha256:a4ce51e988570160af9ccfbbb1b9679546cbb1865d3a74ef0276f37fd94d91d9"}, + {file = "casadi-3.5.5-cp27-none-win_amd64.whl", hash = "sha256:54d89442058271007ae8573dfa33360bea10e26603545481090b45e8b90c9d10"}, + {file = "casadi-3.5.5-cp34-none-manylinux1_x86_64.whl", hash = "sha256:4143803af909f284400c02f59de4d97e5ba9319de28366215ef55ef261914f9a"}, + {file = "casadi-3.5.5-cp34-none-win32.whl", hash = "sha256:7a624d40c7b5ded7916f6cc65998af4585b4557c9ea65dc1e3a6273ebb2313ec"}, + {file = "casadi-3.5.5-cp34-none-win_amd64.whl", hash = "sha256:3aec6737c282e7fb5be41f6c7d0649e52ce49efb3508f30bada707e809bbbb5f"}, + {file = "casadi-3.5.5-cp35-none-macosx_10_13_x86_64.macosx_10_13_intel.whl", hash = "sha256:6192e2ed81c15a7dab2554f5f69b134df8d1a982f8d9f13e57bdef93364d2120"}, + {file = "casadi-3.5.5-cp35-none-manylinux1_i686.whl", hash = "sha256:49a8b713f0ff0bbc2f2af2e71c515cdced238786e25ef504f5982618c84c67a7"}, + {file = "casadi-3.5.5-cp35-none-manylinux1_x86_64.whl", hash = "sha256:13277151efc76b221de8ca6b5ab7b8bbdd2b0e139f282866840adf88dfe53bc9"}, + {file = "casadi-3.5.5-cp35-none-manylinux2014_aarch64.whl", hash = "sha256:253569c85f881a6a8fe5e1c0758858edb1ecb4c3d8bce4aee4b52e5dc59fc091"}, + {file = "casadi-3.5.5-cp35-none-win32.whl", hash = "sha256:5de5c3c1381ac303e71fdef75dace34af6e1d50b46ac081051cd209b8b933837"}, + {file = "casadi-3.5.5-cp35-none-win_amd64.whl", hash = "sha256:4932b2b5361013420189dbc8d30e970672d036b37cb382f1c09c3b6cfe651a37"}, + {file = "casadi-3.5.5-cp36-none-macosx_10_13_x86_64.macosx_10_13_intel.whl", hash = "sha256:2322748a8d5e88750fd2fc0abcdc56cfbad1a8cd538fe0e7d7b6d8ce0cb3fa62"}, + {file = "casadi-3.5.5-cp36-none-manylinux1_i686.whl", hash = "sha256:ab6a600a9b2ea27453d56fd4464ad0db0ae69f5cea42595fcbdaabcd40396440"}, + {file = "casadi-3.5.5-cp36-none-manylinux1_x86_64.whl", hash = "sha256:5f6eb8de31735c14ecc777e3ad77b57767b5f2dbea29265909ef696f51e8be92"}, + {file = "casadi-3.5.5-cp36-none-manylinux2014_aarch64.whl", hash = "sha256:adf20c34ba2cec1840a026023d93cc6d9b3581dfda6a044f434fc75b50c9a2ce"}, + {file = "casadi-3.5.5-cp36-none-win32.whl", hash = "sha256:7309a75b27c57f09b00a61815fb38c40da8e62e3004598e55ea1b8f713d96221"}, + {file = "casadi-3.5.5-cp36-none-win_amd64.whl", hash = "sha256:ab85c7cf772ba54f2718ebe366b836fffff868443f7c0c02389ed0a288cbde1f"}, + {file = "casadi-3.5.5-cp37-none-macosx_10_13_x86_64.macosx_10_13_intel.whl", hash = "sha256:ec26244f9d9047f1bb401f1b86ff4775e1ddf638f4b4992bbc362a27a6f56673"}, + {file = "casadi-3.5.5-cp37-none-manylinux1_i686.whl", hash = "sha256:1c451a07b2440c00d552e040b6285b6e79b677d2978212368b28b86f5d267669"}, + {file = "casadi-3.5.5-cp37-none-manylinux1_x86_64.whl", hash = "sha256:24fbac649ee26572884029dcd0e108b4a2412cad003a84ed915c4e44a94ecae7"}, + {file = "casadi-3.5.5-cp37-none-manylinux2014_aarch64.whl", hash = "sha256:a06c0b96eb9d3bc88c627eec6e465726934ca0394347dc33efc742b8c91db83d"}, + {file = "casadi-3.5.5-cp37-none-win32.whl", hash = "sha256:36db4c84d8f3aad328faaeaeaa454a633c95a854d78ea188791b147888379342"}, + {file = "casadi-3.5.5-cp37-none-win_amd64.whl", hash = "sha256:643e48f92eaf65eb82964816bb7e7064ddb8239959210fa6168e8bce6fe6ef94"}, + {file = "casadi-3.5.5-cp38-none-macosx_10_13_x86_64.macosx_10_13_intel.whl", hash = "sha256:6ce7ac8a301a145f98d46db0bfd13bc8b3831a5bb92e8054d531a1f233bb4b93"}, + {file = "casadi-3.5.5-cp38-none-manylinux1_i686.whl", hash = "sha256:473bb86fa64ac9703d74a474514703b4665fa9a384221ced620b5025e64532a7"}, + {file = "casadi-3.5.5-cp38-none-manylinux1_x86_64.whl", hash = "sha256:292e2768280393bad406256e0ef9c30ddcd4867dbd42148b36f9d92a32d9e199"}, + {file = "casadi-3.5.5-cp38-none-manylinux2014_aarch64.whl", hash = "sha256:353a79e50aa84ac5e0d9f04bc3b2d78a2cc8edae3b842d757756449682778944"}, + {file = "casadi-3.5.5-cp38-none-win32.whl", hash = "sha256:77f33cb95be6a49b93d8d6b81f05193676ae09857699cedf8f1a14a4285d077e"}, + {file = "casadi-3.5.5-cp38-none-win_amd64.whl", hash = "sha256:fbf39dcd63f1d3b63c300fce59b7ea678bd5ea1d014e1e090a5226600a4132cb"}, + {file = "casadi-3.5.5-cp39-none-macosx_10_13_x86_64.macosx_10_13_intel.whl", hash = "sha256:4086669280b2335d235c664373db46dcd7f6485dba4663ce1944ea01753c5e8b"}, + {file = "casadi-3.5.5-cp39-none-manylinux1_i686.whl", hash = "sha256:c3440c90c31b61ae1df82f6c784643393f723354dc08013f9d5cedf25507c67c"}, + {file = "casadi-3.5.5-cp39-none-manylinux1_x86_64.whl", hash = "sha256:bd94048388b602fc30fdac2fecb986c034110ed8d2d17af7fd13b0de45c58bd7"}, + {file = "casadi-3.5.5-cp39-none-manylinux2014_aarch64.whl", hash = "sha256:cd630a2e6ec6df6a4977af63080fa8d63a0053ff8c06ea0200959b47ae75201c"}, + {file = "casadi-3.5.5-cp39-none-win32.whl", hash = "sha256:ac45b91616e9b8afbe266ca08e80770b28e9e6d7a5852e3677fb37e42bde2047"}, + {file = "casadi-3.5.5-cp39-none-win_amd64.whl", hash = "sha256:55df534d003efdd120c4ebfeb6b252c443d273cdc4b97a394eb0268367477795"}, +] +certifi = [ + {file = "certifi-2022.9.24-py3-none-any.whl", hash = "sha256:90c1a32f1d68f940488354e36370f6cca89f0f106db09518524c88d6ed83f382"}, + {file = "certifi-2022.9.24.tar.gz", hash = "sha256:0d9c601124e5a6ba9712dbc60d9c53c21e34f5f641fe83002317394311bdce14"}, +] +cffi = [ + {file = "cffi-1.15.1-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:a66d3508133af6e8548451b25058d5812812ec3798c886bf38ed24a98216fab2"}, + {file = "cffi-1.15.1-cp27-cp27m-manylinux1_i686.whl", hash = "sha256:470c103ae716238bbe698d67ad020e1db9d9dba34fa5a899b5e21577e6d52ed2"}, + {file = "cffi-1.15.1-cp27-cp27m-manylinux1_x86_64.whl", hash = "sha256:9ad5db27f9cabae298d151c85cf2bad1d359a1b9c686a275df03385758e2f914"}, + {file = "cffi-1.15.1-cp27-cp27m-win32.whl", hash = "sha256:b3bbeb01c2b273cca1e1e0c5df57f12dce9a4dd331b4fa1635b8bec26350bde3"}, + {file = "cffi-1.15.1-cp27-cp27m-win_amd64.whl", hash = "sha256:e00b098126fd45523dd056d2efba6c5a63b71ffe9f2bbe1a4fe1716e1d0c331e"}, + {file = "cffi-1.15.1-cp27-cp27mu-manylinux1_i686.whl", hash = "sha256:d61f4695e6c866a23a21acab0509af1cdfd2c013cf256bbf5b6b5e2695827162"}, + {file = "cffi-1.15.1-cp27-cp27mu-manylinux1_x86_64.whl", hash = "sha256:ed9cb427ba5504c1dc15ede7d516b84757c3e3d7868ccc85121d9310d27eed0b"}, + {file = "cffi-1.15.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:39d39875251ca8f612b6f33e6b1195af86d1b3e60086068be9cc053aa4376e21"}, + {file = "cffi-1.15.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:285d29981935eb726a4399badae8f0ffdff4f5050eaa6d0cfc3f64b857b77185"}, + {file = "cffi-1.15.1-cp310-cp310-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3eb6971dcff08619f8d91607cfc726518b6fa2a9eba42856be181c6d0d9515fd"}, + {file = "cffi-1.15.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:21157295583fe8943475029ed5abdcf71eb3911894724e360acff1d61c1d54bc"}, + {file = "cffi-1.15.1-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5635bd9cb9731e6d4a1132a498dd34f764034a8ce60cef4f5319c0541159392f"}, + {file = "cffi-1.15.1-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:2012c72d854c2d03e45d06ae57f40d78e5770d252f195b93f581acf3ba44496e"}, + {file = "cffi-1.15.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dd86c085fae2efd48ac91dd7ccffcfc0571387fe1193d33b6394db7ef31fe2a4"}, + {file = "cffi-1.15.1-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:fa6693661a4c91757f4412306191b6dc88c1703f780c8234035eac011922bc01"}, + {file = "cffi-1.15.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:59c0b02d0a6c384d453fece7566d1c7e6b7bae4fc5874ef2ef46d56776d61c9e"}, + {file = "cffi-1.15.1-cp310-cp310-win32.whl", hash = "sha256:cba9d6b9a7d64d4bd46167096fc9d2f835e25d7e4c121fb2ddfc6528fb0413b2"}, + {file = "cffi-1.15.1-cp310-cp310-win_amd64.whl", hash = "sha256:ce4bcc037df4fc5e3d184794f27bdaab018943698f4ca31630bc7f84a7b69c6d"}, + {file = "cffi-1.15.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:3d08afd128ddaa624a48cf2b859afef385b720bb4b43df214f85616922e6a5ac"}, + {file = "cffi-1.15.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:3799aecf2e17cf585d977b780ce79ff0dc9b78d799fc694221ce814c2c19db83"}, + {file = "cffi-1.15.1-cp311-cp311-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a591fe9e525846e4d154205572a029f653ada1a78b93697f3b5a8f1f2bc055b9"}, + {file = "cffi-1.15.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3548db281cd7d2561c9ad9984681c95f7b0e38881201e157833a2342c30d5e8c"}, + {file = "cffi-1.15.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:91fc98adde3d7881af9b59ed0294046f3806221863722ba7d8d120c575314325"}, + {file = "cffi-1.15.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:94411f22c3985acaec6f83c6df553f2dbe17b698cc7f8ae751ff2237d96b9e3c"}, + {file = "cffi-1.15.1-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:03425bdae262c76aad70202debd780501fabeaca237cdfddc008987c0e0f59ef"}, + {file = "cffi-1.15.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:cc4d65aeeaa04136a12677d3dd0b1c0c94dc43abac5860ab33cceb42b801c1e8"}, + {file = "cffi-1.15.1-cp311-cp311-win32.whl", hash = "sha256:a0f100c8912c114ff53e1202d0078b425bee3649ae34d7b070e9697f93c5d52d"}, + {file = "cffi-1.15.1-cp311-cp311-win_amd64.whl", hash = "sha256:04ed324bda3cda42b9b695d51bb7d54b680b9719cfab04227cdd1e04e5de3104"}, + {file = "cffi-1.15.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:50a74364d85fd319352182ef59c5c790484a336f6db772c1a9231f1c3ed0cbd7"}, + {file = "cffi-1.15.1-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e263d77ee3dd201c3a142934a086a4450861778baaeeb45db4591ef65550b0a6"}, + {file = "cffi-1.15.1-cp36-cp36m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:cec7d9412a9102bdc577382c3929b337320c4c4c4849f2c5cdd14d7368c5562d"}, + {file = "cffi-1.15.1-cp36-cp36m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:4289fc34b2f5316fbb762d75362931e351941fa95fa18789191b33fc4cf9504a"}, + {file = "cffi-1.15.1-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:173379135477dc8cac4bc58f45db08ab45d228b3363adb7af79436135d028405"}, + {file = "cffi-1.15.1-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:6975a3fac6bc83c4a65c9f9fcab9e47019a11d3d2cf7f3c0d03431bf145a941e"}, + {file = "cffi-1.15.1-cp36-cp36m-win32.whl", hash = "sha256:2470043b93ff09bf8fb1d46d1cb756ce6132c54826661a32d4e4d132e1977adf"}, + {file = "cffi-1.15.1-cp36-cp36m-win_amd64.whl", hash = "sha256:30d78fbc8ebf9c92c9b7823ee18eb92f2e6ef79b45ac84db507f52fbe3ec4497"}, + {file = "cffi-1.15.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:198caafb44239b60e252492445da556afafc7d1e3ab7a1fb3f0584ef6d742375"}, + {file = "cffi-1.15.1-cp37-cp37m-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5ef34d190326c3b1f822a5b7a45f6c4535e2f47ed06fec77d3d799c450b2651e"}, + {file = "cffi-1.15.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8102eaf27e1e448db915d08afa8b41d6c7ca7a04b7d73af6514df10a3e74bd82"}, + {file = "cffi-1.15.1-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5df2768244d19ab7f60546d0c7c63ce1581f7af8b5de3eb3004b9b6fc8a9f84b"}, + {file = "cffi-1.15.1-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a8c4917bd7ad33e8eb21e9a5bbba979b49d9a97acb3a803092cbc1133e20343c"}, + {file = "cffi-1.15.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0e2642fe3142e4cc4af0799748233ad6da94c62a8bec3a6648bf8ee68b1c7426"}, + {file = "cffi-1.15.1-cp37-cp37m-win32.whl", hash = "sha256:e229a521186c75c8ad9490854fd8bbdd9a0c9aa3a524326b55be83b54d4e0ad9"}, + {file = "cffi-1.15.1-cp37-cp37m-win_amd64.whl", hash = "sha256:a0b71b1b8fbf2b96e41c4d990244165e2c9be83d54962a9a1d118fd8657d2045"}, + {file = "cffi-1.15.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:320dab6e7cb2eacdf0e658569d2575c4dad258c0fcc794f46215e1e39f90f2c3"}, + {file = "cffi-1.15.1-cp38-cp38-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1e74c6b51a9ed6589199c787bf5f9875612ca4a8a0785fb2d4a84429badaf22a"}, + {file = "cffi-1.15.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a5c84c68147988265e60416b57fc83425a78058853509c1b0629c180094904a5"}, + {file = "cffi-1.15.1-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3b926aa83d1edb5aa5b427b4053dc420ec295a08e40911296b9eb1b6170f6cca"}, + {file = "cffi-1.15.1-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:87c450779d0914f2861b8526e035c5e6da0a3199d8f1add1a665e1cbc6fc6d02"}, + {file = "cffi-1.15.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4f2c9f67e9821cad2e5f480bc8d83b8742896f1242dba247911072d4fa94c192"}, + {file = "cffi-1.15.1-cp38-cp38-win32.whl", hash = "sha256:8b7ee99e510d7b66cdb6c593f21c043c248537a32e0bedf02e01e9553a172314"}, + {file = "cffi-1.15.1-cp38-cp38-win_amd64.whl", hash = "sha256:00a9ed42e88df81ffae7a8ab6d9356b371399b91dbdf0c3cb1e84c03a13aceb5"}, + {file = "cffi-1.15.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:54a2db7b78338edd780e7ef7f9f6c442500fb0d41a5a4ea24fff1c929d5af585"}, + {file = "cffi-1.15.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:fcd131dd944808b5bdb38e6f5b53013c5aa4f334c5cad0c72742f6eba4b73db0"}, + {file = "cffi-1.15.1-cp39-cp39-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7473e861101c9e72452f9bf8acb984947aa1661a7704553a9f6e4baa5ba64415"}, + {file = "cffi-1.15.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6c9a799e985904922a4d207a94eae35c78ebae90e128f0c4e521ce339396be9d"}, + {file = "cffi-1.15.1-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3bcde07039e586f91b45c88f8583ea7cf7a0770df3a1649627bf598332cb6984"}, + {file = "cffi-1.15.1-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:33ab79603146aace82c2427da5ca6e58f2b3f2fb5da893ceac0c42218a40be35"}, + {file = "cffi-1.15.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5d598b938678ebf3c67377cdd45e09d431369c3b1a5b331058c338e201f12b27"}, + {file = "cffi-1.15.1-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:db0fbb9c62743ce59a9ff687eb5f4afbe77e5e8403d6697f7446e5f609976f76"}, + {file = "cffi-1.15.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:98d85c6a2bef81588d9227dde12db8a7f47f639f4a17c9ae08e773aa9c697bf3"}, + {file = "cffi-1.15.1-cp39-cp39-win32.whl", hash = "sha256:40f4774f5a9d4f5e344f31a32b5096977b5d48560c5592e2f3d2c4374bd543ee"}, + {file = "cffi-1.15.1-cp39-cp39-win_amd64.whl", hash = "sha256:70df4e3b545a17496c9b3f41f5115e69a4f2e77e94e1d2a8e1070bc0c38c8a3c"}, + {file = "cffi-1.15.1.tar.gz", hash = "sha256:d400bfb9a37b1351253cb402671cea7e89bdecc294e8016a707f6d1d8ac934f9"}, +] +cfgv = [ + {file = "cfgv-3.3.1-py2.py3-none-any.whl", hash = "sha256:c6a0883f3917a037485059700b9e75da2464e6c27051014ad85ba6aaa5884426"}, + {file = "cfgv-3.3.1.tar.gz", hash = "sha256:f5a830efb9ce7a445376bb66ec94c638a9787422f96264c98edc6bdeed8ab736"}, +] +charset-normalizer = [ + {file = "charset-normalizer-2.1.1.tar.gz", hash = "sha256:5a3d016c7c547f69d6f81fb0db9449ce888b418b5b9952cc5e6e66843e9dd845"}, + {file = "charset_normalizer-2.1.1-py3-none-any.whl", hash = "sha256:83e9a75d1911279afd89352c68b45348559d1fc0506b054b346651b5e7fee29f"}, +] +cleo = [ + {file = "cleo-1.0.0a5-py3-none-any.whl", hash = "sha256:ff53056589300976e960f75afb792dfbfc9c78dcbb5a448e207a17b643826360"}, + {file = "cleo-1.0.0a5.tar.gz", hash = "sha256:097c9d0e0332fd53cc89fc11eb0a6ba0309e6a3933c08f7b38558555486925d3"}, +] +click = [ + {file = "click-8.1.3-py3-none-any.whl", hash = "sha256:bb4d8133cb15a609f44e8213d9b391b0809795062913b383c62be0ee95b1db48"}, + {file = "click-8.1.3.tar.gz", hash = "sha256:7682dc8afb30297001674575ea00d1814d808d6a36af415a82bd481d37ba7b8e"}, +] +cloudpickle = [ + {file = "cloudpickle-2.2.0-py3-none-any.whl", hash = "sha256:7428798d5926d8fcbfd092d18d01a2a03daf8237d8fcdc8095d256b8490796f0"}, + {file = "cloudpickle-2.2.0.tar.gz", hash = "sha256:3f4219469c55453cfe4737e564b67c2a149109dabf7f242478948b895f61106f"}, +] +colorama = [ + {file = "colorama-0.4.5-py2.py3-none-any.whl", hash = "sha256:854bf444933e37f5824ae7bfc1e98d5bce2ebe4160d46b5edf346a89358e99da"}, + {file = "colorama-0.4.5.tar.gz", hash = "sha256:e6c6b4334fc50988a639d9b98aa429a0b57da6e17b9a44f0451f930b6967b7a4"}, +] +coloredlogs = [ + {file = "coloredlogs-15.0.1-py2.py3-none-any.whl", hash = "sha256:612ee75c546f53e92e70049c9dbfcc18c935a2b9a53b66085ce9ef6a6e5c0934"}, + {file = "coloredlogs-15.0.1.tar.gz", hash = "sha256:7c991aa71a4577af2f82600d8f8f3a89f936baeaf9b50a9c197da014e5bf16b0"}, +] +configargparse = [ + {file = "ConfigArgParse-1.5.3-py3-none-any.whl", hash = "sha256:18f6535a2db9f6e02bd5626cc7455eac3e96b9ab3d969d366f9aafd5c5c00fe7"}, + {file = "ConfigArgParse-1.5.3.tar.gz", hash = "sha256:1b0b3cbf664ab59dada57123c81eff3d9737e0d11d8cf79e3d6eb10823f1739f"}, +] +contourpy = [ + {file = "contourpy-1.0.5-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:87121b9428ac568fb84fae4af5e7852fc34f02eadc4e3e91f6c8989327692186"}, + {file = "contourpy-1.0.5-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:1fb782982c42cee667b892a0b0c52a9f6c7ecf1da5c5f4345845f04eaa862f93"}, + {file = "contourpy-1.0.5-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:689d7d2a840619915d0abd1ecc6e399fee202f8ad315acda2807f4ca420d0802"}, + {file = "contourpy-1.0.5-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d88814befbd1433152c5f6dd536905149ba028d795a22555b149ae0a36024d9e"}, + {file = "contourpy-1.0.5-cp310-cp310-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:df65f4b2b4e74977f0336bef12a88051ab24e6a16873cd9249f34d67cb3e345d"}, + {file = "contourpy-1.0.5-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bf6b4c0c723664f65c2a47c8cb6ebbf660b0b2e2d936adf2e8503d4e93359465"}, + {file = "contourpy-1.0.5-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:bcc98d397c3dea45d5b262029564b29cb8e945f2607a38bee6163694c0a8b4ef"}, + {file = "contourpy-1.0.5-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:2bf5c846c257578b03d498b20f54f53551616a507d8e5463511c58bb58e9a9cf"}, + {file = "contourpy-1.0.5-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:cdacddb18d55ffec42d1907079cdc04ec4fa8a990cdf5b9d9fe67d281fc0d12e"}, + {file = "contourpy-1.0.5-cp310-cp310-win32.whl", hash = "sha256:434942fa2f9019b9ae525fb752dc523800c49a1a28fbd6d9240b0fa959573dcc"}, + {file = "contourpy-1.0.5-cp310-cp310-win_amd64.whl", hash = "sha256:3b3082ade8849130203d461b98c2a061b382c46074b43b4edd5cefd81af92b8a"}, + {file = "contourpy-1.0.5-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:057114f698ffb9e54657e8fda6802e2f5c8fad609845cf6afaf31590ef6a33c0"}, + {file = "contourpy-1.0.5-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:218722a29c5c26677d37c44f5f8a372daf6f07870aad793a97d47eb6ad6b3290"}, + {file = "contourpy-1.0.5-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:6c02e22cf09996194bcb3a4784099975cf527d5c29caf759abadf29ebdb2fe27"}, + {file = "contourpy-1.0.5-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c0d5ee865b5fd16bf62d72122aadcc90aab296c30c1adb0a32b4b66bd843163e"}, + {file = "contourpy-1.0.5-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d45822b0a2a452327ab4f95efe368d234d5294bbf89a99968be27c7938a21108"}, + {file = "contourpy-1.0.5-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dca5be83a6dfaf933a46e3bc2b9f2685e5ec61b22f6a38ad740aac9c16e9a0ff"}, + {file = "contourpy-1.0.5-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:3c3f2f6b898a40207843ae01970e57e33d22a26b22f23c6a5e07b4716751085f"}, + {file = "contourpy-1.0.5-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:c2b4eab7c12f9cb460509bc34a3b086f9802f0dba27c89a63df4123819ad64af"}, + {file = "contourpy-1.0.5-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:09ed9b63f4df8a7591b7a4a26c1ad066dcaafda1f846250fdcb534074a411692"}, + {file = "contourpy-1.0.5-cp311-cp311-win32.whl", hash = "sha256:f670686d99c867d0f24b28ce8c6f02429c6eef5e2674aab287850d0ee2d20437"}, + {file = "contourpy-1.0.5-cp311-cp311-win_amd64.whl", hash = "sha256:c51568e94f7f232296de30002f2a50f77a7bd346673da3e4f2aaf9d2b833f2e5"}, + {file = "contourpy-1.0.5-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:7c9e99aac7b430f6a9f15eebf058c742097cea3369f23a2bfc5e64d374b67e3a"}, + {file = "contourpy-1.0.5-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3210d93ad2af742b6a96cf39792f7181822edbb8fe11c3ef29d1583fe637a8d8"}, + {file = "contourpy-1.0.5-cp37-cp37m-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:128bd7acf569f8443ad5b2227f30ac909e4f5399ed221727eeacf0c6476187e6"}, + {file = "contourpy-1.0.5-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:813c2944e940ef8dccea71305bacc942d4b193a021140874b3e58933ec44f5b6"}, + {file = "contourpy-1.0.5-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:a74afd8d560eaafe0d9e3e1db8c06081282a05ca4de00ee416195085a79d7d3d"}, + {file = "contourpy-1.0.5-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:2d0ad9a85f208473b1f3613c45756c7aa6fcc288266a8c7b873f896aaf741b6b"}, + {file = "contourpy-1.0.5-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:60f37acd4e4227c5a29f737d9a85ca3145c529a8dd4bf70af7f0637c61b49222"}, + {file = "contourpy-1.0.5-cp37-cp37m-win32.whl", hash = "sha256:b50e481a4317a8efcfffcfddcd4c9b36eacba440440e70cbe0256aeb6fd6abae"}, + {file = "contourpy-1.0.5-cp37-cp37m-win_amd64.whl", hash = "sha256:0395ae71164bfeb2dedd136e03c71a2718a5aa9873a46f518f4133be0d63e1d2"}, + {file = "contourpy-1.0.5-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:3ca40d7844b391d90b864c6a6d1bb6b88b09035fb4d866d64d43c4d26fb0ab64"}, + {file = "contourpy-1.0.5-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:3109fa601d2a448cec4643abd3a31f972bf05b7c2f2e83df9d3429878f8c10ae"}, + {file = "contourpy-1.0.5-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:06c4d1dde5ee4f909a8a95ba1eb04040c6c26946b4f3b5beaf10d45f14e940ee"}, + {file = "contourpy-1.0.5-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2f54dcc9bb9390fd0636301ead134d46d5229fe86da0db4d974c0fda349f560e"}, + {file = "contourpy-1.0.5-cp38-cp38-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:46b8e24813e2fb5a3e598c1f8b9ae403e1438cb846a80cc2b33cddf19dddd7f2"}, + {file = "contourpy-1.0.5-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:061e1f066c419ffe25b615a1df031b4832ea1d7f2676937e69e8e00e24512005"}, + {file = "contourpy-1.0.5-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:19ea64fa0cf389d2ebc10974616acfa1fdecbd73d1fd9c72215b782f3c40f561"}, + {file = "contourpy-1.0.5-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:dfe924e5a63861c82332a12adeeab955dc8c8009ddbbd80cc2fcca049ff89a49"}, + {file = "contourpy-1.0.5-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:bed3a2a823a041e8d249b1a7ec132933e1505299329b5cfe1b2b5ec689ec7675"}, + {file = "contourpy-1.0.5-cp38-cp38-win32.whl", hash = "sha256:0389349875424aa8c5e61f757e894687916bc4e9616cc6afcbd8051aa2428952"}, + {file = "contourpy-1.0.5-cp38-cp38-win_amd64.whl", hash = "sha256:2b5e334330d82866923015b455260173cb3b9e3b4e297052d758abd262031289"}, + {file = "contourpy-1.0.5-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:def9a01b73c9e27d70ea03b381fb3e7aadfac1f398dbd63751313c3a46747ef5"}, + {file = "contourpy-1.0.5-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:59c827e536bb5e3ef58e06da0faba61fd89a14f30b68bcfeca41f43ca83a1942"}, + {file = "contourpy-1.0.5-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:f05d311c937da03b0cd26ac3e14cb991f6ff8fc94f98b3df9713537817539795"}, + {file = "contourpy-1.0.5-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:970a4be7ec84ccda7c27cb4ae74930bbbd477bc8d849ed55ea798084dd5fca8c"}, + {file = "contourpy-1.0.5-cp39-cp39-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0f7672148f8fca48e4efc16aba24a7455b40c22d4f8abe42475dec6a12b0bb9a"}, + {file = "contourpy-1.0.5-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eba62b7c21a33e72dd8adab2b92dd5610d8527f0b2ac28a8e0770e71b21a13f9"}, + {file = "contourpy-1.0.5-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:dd084459ecdb224e617e4ab3f1d5ebe4d1c48facb41f24952b76aa6ba9712bb0"}, + {file = "contourpy-1.0.5-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:c5158616ab39d34b76c50f40c81552ee180598f7825dc7a66fd187d29958820f"}, + {file = "contourpy-1.0.5-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:f856652f9b533c6cd2b9ad6836a7fc0e43917d7ff15be46c5baf1350f8cdc5d9"}, + {file = "contourpy-1.0.5-cp39-cp39-win32.whl", hash = "sha256:f1cc623fd6855b25da52b3275e0c9e51711b86a9dccc75f8c9ab4432fd8e42c7"}, + {file = "contourpy-1.0.5-cp39-cp39-win_amd64.whl", hash = "sha256:e67dcaa34dcd908fcccbf49194211d847c731b6ebaac661c1c889f1bf6af1e44"}, + {file = "contourpy-1.0.5-pp37-pypy37_pp73-macosx_10_9_x86_64.whl", hash = "sha256:bfd634cb9685161b2a51f73a7fc4736fd0d67a56632d52319317afaa27f08243"}, + {file = "contourpy-1.0.5-pp37-pypy37_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:79908b9d02b1d6c1c71ff3b7ad127f3f82e14a8e091ab44b3c7e34b649fea733"}, + {file = "contourpy-1.0.5-pp37-pypy37_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b4963cf08f4320d98ae72ec7694291b8ab85cb7da3b0cd824bc32701bc992edf"}, + {file = "contourpy-1.0.5-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3cfc067ddde78b76dcbc9684d82688b7d3c5158fa2254a085f9bcb9586c1e2d8"}, + {file = "contourpy-1.0.5-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:9939796abcadb2810a63dfb26ff8ca4595fe7dd70a3ceae7f607a2639b714307"}, + {file = "contourpy-1.0.5-pp38-pypy38_pp73-macosx_10_9_x86_64.whl", hash = "sha256:d8150579bf30cdf896906baf256aa200cd50dbe6e565c17d6fd3d678e21ff5de"}, + {file = "contourpy-1.0.5-pp38-pypy38_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ed9c91bf4ce614efed5388c3f989a7cfe08728ab871d995a486ea74ff88993db"}, + {file = "contourpy-1.0.5-pp38-pypy38_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b46a04588ceb7cf132568e0e564a854627ef87a1ed3bf536234540a79ced44b0"}, + {file = "contourpy-1.0.5-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b85553699862c09937a7a5ea14ee6229087971a7d51ae97d5f4b407f571a2c17"}, + {file = "contourpy-1.0.5-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:99a8071e351b50827ad976b92ed91845fb614ac67a3c41109b24f3d8bd3afada"}, + {file = "contourpy-1.0.5-pp39-pypy39_pp73-macosx_10_9_x86_64.whl", hash = "sha256:fb0458d74726937ead9e2effc91144aea5a58ecee9754242f8539a782bed685a"}, + {file = "contourpy-1.0.5-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0f89f0608a5aa8142ed0e53957916623791a88c7f5e5f07ae530c328beeb888f"}, + {file = "contourpy-1.0.5-pp39-pypy39_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ce763369e646e59e4ca2c09735cd1bdd3048d909ad5f2bc116e83166a9352f3c"}, + {file = "contourpy-1.0.5-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9c16fa267740d67883899e054cccb4279e002f3f4872873b752c1ba15045ff49"}, + {file = "contourpy-1.0.5-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:a30e95274f5c0e007ccc759ec258aa5708c534ec058f153ee25ac700a2f1438b"}, + {file = "contourpy-1.0.5.tar.gz", hash = "sha256:896631cd40222aef3697e4e51177d14c3709fda49d30983269d584f034acc8a4"}, +] +control = [ + {file = "control-0.9.2.tar.gz", hash = "sha256:0891d2d32d6006ac1faa4e238ed8223ca342a4721d202dfeccae24fb02563183"}, +] +coverage = [ + {file = "coverage-6.5.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:ef8674b0ee8cc11e2d574e3e2998aea5df5ab242e012286824ea3c6970580e53"}, + {file = "coverage-6.5.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:784f53ebc9f3fd0e2a3f6a78b2be1bd1f5575d7863e10c6e12504f240fd06660"}, + {file = "coverage-6.5.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b4a5be1748d538a710f87542f22c2cad22f80545a847ad91ce45e77417293eb4"}, + {file = "coverage-6.5.0-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:83516205e254a0cb77d2d7bb3632ee019d93d9f4005de31dca0a8c3667d5bc04"}, + {file = "coverage-6.5.0-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:af4fffaffc4067232253715065e30c5a7ec6faac36f8fc8d6f64263b15f74db0"}, + {file = "coverage-6.5.0-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:97117225cdd992a9c2a5515db1f66b59db634f59d0679ca1fa3fe8da32749cae"}, + {file = "coverage-6.5.0-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:a1170fa54185845505fbfa672f1c1ab175446c887cce8212c44149581cf2d466"}, + {file = "coverage-6.5.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:11b990d520ea75e7ee8dcab5bc908072aaada194a794db9f6d7d5cfd19661e5a"}, + {file = "coverage-6.5.0-cp310-cp310-win32.whl", hash = "sha256:5dbec3b9095749390c09ab7c89d314727f18800060d8d24e87f01fb9cfb40b32"}, + {file = "coverage-6.5.0-cp310-cp310-win_amd64.whl", hash = "sha256:59f53f1dc5b656cafb1badd0feb428c1e7bc19b867479ff72f7a9dd9b479f10e"}, + {file = "coverage-6.5.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:4a5375e28c5191ac38cca59b38edd33ef4cc914732c916f2929029b4bfb50795"}, + {file = "coverage-6.5.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c4ed2820d919351f4167e52425e096af41bfabacb1857186c1ea32ff9983ed75"}, + {file = "coverage-6.5.0-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:33a7da4376d5977fbf0a8ed91c4dffaaa8dbf0ddbf4c8eea500a2486d8bc4d7b"}, + {file = "coverage-6.5.0-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a8fb6cf131ac4070c9c5a3e21de0f7dc5a0fbe8bc77c9456ced896c12fcdad91"}, + {file = "coverage-6.5.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:a6b7d95969b8845250586f269e81e5dfdd8ff828ddeb8567a4a2eaa7313460c4"}, + {file = "coverage-6.5.0-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:1ef221513e6f68b69ee9e159506d583d31aa3567e0ae84eaad9d6ec1107dddaa"}, + {file = "coverage-6.5.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:cca4435eebea7962a52bdb216dec27215d0df64cf27fc1dd538415f5d2b9da6b"}, + {file = "coverage-6.5.0-cp311-cp311-win32.whl", hash = "sha256:98e8a10b7a314f454d9eff4216a9a94d143a7ee65018dd12442e898ee2310578"}, + {file = "coverage-6.5.0-cp311-cp311-win_amd64.whl", hash = "sha256:bc8ef5e043a2af066fa8cbfc6e708d58017024dc4345a1f9757b329a249f041b"}, + {file = "coverage-6.5.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:4433b90fae13f86fafff0b326453dd42fc9a639a0d9e4eec4d366436d1a41b6d"}, + {file = "coverage-6.5.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f4f05d88d9a80ad3cac6244d36dd89a3c00abc16371769f1340101d3cb899fc3"}, + {file = "coverage-6.5.0-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:94e2565443291bd778421856bc975d351738963071e9b8839ca1fc08b42d4bef"}, + {file = "coverage-6.5.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:027018943386e7b942fa832372ebc120155fd970837489896099f5cfa2890f79"}, + {file = "coverage-6.5.0-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:255758a1e3b61db372ec2736c8e2a1fdfaf563977eedbdf131de003ca5779b7d"}, + {file = "coverage-6.5.0-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:851cf4ff24062c6aec510a454b2584f6e998cada52d4cb58c5e233d07172e50c"}, + {file = "coverage-6.5.0-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:12adf310e4aafddc58afdb04d686795f33f4d7a6fa67a7a9d4ce7d6ae24d949f"}, + {file = "coverage-6.5.0-cp37-cp37m-win32.whl", hash = "sha256:b5604380f3415ba69de87a289a2b56687faa4fe04dbee0754bfcae433489316b"}, + {file = "coverage-6.5.0-cp37-cp37m-win_amd64.whl", hash = "sha256:4a8dbc1f0fbb2ae3de73eb0bdbb914180c7abfbf258e90b311dcd4f585d44bd2"}, + {file = "coverage-6.5.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:d900bb429fdfd7f511f868cedd03a6bbb142f3f9118c09b99ef8dc9bf9643c3c"}, + {file = "coverage-6.5.0-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:2198ea6fc548de52adc826f62cb18554caedfb1d26548c1b7c88d8f7faa8f6ba"}, + {file = "coverage-6.5.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6c4459b3de97b75e3bd6b7d4b7f0db13f17f504f3d13e2a7c623786289dd670e"}, + {file = "coverage-6.5.0-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:20c8ac5386253717e5ccc827caad43ed66fea0efe255727b1053a8154d952398"}, + {file = "coverage-6.5.0-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6b07130585d54fe8dff3d97b93b0e20290de974dc8177c320aeaf23459219c0b"}, + {file = "coverage-6.5.0-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:dbdb91cd8c048c2b09eb17713b0c12a54fbd587d79adcebad543bc0cd9a3410b"}, + {file = "coverage-6.5.0-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:de3001a203182842a4630e7b8d1a2c7c07ec1b45d3084a83d5d227a3806f530f"}, + {file = "coverage-6.5.0-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:e07f4a4a9b41583d6eabec04f8b68076ab3cd44c20bd29332c6572dda36f372e"}, + {file = "coverage-6.5.0-cp38-cp38-win32.whl", hash = "sha256:6d4817234349a80dbf03640cec6109cd90cba068330703fa65ddf56b60223a6d"}, + {file = "coverage-6.5.0-cp38-cp38-win_amd64.whl", hash = "sha256:7ccf362abd726b0410bf8911c31fbf97f09f8f1061f8c1cf03dfc4b6372848f6"}, + {file = "coverage-6.5.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:633713d70ad6bfc49b34ead4060531658dc6dfc9b3eb7d8a716d5873377ab745"}, + {file = "coverage-6.5.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:95203854f974e07af96358c0b261f1048d8e1083f2de9b1c565e1be4a3a48cfc"}, + {file = "coverage-6.5.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b9023e237f4c02ff739581ef35969c3739445fb059b060ca51771e69101efffe"}, + {file = "coverage-6.5.0-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:265de0fa6778d07de30bcf4d9dc471c3dc4314a23a3c6603d356a3c9abc2dfcf"}, + {file = "coverage-6.5.0-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8f830ed581b45b82451a40faabb89c84e1a998124ee4212d440e9c6cf70083e5"}, + {file = "coverage-6.5.0-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:7b6be138d61e458e18d8e6ddcddd36dd96215edfe5f1168de0b1b32635839b62"}, + {file = "coverage-6.5.0-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:42eafe6778551cf006a7c43153af1211c3aaab658d4d66fa5fcc021613d02518"}, + {file = "coverage-6.5.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:723e8130d4ecc8f56e9a611e73b31219595baa3bb252d539206f7bbbab6ffc1f"}, + {file = "coverage-6.5.0-cp39-cp39-win32.whl", hash = "sha256:d9ecf0829c6a62b9b573c7bb6d4dcd6ba8b6f80be9ba4fc7ed50bf4ac9aecd72"}, + {file = "coverage-6.5.0-cp39-cp39-win_amd64.whl", hash = "sha256:fc2af30ed0d5ae0b1abdb4ebdce598eafd5b35397d4d75deb341a614d333d987"}, + {file = "coverage-6.5.0-pp36.pp37.pp38-none-any.whl", hash = "sha256:1431986dac3923c5945271f169f59c45b8802a114c8f548d611f2015133df77a"}, + {file = "coverage-6.5.0.tar.gz", hash = "sha256:f642e90754ee3e06b0e7e51bce3379590e76b7f76b708e1a71ff043f87025c84"}, +] +crashtest = [ + {file = "crashtest-0.3.1-py3-none-any.whl", hash = "sha256:300f4b0825f57688b47b6d70c6a31de33512eb2fa1ac614f780939aa0cf91680"}, + {file = "crashtest-0.3.1.tar.gz", hash = "sha256:42ca7b6ce88b6c7433e2ce47ea884e91ec93104a4b754998be498a8e6c3d37dd"}, +] +crcmod = [ + {file = "crcmod-1.7.tar.gz", hash = "sha256:dc7051a0db5f2bd48665a990d3ec1cc305a466a77358ca4492826f41f283601e"}, +] +cryptography = [ + {file = "cryptography-37.0.4-cp36-abi3-macosx_10_10_universal2.whl", hash = "sha256:549153378611c0cca1042f20fd9c5030d37a72f634c9326e225c9f666d472884"}, + {file = "cryptography-37.0.4-cp36-abi3-macosx_10_10_x86_64.whl", hash = "sha256:a958c52505c8adf0d3822703078580d2c0456dd1d27fabfb6f76fe63d2971cd6"}, + {file = "cryptography-37.0.4-cp36-abi3-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:f721d1885ecae9078c3f6bbe8a88bc0786b6e749bf32ccec1ef2b18929a05046"}, + {file = "cryptography-37.0.4-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:3d41b965b3380f10e4611dbae366f6dc3cefc7c9ac4e8842a806b9672ae9add5"}, + {file = "cryptography-37.0.4-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:80f49023dd13ba35f7c34072fa17f604d2f19bf0989f292cedf7ab5770b87a0b"}, + {file = "cryptography-37.0.4-cp36-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f2dcb0b3b63afb6df7fd94ec6fbddac81b5492513f7b0436210d390c14d46ee8"}, + {file = "cryptography-37.0.4-cp36-abi3-manylinux_2_24_x86_64.whl", hash = "sha256:b7f8dd0d4c1f21759695c05a5ec8536c12f31611541f8904083f3dc582604280"}, + {file = "cryptography-37.0.4-cp36-abi3-musllinux_1_1_aarch64.whl", hash = "sha256:30788e070800fec9bbcf9faa71ea6d8068f5136f60029759fd8c3efec3c9dcb3"}, + {file = "cryptography-37.0.4-cp36-abi3-musllinux_1_1_x86_64.whl", hash = "sha256:190f82f3e87033821828f60787cfa42bff98404483577b591429ed99bed39d59"}, + {file = "cryptography-37.0.4-cp36-abi3-win32.whl", hash = "sha256:b62439d7cd1222f3da897e9a9fe53bbf5c104fff4d60893ad1355d4c14a24157"}, + {file = "cryptography-37.0.4-cp36-abi3-win_amd64.whl", hash = "sha256:f7a6de3e98771e183645181b3627e2563dcde3ce94a9e42a3f427d2255190327"}, + {file = "cryptography-37.0.4-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6bc95ed67b6741b2607298f9ea4932ff157e570ef456ef7ff0ef4884a134cc4b"}, + {file = "cryptography-37.0.4-pp37-pypy37_pp73-manylinux_2_24_x86_64.whl", hash = "sha256:f8c0a6e9e1dd3eb0414ba320f85da6b0dcbd543126e30fcc546e7372a7fbf3b9"}, + {file = "cryptography-37.0.4-pp38-pypy38_pp73-macosx_10_10_x86_64.whl", hash = "sha256:e007f052ed10cc316df59bc90fbb7ff7950d7e2919c9757fd42a2b8ecf8a5f67"}, + {file = "cryptography-37.0.4-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7bc997818309f56c0038a33b8da5c0bfbb3f1f067f315f9abd6fc07ad359398d"}, + {file = "cryptography-37.0.4-pp38-pypy38_pp73-manylinux_2_24_x86_64.whl", hash = "sha256:d204833f3c8a33bbe11eda63a54b1aad7aa7456ed769a982f21ec599ba5fa282"}, + {file = "cryptography-37.0.4-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:75976c217f10d48a8b5a8de3d70c454c249e4b91851f6838a4e48b8f41eb71aa"}, + {file = "cryptography-37.0.4-pp39-pypy39_pp73-macosx_10_10_x86_64.whl", hash = "sha256:7099a8d55cd49b737ffc99c17de504f2257e3787e02abe6d1a6d136574873441"}, + {file = "cryptography-37.0.4-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2be53f9f5505673eeda5f2736bea736c40f051a739bfae2f92d18aed1eb54596"}, + {file = "cryptography-37.0.4-pp39-pypy39_pp73-manylinux_2_24_x86_64.whl", hash = "sha256:91ce48d35f4e3d3f1d83e29ef4a9267246e6a3be51864a5b7d2247d5086fa99a"}, + {file = "cryptography-37.0.4-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:4c590ec31550a724ef893c50f9a97a0c14e9c851c85621c5650d699a7b88f7ab"}, + {file = "cryptography-37.0.4.tar.gz", hash = "sha256:63f9c17c0e2474ccbebc9302ce2f07b55b3b3fcb211ded18a42d5764f5c10a82"}, +] +cupy-cuda113 = [ + {file = "cupy_cuda113-10.6.0-cp310-cp310-manylinux1_x86_64.whl", hash = "sha256:27e5efe2c3afa80ff48654cb27f9e0eddb36f8b26ef0d32d3ba0a233e1359b51"}, + {file = "cupy_cuda113-10.6.0-cp310-cp310-win_amd64.whl", hash = "sha256:8b96076d1ddd33fdb2c908ed0f8109caf69d37d36f839a8a8cdae1312508336f"}, + {file = "cupy_cuda113-10.6.0-cp37-cp37m-manylinux1_x86_64.whl", hash = "sha256:22363c2863727cae5154aa4bab9e8a648d7fe66c9e2195d81dd4e8693c2e61ce"}, + {file = "cupy_cuda113-10.6.0-cp37-cp37m-win_amd64.whl", hash = "sha256:8cc69b9d5735372477a7af3822c8f8e996ffe6de05cfc917500af9dc0117ca3e"}, + {file = "cupy_cuda113-10.6.0-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:10dc6899577e445426d81f0960ba9059d9aaa750426997c61fad882d6345264c"}, + {file = "cupy_cuda113-10.6.0-cp38-cp38-win_amd64.whl", hash = "sha256:c6893ac9040a11610e63973063dfd715dbda8bd07ef99951bab7a09c7f335e1e"}, + {file = "cupy_cuda113-10.6.0-cp39-cp39-manylinux1_x86_64.whl", hash = "sha256:4bf4bc06d991c06b95f6fe558d117cafd93bd4eeaf80606f18dd31d20d2eff25"}, + {file = "cupy_cuda113-10.6.0-cp39-cp39-win_amd64.whl", hash = "sha256:3745fc42dca86ba8a1109ddc7964aed8e1efc0ce8085cb2f140dcd6429f26354"}, +] +cycler = [ + {file = "cycler-0.11.0-py3-none-any.whl", hash = "sha256:3a27e95f763a428a739d2add979fa7494c912a32c17c4c38c4d5f082cad165a3"}, + {file = "cycler-0.11.0.tar.gz", hash = "sha256:9c87405839a19696e837b3b818fed3f5f69f16f1eec1a1ad77e043dcea9c772f"}, +] +cython = [ + {file = "Cython-0.29.32-cp27-cp27m-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:39afb4679b8c6bf7ccb15b24025568f4f9b4d7f9bf3cbd981021f542acecd75b"}, + {file = "Cython-0.29.32-cp27-cp27m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:dbee03b8d42dca924e6aa057b836a064c769ddfd2a4c2919e65da2c8a362d528"}, + {file = "Cython-0.29.32-cp27-cp27mu-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:5ba622326f2862f9c1f99ca8d47ade49871241920a352c917e16861e25b0e5c3"}, + {file = "Cython-0.29.32-cp27-cp27mu-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:e6ffa08aa1c111a1ebcbd1cf4afaaec120bc0bbdec3f2545f8bb7d3e8e77a1cd"}, + {file = "Cython-0.29.32-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:97335b2cd4acebf30d14e2855d882de83ad838491a09be2011745579ac975833"}, + {file = "Cython-0.29.32-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:06be83490c906b6429b4389e13487a26254ccaad2eef6f3d4ee21d8d3a4aaa2b"}, + {file = "Cython-0.29.32-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_24_i686.whl", hash = "sha256:eefd2b9a5f38ded8d859fe96cc28d7d06e098dc3f677e7adbafda4dcdd4a461c"}, + {file = "Cython-0.29.32-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:5514f3b4122cb22317122a48e175a7194e18e1803ca555c4c959d7dfe68eaf98"}, + {file = "Cython-0.29.32-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:656dc5ff1d269de4d11ee8542f2ffd15ab466c447c1f10e5b8aba6f561967276"}, + {file = "Cython-0.29.32-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:cdf10af3e2e3279dc09fdc5f95deaa624850a53913f30350ceee824dc14fc1a6"}, + {file = "Cython-0.29.32-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_24_i686.whl", hash = "sha256:3875c2b2ea752816a4d7ae59d45bb546e7c4c79093c83e3ba7f4d9051dd02928"}, + {file = "Cython-0.29.32-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:79e3bab19cf1b021b613567c22eb18b76c0c547b9bc3903881a07bfd9e7e64cf"}, + {file = "Cython-0.29.32-cp35-cp35m-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:b0595aee62809ba353cebc5c7978e0e443760c3e882e2c7672c73ffe46383673"}, + {file = "Cython-0.29.32-cp35-cp35m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:0ea8267fc373a2c5064ad77d8ff7bf0ea8b88f7407098ff51829381f8ec1d5d9"}, + {file = "Cython-0.29.32-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:c8e8025f496b5acb6ba95da2fb3e9dacffc97d9a92711aacfdd42f9c5927e094"}, + {file = "Cython-0.29.32-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:afbce249133a830f121b917f8c9404a44f2950e0e4f5d1e68f043da4c2e9f457"}, + {file = "Cython-0.29.32-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_24_i686.whl", hash = "sha256:513e9707407608ac0d306c8b09d55a28be23ea4152cbd356ceaec0f32ef08d65"}, + {file = "Cython-0.29.32-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:e83228e0994497900af954adcac27f64c9a57cd70a9ec768ab0cb2c01fd15cf1"}, + {file = "Cython-0.29.32-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:ea1dcc07bfb37367b639415333cfbfe4a93c3be340edf1db10964bc27d42ed64"}, + {file = "Cython-0.29.32-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:8669cadeb26d9a58a5e6b8ce34d2c8986cc3b5c0bfa77eda6ceb471596cb2ec3"}, + {file = "Cython-0.29.32-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:ed087eeb88a8cf96c60fb76c5c3b5fb87188adee5e179f89ec9ad9a43c0c54b3"}, + {file = "Cython-0.29.32-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:3f85eb2343d20d91a4ea9cf14e5748092b376a64b7e07fc224e85b2753e9070b"}, + {file = "Cython-0.29.32-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_24_i686.whl", hash = "sha256:63b79d9e1f7c4d1f498ab1322156a0d7dc1b6004bf981a8abda3f66800e140cd"}, + {file = "Cython-0.29.32-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:e1958e0227a4a6a2c06fd6e35b7469de50adf174102454db397cec6e1403cce3"}, + {file = "Cython-0.29.32-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:856d2fec682b3f31583719cb6925c6cdbb9aa30f03122bcc45c65c8b6f515754"}, + {file = "Cython-0.29.32-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:479690d2892ca56d34812fe6ab8f58e4b2e0129140f3d94518f15993c40553da"}, + {file = "Cython-0.29.32-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:67fdd2f652f8d4840042e2d2d91e15636ba2bcdcd92e7e5ffbc68e6ef633a754"}, + {file = "Cython-0.29.32-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:4a4b03ab483271f69221c3210f7cde0dcc456749ecf8243b95bc7a701e5677e0"}, + {file = "Cython-0.29.32-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_24_i686.whl", hash = "sha256:40eff7aa26e91cf108fd740ffd4daf49f39b2fdffadabc7292b4b7dc5df879f0"}, + {file = "Cython-0.29.32-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:0bbc27abdf6aebfa1bce34cd92bd403070356f28b0ecb3198ff8a182791d58b9"}, + {file = "Cython-0.29.32-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:cddc47ec746a08603037731f5d10aebf770ced08666100bd2cdcaf06a85d4d1b"}, + {file = "Cython-0.29.32-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:eca3065a1279456e81c615211d025ea11bfe4e19f0c5650b859868ca04b3fcbd"}, + {file = "Cython-0.29.32-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:d968ffc403d92addf20b68924d95428d523436adfd25cf505d427ed7ba3bee8b"}, + {file = "Cython-0.29.32-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:f3fd44cc362eee8ae569025f070d56208908916794b6ab21e139cea56470a2b3"}, + {file = "Cython-0.29.32-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_24_i686.whl", hash = "sha256:b6da3063c5c476f5311fd76854abae6c315f1513ef7d7904deed2e774623bbb9"}, + {file = "Cython-0.29.32-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:061e25151c38f2361bc790d3bcf7f9d9828a0b6a4d5afa56fbed3bd33fb2373a"}, + {file = "Cython-0.29.32-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:f9944013588a3543fca795fffb0a070a31a243aa4f2d212f118aa95e69485831"}, + {file = "Cython-0.29.32-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:07d173d3289415bb496e72cb0ddd609961be08fe2968c39094d5712ffb78672b"}, + {file = "Cython-0.29.32-py2.py3-none-any.whl", hash = "sha256:eeb475eb6f0ccf6c039035eb4f0f928eb53ead88777e0a760eccb140ad90930b"}, + {file = "Cython-0.29.32.tar.gz", hash = "sha256:8733cf4758b79304f2a4e39ebfac5e92341bce47bcceb26c1254398b2f8c1af7"}, +] +datadog = [ + {file = "datadog-0.44.0-py2.py3-none-any.whl", hash = "sha256:57c4878d3a8351f652792cdba78050274789dcc44313adec096e87f9d3ca5992"}, + {file = "datadog-0.44.0.tar.gz", hash = "sha256:071170f0c7ef22511dbf7f9bd76c4be500ee2d3d52072900a5c87b5495d2c733"}, +] +debugpy = [ + {file = "debugpy-1.6.3-cp310-cp310-macosx_10_15_x86_64.whl", hash = "sha256:c4b2bd5c245eeb49824bf7e539f95fb17f9a756186e51c3e513e32999d8846f3"}, + {file = "debugpy-1.6.3-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:b8deaeb779699350deeed835322730a3efec170b88927debc9ba07a1a38e2585"}, + {file = "debugpy-1.6.3-cp310-cp310-win32.whl", hash = "sha256:fc233a0160f3b117b20216f1169e7211b83235e3cd6749bcdd8dbb72177030c7"}, + {file = "debugpy-1.6.3-cp310-cp310-win_amd64.whl", hash = "sha256:dda8652520eae3945833e061cbe2993ad94a0b545aebd62e4e6b80ee616c76b2"}, + {file = "debugpy-1.6.3-cp37-cp37m-macosx_10_15_x86_64.whl", hash = "sha256:d5c814596a170a0a58fa6fad74947e30bfd7e192a5d2d7bd6a12156c2899e13a"}, + {file = "debugpy-1.6.3-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:c4cd6f37e3c168080d61d698390dfe2cd9e74ebf80b448069822a15dadcda57d"}, + {file = "debugpy-1.6.3-cp37-cp37m-win32.whl", hash = "sha256:3c9f985944a30cfc9ae4306ac6a27b9c31dba72ca943214dad4a0ab3840f6161"}, + {file = "debugpy-1.6.3-cp37-cp37m-win_amd64.whl", hash = "sha256:5ad571a36cec137ae6ed951d0ff75b5e092e9af6683da084753231150cbc5b25"}, + {file = "debugpy-1.6.3-cp38-cp38-macosx_10_15_x86_64.whl", hash = "sha256:adcfea5ea06d55d505375995e150c06445e2b20cd12885bcae566148c076636b"}, + {file = "debugpy-1.6.3-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:daadab4403427abd090eccb38d8901afd8b393e01fd243048fab3f1d7132abb4"}, + {file = "debugpy-1.6.3-cp38-cp38-win32.whl", hash = "sha256:6efc30325b68e451118b795eff6fe8488253ca3958251d5158106d9c87581bc6"}, + {file = "debugpy-1.6.3-cp38-cp38-win_amd64.whl", hash = "sha256:86d784b72c5411c833af1cd45b83d80c252b77c3bfdb43db17c441d772f4c734"}, + {file = "debugpy-1.6.3-cp39-cp39-macosx_10_15_x86_64.whl", hash = "sha256:4e255982552b0edfe3a6264438dbd62d404baa6556a81a88f9420d3ed79b06ae"}, + {file = "debugpy-1.6.3-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:cca23cb6161ac89698d629d892520327dd1be9321c0960e610bbcb807232b45d"}, + {file = "debugpy-1.6.3-cp39-cp39-win32.whl", hash = "sha256:7c302095a81be0d5c19f6529b600bac971440db3e226dce85347cc27e6a61908"}, + {file = "debugpy-1.6.3-cp39-cp39-win_amd64.whl", hash = "sha256:34d2cdd3a7c87302ba5322b86e79c32c2115be396f3f09ca13306d8a04fe0f16"}, + {file = "debugpy-1.6.3-py2.py3-none-any.whl", hash = "sha256:84c39940a0cac410bf6aa4db00ba174f973eef521fbe9dd058e26bcabad89c4f"}, + {file = "debugpy-1.6.3.zip", hash = "sha256:e8922090514a890eec99cfb991bab872dd2e353ebb793164d5f01c362b9a40bf"}, +] +decorator = [ + {file = "decorator-5.1.1-py3-none-any.whl", hash = "sha256:b8c3f85900b9dc423225913c5aace94729fe1fa9763b38939a95226f02d37186"}, + {file = "decorator-5.1.1.tar.gz", hash = "sha256:637996211036b6385ef91435e4fae22989472f9d571faba8927ba8253acbc330"}, +] +defusedxml = [ + {file = "defusedxml-0.7.1-py2.py3-none-any.whl", hash = "sha256:a352e7e428770286cc899e2542b6cdaedb2b4953ff269a210103ec58f6198a61"}, + {file = "defusedxml-0.7.1.tar.gz", hash = "sha256:1bb3032db185915b62d7c6209c5a8792be6a32ab2fedacc84e01b52c51aa3e69"}, +] +deprecated = [ + {file = "Deprecated-1.2.13-py2.py3-none-any.whl", hash = "sha256:64756e3e14c8c5eea9795d93c524551432a0be75629f8f29e67ab8caf076c76d"}, + {file = "Deprecated-1.2.13.tar.gz", hash = "sha256:43ac5335da90c31c24ba028af536a91d41d53f9e6901ddb021bcc572ce44e38d"}, +] +dictdiffer = [ + {file = "dictdiffer-0.9.0-py2.py3-none-any.whl", hash = "sha256:442bfc693cfcadaf46674575d2eba1c53b42f5e404218ca2c2ff549f2df56595"}, + {file = "dictdiffer-0.9.0.tar.gz", hash = "sha256:17bacf5fbfe613ccf1b6d512bd766e6b21fb798822a133aa86098b8ac9997578"}, +] +dill = [ + {file = "dill-0.3.5.1-py2.py3-none-any.whl", hash = "sha256:33501d03270bbe410c72639b350e941882a8b0fd55357580fbc873fba0c59302"}, + {file = "dill-0.3.5.1.tar.gz", hash = "sha256:d75e41f3eff1eee599d738e76ba8f4ad98ea229db8b085318aa2b3333a208c86"}, +] +distlib = [ + {file = "distlib-0.3.6-py2.py3-none-any.whl", hash = "sha256:f35c4b692542ca110de7ef0bea44d73981caeb34ca0b9b6b2e6d7790dda8f80e"}, + {file = "distlib-0.3.6.tar.gz", hash = "sha256:14bad2d9b04d3a36127ac97f30b12a19268f211063d8f8ee4f47108896e11b46"}, +] +docutils = [ + {file = "docutils-0.17.1-py2.py3-none-any.whl", hash = "sha256:cf316c8370a737a022b72b56874f6602acf974a37a9fba42ec2876387549fc61"}, + {file = "docutils-0.17.1.tar.gz", hash = "sha256:686577d2e4c32380bb50cbb22f575ed742d58168cee37e99117a854bcd88f125"}, +] +dotmap = [ + {file = "dotmap-1.3.30-py3-none-any.whl", hash = "sha256:bd9fa15286ea2ad899a4d1dc2445ed85a1ae884a42effb87c89a6ecce71243c6"}, + {file = "dotmap-1.3.30.tar.gz", hash = "sha256:5821a7933f075fb47563417c0e92e0b7c031158b4c9a6a7e56163479b658b368"}, +] +dulwich = [ + {file = "dulwich-0.20.46-cp310-cp310-macosx_10_15_x86_64.whl", hash = "sha256:6676196e9cf377cde62aa2f5d741e93207437343e0c62368bd0d784c322a3c49"}, + {file = "dulwich-0.20.46-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0a1ca555a3eafe7388d6cb81bb08f34608a1592500f0bd4c26734c91d208a546"}, + {file = "dulwich-0.20.46-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:769442c9657b10fc35ac625beeaf440540c9288c96fcfaba3e58adf745c5cafd"}, + {file = "dulwich-0.20.46-cp310-cp310-win32.whl", hash = "sha256:de22a54f68c6c4e97f9b924abd46da4618536d7934b9849066be9fc5cd31205d"}, + {file = "dulwich-0.20.46-cp310-cp310-win_amd64.whl", hash = "sha256:42fa5a68908556eb6c40f231a67caf6a4660588aad707a9d6b334fa1d8f04bf7"}, + {file = "dulwich-0.20.46-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:3e16376031466848e44aabf3489fafb054482143744b21167dbd168731041c74"}, + {file = "dulwich-0.20.46-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:153c7512587384a290c60fef330f1ab397a59559e19e8b02a0169ff21b4c69fb"}, + {file = "dulwich-0.20.46-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a5b68bd815cd2769c75e5a78708eb0440612df19b370a977aa9e01a056baa9ed"}, + {file = "dulwich-0.20.46-cp311-cp311-win32.whl", hash = "sha256:b1339bca70764eb8e780d80c72e7c1cb4651201dc9e43ec5d616bf51eb3bb3a6"}, + {file = "dulwich-0.20.46-cp311-cp311-win_amd64.whl", hash = "sha256:1162fdafb2abdfe66649617061f3853cb26384fade1f6884f6fe6e9c570a7552"}, + {file = "dulwich-0.20.46-cp36-cp36m-macosx_10_14_x86_64.whl", hash = "sha256:6826512f778eaa47e2e8c0a46cdc555958f9f5286771490b8642b4b508ea5d25"}, + {file = "dulwich-0.20.46-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:100d39bc18196a07c521fd5f60f78f397493303daa0b8690216864bbc621cd5d"}, + {file = "dulwich-0.20.46-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c4cd2cd7baa81246bdc8c5272d4e9224e2255da7a0618a220aab5e07b9888e9b"}, + {file = "dulwich-0.20.46-cp36-cp36m-win32.whl", hash = "sha256:6eed5a3194d64112605fc0f638f4fa91771495e8674fa3e6d6b33bf150d297d5"}, + {file = "dulwich-0.20.46-cp36-cp36m-win_amd64.whl", hash = "sha256:9ca4d73987f5b0e2e843497876f9bb39a47384a2e50597a85542285f5c890293"}, + {file = "dulwich-0.20.46-cp37-cp37m-macosx_10_15_x86_64.whl", hash = "sha256:b9f49de83911eed7adbe83136229837ef9d102e42dbe6aacb1a18be45c997ace"}, + {file = "dulwich-0.20.46-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d38be7d3a78d608ecab3348f7920d6b9002e7972dd245206dc8075cfdb91621d"}, + {file = "dulwich-0.20.46-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f4b7a7feb966a4669c254b18385fe0b3c639f3b1f5ddef0d9e083364cc762847"}, + {file = "dulwich-0.20.46-cp37-cp37m-win32.whl", hash = "sha256:f9552ac246bceab1c5cdd1ec3cfe9446fe76b9853eaf59d3244df03eb27fd3fe"}, + {file = "dulwich-0.20.46-cp37-cp37m-win_amd64.whl", hash = "sha256:90a075aeb0fdbad7e18b9db3af161e3d635e2b7697b7a4b467e6844a13b0b210"}, + {file = "dulwich-0.20.46-cp38-cp38-macosx_10_15_x86_64.whl", hash = "sha256:8d6fee82cedb2362942d9ef94061901f7e07d7d8674e4c7b6fceeef7822ae275"}, + {file = "dulwich-0.20.46-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:669c6b3d82996518a7fec4604771bd285e23f0860f41f565fef5987265d431d9"}, + {file = "dulwich-0.20.46-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dd3eac228117487a959ac8f49ea2787eac34acc69999fe7adae70b23e3c3571c"}, + {file = "dulwich-0.20.46-cp38-cp38-win32.whl", hash = "sha256:92024f572d32680e021219f77015c8b443c38022e502b7f51ad7cf51a6285a36"}, + {file = "dulwich-0.20.46-cp38-cp38-win_amd64.whl", hash = "sha256:d928de1eba0326a2a8a52ed94c9bf7c315ff4db606a1aa3ae688d39574f93267"}, + {file = "dulwich-0.20.46-cp39-cp39-macosx_10_15_x86_64.whl", hash = "sha256:a5d1b7a3a7d84a5dedbb90092e00097357106b9642ac08a96c2ae89ccd8afd9a"}, + {file = "dulwich-0.20.46-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b739d759c10e2af7c964dcc97fd4e5dc49e8567d080eed8906fc422c79b7fdcf"}, + {file = "dulwich-0.20.46-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9fc7a4f633f5468453d5dd84a753cd99d4433f0397437229a0a8b10347935591"}, + {file = "dulwich-0.20.46-cp39-cp39-win32.whl", hash = "sha256:525115c4d1fbf60a5fe98f340b4ca597ba47b2c75d9c5ec750dd0e9115ef8ec6"}, + {file = "dulwich-0.20.46-cp39-cp39-win_amd64.whl", hash = "sha256:73e2585a9fcf1f8cdad8597a0c384c0b365b2e8346463130c96d9ea1478587ae"}, + {file = "dulwich-0.20.46.tar.gz", hash = "sha256:4f0e88ffff5db1523d93d92f1525fe5fa161318ffbaad502c1b9b3be7a067172"}, +] +efficientnet-pytorch = [ + {file = "efficientnet_pytorch-0.6.3.tar.gz", hash = "sha256:6667459336893e9bf6367de3788ba449fed97f65da3b6782bf2204b6273a319f"}, +] +einops = [ + {file = "einops-0.5.0-py3-none-any.whl", hash = "sha256:055de7eeb3cb9e9710ef3085a811090c6b52e809b7044e8785824ed185f486d1"}, + {file = "einops-0.5.0.tar.gz", hash = "sha256:8b7a83cffc1ea88e306df099b7cbb9c3ba5003bd84d05ae44be5655864abb8d3"}, +] +elastic-transport = [ + {file = "elastic-transport-8.4.0.tar.gz", hash = "sha256:b9ad708ceb7fcdbc6b30a96f886609a109f042c0b9d9f2e44403b3133ba7ff10"}, + {file = "elastic_transport-8.4.0-py3-none-any.whl", hash = "sha256:19db271ab79c9f70f8c43f8f5b5111408781a6176b54ab2e54d713b6d9ceb815"}, +] +elasticsearch = [ + {file = "elasticsearch-8.4.3-py3-none-any.whl", hash = "sha256:14c68a96b7bbbf150dd9fca5ff65da9c50e791c0fdba474a328e43828fdd7f42"}, + {file = "elasticsearch-8.4.3.tar.gz", hash = "sha256:d34d43a6c349d15c9d91840f791eeba80fc50ee070caf6695130f56b7f41a02d"}, +] +entrypoints = [ + {file = "entrypoints-0.4-py3-none-any.whl", hash = "sha256:f174b5ff827504fd3cd97cc3f8649f3693f51538c7e4bdf3ef002c8429d42f9f"}, + {file = "entrypoints-0.4.tar.gz", hash = "sha256:b706eddaa9218a19ebcd67b56818f05bb27589b1ca9e8d797b74affad4ccacd4"}, +] +execnet = [ + {file = "execnet-1.9.0-py2.py3-none-any.whl", hash = "sha256:a295f7cc774947aac58dde7fdc85f4aa00c42adf5d8f5468fc630c1acf30a142"}, + {file = "execnet-1.9.0.tar.gz", hash = "sha256:8f694f3ba9cc92cab508b152dcfe322153975c29bda272e2fd7f3f00f36e47c5"}, +] +executing = [ + {file = "executing-1.1.1-py2.py3-none-any.whl", hash = "sha256:236ea5f059a38781714a8bfba46a70fad3479c2f552abee3bbafadc57ed111b8"}, + {file = "executing-1.1.1.tar.gz", hash = "sha256:b0d7f8dcc2bac47ce6e39374397e7acecea6fdc380a6d5323e26185d70f38ea8"}, +] +fastcluster = [ + {file = "fastcluster-1.2.6-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:d0e8faef0437a25fd083df70fb86cc65ce3c9c9780d4ae377cbe6521e7746ce0"}, + {file = "fastcluster-1.2.6-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:c8be01f97bc2bf11a9188537864f8e520e1103cdc6007aa2c5d7979b1363b121"}, + {file = "fastcluster-1.2.6-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:855ab2b7e6fa9b05f19c4f3023dedfb1a35a88d831933d65d0d9e10a070a9e85"}, + {file = "fastcluster-1.2.6-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:72503e727887a61a15f9aaa13178798d3994dfec58aa7a943e42dcfda07c0149"}, + {file = "fastcluster-1.2.6-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:2fcb0973ca0e6978e3242046338c350cbed1493108929231fae9bd35ad05a6d6"}, + {file = "fastcluster-1.2.6-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9020899b67fe492d0ed87a3e993ec9962c5a0b51ea2df71d86b1766f065f1cef"}, + {file = "fastcluster-1.2.6-cp310-cp310-win32.whl", hash = "sha256:6cf156d4203708348522393c523c2e61c81f5a6a500e0411dcba2b064551ea2f"}, + {file = "fastcluster-1.2.6-cp310-cp310-win_amd64.whl", hash = "sha256:1801c9daa9aa5bbbb0830efe8bd3034b4b7a417e4b8dd353683999be29797df2"}, + {file = "fastcluster-1.2.6-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:cf5acfe1156849279ebd44a8d1fbcbe8b8e21334f7538eda782ae31e7dade9e2"}, + {file = "fastcluster-1.2.6-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cb27c13225f5f77f3c5986a27ca27277cce7db12844330cf535019cd38021257"}, + {file = "fastcluster-1.2.6-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5fe543b6d45da27e84e5af6248722475b88943d8ef40d835cbabbb0ba5ee786b"}, + {file = "fastcluster-1.2.6-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c12224da0b1f2f9d2b3d715dc82ecb1a3a33b990606f97da075cc46bc6d9576f"}, + {file = "fastcluster-1.2.6-cp36-cp36m-win32.whl", hash = "sha256:86a1ad972e83ba48144884fa849f87626346308b650002157123aee67d3b16fe"}, + {file = "fastcluster-1.2.6-cp36-cp36m-win_amd64.whl", hash = "sha256:8d3c9eab8e69cb36dcdd64c8b3200e008aedf88e34d39e01ae6af98a9605ad18"}, + {file = "fastcluster-1.2.6-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:c61be0bad81a21ee3e5bef91469fdd11968f33d41d142c656accba9b2992babe"}, + {file = "fastcluster-1.2.6-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:06df1d97edca68b2ffa43d81c3b5f4e4147bc12ab241c6585fadcdeb0bfa23ca"}, + {file = "fastcluster-1.2.6-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ab9337b0a6a9b07b6f86fc724972d1ad729c890e2f539c1b33271c2f1f00af8b"}, + {file = "fastcluster-1.2.6-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4093d5454bcbe48b30e32da5db43056a08889480a96e4555f28c1f7004fc5323"}, + {file = "fastcluster-1.2.6-cp37-cp37m-win32.whl", hash = "sha256:58958a0333e3dfbad198394e9b7dd6254de0a3e622019b057288405b2a4a6bba"}, + {file = "fastcluster-1.2.6-cp37-cp37m-win_amd64.whl", hash = "sha256:03f8efe6435a7b947fa4a420676942d0267dac0d323ec5ead50f1856cc7cf96f"}, + {file = "fastcluster-1.2.6-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:a5ceb39379327316d34613f7c16c06d7a3816aa38f4437b5e8433aa1bf149e2c"}, + {file = "fastcluster-1.2.6-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:0bb54283b4d5ec96f167c7fd31921f169226c1261637434fdae7a69ee3c69573"}, + {file = "fastcluster-1.2.6-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:6e51db0067e65687a5c46f00a11843d0bb15ca759e8a1767eebac8c4f6e3f4df"}, + {file = "fastcluster-1.2.6-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:11748a4e245c745030e9ddd8c2c37e378f8ad8bd8e869d954c84ff674495499f"}, + {file = "fastcluster-1.2.6-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7254f81dc71cd29ef6f2d9747cf97ff907b569c9ef9d9760352391be5b57118c"}, + {file = "fastcluster-1.2.6-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:aa4a4c01c5fbec3623e92bc33a9f712ca416ce93255c402f5c904ac4b890ac3c"}, + {file = "fastcluster-1.2.6-cp38-cp38-win32.whl", hash = "sha256:ffdb00782cd63bbf2c45bb048897531e868326dff5081ab9b752d294b0426c1d"}, + {file = "fastcluster-1.2.6-cp38-cp38-win_amd64.whl", hash = "sha256:a952a84453123db0c2336b9a9c86162e99ad0b897bae8213107c055a64effd41"}, + {file = "fastcluster-1.2.6-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:a085e7e13f1afc517358981b2b7ed774dc9abf95f2be0da9a495d9e6b58c4409"}, + {file = "fastcluster-1.2.6-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:6a7c7f51a6d2f5ab58b1d85e9d0af2af9600ec13bb43bc6aafc9085d2c4ccd93"}, + {file = "fastcluster-1.2.6-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:8bac5cf64691060cf86b0752dd385ef1eccff6d24bdb8b60691cf8cbf0e4f9ef"}, + {file = "fastcluster-1.2.6-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:060c1cb3c84942d8d3618385e2c25998ba690c46ec8c73d64477f808abfac3f2"}, + {file = "fastcluster-1.2.6-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e03a228e018457842eb81de85be7af0b5fe8065d666dd093193e3bdcf1f13d2e"}, + {file = "fastcluster-1.2.6-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a6f8da329c0032f2acaf4beaef958a2db0dae43d3f946f592dad5c29aa82c832"}, + {file = "fastcluster-1.2.6-cp39-cp39-win32.whl", hash = "sha256:eb3f98791427d5d5d02d023b66bcef61e48954edfadae6527ef72d70cf32ec86"}, + {file = "fastcluster-1.2.6-cp39-cp39-win_amd64.whl", hash = "sha256:4b9cfd426966b8037bec2fc03a0d7a9c87313482c699b36ffa1432b49f84ed2e"}, + {file = "fastcluster-1.2.6.tar.gz", hash = "sha256:aab886efa7b6bba7ac124f4498153d053e5a08b822d2254926b7206cdf5a8aa6"}, +] +fastjsonschema = [ + {file = "fastjsonschema-2.16.2-py3-none-any.whl", hash = "sha256:21f918e8d9a1a4ba9c22e09574ba72267a6762d47822db9add95f6454e51cc1c"}, + {file = "fastjsonschema-2.16.2.tar.gz", hash = "sha256:01e366f25d9047816fe3d288cbfc3e10541daf0af2044763f3d0ade42476da18"}, +] +fastrlock = [ + {file = "fastrlock-0.8-cp27-cp27m-win32.whl", hash = "sha256:4d414a5e97a545fee64437586c70bd295d22ac49614eeb76fb67980e32a0d1ae"}, + {file = "fastrlock-0.8-cp27-cp27m-win_amd64.whl", hash = "sha256:b991766baec0113829c5a10bec4c5ec987cab31dfcb1fabf53e370b83b939ef9"}, + {file = "fastrlock-0.8-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5356a15375fab5a8090f255b54122eead504ebcec8a67ac369489e3e315dfd21"}, + {file = "fastrlock-0.8-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:8369ce6d228fc3efbfcff5499468200bd12c35efdbc787eeaf8064153bcf0d72"}, + {file = "fastrlock-0.8-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:09314c5c0f63fe252a3ee038af855d7fb5668d0ccbae94846a35b32487c6256c"}, + {file = "fastrlock-0.8-cp35-cp35m-win32.whl", hash = "sha256:b724a7f5c1d5f9cdc30a13022e6e8cf319812c40dad0fd722b5ea18d2cfc4c4d"}, + {file = "fastrlock-0.8-cp35-cp35m-win_amd64.whl", hash = "sha256:c7ec22a5726467af53950a8baba92327620c0f73c34fab930ce29b94c8645c7e"}, + {file = "fastrlock-0.8-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:dcd7a05ba34702d0f0e9751d35afb06be21034fcf00197567ff0dcdf48cde8e7"}, + {file = "fastrlock-0.8-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:997bc6c4fafda396449e2410a5d32b69d231fdccc5af6de6cefe9d67e5f7157e"}, + {file = "fastrlock-0.8-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:4ba3d3dc0dbb1cff2eee033a1f6369c24a86e8c20b427edfceff3f38b48b391c"}, + {file = "fastrlock-0.8-cp36-cp36m-win32.whl", hash = "sha256:f365fc1de226ce96fedbb475c4523b304ce00f9a59beea620dba34e21239f5f3"}, + {file = "fastrlock-0.8-cp36-cp36m-win_amd64.whl", hash = "sha256:7c9c66ab93877272169b017dc24f63c9c94b3f9d55b0b0b8c3f6d9644280120c"}, + {file = "fastrlock-0.8-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b5d5fd2a76aa9cd451a8820e2427e512620062ffa62ea5732da0ab8888b6be6e"}, + {file = "fastrlock-0.8-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:340ae0734305d780aaad0893dba8185f4dbb0575d5fd696b5720eaf800526bbc"}, + {file = "fastrlock-0.8-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:719743b5b3c2b214fdf63096ac6a68615b4d9b8cb210e9e6ddf0293b38da2c9a"}, + {file = "fastrlock-0.8-cp37-cp37m-win32.whl", hash = "sha256:1cfb5ac6336ff327359a31b690898adf9a813fd44a76196115a3f0afb2367c81"}, + {file = "fastrlock-0.8-cp37-cp37m-win_amd64.whl", hash = "sha256:5aa6b442b12fa1f9041248506c8ea5ae909a92aedd5a139647dce2ee87e5b944"}, + {file = "fastrlock-0.8-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:af9df4c17c3142c9774cd1b9edea586f709c6421f02bcf7614507937b921ea7f"}, + {file = "fastrlock-0.8-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:951a5c4dc6fbe4481082752ce9f21aabcaa1cf6185f683d7b5cbae254f10bb46"}, + {file = "fastrlock-0.8-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:5c75985ba70fb4e8af595a0f67f58b96e0dbc53562768208890b4b2ac25b4b52"}, + {file = "fastrlock-0.8-cp38-cp38-win32.whl", hash = "sha256:0b459511349dc96c8961f1d43635bb94cfc2404a8899792a1f9aaa9998fa0eca"}, + {file = "fastrlock-0.8-cp38-cp38-win_amd64.whl", hash = "sha256:7b612474ddacf808c663aa8020db0a78f54a665ccabd9dbe505d3d4c4b3f6044"}, + {file = "fastrlock-0.8-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:fe85f98fa66de41f929b8e01e4a9c5a7d20e660f605054b847c4ac54fadc8f79"}, + {file = "fastrlock-0.8-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:d2029fb44eac8ab5f7aafb3fcde9419cbdaa07a08f72dac8cd7790dc0f73e596"}, + {file = "fastrlock-0.8-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:3bba2a866c9f6eb1923ead5e70e1da02b3e57c531830eb4fcbd2d8e9530a2d7e"}, + {file = "fastrlock-0.8-cp39-cp39-win32.whl", hash = "sha256:85c36ac55dc917c7e1f4fb03a841fe84b3fb2669dd0306bb94bf62c5749b1a7f"}, + {file = "fastrlock-0.8-cp39-cp39-win_amd64.whl", hash = "sha256:4bb33625117bc9f1a66a5049a5d03ac4b38a44cb8eefdff1a394f7a435da54c9"}, + {file = "fastrlock-0.8.tar.gz", hash = "sha256:9cc100ed0924b32173d7de705a82fdf1257cdf60af1952a13f64759307b40931"}, +] +filelock = [ + {file = "filelock-3.8.0-py3-none-any.whl", hash = "sha256:617eb4e5eedc82fc5f47b6d61e4d11cb837c56cb4544e39081099fa17ad109d4"}, + {file = "filelock-3.8.0.tar.gz", hash = "sha256:55447caa666f2198c5b6b13a26d2084d26fa5b115c00d065664b2124680c4edc"}, +] +flake8 = [ + {file = "flake8-4.0.1-py2.py3-none-any.whl", hash = "sha256:479b1304f72536a55948cb40a32dce8bb0ffe3501e26eaf292c7e60eb5e0428d"}, + {file = "flake8-4.0.1.tar.gz", hash = "sha256:806e034dda44114815e23c16ef92f95c91e4c71100ff52813adf7132a6ad870d"}, +] +flask = [ + {file = "Flask-2.2.2-py3-none-any.whl", hash = "sha256:b9c46cc36662a7949f34b52d8ec7bb59c0d74ba08ba6cb9ce9adc1d8676d9526"}, + {file = "Flask-2.2.2.tar.gz", hash = "sha256:642c450d19c4ad482f96729bd2a8f6d32554aa1e231f4f6b4e7e5264b16cca2b"}, +] +flask-cors = [ + {file = "Flask-Cors-3.0.10.tar.gz", hash = "sha256:b60839393f3b84a0f3746f6cdca56c1ad7426aa738b70d6c61375857823181de"}, + {file = "Flask_Cors-3.0.10-py2.py3-none-any.whl", hash = "sha256:74efc975af1194fc7891ff5cd85b0f7478be4f7f59fe158102e91abb72bb4438"}, +] +flask-socketio = [ + {file = "Flask-SocketIO-5.3.1.tar.gz", hash = "sha256:fd0ed0fc1341671d92d5f5b2f5503916deb7aa7e2940e6636cfa2c087c828bf9"}, + {file = "Flask_SocketIO-5.3.1-py3-none-any.whl", hash = "sha256:ff0c721f20bff1e2cfba77948727a8db48f187e89a72fe50c34478ce6efb3353"}, +] +flatbuffers = [ + {file = "flatbuffers-22.9.24-py2.py3-none-any.whl", hash = "sha256:fc30f024e2eee55922d610f4d68626002fcd3c8f87d8058ec5ae9edd86993bcb"}, +] +fonttools = [ + {file = "fonttools-4.37.4-py3-none-any.whl", hash = "sha256:afae1b39555f9c3f0ad1f0f1daf678e5ad157e38c8842ecb567951bf1a9b9fd7"}, + {file = "fonttools-4.37.4.zip", hash = "sha256:86918c150c6412798e15a0de6c3e0d061ddefddd00f97b4f7b43dfa867ad315e"}, +] +frozenlist = [ + {file = "frozenlist-1.3.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:5f271c93f001748fc26ddea409241312a75e13466b06c94798d1a341cf0e6989"}, + {file = "frozenlist-1.3.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:9c6ef8014b842f01f5d2b55315f1af5cbfde284eb184075c189fd657c2fd8204"}, + {file = "frozenlist-1.3.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:219a9676e2eae91cb5cc695a78b4cb43d8123e4160441d2b6ce8d2c70c60e2f3"}, + {file = "frozenlist-1.3.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b47d64cdd973aede3dd71a9364742c542587db214e63b7529fbb487ed67cddd9"}, + {file = "frozenlist-1.3.1-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2af6f7a4e93f5d08ee3f9152bce41a6015b5cf87546cb63872cc19b45476e98a"}, + {file = "frozenlist-1.3.1-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a718b427ff781c4f4e975525edb092ee2cdef6a9e7bc49e15063b088961806f8"}, + {file = "frozenlist-1.3.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c56c299602c70bc1bb5d1e75f7d8c007ca40c9d7aebaf6e4ba52925d88ef826d"}, + {file = "frozenlist-1.3.1-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:717470bfafbb9d9be624da7780c4296aa7935294bd43a075139c3d55659038ca"}, + {file = "frozenlist-1.3.1-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:31b44f1feb3630146cffe56344704b730c33e042ffc78d21f2125a6a91168131"}, + {file = "frozenlist-1.3.1-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:c3b31180b82c519b8926e629bf9f19952c743e089c41380ddca5db556817b221"}, + {file = "frozenlist-1.3.1-cp310-cp310-musllinux_1_1_ppc64le.whl", hash = "sha256:d82bed73544e91fb081ab93e3725e45dd8515c675c0e9926b4e1f420a93a6ab9"}, + {file = "frozenlist-1.3.1-cp310-cp310-musllinux_1_1_s390x.whl", hash = "sha256:49459f193324fbd6413e8e03bd65789e5198a9fa3095e03f3620dee2f2dabff2"}, + {file = "frozenlist-1.3.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:94e680aeedc7fd3b892b6fa8395b7b7cc4b344046c065ed4e7a1e390084e8cb5"}, + {file = "frozenlist-1.3.1-cp310-cp310-win32.whl", hash = "sha256:fabb953ab913dadc1ff9dcc3a7a7d3dc6a92efab3a0373989b8063347f8705be"}, + {file = "frozenlist-1.3.1-cp310-cp310-win_amd64.whl", hash = "sha256:eee0c5ecb58296580fc495ac99b003f64f82a74f9576a244d04978a7e97166db"}, + {file = "frozenlist-1.3.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:0bc75692fb3770cf2b5856a6c2c9de967ca744863c5e89595df64e252e4b3944"}, + {file = "frozenlist-1.3.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:086ca1ac0a40e722d6833d4ce74f5bf1aba2c77cbfdc0cd83722ffea6da52a04"}, + {file = "frozenlist-1.3.1-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1b51eb355e7f813bcda00276b0114c4172872dc5fb30e3fea059b9367c18fbcb"}, + {file = "frozenlist-1.3.1-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:74140933d45271c1a1283f708c35187f94e1256079b3c43f0c2267f9db5845ff"}, + {file = "frozenlist-1.3.1-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ee4c5120ddf7d4dd1eaf079af3af7102b56d919fa13ad55600a4e0ebe532779b"}, + {file = "frozenlist-1.3.1-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:97d9e00f3ac7c18e685320601f91468ec06c58acc185d18bb8e511f196c8d4b2"}, + {file = "frozenlist-1.3.1-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:6e19add867cebfb249b4e7beac382d33215d6d54476bb6be46b01f8cafb4878b"}, + {file = "frozenlist-1.3.1-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:a027f8f723d07c3f21963caa7d585dcc9b089335565dabe9c814b5f70c52705a"}, + {file = "frozenlist-1.3.1-cp37-cp37m-musllinux_1_1_ppc64le.whl", hash = "sha256:61d7857950a3139bce035ad0b0945f839532987dfb4c06cfe160254f4d19df03"}, + {file = "frozenlist-1.3.1-cp37-cp37m-musllinux_1_1_s390x.whl", hash = "sha256:53b2b45052e7149ee8b96067793db8ecc1ae1111f2f96fe1f88ea5ad5fd92d10"}, + {file = "frozenlist-1.3.1-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:bbb1a71b1784e68870800b1bc9f3313918edc63dbb8f29fbd2e767ce5821696c"}, + {file = "frozenlist-1.3.1-cp37-cp37m-win32.whl", hash = "sha256:ab6fa8c7871877810e1b4e9392c187a60611fbf0226a9e0b11b7b92f5ac72792"}, + {file = "frozenlist-1.3.1-cp37-cp37m-win_amd64.whl", hash = "sha256:f89139662cc4e65a4813f4babb9ca9544e42bddb823d2ec434e18dad582543bc"}, + {file = "frozenlist-1.3.1-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:4c0c99e31491a1d92cde8648f2e7ccad0e9abb181f6ac3ddb9fc48b63301808e"}, + {file = "frozenlist-1.3.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:61e8cb51fba9f1f33887e22488bad1e28dd8325b72425f04517a4d285a04c519"}, + {file = "frozenlist-1.3.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:cc2f3e368ee5242a2cbe28323a866656006382872c40869b49b265add546703f"}, + {file = "frozenlist-1.3.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:58fb94a01414cddcdc6839807db77ae8057d02ddafc94a42faee6004e46c9ba8"}, + {file = "frozenlist-1.3.1-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:022178b277cb9277d7d3b3f2762d294f15e85cd2534047e68a118c2bb0058f3e"}, + {file = "frozenlist-1.3.1-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:572ce381e9fe027ad5e055f143763637dcbac2542cfe27f1d688846baeef5170"}, + {file = "frozenlist-1.3.1-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:19127f8dcbc157ccb14c30e6f00392f372ddb64a6ffa7106b26ff2196477ee9f"}, + {file = "frozenlist-1.3.1-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:42719a8bd3792744c9b523674b752091a7962d0d2d117f0b417a3eba97d1164b"}, + {file = "frozenlist-1.3.1-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:2743bb63095ef306041c8f8ea22bd6e4d91adabf41887b1ad7886c4c1eb43d5f"}, + {file = "frozenlist-1.3.1-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:fa47319a10e0a076709644a0efbcaab9e91902c8bd8ef74c6adb19d320f69b83"}, + {file = "frozenlist-1.3.1-cp38-cp38-musllinux_1_1_ppc64le.whl", hash = "sha256:52137f0aea43e1993264a5180c467a08a3e372ca9d378244c2d86133f948b26b"}, + {file = "frozenlist-1.3.1-cp38-cp38-musllinux_1_1_s390x.whl", hash = "sha256:f5abc8b4d0c5b556ed8cd41490b606fe99293175a82b98e652c3f2711b452988"}, + {file = "frozenlist-1.3.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:1e1cf7bc8cbbe6ce3881863671bac258b7d6bfc3706c600008925fb799a256e2"}, + {file = "frozenlist-1.3.1-cp38-cp38-win32.whl", hash = "sha256:0dde791b9b97f189874d654c55c24bf7b6782343e14909c84beebd28b7217845"}, + {file = "frozenlist-1.3.1-cp38-cp38-win_amd64.whl", hash = "sha256:9494122bf39da6422b0972c4579e248867b6b1b50c9b05df7e04a3f30b9a413d"}, + {file = "frozenlist-1.3.1-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:31bf9539284f39ff9398deabf5561c2b0da5bb475590b4e13dd8b268d7a3c5c1"}, + {file = "frozenlist-1.3.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:e0c8c803f2f8db7217898d11657cb6042b9b0553a997c4a0601f48a691480fab"}, + {file = "frozenlist-1.3.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:da5ba7b59d954f1f214d352308d1d86994d713b13edd4b24a556bcc43d2ddbc3"}, + {file = "frozenlist-1.3.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:74e6b2b456f21fc93ce1aff2b9728049f1464428ee2c9752a4b4f61e98c4db96"}, + {file = "frozenlist-1.3.1-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:526d5f20e954d103b1d47232e3839f3453c02077b74203e43407b962ab131e7b"}, + {file = "frozenlist-1.3.1-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b499c6abe62a7a8d023e2c4b2834fce78a6115856ae95522f2f974139814538c"}, + {file = "frozenlist-1.3.1-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ab386503f53bbbc64d1ad4b6865bf001414930841a870fc97f1546d4d133f141"}, + {file = "frozenlist-1.3.1-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5f63c308f82a7954bf8263a6e6de0adc67c48a8b484fab18ff87f349af356efd"}, + {file = "frozenlist-1.3.1-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:12607804084d2244a7bd4685c9d0dca5df17a6a926d4f1967aa7978b1028f89f"}, + {file = "frozenlist-1.3.1-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:da1cdfa96425cbe51f8afa43e392366ed0b36ce398f08b60de6b97e3ed4affef"}, + {file = "frozenlist-1.3.1-cp39-cp39-musllinux_1_1_ppc64le.whl", hash = "sha256:f810e764617b0748b49a731ffaa525d9bb36ff38332411704c2400125af859a6"}, + {file = "frozenlist-1.3.1-cp39-cp39-musllinux_1_1_s390x.whl", hash = "sha256:35c3d79b81908579beb1fb4e7fcd802b7b4921f1b66055af2578ff7734711cfa"}, + {file = "frozenlist-1.3.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:c92deb5d9acce226a501b77307b3b60b264ca21862bd7d3e0c1f3594022f01bc"}, + {file = "frozenlist-1.3.1-cp39-cp39-win32.whl", hash = "sha256:5e77a8bd41e54b05e4fb2708dc6ce28ee70325f8c6f50f3df86a44ecb1d7a19b"}, + {file = "frozenlist-1.3.1-cp39-cp39-win_amd64.whl", hash = "sha256:625d8472c67f2d96f9a4302a947f92a7adbc1e20bedb6aff8dbc8ff039ca6189"}, + {file = "frozenlist-1.3.1.tar.gz", hash = "sha256:3a735e4211a04ccfa3f4833547acdf5d2f863bfeb01cfd3edaffbc251f15cec8"}, +] +ft4222 = [ + {file = "ft4222-1.6.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:64c80402e19ada10f142cf9d5f5b343a121689b94dfc31fafc7864db13ac7f79"}, + {file = "ft4222-1.6.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:5c713b6527513a77e674a6db60d97f67b18ce9f85727168ecbeef82557f2b2d1"}, + {file = "ft4222-1.6.0-cp310-cp310-win32.whl", hash = "sha256:324d6330d501bf6f7746aa1b81f9540a2b385e9318bd4e6e4f744d7107f90c67"}, + {file = "ft4222-1.6.0-cp310-cp310-win_amd64.whl", hash = "sha256:1279115892441e4a2ab468429e5003c72f47423daa4d7179c0da4af3522c056a"}, + {file = "ft4222-1.6.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:719ec8f9c05636d8306a64f8f6f86dd9ec27d80afb3fc07e7d0b01c9b3d83d1e"}, + {file = "ft4222-1.6.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:886f3b53bad1dc238a3d6e5105b6d7442244ea854afea38daf84529491ad6e3d"}, + {file = "ft4222-1.6.0-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:c28fb526ec98afefebb24f0e333bfef0def3ca46f8b4f84712c5e6e3c7e0fe9c"}, + {file = "ft4222-1.6.0-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:f4b3ced3e5603f6bb22fcfcf9567a95ec47a93dd453a911e438c02d665bf657c"}, + {file = "ft4222-1.6.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:376ddba0e44a24237d926bc28a519ef7877174726629c3335529f548a829e857"}, + {file = "ft4222-1.6.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:3dff18e3d95027fb7407748d9a92eece9a2e88c3f7521be59fc848fe32a3780f"}, + {file = "ft4222-1.6.0-cp37-cp37m-win32.whl", hash = "sha256:c0673a1420bd10b3dd782d307c60516bcd4ff24f7c27661b319c781e8a0618df"}, + {file = "ft4222-1.6.0-cp37-cp37m-win_amd64.whl", hash = "sha256:de38894f69cd0253a4b683612006912c5d98fae94f07f910650ab5027dc3df8e"}, + {file = "ft4222-1.6.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:e3aae2cbd0a15f7dd9506971f32ab67dcf192c24b012258ccf2e0daeb099d8e5"}, + {file = "ft4222-1.6.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:f4d6d21e8e00b9c5aabaff48489973cf45452cb88a9d6946eaa6aea1d48c0794"}, + {file = "ft4222-1.6.0-cp38-cp38-win32.whl", hash = "sha256:eeb1f8cf04262e2bcdaf159a767148a61ef91aa8b86950ae883bb8ba8f0e82da"}, + {file = "ft4222-1.6.0-cp38-cp38-win_amd64.whl", hash = "sha256:06419df94566e5e62358f7d68055fd4155b916646ead2c479e75b964548714e3"}, + {file = "ft4222-1.6.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:7a91689f9e44c6a8afedb6e5a11ba70d0c661e879607fd8635c76ebaa503cd90"}, + {file = "ft4222-1.6.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:31976a15a7cd649814887e3887480f3f625e82e7e2d354f33d582a0faf4c7689"}, + {file = "ft4222-1.6.0-cp39-cp39-win32.whl", hash = "sha256:b4c8309bbc2d0cf2704dd8737bcf2a6ae27284f7cf45746e79d3dbd4810e0cb3"}, + {file = "ft4222-1.6.0-cp39-cp39-win_amd64.whl", hash = "sha256:395596fd03120015b7a049928ba31983f7e71596bcdb85bd78eff4293e955266"}, + {file = "ft4222-1.6.0-pp37-pypy37_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:937124275e50adc87213fa3bda52e3ac08348454eee21b23e23ce4afd656035b"}, + {file = "ft4222-1.6.0-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:eb9752990913ee327ebf1279f4a4847b54cacbf95aa920d24f07cb687a77572b"}, + {file = "ft4222-1.6.0-pp38-pypy38_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:37696c46340064e7518e4d77c8f8b044d72af26850f2e3370369201dd44b08b9"}, + {file = "ft4222-1.6.0-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:ea7fdf9f5757e981445bbf80669f4f059912963f5718d16736c0f2b341a05610"}, + {file = "ft4222-1.6.0-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:f242776c497d49f0533c643138375a59fe1745c159e43ec55845fe59c1f17020"}, + {file = "ft4222-1.6.0-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:5ba637e9c43c7aaa82915b06c4098ac885f2ae45152b1f01584307b8e6e5b005"}, + {file = "ft4222-1.6.0.tar.gz", hash = "sha256:537de8f49c21fe49f4be16e0a359315e72322a6a513b153effc95c8105c6af06"}, +] +future = [ + {file = "future-0.18.2.tar.gz", hash = "sha256:b1bead90b70cf6ec3f0710ae53a525360fa360d306a86583adc6bf83a4db537d"}, +] +future-fstrings = [ + {file = "future_fstrings-1.2.0-py2.py3-none-any.whl", hash = "sha256:90e49598b553d8746c4dc7d9442e0359d038c3039d802c91c0a55505da318c63"}, + {file = "future_fstrings-1.2.0.tar.gz", hash = "sha256:6cf41cbe97c398ab5a81168ce0dbb8ad95862d3caf23c21e4430627b90844089"}, +] +geoalchemy2 = [ + {file = "GeoAlchemy2-0.12.5-py2.py3-none-any.whl", hash = "sha256:3a59eb651df95b3dfee8e1d82f4d18c80b75f712860a0a3080defc6b0435070d"}, + {file = "GeoAlchemy2-0.12.5.tar.gz", hash = "sha256:31c2502dce317b57b335e4eb87562d501fa39e46c728be514d9b86091e08dd67"}, +] +gevent = [ + {file = "gevent-22.10.1-cp27-cp27m-win32.whl", hash = "sha256:702a51b8f21bad1976b0893f90ade466e8c27039b846b611ad2beb8c6e6ac701"}, + {file = "gevent-22.10.1-cp27-cp27m-win_amd64.whl", hash = "sha256:af7baec79a5f8ad1cc132d3b14edd12661c628d8094e501b089b1fe2d3df7f6e"}, + {file = "gevent-22.10.1-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:cf6dd33052919de8fb56e0bea0e6a7c7d6545281fe280ea78e311621c7adb50e"}, + {file = "gevent-22.10.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f16c6937d47593f051fc3ac7996c819919082a1e7e0dec927cdae8771d26ed45"}, + {file = "gevent-22.10.1-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:21dbeb6d3b47093f40ca97aab493b2fb64b6f22112f88f56d79cf6f52a8c1c16"}, + {file = "gevent-22.10.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:acb21bee2e66da45b8916073c8ae54c44629beb94d49120c188d27aff4ebf8dd"}, + {file = "gevent-22.10.1-cp310-cp310-win_amd64.whl", hash = "sha256:d2ea4ce36c09355379bc038be2bd50118f97d2eb6381b7096de4d05aa4c3e241"}, + {file = "gevent-22.10.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3e73c9f71aa2a6795ecbec9b57282b002375e863e283558feb87b62840c8c1ac"}, + {file = "gevent-22.10.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5bc3758f0dc95007c1780d28a9fd2150416a79c50f308f62a674d78a845ea1b9"}, + {file = "gevent-22.10.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:03c10ca0beeab0c6be516030471ea630447ddd1f649d3335e5b162097cd4130a"}, + {file = "gevent-22.10.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:fe2c0ff095171c49f78f1d4e6dc89fa58253783c7b6dccab9f1d76e2ee391f10"}, + {file = "gevent-22.10.1-cp36-cp36m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:d18fcc324f39a3b21795022eb47c7752d6e4f4ed89d8cca41f1cc604553265b3"}, + {file = "gevent-22.10.1-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:06ea39c70ce166c4a1d4386c7fae96cb8d84ad799527b3378406051104d15443"}, + {file = "gevent-22.10.1-cp36-cp36m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:04a920a812b6c0c36d4613a15c254ca1ce415ee75ade0df3b8941ab61ae7ce3f"}, + {file = "gevent-22.10.1-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:33c4cd095f99768ecc4b3bb75a12f52ea9df5c40a58671c667f86ea087a075e1"}, + {file = "gevent-22.10.1-cp36-cp36m-win32.whl", hash = "sha256:db592cfe5106730667ac36f43554e7a869d757e411f8a08116c3739cee507145"}, + {file = "gevent-22.10.1-cp36-cp36m-win_amd64.whl", hash = "sha256:a12443b7326e40d00fb445d37bae154fd1f4693055330c6b4e68670ca3b6e6bf"}, + {file = "gevent-22.10.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:5d64b208bec99adc7e0b6e08a3e2c296065c665ca725ca8da434c4ffc5aa302e"}, + {file = "gevent-22.10.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1ac816f5e8e318c5fa27091ee43fcf4caaa6ae73a487e875a1a296a04c3da5af"}, + {file = "gevent-22.10.1-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:eb0d9d6f869ba7c49d7f9b7d244dd20daec5cc87cd3e2e90209d6ed8172e0cad"}, + {file = "gevent-22.10.1-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:3c1cfd9f9fb6a2a5a9a04132d315db7fb819db019dea260695fe6e4012416f96"}, + {file = "gevent-22.10.1-cp37-cp37m-win32.whl", hash = "sha256:4b0d29fc18ee338a85396facfc508e5f26e2e0e90f4c2889f8a9e74d341ad467"}, + {file = "gevent-22.10.1-cp37-cp37m-win_amd64.whl", hash = "sha256:36e47ca663081a71fca137b7c852e99e7ee3761082070c13aa2ae3b5b6234af6"}, + {file = "gevent-22.10.1-cp38-cp38-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:a838437b7b629328ad457cd36df454500afe7f3df4b971a6ff85851dfcf8c844"}, + {file = "gevent-22.10.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4c06c0f3f4f1b147f51a934fbf541880cee769492b98c4ebd3e930b5ff862646"}, + {file = "gevent-22.10.1-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d701208d4d65dbdf9feb02561a75ecc5bd28300e47b59f74033a07b593887806"}, + {file = "gevent-22.10.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:7e8c4ccc544f6e6c26ab10d0d6a7be86bd522222ce40f00bfafa01289f04bffc"}, + {file = "gevent-22.10.1-cp38-cp38-win32.whl", hash = "sha256:4be5859af086de1ed85702c0a84479387087ddf49e38332c41861b0a10e96d8f"}, + {file = "gevent-22.10.1-cp38-cp38-win_amd64.whl", hash = "sha256:be43278781d39b4081f7f4d3e8ebb1dac188c9fe98f25da817325cb12c01887a"}, + {file = "gevent-22.10.1-cp39-cp39-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:0cafb8f5399224990a5329bca3606bf399ee3604ae711b2d9238129b44551ad5"}, + {file = "gevent-22.10.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1e1c609f9e4171588006bea7ff41bb830ff27c27d071bbd311f91860fb5ef4cc"}, + {file = "gevent-22.10.1-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2dcfd8ef9dcca78c51dd266d0f4b48d9b7ea2592ae881bf66d8dbe59bb16631a"}, + {file = "gevent-22.10.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:eefcb21fda3055f2e7eaad2e8098885a7bbddd83b174b012e2142db6b2b4c09d"}, + {file = "gevent-22.10.1-cp39-cp39-win32.whl", hash = "sha256:3f7d11136b3ae6312effbc2ac0ed902ae718d86e7acb9a51cf927262cfb2931e"}, + {file = "gevent-22.10.1-cp39-cp39-win_amd64.whl", hash = "sha256:1ec5f77f629d997668983be53bad2a90d1b858a00e43b9e75e1c9a118c3a840b"}, + {file = "gevent-22.10.1-pp27-pypy_73-win_amd64.whl", hash = "sha256:d8df3f628c8a9fb339b87a849dc2076e56d124e2169261fa58b4a01db3a335b6"}, + {file = "gevent-22.10.1-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:0569e133bb620de1001ac807ad9a8abaadedd25349c6d695f80c9048a3f59d42"}, + {file = "gevent-22.10.1.tar.gz", hash = "sha256:df3042349c9a4460eeaec8d0e56d737cb183eed055e75a6af9dbda94aaddaf4d"}, +] +greenlet = [ + {file = "greenlet-1.1.3.post0-cp27-cp27m-macosx_10_14_x86_64.whl", hash = "sha256:949c9061b8c6d3e6e439466a9be1e787208dec6246f4ec5fffe9677b4c19fcc3"}, + {file = "greenlet-1.1.3.post0-cp27-cp27m-manylinux1_x86_64.whl", hash = "sha256:d7815e1519a8361c5ea2a7a5864945906f8e386fa1bc26797b4d443ab11a4589"}, + {file = "greenlet-1.1.3.post0-cp27-cp27m-manylinux2010_x86_64.whl", hash = "sha256:9649891ab4153f217f319914455ccf0b86986b55fc0573ce803eb998ad7d6854"}, + {file = "greenlet-1.1.3.post0-cp27-cp27m-win32.whl", hash = "sha256:11fc7692d95cc7a6a8447bb160d98671ab291e0a8ea90572d582d57361360f05"}, + {file = "greenlet-1.1.3.post0-cp27-cp27m-win_amd64.whl", hash = "sha256:05ae7383f968bba4211b1fbfc90158f8e3da86804878442b4fb6c16ccbcaa519"}, + {file = "greenlet-1.1.3.post0-cp27-cp27mu-manylinux1_x86_64.whl", hash = "sha256:ccbe7129a282ec5797df0451ca1802f11578be018a32979131065565da89b392"}, + {file = "greenlet-1.1.3.post0-cp27-cp27mu-manylinux2010_x86_64.whl", hash = "sha256:4a8b58232f5b72973350c2b917ea3df0bebd07c3c82a0a0e34775fc2c1f857e9"}, + {file = "greenlet-1.1.3.post0-cp310-cp310-macosx_10_15_x86_64.whl", hash = "sha256:f6661b58412879a2aa099abb26d3c93e91dedaba55a6394d1fb1512a77e85de9"}, + {file = "greenlet-1.1.3.post0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2c6e942ca9835c0b97814d14f78da453241837419e0d26f7403058e8db3e38f8"}, + {file = "greenlet-1.1.3.post0-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a812df7282a8fc717eafd487fccc5ba40ea83bb5b13eb3c90c446d88dbdfd2be"}, + {file = "greenlet-1.1.3.post0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:83a7a6560df073ec9de2b7cb685b199dfd12519bc0020c62db9d1bb522f989fa"}, + {file = "greenlet-1.1.3.post0-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:17a69967561269b691747e7f436d75a4def47e5efcbc3c573180fc828e176d80"}, + {file = "greenlet-1.1.3.post0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:60839ab4ea7de6139a3be35b77e22e0398c270020050458b3d25db4c7c394df5"}, + {file = "greenlet-1.1.3.post0-cp310-cp310-win_amd64.whl", hash = "sha256:8926a78192b8b73c936f3e87929931455a6a6c6c385448a07b9f7d1072c19ff3"}, + {file = "greenlet-1.1.3.post0-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:c6f90234e4438062d6d09f7d667f79edcc7c5e354ba3a145ff98176f974b8132"}, + {file = "greenlet-1.1.3.post0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:814f26b864ed2230d3a7efe0336f5766ad012f94aad6ba43a7c54ca88dd77cba"}, + {file = "greenlet-1.1.3.post0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8fda1139d87ce5f7bd80e80e54f9f2c6fe2f47983f1a6f128c47bf310197deb6"}, + {file = "greenlet-1.1.3.post0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c0643250dd0756f4960633f5359884f609a234d4066686754e834073d84e9b51"}, + {file = "greenlet-1.1.3.post0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:cb863057bed786f6622982fb8b2c122c68e6e9eddccaa9fa98fd937e45ee6c4f"}, + {file = "greenlet-1.1.3.post0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:8c0581077cf2734569f3e500fab09c0ff6a2ab99b1afcacbad09b3c2843ae743"}, + {file = "greenlet-1.1.3.post0-cp35-cp35m-macosx_10_14_x86_64.whl", hash = "sha256:695d0d8b5ae42c800f1763c9fce9d7b94ae3b878919379150ee5ba458a460d57"}, + {file = "greenlet-1.1.3.post0-cp35-cp35m-manylinux1_x86_64.whl", hash = "sha256:5662492df0588a51d5690f6578f3bbbd803e7f8d99a99f3bf6128a401be9c269"}, + {file = "greenlet-1.1.3.post0-cp35-cp35m-manylinux2010_x86_64.whl", hash = "sha256:bffba15cff4802ff493d6edcf20d7f94ab1c2aee7cfc1e1c7627c05f1102eee8"}, + {file = "greenlet-1.1.3.post0-cp35-cp35m-win32.whl", hash = "sha256:7afa706510ab079fd6d039cc6e369d4535a48e202d042c32e2097f030a16450f"}, + {file = "greenlet-1.1.3.post0-cp35-cp35m-win_amd64.whl", hash = "sha256:3a24f3213579dc8459e485e333330a921f579543a5214dbc935bc0763474ece3"}, + {file = "greenlet-1.1.3.post0-cp36-cp36m-macosx_10_14_x86_64.whl", hash = "sha256:64e10f303ea354500c927da5b59c3802196a07468332d292aef9ddaca08d03dd"}, + {file = "greenlet-1.1.3.post0-cp36-cp36m-manylinux1_x86_64.whl", hash = "sha256:eb6ac495dccb1520667cfea50d89e26f9ffb49fa28496dea2b95720d8b45eb54"}, + {file = "greenlet-1.1.3.post0-cp36-cp36m-manylinux2010_x86_64.whl", hash = "sha256:88720794390002b0c8fa29e9602b395093a9a766b229a847e8d88349e418b28a"}, + {file = "greenlet-1.1.3.post0-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:39464518a2abe9c505a727af7c0b4efff2cf242aa168be5f0daa47649f4d7ca8"}, + {file = "greenlet-1.1.3.post0-cp36-cp36m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:0914f02fcaa8f84f13b2df4a81645d9e82de21ed95633765dd5cc4d3af9d7403"}, + {file = "greenlet-1.1.3.post0-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:96656c5f7c95fc02c36d4f6ef32f4e94bb0b6b36e6a002c21c39785a4eec5f5d"}, + {file = "greenlet-1.1.3.post0-cp36-cp36m-musllinux_1_1_aarch64.whl", hash = "sha256:4f74aa0092602da2069df0bc6553919a15169d77bcdab52a21f8c5242898f519"}, + {file = "greenlet-1.1.3.post0-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:3aeac044c324c1a4027dca0cde550bd83a0c0fbff7ef2c98df9e718a5086c194"}, + {file = "greenlet-1.1.3.post0-cp36-cp36m-win32.whl", hash = "sha256:fe7c51f8a2ab616cb34bc33d810c887e89117771028e1e3d3b77ca25ddeace04"}, + {file = "greenlet-1.1.3.post0-cp36-cp36m-win_amd64.whl", hash = "sha256:70048d7b2c07c5eadf8393e6398595591df5f59a2f26abc2f81abca09610492f"}, + {file = "greenlet-1.1.3.post0-cp37-cp37m-macosx_10_15_x86_64.whl", hash = "sha256:66aa4e9a726b70bcbfcc446b7ba89c8cec40f405e51422c39f42dfa206a96a05"}, + {file = "greenlet-1.1.3.post0-cp37-cp37m-manylinux1_x86_64.whl", hash = "sha256:025b8de2273d2809f027d347aa2541651d2e15d593bbce0d5f502ca438c54136"}, + {file = "greenlet-1.1.3.post0-cp37-cp37m-manylinux2010_x86_64.whl", hash = "sha256:82a38d7d2077128a017094aff334e67e26194f46bd709f9dcdacbf3835d47ef5"}, + {file = "greenlet-1.1.3.post0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f7d20c3267385236b4ce54575cc8e9f43e7673fc761b069c820097092e318e3b"}, + {file = "greenlet-1.1.3.post0-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c8ece5d1a99a2adcb38f69af2f07d96fb615415d32820108cd340361f590d128"}, + {file = "greenlet-1.1.3.post0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2794eef1b04b5ba8948c72cc606aab62ac4b0c538b14806d9c0d88afd0576d6b"}, + {file = "greenlet-1.1.3.post0-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:a8d24eb5cb67996fb84633fdc96dbc04f2d8b12bfcb20ab3222d6be271616b67"}, + {file = "greenlet-1.1.3.post0-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:0120a879aa2b1ac5118bce959ea2492ba18783f65ea15821680a256dfad04754"}, + {file = "greenlet-1.1.3.post0-cp37-cp37m-win32.whl", hash = "sha256:bef49c07fcb411c942da6ee7d7ea37430f830c482bf6e4b72d92fd506dd3a427"}, + {file = "greenlet-1.1.3.post0-cp37-cp37m-win_amd64.whl", hash = "sha256:62723e7eb85fa52e536e516ee2ac91433c7bb60d51099293671815ff49ed1c21"}, + {file = "greenlet-1.1.3.post0-cp38-cp38-macosx_10_15_x86_64.whl", hash = "sha256:d25cdedd72aa2271b984af54294e9527306966ec18963fd032cc851a725ddc1b"}, + {file = "greenlet-1.1.3.post0-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:924df1e7e5db27d19b1359dc7d052a917529c95ba5b8b62f4af611176da7c8ad"}, + {file = "greenlet-1.1.3.post0-cp38-cp38-manylinux2010_x86_64.whl", hash = "sha256:ec615d2912b9ad807afd3be80bf32711c0ff9c2b00aa004a45fd5d5dde7853d9"}, + {file = "greenlet-1.1.3.post0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0971d37ae0eaf42344e8610d340aa0ad3d06cd2eee381891a10fe771879791f9"}, + {file = "greenlet-1.1.3.post0-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:325f272eb997916b4a3fc1fea7313a8adb760934c2140ce13a2117e1b0a8095d"}, + {file = "greenlet-1.1.3.post0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d75afcbb214d429dacdf75e03a1d6d6c5bd1fa9c35e360df8ea5b6270fb2211c"}, + {file = "greenlet-1.1.3.post0-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:5c2d21c2b768d8c86ad935e404cc78c30d53dea009609c3ef3a9d49970c864b5"}, + {file = "greenlet-1.1.3.post0-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:467b73ce5dcd89e381292fb4314aede9b12906c18fab903f995b86034d96d5c8"}, + {file = "greenlet-1.1.3.post0-cp38-cp38-win32.whl", hash = "sha256:8149a6865b14c33be7ae760bcdb73548bb01e8e47ae15e013bf7ef9290ca309a"}, + {file = "greenlet-1.1.3.post0-cp38-cp38-win_amd64.whl", hash = "sha256:104f29dd822be678ef6b16bf0035dcd43206a8a48668a6cae4d2fe9c7a7abdeb"}, + {file = "greenlet-1.1.3.post0-cp39-cp39-macosx_10_15_x86_64.whl", hash = "sha256:c8c9301e3274276d3d20ab6335aa7c5d9e5da2009cccb01127bddb5c951f8870"}, + {file = "greenlet-1.1.3.post0-cp39-cp39-manylinux1_x86_64.whl", hash = "sha256:8415239c68b2ec9de10a5adf1130ee9cb0ebd3e19573c55ba160ff0ca809e012"}, + {file = "greenlet-1.1.3.post0-cp39-cp39-manylinux2010_x86_64.whl", hash = "sha256:3c22998bfef3fcc1b15694818fc9b1b87c6cc8398198b96b6d355a7bcb8c934e"}, + {file = "greenlet-1.1.3.post0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0aa1845944e62f358d63fcc911ad3b415f585612946b8edc824825929b40e59e"}, + {file = "greenlet-1.1.3.post0-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:890f633dc8cb307761ec566bc0b4e350a93ddd77dc172839be122be12bae3e10"}, + {file = "greenlet-1.1.3.post0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7cf37343e43404699d58808e51f347f57efd3010cc7cee134cdb9141bd1ad9ea"}, + {file = "greenlet-1.1.3.post0-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:5edf75e7fcfa9725064ae0d8407c849456553a181ebefedb7606bac19aa1478b"}, + {file = "greenlet-1.1.3.post0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:0a954002064ee919b444b19c1185e8cce307a1f20600f47d6f4b6d336972c809"}, + {file = "greenlet-1.1.3.post0-cp39-cp39-win32.whl", hash = "sha256:2ccdc818cc106cc238ff7eba0d71b9c77be868fdca31d6c3b1347a54c9b187b2"}, + {file = "greenlet-1.1.3.post0-cp39-cp39-win_amd64.whl", hash = "sha256:91a84faf718e6f8b888ca63d0b2d6d185c8e2a198d2a7322d75c303e7097c8b7"}, + {file = "greenlet-1.1.3.post0.tar.gz", hash = "sha256:f5e09dc5c6e1796969fd4b775ea1417d70e49a5df29aaa8e5d10675d9e11872c"}, +] +gunicorn = [ + {file = "gunicorn-20.1.0-py3-none-any.whl", hash = "sha256:9dcc4547dbb1cb284accfb15ab5667a0e5d1881cc443e0677b4882a4067a807e"}, + {file = "gunicorn-20.1.0.tar.gz", hash = "sha256:e0a968b5ba15f8a328fdfd7ab1fcb5af4470c28aaf7e55df02a99bc13138e6e8"}, +] +h3 = [ + {file = "h3-3.7.4-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:e61d3c6b1b66072f5b74d46dbee7df29daac6ce9738b9a6223a67dc577114515"}, + {file = "h3-3.7.4-cp27-cp27m-manylinux2010_x86_64.whl", hash = "sha256:960cd005b8817314d95fbaff3e848a72385df4e3c6c9703ff99b08581c8def69"}, + {file = "h3-3.7.4-cp27-cp27mu-manylinux2010_x86_64.whl", hash = "sha256:68227df989274b0da54de9101a50741c70c48197ba3beacfb97c88170445c18e"}, + {file = "h3-3.7.4-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:2bf4d75fe42a260ac23bf4cb9f9de6e6f2aa37279b2719387711f3e0727c4653"}, + {file = "h3-3.7.4-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:c644ab3f221c7faaab2d1ccd11bc3b1106f172e9bb1c85a863b0a097f6b71cce"}, + {file = "h3-3.7.4-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7c5366d24c2c01ef3bae68547c15f1965fac6053b2596c0073766bf7544ecaf0"}, + {file = "h3-3.7.4-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:83c2b0cd8259541f95b0493a620fb781b6a18c7c1e8fac1bda4fb234ae23ab43"}, + {file = "h3-3.7.4-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:c1108a9acb755310dce50a6e3c58ae1a2460ef60901d40e1155d633c7392f858"}, + {file = "h3-3.7.4-cp310-cp310-win_amd64.whl", hash = "sha256:ce86c6dce2c923bfb16e26586bc5f0443a8be61d4f43227be8587ccb95588a46"}, + {file = "h3-3.7.4-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:ad21cfa8d97a62984ce30692a7ddf71a32a0c744cc247c43cbdbac1536aec4de"}, + {file = "h3-3.7.4-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:be63482de86bbb91db7f3f3b7dd452b9e08a11dacbda2088386831fb0e7de59c"}, + {file = "h3-3.7.4-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0a96ea1844182bd0511cdcdc89e38e3026d9a3d4139fd0c5e899709edd798ffa"}, + {file = "h3-3.7.4-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:2faf304020493c5ffede34264bd28ed529b8b7238103e0904c0f3e9ca880bcfd"}, + {file = "h3-3.7.4-cp36-cp36m-win_amd64.whl", hash = "sha256:3b1642085939c597a9c723ae3b187f80527ffc79cad0ded0e55be9c9bac69c6c"}, + {file = "h3-3.7.4-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:8d03622433da1a2761574311af378ff1ff841f5956db25927837c6aee9d1c13c"}, + {file = "h3-3.7.4-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:08a09f7a43ed142573c602ef487a058da54ab4d86c173082b29a5057805fe2d3"}, + {file = "h3-3.7.4-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4469fdf90034b1a67e155cac4f46b077fdc404b6182ab33abcb7081c9bfbf411"}, + {file = "h3-3.7.4-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:33b147ecc0e19ab1f27303d0e3ae28e5a457f3347ce18ca9a58b694a8b0cdd0a"}, + {file = "h3-3.7.4-cp37-cp37m-win_amd64.whl", hash = "sha256:c95c0818c163b69989c9e876dd82005e60edfbaabfd45429abebfc26f9a357e8"}, + {file = "h3-3.7.4-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:7b0ddfdd02920996d7c6672c91e83efb5432c67ff83f89a03f774e84bcfe19f8"}, + {file = "h3-3.7.4-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:46a1284521d86cab414981056390be944dca780fe74c6c9e463a16d1c8d24871"}, + {file = "h3-3.7.4-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:585f375ba2a95ceb16b115a378e9118159c912c26703cf1627f57a004818c3b3"}, + {file = "h3-3.7.4-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cdd68e684f0c6e18604d46ee04dbcfe5c79de62238b2c29f1db0f3a5d8dfa47b"}, + {file = "h3-3.7.4-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:a59d7d10597a2da9e9729637a625ae8dff2ed4e7c6c0b4952f0a5b2db6ef7152"}, + {file = "h3-3.7.4-cp38-cp38-win_amd64.whl", hash = "sha256:38a084d74b234d48aafc01e4329cd9a92966e3f45b8cf21224118643b6eaa1c0"}, + {file = "h3-3.7.4-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:a33fae02a54c63acb3c30fe49388715d658d76d42858a6ad4563e7e6859a9e57"}, + {file = "h3-3.7.4-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:9b0277d82578b3ed3220167ef5c5acd8b4e0ef2fcd6c2fd69dbf29e0c4e03765"}, + {file = "h3-3.7.4-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8155b2de1938eb56128fe4fd96e4f6d2022d4c34d8137bc95d73cbf329f8f89e"}, + {file = "h3-3.7.4-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1387166f453816f91d624c6ce70876a3c20356cd28a3a759920dee23c78684cf"}, + {file = "h3-3.7.4-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:62057c1c3d1c7fe492841e42fa360825d66fafd55ac37dc4e90b2292af21cb47"}, + {file = "h3-3.7.4-cp39-cp39-win_amd64.whl", hash = "sha256:25f0c22f4802ab71c45b86d206bd30fa0a6c7fbc3b630398b60c22907e9742e6"}, + {file = "h3-3.7.4.tar.gz", hash = "sha256:f8edf5a546b31afdcd801b60448ea890ce1ff418fb784335e1329519f13aa85e"}, +] +hatanaka = [ + {file = "hatanaka-2.4.0-py3-none-macosx_10_14_x86_64.whl", hash = "sha256:ef594d63473782fac46df5b0c92a59211a3efea1d47c1a964244a0abffc9f3f6"}, + {file = "hatanaka-2.4.0-py3-none-manylinux1_x86_64.whl", hash = "sha256:8fda4aa56f27313de75a806a2f5aa83ed5bb2dc7561bebab856a774d06cf1ee7"}, + {file = "hatanaka-2.4.0-py3-none-win_amd64.whl", hash = "sha256:5a0624f6812b13abb4c996398a60338566885c1786841c4c04de9b1b91da28d2"}, + {file = "hatanaka-2.4.0.tar.gz", hash = "sha256:c22970b99169bddaf22e5239672e856a6bc9602c435f8793d26ad49619a70a99"}, +] +hexdump = [ + {file = "hexdump-3.3.zip", hash = "sha256:d781a43b0c16ace3f9366aade73e8ad3a7bd5137d58f0b45ab2d3f54876f20db"}, +] +html5lib = [ + {file = "html5lib-1.1-py2.py3-none-any.whl", hash = "sha256:0d78f8fde1c230e99fe37986a60526d7049ed4bf8a9fadbad5f00e22e58e041d"}, + {file = "html5lib-1.1.tar.gz", hash = "sha256:b2e5b40261e20f354d198eae92afc10d750afb487ed5e50f9c4eaf07c184146f"}, +] +humanfriendly = [ + {file = "humanfriendly-10.0-py2.py3-none-any.whl", hash = "sha256:1697e1a8a8f550fd43c2865cd84542fc175a61dcb779b6fee18cf6b6ccba1477"}, + {file = "humanfriendly-10.0.tar.gz", hash = "sha256:6b0b831ce8f15f7300721aa49829fc4e83921a9a301cc7f606be6686a2288ddc"}, +] +hypothesis = [ + {file = "hypothesis-6.46.7-py3-none-any.whl", hash = "sha256:2696cdb9005946bf1d2b215cc91d3fc01625e3342eb8743ddd04b667b2f1882b"}, + {file = "hypothesis-6.46.7.tar.gz", hash = "sha256:967009fa561b3a3f8363a73d71923357271c37dc7fa27b30c2d21a1b6092b240"}, +] +identify = [ + {file = "identify-2.5.6-py2.py3-none-any.whl", hash = "sha256:b276db7ec52d7e89f5bc4653380e33054ddc803d25875952ad90b0f012cbcdaa"}, + {file = "identify-2.5.6.tar.gz", hash = "sha256:6c32dbd747aa4ceee1df33f25fed0b0f6e0d65721b15bd151307ff7056d50245"}, +] +idna = [ + {file = "idna-3.4-py3-none-any.whl", hash = "sha256:90b77e79eaa3eba6de819a0c442c0b4ceefc341a7a2ab77d7562bf49f425c5c2"}, + {file = "idna-3.4.tar.gz", hash = "sha256:814f528e8dead7d329833b91c5faa87d60bf71824cd12a7530b5526063d02cb4"}, +] +imageio = [ + {file = "imageio-2.22.2-py3-none-any.whl", hash = "sha256:9bdafe9c5a3d336a187f3f554f3e30bcdbf8a1d7d46f0e4d94e4a535adfb64c7"}, + {file = "imageio-2.22.2.tar.gz", hash = "sha256:db7010cd10712518819a4187baf61b05988361ea20c23e829918727b27acb977"}, +] +imagesize = [ + {file = "imagesize-1.4.1-py2.py3-none-any.whl", hash = "sha256:0d8d18d08f840c19d0ee7ca1fd82490fdc3729b7ac93f49870406ddde8ef8d8b"}, + {file = "imagesize-1.4.1.tar.gz", hash = "sha256:69150444affb9cb0d5cc5a92b3676f0b2fb7cd9ae39e947a5e11a36b4497cd4a"}, +] +importlib-metadata = [ + {file = "importlib_metadata-4.13.0-py3-none-any.whl", hash = "sha256:8a8a81bcf996e74fee46f0d16bd3eaa382a7eb20fd82445c3ad11f4090334116"}, + {file = "importlib_metadata-4.13.0.tar.gz", hash = "sha256:dd0173e8f150d6815e098fd354f6414b0f079af4644ddfe90c71e2fc6174346d"}, +] +importlib-resources = [ + {file = "importlib_resources-5.10.0-py3-none-any.whl", hash = "sha256:ee17ec648f85480d523596ce49eae8ead87d5631ae1551f913c0100b5edd3437"}, + {file = "importlib_resources-5.10.0.tar.gz", hash = "sha256:c01b1b94210d9849f286b86bb51bcea7cd56dde0600d8db721d7b81330711668"}, +] +influxdb-client = [ + {file = "influxdb_client-1.33.0-py3-none-any.whl", hash = "sha256:38a8bedce673ffd2211f60012b5848cb2418977c19f83a43454882b665acbc69"}, + {file = "influxdb_client-1.33.0.tar.gz", hash = "sha256:45f6a1763804a19b972890daf4c5f0bd2d3ae2f202b86451c579e09dcadd30e6"}, +] +iniconfig = [ + {file = "iniconfig-1.1.1-py2.py3-none-any.whl", hash = "sha256:011e24c64b7f47f6ebd835bb12a743f2fbe9a26d4cecaa7f53bc4f35ee9da8b3"}, + {file = "iniconfig-1.1.1.tar.gz", hash = "sha256:bc3af051d7d14b2ee5ef9969666def0cd1a000e121eaea580d4a313df4b37f32"}, +] +inputs = [ + {file = "inputs-0.5-py2.py3-none-any.whl", hash = "sha256:13f894564e52134cf1e3862b1811da034875eb1f2b62e6021e3776e9669a96ec"}, + {file = "inputs-0.5.tar.gz", hash = "sha256:a31d5b96a3525f1232f326be9e7ce8ccaf873c6b1fb84d9f3c9bc3d79b23eae4"}, +] +ipykernel = [ + {file = "ipykernel-6.16.1-py3-none-any.whl", hash = "sha256:32eb7bdc5af57185e9a42b0dcef66413ef91a0490b378eae46cbdf0d4e0b5912"}, + {file = "ipykernel-6.16.1.tar.gz", hash = "sha256:3a27a550c1d682e7825f0f7732b0142b79ef1b21cd2e713cacac0c9847535f13"}, +] +ipython = [ + {file = "ipython-8.5.0-py3-none-any.whl", hash = "sha256:6f090e29ab8ef8643e521763a4f1f39dc3914db643122b1e9d3328ff2e43ada2"}, + {file = "ipython-8.5.0.tar.gz", hash = "sha256:097bdf5cd87576fd066179c9f7f208004f7a6864ee1b20f37d346c0bcb099f84"}, +] +ipython-genutils = [ + {file = "ipython_genutils-0.2.0-py2.py3-none-any.whl", hash = "sha256:72dd37233799e619666c9f639a9da83c34013a73e8bbc79a7a6348d93c61fab8"}, + {file = "ipython_genutils-0.2.0.tar.gz", hash = "sha256:eb2e116e75ecef9d4d228fdc66af54269afa26ab4463042e33785b887c628ba8"}, +] +ipywidgets = [ + {file = "ipywidgets-8.0.2-py3-none-any.whl", hash = "sha256:1dc3dd4ee19ded045ea7c86eb273033d238d8e43f9e7872c52d092683f263891"}, + {file = "ipywidgets-8.0.2.tar.gz", hash = "sha256:08cb75c6e0a96836147cbfdc55580ae04d13e05d26ffbc377b4e1c68baa28b1f"}, +] +isodate = [ + {file = "isodate-0.6.1-py2.py3-none-any.whl", hash = "sha256:0751eece944162659049d35f4f549ed815792b38793f07cf73381c1c87cbed96"}, + {file = "isodate-0.6.1.tar.gz", hash = "sha256:48c5881de7e8b0a0d648cb024c8062dc84e7b840ed81e864c7614fd3c127bde9"}, +] +isort = [ + {file = "isort-5.10.1-py3-none-any.whl", hash = "sha256:6f62d78e2f89b4500b080fe3a81690850cd254227f27f75c3a0c491a1f351ba7"}, + {file = "isort-5.10.1.tar.gz", hash = "sha256:e8443a5e7a020e9d7f97f1d7d9cd17c88bcb3bc7e218bf9cf5095fe550be2951"}, +] +itsdangerous = [ + {file = "itsdangerous-2.1.2-py3-none-any.whl", hash = "sha256:2c2349112351b88699d8d4b6b075022c0808887cb7ad10069318a8b0bc88db44"}, + {file = "itsdangerous-2.1.2.tar.gz", hash = "sha256:5dbbc68b317e5e42f327f9021763545dc3fc3bfe22e6deb96aaf1fc38874156a"}, +] +jaraco-classes = [ + {file = "jaraco.classes-3.2.3-py3-none-any.whl", hash = "sha256:2353de3288bc6b82120752201c6b1c1a14b058267fa424ed5ce5984e3b922158"}, + {file = "jaraco.classes-3.2.3.tar.gz", hash = "sha256:89559fa5c1d3c34eff6f631ad80bb21f378dbcbb35dd161fd2c6b93f5be2f98a"}, +] +jedi = [ + {file = "jedi-0.18.1-py2.py3-none-any.whl", hash = "sha256:637c9635fcf47945ceb91cd7f320234a7be540ded6f3e99a50cb6febdfd1ba8d"}, + {file = "jedi-0.18.1.tar.gz", hash = "sha256:74137626a64a99c8eb6ae5832d99b3bdd7d29a3850fe2aa80a4126b2a7d949ab"}, +] +jeepney = [ + {file = "jeepney-0.8.0-py3-none-any.whl", hash = "sha256:c0a454ad016ca575060802ee4d590dd912e35c122fa04e70306de3d076cce755"}, + {file = "jeepney-0.8.0.tar.gz", hash = "sha256:5efe48d255973902f6badc3ce55e2aa6c5c3b3bc642059ef3a91247bcfcc5806"}, +] +jinja2 = [ + {file = "Jinja2-3.1.2-py3-none-any.whl", hash = "sha256:6088930bfe239f0e6710546ab9c19c9ef35e29792895fed6e6e31a023a182a61"}, + {file = "Jinja2-3.1.2.tar.gz", hash = "sha256:31351a702a408a9e7595a8fc6150fc3f43bb6bf7e319770cbc0db9df9437e852"}, +] +jmespath = [ + {file = "jmespath-1.0.1-py3-none-any.whl", hash = "sha256:02e2e4cc71b5bcab88332eebf907519190dd9e6e82107fa7f83b1003a6252980"}, + {file = "jmespath-1.0.1.tar.gz", hash = "sha256:90261b206d6defd58fdd5e85f478bf633a2901798906be2ad389150c5c60edbe"}, +] +joblib = [ + {file = "joblib-1.2.0-py3-none-any.whl", hash = "sha256:091138ed78f800342968c523bdde947e7a305b8594b910a0fea2ab83c3c6d385"}, + {file = "joblib-1.2.0.tar.gz", hash = "sha256:e1cee4a79e4af22881164f218d4311f60074197fb707e082e803b61f6d137018"}, +] +json-logging-py = [ + {file = "json-logging-py-0.2.tar.gz", hash = "sha256:118b1fe1f4eacaea6370e5b9710d0f6d0c0a4599aef9d5b9875a6a579974fc9a"}, +] +json-rpc = [ + {file = "json-rpc-1.13.0.tar.gz", hash = "sha256:def0dbcf5b7084fc31d677f2f5990d988d06497f2f47f13024274cfb2d5d7589"}, + {file = "json_rpc-1.13.0-py2.py3-none-any.whl", hash = "sha256:84b45058e5ba95f49c7b6afcf7e03ab86bee89bf2c01f3ad8dd41fe114fc1f84"}, +] +json5 = [ + {file = "json5-0.9.10-py2.py3-none-any.whl", hash = "sha256:993189671e7412e9cdd8be8dc61cf402e8e579b35f1d1bb20ae6b09baa78bbce"}, + {file = "json5-0.9.10.tar.gz", hash = "sha256:ad9f048c5b5a4c3802524474ce40a622fae789860a86f10cc4f7e5f9cf9b46ab"}, +] +jsonschema = [ + {file = "jsonschema-4.16.0-py3-none-any.whl", hash = "sha256:9e74b8f9738d6a946d70705dc692b74b5429cd0960d58e79ffecfc43b2221eb9"}, + {file = "jsonschema-4.16.0.tar.gz", hash = "sha256:165059f076eff6971bae5b742fc029a7b4ef3f9bcf04c14e4776a7605de14b23"}, +] +jupyter = [ + {file = "jupyter-1.0.0-py2.py3-none-any.whl", hash = "sha256:5b290f93b98ffbc21c0c7e749f054b3267782166d72fa5e3ed1ed4eaf34a2b78"}, + {file = "jupyter-1.0.0.tar.gz", hash = "sha256:d9dc4b3318f310e34c82951ea5d6683f67bed7def4b259fafbfe4f1beb1d8e5f"}, + {file = "jupyter-1.0.0.zip", hash = "sha256:3e1f86076bbb7c8c207829390305a2b1fe836d471ed54be66a3b8c41e7f46cc7"}, +] +jupyter-client = [ + {file = "jupyter_client-7.4.3-py3-none-any.whl", hash = "sha256:8845e3f5a339734b1ecc21d2100638aa1c7a145e356a31845f155cda5b624b1c"}, + {file = "jupyter_client-7.4.3.tar.gz", hash = "sha256:4fa2514cdb54dd9fbdcf7d7e4c5c3c8a973028168a8b4fc097b6aef625be13b0"}, +] +jupyter-console = [ + {file = "jupyter_console-6.4.4-py3-none-any.whl", hash = "sha256:756df7f4f60c986e7bc0172e4493d3830a7e6e75c08750bbe59c0a5403ad6dee"}, + {file = "jupyter_console-6.4.4.tar.gz", hash = "sha256:172f5335e31d600df61613a97b7f0352f2c8250bbd1092ef2d658f77249f89fb"}, +] +jupyter-core = [ + {file = "jupyter_core-4.11.2-py3-none-any.whl", hash = "sha256:3815e80ec5272c0c19aad087a0d2775df2852cfca8f5a17069e99c9350cecff8"}, + {file = "jupyter_core-4.11.2.tar.gz", hash = "sha256:c2909b9bc7dca75560a6c5ae78c34fd305ede31cd864da3c0d0bb2ed89aa9337"}, +] +jupyter-server = [ + {file = "jupyter_server-1.21.0-py3-none-any.whl", hash = "sha256:992531008544d77e05a16251cdfbd0bdff1b1efa14760c79b9cc776ac9214cf1"}, + {file = "jupyter_server-1.21.0.tar.gz", hash = "sha256:d0adca19913a3763359be7f0b8c2ea8bfde356f4b8edd8e3149d7d0fbfaa248b"}, +] +jupyterlab = [ + {file = "jupyterlab-3.4.8-py3-none-any.whl", hash = "sha256:4626a0434c76a3a22f11c4efaa1d031d2586367f72cfdbdbff6b08b6ef0060f7"}, + {file = "jupyterlab-3.4.8.tar.gz", hash = "sha256:1fafb8b657005d91603f3c3adfd6d9e8eaf33fdc601537fef09283332efe67cb"}, +] +jupyterlab-pygments = [ + {file = "jupyterlab_pygments-0.2.2-py2.py3-none-any.whl", hash = "sha256:2405800db07c9f770863bcf8049a529c3dd4d3e28536638bd7c1c01d2748309f"}, + {file = "jupyterlab_pygments-0.2.2.tar.gz", hash = "sha256:7405d7fde60819d905a9fa8ce89e4cd830e318cdad22a0030f7a901da705585d"}, +] +jupyterlab-server = [ + {file = "jupyterlab_server-2.16.1-py3-none-any.whl", hash = "sha256:b572cd3e59b0722120f41d47f2363a0072765227184aea418b7cc276db4d75fd"}, + {file = "jupyterlab_server-2.16.1.tar.gz", hash = "sha256:fe0de558ff3bb447a32e24099aa7e17444fdbc8c08f6dbc0171cb1a0ae382d3f"}, +] +jupyterlab-vim = [ + {file = "jupyterlab_vim-0.15.1-py3-none-any.whl", hash = "sha256:e3ea4a0f140bb2956fa7c3b75442121cce264930fb94f06e5b0f75ccae2bde2e"}, + {file = "jupyterlab_vim-0.15.1.tar.gz", hash = "sha256:c4282beb4a67d21f7126e32cda19f99ed324a1d3fc494560e393fe53f7519a74"}, +] +jupyterlab-widgets = [ + {file = "jupyterlab_widgets-3.0.3-py3-none-any.whl", hash = "sha256:6aa1bc0045470d54d76b9c0b7609a8f8f0087573bae25700a370c11f82cb38c8"}, + {file = "jupyterlab_widgets-3.0.3.tar.gz", hash = "sha256:c767181399b4ca8b647befe2d913b1260f51bf9d8ef9b7a14632d4c1a7b536bd"}, +] +keyring = [ + {file = "keyring-23.9.3-py3-none-any.whl", hash = "sha256:69732a15cb1433bdfbc3b980a8a36a04878a6cfd7cb99f497b573f31618001c0"}, + {file = "keyring-23.9.3.tar.gz", hash = "sha256:69b01dd83c42f590250fe7a1f503fc229b14de83857314b1933a3ddbf595c4a5"}, +] +kiwisolver = [ + {file = "kiwisolver-1.4.4-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:2f5e60fabb7343a836360c4f0919b8cd0d6dbf08ad2ca6b9cf90bf0c76a3c4f6"}, + {file = "kiwisolver-1.4.4-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:10ee06759482c78bdb864f4109886dff7b8a56529bc1609d4f1112b93fe6423c"}, + {file = "kiwisolver-1.4.4-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:c79ebe8f3676a4c6630fd3f777f3cfecf9289666c84e775a67d1d358578dc2e3"}, + {file = "kiwisolver-1.4.4-cp310-cp310-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:abbe9fa13da955feb8202e215c4018f4bb57469b1b78c7a4c5c7b93001699938"}, + {file = "kiwisolver-1.4.4-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:7577c1987baa3adc4b3c62c33bd1118c3ef5c8ddef36f0f2c950ae0b199e100d"}, + {file = "kiwisolver-1.4.4-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f8ad8285b01b0d4695102546b342b493b3ccc6781fc28c8c6a1bb63e95d22f09"}, + {file = "kiwisolver-1.4.4-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8ed58b8acf29798b036d347791141767ccf65eee7f26bde03a71c944449e53de"}, + {file = "kiwisolver-1.4.4-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a68b62a02953b9841730db7797422f983935aeefceb1679f0fc85cbfbd311c32"}, + {file = "kiwisolver-1.4.4-cp310-cp310-win32.whl", hash = "sha256:e92a513161077b53447160b9bd8f522edfbed4bd9759e4c18ab05d7ef7e49408"}, + {file = "kiwisolver-1.4.4-cp310-cp310-win_amd64.whl", hash = "sha256:3fe20f63c9ecee44560d0e7f116b3a747a5d7203376abeea292ab3152334d004"}, + {file = "kiwisolver-1.4.4-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:e0ea21f66820452a3f5d1655f8704a60d66ba1191359b96541eaf457710a5fc6"}, + {file = "kiwisolver-1.4.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:bc9db8a3efb3e403e4ecc6cd9489ea2bac94244f80c78e27c31dcc00d2790ac2"}, + {file = "kiwisolver-1.4.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:d5b61785a9ce44e5a4b880272baa7cf6c8f48a5180c3e81c59553ba0cb0821ca"}, + {file = "kiwisolver-1.4.4-cp311-cp311-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c2dbb44c3f7e6c4d3487b31037b1bdbf424d97687c1747ce4ff2895795c9bf69"}, + {file = "kiwisolver-1.4.4-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6295ecd49304dcf3bfbfa45d9a081c96509e95f4b9d0eb7ee4ec0530c4a96514"}, + {file = "kiwisolver-1.4.4-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4bd472dbe5e136f96a4b18f295d159d7f26fd399136f5b17b08c4e5f498cd494"}, + {file = "kiwisolver-1.4.4-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:bf7d9fce9bcc4752ca4a1b80aabd38f6d19009ea5cbda0e0856983cf6d0023f5"}, + {file = "kiwisolver-1.4.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:78d6601aed50c74e0ef02f4204da1816147a6d3fbdc8b3872d263338a9052c51"}, + {file = "kiwisolver-1.4.4-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:877272cf6b4b7e94c9614f9b10140e198d2186363728ed0f701c6eee1baec1da"}, + {file = "kiwisolver-1.4.4-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:db608a6757adabb32f1cfe6066e39b3706d8c3aa69bbc353a5b61edad36a5cb4"}, + {file = "kiwisolver-1.4.4-cp311-cp311-musllinux_1_1_ppc64le.whl", hash = "sha256:5853eb494c71e267912275e5586fe281444eb5e722de4e131cddf9d442615626"}, + {file = "kiwisolver-1.4.4-cp311-cp311-musllinux_1_1_s390x.whl", hash = "sha256:f0a1dbdb5ecbef0d34eb77e56fcb3e95bbd7e50835d9782a45df81cc46949750"}, + {file = "kiwisolver-1.4.4-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:283dffbf061a4ec60391d51e6155e372a1f7a4f5b15d59c8505339454f8989e4"}, + {file = "kiwisolver-1.4.4-cp311-cp311-win32.whl", hash = "sha256:d06adcfa62a4431d404c31216f0f8ac97397d799cd53800e9d3efc2fbb3cf14e"}, + {file = "kiwisolver-1.4.4-cp311-cp311-win_amd64.whl", hash = "sha256:e7da3fec7408813a7cebc9e4ec55afed2d0fd65c4754bc376bf03498d4e92686"}, + {file = "kiwisolver-1.4.4-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:62ac9cc684da4cf1778d07a89bf5f81b35834cb96ca523d3a7fb32509380cbf6"}, + {file = "kiwisolver-1.4.4-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:41dae968a94b1ef1897cb322b39360a0812661dba7c682aa45098eb8e193dbdf"}, + {file = "kiwisolver-1.4.4-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:02f79693ec433cb4b5f51694e8477ae83b3205768a6fb48ffba60549080e295b"}, + {file = "kiwisolver-1.4.4-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d0611a0a2a518464c05ddd5a3a1a0e856ccc10e67079bb17f265ad19ab3c7597"}, + {file = "kiwisolver-1.4.4-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:db5283d90da4174865d520e7366801a93777201e91e79bacbac6e6927cbceede"}, + {file = "kiwisolver-1.4.4-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:1041feb4cda8708ce73bb4dcb9ce1ccf49d553bf87c3954bdfa46f0c3f77252c"}, + {file = "kiwisolver-1.4.4-cp37-cp37m-win32.whl", hash = "sha256:a553dadda40fef6bfa1456dc4be49b113aa92c2a9a9e8711e955618cd69622e3"}, + {file = "kiwisolver-1.4.4-cp37-cp37m-win_amd64.whl", hash = "sha256:03baab2d6b4a54ddbb43bba1a3a2d1627e82d205c5cf8f4c924dc49284b87166"}, + {file = "kiwisolver-1.4.4-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:841293b17ad704d70c578f1f0013c890e219952169ce8a24ebc063eecf775454"}, + {file = "kiwisolver-1.4.4-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:f4f270de01dd3e129a72efad823da90cc4d6aafb64c410c9033aba70db9f1ff0"}, + {file = "kiwisolver-1.4.4-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:f9f39e2f049db33a908319cf46624a569b36983c7c78318e9726a4cb8923b26c"}, + {file = "kiwisolver-1.4.4-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c97528e64cb9ebeff9701e7938653a9951922f2a38bd847787d4a8e498cc83ae"}, + {file = "kiwisolver-1.4.4-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1d1573129aa0fd901076e2bfb4275a35f5b7aa60fbfb984499d661ec950320b0"}, + {file = "kiwisolver-1.4.4-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ad881edc7ccb9d65b0224f4e4d05a1e85cf62d73aab798943df6d48ab0cd79a1"}, + {file = "kiwisolver-1.4.4-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:b428ef021242344340460fa4c9185d0b1f66fbdbfecc6c63eff4b7c29fad429d"}, + {file = "kiwisolver-1.4.4-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:2e407cb4bd5a13984a6c2c0fe1845e4e41e96f183e5e5cd4d77a857d9693494c"}, + {file = "kiwisolver-1.4.4-cp38-cp38-win32.whl", hash = "sha256:75facbe9606748f43428fc91a43edb46c7ff68889b91fa31f53b58894503a191"}, + {file = "kiwisolver-1.4.4-cp38-cp38-win_amd64.whl", hash = "sha256:5bce61af018b0cb2055e0e72e7d65290d822d3feee430b7b8203d8a855e78766"}, + {file = "kiwisolver-1.4.4-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:8c808594c88a025d4e322d5bb549282c93c8e1ba71b790f539567932722d7bd8"}, + {file = "kiwisolver-1.4.4-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:f0a71d85ecdd570ded8ac3d1c0f480842f49a40beb423bb8014539a9f32a5897"}, + {file = "kiwisolver-1.4.4-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:b533558eae785e33e8c148a8d9921692a9fe5aa516efbdff8606e7d87b9d5824"}, + {file = "kiwisolver-1.4.4-cp39-cp39-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:efda5fc8cc1c61e4f639b8067d118e742b812c930f708e6667a5ce0d13499e29"}, + {file = "kiwisolver-1.4.4-cp39-cp39-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:7c43e1e1206cd421cd92e6b3280d4385d41d7166b3ed577ac20444b6995a445f"}, + {file = "kiwisolver-1.4.4-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bc8d3bd6c72b2dd9decf16ce70e20abcb3274ba01b4e1c96031e0c4067d1e7cd"}, + {file = "kiwisolver-1.4.4-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4ea39b0ccc4f5d803e3337dd46bcce60b702be4d86fd0b3d7531ef10fd99a1ac"}, + {file = "kiwisolver-1.4.4-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:968f44fdbf6dd757d12920d63b566eeb4d5b395fd2d00d29d7ef00a00582aac9"}, + {file = "kiwisolver-1.4.4-cp39-cp39-win32.whl", hash = "sha256:da7e547706e69e45d95e116e6939488d62174e033b763ab1496b4c29b76fabea"}, + {file = "kiwisolver-1.4.4-cp39-cp39-win_amd64.whl", hash = "sha256:ba59c92039ec0a66103b1d5fe588fa546373587a7d68f5c96f743c3396afc04b"}, + {file = "kiwisolver-1.4.4-pp37-pypy37_pp73-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:91672bacaa030f92fc2f43b620d7b337fd9a5af28b0d6ed3f77afc43c4a64b5a"}, + {file = "kiwisolver-1.4.4-pp37-pypy37_pp73-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:787518a6789009c159453da4d6b683f468ef7a65bbde796bcea803ccf191058d"}, + {file = "kiwisolver-1.4.4-pp37-pypy37_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:da152d8cdcab0e56e4f45eb08b9aea6455845ec83172092f09b0e077ece2cf7a"}, + {file = "kiwisolver-1.4.4-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:ecb1fa0db7bf4cff9dac752abb19505a233c7f16684c5826d1f11ebd9472b871"}, + {file = "kiwisolver-1.4.4-pp38-pypy38_pp73-macosx_10_9_x86_64.whl", hash = "sha256:28bc5b299f48150b5f822ce68624e445040595a4ac3d59251703779836eceff9"}, + {file = "kiwisolver-1.4.4-pp38-pypy38_pp73-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:81e38381b782cc7e1e46c4e14cd997ee6040768101aefc8fa3c24a4cc58e98f8"}, + {file = "kiwisolver-1.4.4-pp38-pypy38_pp73-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:2a66fdfb34e05b705620dd567f5a03f239a088d5a3f321e7b6ac3239d22aa286"}, + {file = "kiwisolver-1.4.4-pp38-pypy38_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:872b8ca05c40d309ed13eb2e582cab0c5a05e81e987ab9c521bf05ad1d5cf5cb"}, + {file = "kiwisolver-1.4.4-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:70e7c2e7b750585569564e2e5ca9845acfaa5da56ac46df68414f29fea97be9f"}, + {file = "kiwisolver-1.4.4-pp39-pypy39_pp73-macosx_10_9_x86_64.whl", hash = "sha256:9f85003f5dfa867e86d53fac6f7e6f30c045673fa27b603c397753bebadc3008"}, + {file = "kiwisolver-1.4.4-pp39-pypy39_pp73-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:2e307eb9bd99801f82789b44bb45e9f541961831c7311521b13a6c85afc09767"}, + {file = "kiwisolver-1.4.4-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b1792d939ec70abe76f5054d3f36ed5656021dcad1322d1cc996d4e54165cef9"}, + {file = "kiwisolver-1.4.4-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f6cb459eea32a4e2cf18ba5fcece2dbdf496384413bc1bae15583f19e567f3b2"}, + {file = "kiwisolver-1.4.4-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:36dafec3d6d6088d34e2de6b85f9d8e2324eb734162fba59d2ba9ed7a2043d5b"}, + {file = "kiwisolver-1.4.4.tar.gz", hash = "sha256:d41997519fcba4a1e46eb4a2fe31bc12f0ff957b2b81bac28db24744f333e955"}, +] +knack = [ + {file = "knack-0.10.0-py3-none-any.whl", hash = "sha256:9e989286622d4a028ba738111f9fac475bae93146d375522141908ce43077cda"}, + {file = "knack-0.10.0.tar.gz", hash = "sha256:13190fa95d4c21bce04b4bee22d6a4e3fb19a93b6999b1d104bd02c476706c28"}, +] +lazy-object-proxy = [ + {file = "lazy-object-proxy-1.7.1.tar.gz", hash = "sha256:d609c75b986def706743cdebe5e47553f4a5a1da9c5ff66d76013ef396b5a8a4"}, + {file = "lazy_object_proxy-1.7.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:bb8c5fd1684d60a9902c60ebe276da1f2281a318ca16c1d0a96db28f62e9166b"}, + {file = "lazy_object_proxy-1.7.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a57d51ed2997e97f3b8e3500c984db50a554bb5db56c50b5dab1b41339b37e36"}, + {file = "lazy_object_proxy-1.7.1-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd45683c3caddf83abbb1249b653a266e7069a09f486daa8863fb0e7496a9fdb"}, + {file = "lazy_object_proxy-1.7.1-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:8561da8b3dd22d696244d6d0d5330618c993a215070f473b699e00cf1f3f6443"}, + {file = "lazy_object_proxy-1.7.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:fccdf7c2c5821a8cbd0a9440a456f5050492f2270bd54e94360cac663398739b"}, + {file = "lazy_object_proxy-1.7.1-cp310-cp310-win32.whl", hash = "sha256:898322f8d078f2654d275124a8dd19b079080ae977033b713f677afcfc88e2b9"}, + {file = "lazy_object_proxy-1.7.1-cp310-cp310-win_amd64.whl", hash = "sha256:85b232e791f2229a4f55840ed54706110c80c0a210d076eee093f2b2e33e1bfd"}, + {file = "lazy_object_proxy-1.7.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:46ff647e76f106bb444b4533bb4153c7370cdf52efc62ccfc1a28bdb3cc95442"}, + {file = "lazy_object_proxy-1.7.1-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:12f3bb77efe1367b2515f8cb4790a11cffae889148ad33adad07b9b55e0ab22c"}, + {file = "lazy_object_proxy-1.7.1-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c19814163728941bb871240d45c4c30d33b8a2e85972c44d4e63dd7107faba44"}, + {file = "lazy_object_proxy-1.7.1-cp36-cp36m-musllinux_1_1_aarch64.whl", hash = "sha256:e40f2013d96d30217a51eeb1db28c9ac41e9d0ee915ef9d00da639c5b63f01a1"}, + {file = "lazy_object_proxy-1.7.1-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:2052837718516a94940867e16b1bb10edb069ab475c3ad84fd1e1a6dd2c0fcfc"}, + {file = "lazy_object_proxy-1.7.1-cp36-cp36m-win32.whl", hash = "sha256:6a24357267aa976abab660b1d47a34aaf07259a0c3859a34e536f1ee6e76b5bb"}, + {file = "lazy_object_proxy-1.7.1-cp36-cp36m-win_amd64.whl", hash = "sha256:6aff3fe5de0831867092e017cf67e2750c6a1c7d88d84d2481bd84a2e019ec35"}, + {file = "lazy_object_proxy-1.7.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:6a6e94c7b02641d1311228a102607ecd576f70734dc3d5e22610111aeacba8a0"}, + {file = "lazy_object_proxy-1.7.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c4ce15276a1a14549d7e81c243b887293904ad2d94ad767f42df91e75fd7b5b6"}, + {file = "lazy_object_proxy-1.7.1-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e368b7f7eac182a59ff1f81d5f3802161932a41dc1b1cc45c1f757dc876b5d2c"}, + {file = "lazy_object_proxy-1.7.1-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:6ecbb350991d6434e1388bee761ece3260e5228952b1f0c46ffc800eb313ff42"}, + {file = "lazy_object_proxy-1.7.1-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:553b0f0d8dbf21890dd66edd771f9b1b5f51bd912fa5f26de4449bfc5af5e029"}, + {file = "lazy_object_proxy-1.7.1-cp37-cp37m-win32.whl", hash = "sha256:c7a683c37a8a24f6428c28c561c80d5f4fd316ddcf0c7cab999b15ab3f5c5c69"}, + {file = "lazy_object_proxy-1.7.1-cp37-cp37m-win_amd64.whl", hash = "sha256:df2631f9d67259dc9620d831384ed7732a198eb434eadf69aea95ad18c587a28"}, + {file = "lazy_object_proxy-1.7.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:07fa44286cda977bd4803b656ffc1c9b7e3bc7dff7d34263446aec8f8c96f88a"}, + {file = "lazy_object_proxy-1.7.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4dca6244e4121c74cc20542c2ca39e5c4a5027c81d112bfb893cf0790f96f57e"}, + {file = "lazy_object_proxy-1.7.1-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:91ba172fc5b03978764d1df5144b4ba4ab13290d7bab7a50f12d8117f8630c38"}, + {file = "lazy_object_proxy-1.7.1-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:043651b6cb706eee4f91854da4a089816a6606c1428fd391573ef8cb642ae4f7"}, + {file = "lazy_object_proxy-1.7.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:b9e89b87c707dd769c4ea91f7a31538888aad05c116a59820f28d59b3ebfe25a"}, + {file = "lazy_object_proxy-1.7.1-cp38-cp38-win32.whl", hash = "sha256:9d166602b525bf54ac994cf833c385bfcc341b364e3ee71e3bf5a1336e677b55"}, + {file = "lazy_object_proxy-1.7.1-cp38-cp38-win_amd64.whl", hash = "sha256:8f3953eb575b45480db6568306893f0bd9d8dfeeebd46812aa09ca9579595148"}, + {file = "lazy_object_proxy-1.7.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:dd7ed7429dbb6c494aa9bc4e09d94b778a3579be699f9d67da7e6804c422d3de"}, + {file = "lazy_object_proxy-1.7.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:70ed0c2b380eb6248abdef3cd425fc52f0abd92d2b07ce26359fcbc399f636ad"}, + {file = "lazy_object_proxy-1.7.1-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7096a5e0c1115ec82641afbdd70451a144558ea5cf564a896294e346eb611be1"}, + {file = "lazy_object_proxy-1.7.1-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:f769457a639403073968d118bc70110e7dce294688009f5c24ab78800ae56dc8"}, + {file = "lazy_object_proxy-1.7.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:39b0e26725c5023757fc1ab2a89ef9d7ab23b84f9251e28f9cc114d5b59c1b09"}, + {file = "lazy_object_proxy-1.7.1-cp39-cp39-win32.whl", hash = "sha256:2130db8ed69a48a3440103d4a520b89d8a9405f1b06e2cc81640509e8bf6548f"}, + {file = "lazy_object_proxy-1.7.1-cp39-cp39-win_amd64.whl", hash = "sha256:677ea950bef409b47e51e733283544ac3d660b709cfce7b187f5ace137960d61"}, + {file = "lazy_object_proxy-1.7.1-pp37.pp38-none-any.whl", hash = "sha256:d66906d5785da8e0be7360912e99c9188b70f52c422f9fc18223347235691a84"}, +] +libusb1 = [ + {file = "libusb1-3.0.0-py3-none-any.whl", hash = "sha256:0e652b04cbe85ec8e74f9ee82b49f861fb14b5320ae51399387ad2601ccc0500"}, + {file = "libusb1-3.0.0-py3-none-win32.whl", hash = "sha256:083f75e5d15cb5e2159e64c308c5317284eae926a820d6dce53a9505d18be3b2"}, + {file = "libusb1-3.0.0-py3-none-win_amd64.whl", hash = "sha256:6f6bb010632ada35c661d17a65e135077beef0fbb2434d5ffdb3a4a911fd9490"}, + {file = "libusb1-3.0.0.tar.gz", hash = "sha256:5792a9defee40f15d330a40d9b1800545c32e47ba7fc66b6f28f133c9fcc8538"}, +] +lockfile = [ + {file = "lockfile-0.12.2-py2.py3-none-any.whl", hash = "sha256:6c3cb24f344923d30b2785d5ad75182c8ea7ac1b6171b08657258ec7429d50fa"}, + {file = "lockfile-0.12.2.tar.gz", hash = "sha256:6aed02de03cba24efabcd600b30540140634fc06cfa603822d508d5361e9f799"}, +] +lru-dict = [ + {file = "lru-dict-1.1.8.tar.gz", hash = "sha256:878bc8ef4073e5cfb953dfc1cf4585db41e8b814c0106abde34d00ee0d0b3115"}, + {file = "lru_dict-1.1.8-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:f9d5815c0e85922cd0fb8344ca8b1c7cf020bf9fc45e670d34d51932c91fd7ec"}, + {file = "lru_dict-1.1.8-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f877f53249c3e49bbd7612f9083127290bede6c7d6501513567ab1bf9c581381"}, + {file = "lru_dict-1.1.8-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3fef595c4f573141d54a38bda9221b9ee3cbe0acc73d67304a1a6d5972eb2a02"}, + {file = "lru_dict-1.1.8-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:db20597c4e67b4095b376ce2e83930c560f4ce481e8d05737885307ed02ba7c1"}, + {file = "lru_dict-1.1.8-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:5b09dbe47bc4b4d45ffe56067aff190bc3c0049575da6e52127e114236e0a6a7"}, + {file = "lru_dict-1.1.8-cp310-cp310-win32.whl", hash = "sha256:3b1692755fef288b67af5cd8a973eb331d1f44cb02cbdc13660040809c2bfec6"}, + {file = "lru_dict-1.1.8-cp310-cp310-win_amd64.whl", hash = "sha256:8f6561f9cd5a452cb84905c6a87aa944fdfdc0f41cc057d03b71f9b29b2cc4bd"}, + {file = "lru_dict-1.1.8-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:ca8f89361e0e7aad0bf93ae03a31502e96280faeb7fb92267f4998fb230d36b2"}, + {file = "lru_dict-1.1.8-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:8c50ab9edaa5da5838426816a2b7bcde9d576b4fc50e6a8c062073dbc4969d78"}, + {file = "lru_dict-1.1.8-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1fe16ade5fd0a57e9a335f69b8055aaa6fb278fbfa250458e4f6b8255115578f"}, + {file = "lru_dict-1.1.8-cp36-cp36m-musllinux_1_1_i686.whl", hash = "sha256:de972c7f4bc7b6002acff2a8de984c55fbd7f2289dba659cfd90f7a0f5d8f5d1"}, + {file = "lru_dict-1.1.8-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:3d003a864899c29b0379e412709a6e516cbd6a72ee10b09d0b33226343617412"}, + {file = "lru_dict-1.1.8-cp36-cp36m-win32.whl", hash = "sha256:6e2a7aa9e36626fb48fdc341c7e3685a31a7b50ea4918677ea436271ad0d904d"}, + {file = "lru_dict-1.1.8-cp36-cp36m-win_amd64.whl", hash = "sha256:d2ed4151445c3f30423c2698f72197d64b27b1cd61d8d56702ffe235584e47c2"}, + {file = "lru_dict-1.1.8-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:075b9dd46d7022b675419bc6e3631748ae184bc8af195d20365a98b4f3bb2914"}, + {file = "lru_dict-1.1.8-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:70364e3cbef536adab8762b4835e18f5ca8e3fddd8bd0ec9258c42bbebd0ee77"}, + {file = "lru_dict-1.1.8-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:720f5728e537f11a311e8b720793a224e985d20e6b7c3d34a891a391865af1a2"}, + {file = "lru_dict-1.1.8-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:c2fe692332c2f1d81fd27457db4b35143801475bfc2e57173a2403588dd82a42"}, + {file = "lru_dict-1.1.8-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:86d32a4498b74a75340497890a260d37bf1560ad2683969393032977dd36b088"}, + {file = "lru_dict-1.1.8-cp37-cp37m-win32.whl", hash = "sha256:348167f110494cfafae70c066470a6f4e4d43523933edf16ccdb8947f3b5fae0"}, + {file = "lru_dict-1.1.8-cp37-cp37m-win_amd64.whl", hash = "sha256:9be6c4039ef328676b868acea619cd100e3de1a35b3be211cf0eaf9775563b65"}, + {file = "lru_dict-1.1.8-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:a777d48319d293b1b6a933d606c0e4899690a139b4c81173451913bbcab6f44f"}, + {file = "lru_dict-1.1.8-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:99f6cfb3e28490357a0805b409caf693e46c61f8dbb789c51355adb693c568d3"}, + {file = "lru_dict-1.1.8-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:163079dbda54c3e6422b23da39fb3ecc561035d65e8496ff1950cbdb376018e1"}, + {file = "lru_dict-1.1.8-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:0972d669e9e207617e06416166718b073a49bf449abbd23940d9545c0847a4d9"}, + {file = "lru_dict-1.1.8-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:97c24ffc55de6013075979f440acd174e88819f30387074639fb7d7178ca253e"}, + {file = "lru_dict-1.1.8-cp38-cp38-win32.whl", hash = "sha256:0f83cd70a6d32f9018d471be609f3af73058f700691657db4a3d3dd78d3f96dd"}, + {file = "lru_dict-1.1.8-cp38-cp38-win_amd64.whl", hash = "sha256:add762163f4af7f4173fafa4092eb7c7f023cf139ef6d2015cfea867e1440d82"}, + {file = "lru_dict-1.1.8-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:484ac524e4615f06dc72ffbfd83f26e073c9ec256de5413634fbd024c010a8bc"}, + {file = "lru_dict-1.1.8-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7284bdbc5579bbdc3fc8f869ed4c169f403835566ab0f84567cdbfdd05241847"}, + {file = "lru_dict-1.1.8-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3ca497cb25f19f24171f9172805f3ff135b911aeb91960bd4af8e230421ccb51"}, + {file = "lru_dict-1.1.8-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:f1df1da204a9f0b5eb8393a46070f1d984fa8559435ee790d7f8f5602038fc00"}, + {file = "lru_dict-1.1.8-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:f4d0a6d733a23865019b1c97ed6fb1fdb739be923192abf4dbb644f697a26a69"}, + {file = "lru_dict-1.1.8-cp39-cp39-win32.whl", hash = "sha256:7be1b66926277993cecdc174c15a20c8ce785c1f8b39aa560714a513eef06473"}, + {file = "lru_dict-1.1.8-cp39-cp39-win_amd64.whl", hash = "sha256:881104711900af45967c2e5ce3e62291dd57d5b2a224d58b7c9f60bf4ad41b8c"}, + {file = "lru_dict-1.1.8-pp37-pypy37_pp73-macosx_10_9_x86_64.whl", hash = "sha256:beb089c46bd95243d1ac5b2bd13627317b08bf40dd8dc16d4b7ee7ecb3cf65ca"}, + {file = "lru_dict-1.1.8-pp37-pypy37_pp73-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:10fe823ff90b655f0b6ba124e2b576ecda8c61b8ead76b456db67831942d22f2"}, + {file = "lru_dict-1.1.8-pp37-pypy37_pp73-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c07163c9dcbb2eca377f366b1331f46302fd8b6b72ab4d603087feca00044bb0"}, + {file = "lru_dict-1.1.8-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:93336911544ebc0e466272043adab9fb9f6e9dcba6024b639c32553a3790e089"}, + {file = "lru_dict-1.1.8-pp38-pypy38_pp73-macosx_10_9_x86_64.whl", hash = "sha256:55aeda6b6789b2d030066b4f5f6fc3596560ba2a69028f35f3682a795701b5b1"}, + {file = "lru_dict-1.1.8-pp38-pypy38_pp73-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:262a4e622010ceb960a6a5222ed011090e50954d45070fd369c0fa4d2ed7d9a9"}, + {file = "lru_dict-1.1.8-pp38-pypy38_pp73-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b6f64005ede008b7a866be8f3f6274dbf74e656e15e4004e9d99ad65efb01809"}, + {file = "lru_dict-1.1.8-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:9d70257246b8207e8ef3d8b18457089f5ff0dfb087bd36eb33bce6584f2e0b3a"}, + {file = "lru_dict-1.1.8-pp39-pypy39_pp73-macosx_10_9_x86_64.whl", hash = "sha256:f874e9c2209dada1a080545331aa1277ec060a13f61684a8642788bf44b2325f"}, + {file = "lru_dict-1.1.8-pp39-pypy39_pp73-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5a592363c93d6fc6472d5affe2819e1c7590746aecb464774a4f67e09fbefdfc"}, + {file = "lru_dict-1.1.8-pp39-pypy39_pp73-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2f340b61f3cdfee71f66da7dbfd9a5ea2db6974502ccff2065cdb76619840dca"}, + {file = "lru_dict-1.1.8-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:9447214e4857e16d14158794ef01e4501d8fad07d298d03308d9f90512df02fa"}, +] +lxml = [ + {file = "lxml-4.9.1-cp27-cp27m-macosx_10_15_x86_64.whl", hash = "sha256:98cafc618614d72b02185ac583c6f7796202062c41d2eeecdf07820bad3295ed"}, + {file = "lxml-4.9.1-cp27-cp27m-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:c62e8dd9754b7debda0c5ba59d34509c4688f853588d75b53c3791983faa96fc"}, + {file = "lxml-4.9.1-cp27-cp27m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:21fb3d24ab430fc538a96e9fbb9b150029914805d551deeac7d7822f64631dfc"}, + {file = "lxml-4.9.1-cp27-cp27m-win32.whl", hash = "sha256:86e92728ef3fc842c50a5cb1d5ba2bc66db7da08a7af53fb3da79e202d1b2cd3"}, + {file = "lxml-4.9.1-cp27-cp27m-win_amd64.whl", hash = "sha256:4cfbe42c686f33944e12f45a27d25a492cc0e43e1dc1da5d6a87cbcaf2e95627"}, + {file = "lxml-4.9.1-cp27-cp27mu-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:dad7b164905d3e534883281c050180afcf1e230c3d4a54e8038aa5cfcf312b84"}, + {file = "lxml-4.9.1-cp27-cp27mu-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:a614e4afed58c14254e67862456d212c4dcceebab2eaa44d627c2ca04bf86837"}, + {file = "lxml-4.9.1-cp310-cp310-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_24_i686.whl", hash = "sha256:f9ced82717c7ec65a67667bb05865ffe38af0e835cdd78728f1209c8fffe0cad"}, + {file = "lxml-4.9.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:d9fc0bf3ff86c17348dfc5d322f627d78273eba545db865c3cd14b3f19e57fa5"}, + {file = "lxml-4.9.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:e5f66bdf0976ec667fc4594d2812a00b07ed14d1b44259d19a41ae3fff99f2b8"}, + {file = "lxml-4.9.1-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:fe17d10b97fdf58155f858606bddb4e037b805a60ae023c009f760d8361a4eb8"}, + {file = "lxml-4.9.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:8caf4d16b31961e964c62194ea3e26a0e9561cdf72eecb1781458b67ec83423d"}, + {file = "lxml-4.9.1-cp310-cp310-win32.whl", hash = "sha256:4780677767dd52b99f0af1f123bc2c22873d30b474aa0e2fc3fe5e02217687c7"}, + {file = "lxml-4.9.1-cp310-cp310-win_amd64.whl", hash = "sha256:b122a188cd292c4d2fcd78d04f863b789ef43aa129b233d7c9004de08693728b"}, + {file = "lxml-4.9.1-cp311-cp311-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_24_i686.whl", hash = "sha256:be9eb06489bc975c38706902cbc6888f39e946b81383abc2838d186f0e8b6a9d"}, + {file = "lxml-4.9.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:f1be258c4d3dc609e654a1dc59d37b17d7fef05df912c01fc2e15eb43a9735f3"}, + {file = "lxml-4.9.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:927a9dd016d6033bc12e0bf5dee1dde140235fc8d0d51099353c76081c03dc29"}, + {file = "lxml-4.9.1-cp35-cp35m-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:9232b09f5efee6a495a99ae6824881940d6447debe272ea400c02e3b68aad85d"}, + {file = "lxml-4.9.1-cp35-cp35m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:04da965dfebb5dac2619cb90fcf93efdb35b3c6994fea58a157a834f2f94b318"}, + {file = "lxml-4.9.1-cp35-cp35m-win32.whl", hash = "sha256:4d5bae0a37af799207140652a700f21a85946f107a199bcb06720b13a4f1f0b7"}, + {file = "lxml-4.9.1-cp35-cp35m-win_amd64.whl", hash = "sha256:4878e667ebabe9b65e785ac8da4d48886fe81193a84bbe49f12acff8f7a383a4"}, + {file = "lxml-4.9.1-cp36-cp36m-macosx_10_15_x86_64.whl", hash = "sha256:1355755b62c28950f9ce123c7a41460ed9743c699905cbe664a5bcc5c9c7c7fb"}, + {file = "lxml-4.9.1-cp36-cp36m-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_24_i686.whl", hash = "sha256:bcaa1c495ce623966d9fc8a187da80082334236a2a1c7e141763ffaf7a405067"}, + {file = "lxml-4.9.1-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6eafc048ea3f1b3c136c71a86db393be36b5b3d9c87b1c25204e7d397cee9536"}, + {file = "lxml-4.9.1-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:13c90064b224e10c14dcdf8086688d3f0e612db53766e7478d7754703295c7c8"}, + {file = "lxml-4.9.1-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:206a51077773c6c5d2ce1991327cda719063a47adc02bd703c56a662cdb6c58b"}, + {file = "lxml-4.9.1-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:e8f0c9d65da595cfe91713bc1222af9ecabd37971762cb830dea2fc3b3bb2acf"}, + {file = "lxml-4.9.1-cp36-cp36m-musllinux_1_1_aarch64.whl", hash = "sha256:8f0a4d179c9a941eb80c3a63cdb495e539e064f8054230844dcf2fcb812b71d3"}, + {file = "lxml-4.9.1-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:830c88747dce8a3e7525defa68afd742b4580df6aa2fdd6f0855481e3994d391"}, + {file = "lxml-4.9.1-cp36-cp36m-win32.whl", hash = "sha256:1e1cf47774373777936c5aabad489fef7b1c087dcd1f426b621fda9dcc12994e"}, + {file = "lxml-4.9.1-cp36-cp36m-win_amd64.whl", hash = "sha256:5974895115737a74a00b321e339b9c3f45c20275d226398ae79ac008d908bff7"}, + {file = "lxml-4.9.1-cp37-cp37m-macosx_10_15_x86_64.whl", hash = "sha256:1423631e3d51008871299525b541413c9b6c6423593e89f9c4cfbe8460afc0a2"}, + {file = "lxml-4.9.1-cp37-cp37m-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_24_i686.whl", hash = "sha256:2aaf6a0a6465d39b5ca69688fce82d20088c1838534982996ec46633dc7ad6cc"}, + {file = "lxml-4.9.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:9f36de4cd0c262dd9927886cc2305aa3f2210db437aa4fed3fb4940b8bf4592c"}, + {file = "lxml-4.9.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:ae06c1e4bc60ee076292e582a7512f304abdf6c70db59b56745cca1684f875a4"}, + {file = "lxml-4.9.1-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:57e4d637258703d14171b54203fd6822fda218c6c2658a7d30816b10995f29f3"}, + {file = "lxml-4.9.1-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:6d279033bf614953c3fc4a0aa9ac33a21e8044ca72d4fa8b9273fe75359d5cca"}, + {file = "lxml-4.9.1-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:a60f90bba4c37962cbf210f0188ecca87daafdf60271f4c6948606e4dabf8785"}, + {file = "lxml-4.9.1-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:6ca2264f341dd81e41f3fffecec6e446aa2121e0b8d026fb5130e02de1402785"}, + {file = "lxml-4.9.1-cp37-cp37m-win32.whl", hash = "sha256:27e590352c76156f50f538dbcebd1925317a0f70540f7dc8c97d2931c595783a"}, + {file = "lxml-4.9.1-cp37-cp37m-win_amd64.whl", hash = "sha256:eea5d6443b093e1545ad0210e6cf27f920482bfcf5c77cdc8596aec73523bb7e"}, + {file = "lxml-4.9.1-cp38-cp38-macosx_10_15_x86_64.whl", hash = "sha256:f05251bbc2145349b8d0b77c0d4e5f3b228418807b1ee27cefb11f69ed3d233b"}, + {file = "lxml-4.9.1-cp38-cp38-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_24_i686.whl", hash = "sha256:487c8e61d7acc50b8be82bda8c8d21d20e133c3cbf41bd8ad7eb1aaeb3f07c97"}, + {file = "lxml-4.9.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:8d1a92d8e90b286d491e5626af53afef2ba04da33e82e30744795c71880eaa21"}, + {file = "lxml-4.9.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:b570da8cd0012f4af9fa76a5635cd31f707473e65a5a335b186069d5c7121ff2"}, + {file = "lxml-4.9.1-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:5ef87fca280fb15342726bd5f980f6faf8b84a5287fcc2d4962ea8af88b35130"}, + {file = "lxml-4.9.1-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:93e414e3206779ef41e5ff2448067213febf260ba747fc65389a3ddaa3fb8715"}, + {file = "lxml-4.9.1-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:6653071f4f9bac46fbc30f3c7838b0e9063ee335908c5d61fb7a4a86c8fd2036"}, + {file = "lxml-4.9.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:32a73c53783becdb7eaf75a2a1525ea8e49379fb7248c3eeefb9412123536387"}, + {file = "lxml-4.9.1-cp38-cp38-win32.whl", hash = "sha256:1a7c59c6ffd6ef5db362b798f350e24ab2cfa5700d53ac6681918f314a4d3b94"}, + {file = "lxml-4.9.1-cp38-cp38-win_amd64.whl", hash = "sha256:1436cf0063bba7888e43f1ba8d58824f085410ea2025befe81150aceb123e345"}, + {file = "lxml-4.9.1-cp39-cp39-macosx_10_15_x86_64.whl", hash = "sha256:4beea0f31491bc086991b97517b9683e5cfb369205dac0148ef685ac12a20a67"}, + {file = "lxml-4.9.1-cp39-cp39-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_24_i686.whl", hash = "sha256:41fb58868b816c202e8881fd0f179a4644ce6e7cbbb248ef0283a34b73ec73bb"}, + {file = "lxml-4.9.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:bd34f6d1810d9354dc7e35158aa6cc33456be7706df4420819af6ed966e85448"}, + {file = "lxml-4.9.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:edffbe3c510d8f4bf8640e02ca019e48a9b72357318383ca60e3330c23aaffc7"}, + {file = "lxml-4.9.1-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:6d949f53ad4fc7cf02c44d6678e7ff05ec5f5552b235b9e136bd52e9bf730b91"}, + {file = "lxml-4.9.1-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:079b68f197c796e42aa80b1f739f058dcee796dc725cc9a1be0cdb08fc45b000"}, + {file = "lxml-4.9.1-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:9c3a88d20e4fe4a2a4a84bf439a5ac9c9aba400b85244c63a1ab7088f85d9d25"}, + {file = "lxml-4.9.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:4e285b5f2bf321fc0857b491b5028c5f276ec0c873b985d58d7748ece1d770dd"}, + {file = "lxml-4.9.1-cp39-cp39-win32.whl", hash = "sha256:ef72013e20dd5ba86a8ae1aed7f56f31d3374189aa8b433e7b12ad182c0d2dfb"}, + {file = "lxml-4.9.1-cp39-cp39-win_amd64.whl", hash = "sha256:10d2017f9150248563bb579cd0d07c61c58da85c922b780060dcc9a3aa9f432d"}, + {file = "lxml-4.9.1-pp37-pypy37_pp73-macosx_10_15_x86_64.whl", hash = "sha256:0538747a9d7827ce3e16a8fdd201a99e661c7dee3c96c885d8ecba3c35d1032c"}, + {file = "lxml-4.9.1-pp37-pypy37_pp73-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_24_i686.whl", hash = "sha256:0645e934e940107e2fdbe7c5b6fb8ec6232444260752598bc4d09511bd056c0b"}, + {file = "lxml-4.9.1-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:6daa662aba22ef3258934105be2dd9afa5bb45748f4f702a3b39a5bf53a1f4dc"}, + {file = "lxml-4.9.1-pp38-pypy38_pp73-macosx_10_15_x86_64.whl", hash = "sha256:603a464c2e67d8a546ddaa206d98e3246e5db05594b97db844c2f0a1af37cf5b"}, + {file = "lxml-4.9.1-pp38-pypy38_pp73-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_24_i686.whl", hash = "sha256:c4b2e0559b68455c085fb0f6178e9752c4be3bba104d6e881eb5573b399d1eb2"}, + {file = "lxml-4.9.1-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:0f3f0059891d3254c7b5fb935330d6db38d6519ecd238ca4fce93c234b4a0f73"}, + {file = "lxml-4.9.1-pp39-pypy39_pp73-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_24_i686.whl", hash = "sha256:c852b1530083a620cb0de5f3cd6826f19862bafeaf77586f1aef326e49d95f0c"}, + {file = "lxml-4.9.1-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:287605bede6bd36e930577c5925fcea17cb30453d96a7b4c63c14a257118dbb9"}, + {file = "lxml-4.9.1.tar.gz", hash = "sha256:fe749b052bb7233fe5d072fcb549221a8cb1a16725c47c37e42b0b9cb3ff2c3f"}, +] +mako = [ + {file = "Mako-1.2.3-py3-none-any.whl", hash = "sha256:c413a086e38cd885088d5e165305ee8eed04e8b3f8f62df343480da0a385735f"}, + {file = "Mako-1.2.3.tar.gz", hash = "sha256:7fde96466fcfeedb0eed94f187f20b23d85e4cb41444be0e542e2c8c65c396cd"}, +] +markdown = [ + {file = "Markdown-3.4.1-py3-none-any.whl", hash = "sha256:08fb8465cffd03d10b9dd34a5c3fea908e20391a2a90b88d66362cb05beed186"}, + {file = "Markdown-3.4.1.tar.gz", hash = "sha256:3b809086bb6efad416156e00a0da66fe47618a5d6918dd688f53f40c8e4cfeff"}, +] +markdown-it-py = [ + {file = "markdown-it-py-2.1.0.tar.gz", hash = "sha256:cf7e59fed14b5ae17c0006eff14a2d9a00ed5f3a846148153899a0224e2c07da"}, + {file = "markdown_it_py-2.1.0-py3-none-any.whl", hash = "sha256:93de681e5c021a432c63147656fe21790bc01231e0cd2da73626f1aa3ac0fe27"}, +] +markupsafe = [ + {file = "MarkupSafe-2.1.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:86b1f75c4e7c2ac2ccdaec2b9022845dbb81880ca318bb7a0a01fbf7813e3812"}, + {file = "MarkupSafe-2.1.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:f121a1420d4e173a5d96e47e9a0c0dcff965afdf1626d28de1460815f7c4ee7a"}, + {file = "MarkupSafe-2.1.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a49907dd8420c5685cfa064a1335b6754b74541bbb3706c259c02ed65b644b3e"}, + {file = "MarkupSafe-2.1.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:10c1bfff05d95783da83491be968e8fe789263689c02724e0c691933c52994f5"}, + {file = "MarkupSafe-2.1.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b7bd98b796e2b6553da7225aeb61f447f80a1ca64f41d83612e6139ca5213aa4"}, + {file = "MarkupSafe-2.1.1-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:b09bf97215625a311f669476f44b8b318b075847b49316d3e28c08e41a7a573f"}, + {file = "MarkupSafe-2.1.1-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:694deca8d702d5db21ec83983ce0bb4b26a578e71fbdbd4fdcd387daa90e4d5e"}, + {file = "MarkupSafe-2.1.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:efc1913fd2ca4f334418481c7e595c00aad186563bbc1ec76067848c7ca0a933"}, + {file = "MarkupSafe-2.1.1-cp310-cp310-win32.whl", hash = "sha256:4a33dea2b688b3190ee12bd7cfa29d39c9ed176bda40bfa11099a3ce5d3a7ac6"}, + {file = "MarkupSafe-2.1.1-cp310-cp310-win_amd64.whl", hash = "sha256:dda30ba7e87fbbb7eab1ec9f58678558fd9a6b8b853530e176eabd064da81417"}, + {file = "MarkupSafe-2.1.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:671cd1187ed5e62818414afe79ed29da836dde67166a9fac6d435873c44fdd02"}, + {file = "MarkupSafe-2.1.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3799351e2336dc91ea70b034983ee71cf2f9533cdff7c14c90ea126bfd95d65a"}, + {file = "MarkupSafe-2.1.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e72591e9ecd94d7feb70c1cbd7be7b3ebea3f548870aa91e2732960fa4d57a37"}, + {file = "MarkupSafe-2.1.1-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6fbf47b5d3728c6aea2abb0589b5d30459e369baa772e0f37a0320185e87c980"}, + {file = "MarkupSafe-2.1.1-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:d5ee4f386140395a2c818d149221149c54849dfcfcb9f1debfe07a8b8bd63f9a"}, + {file = "MarkupSafe-2.1.1-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:bcb3ed405ed3222f9904899563d6fc492ff75cce56cba05e32eff40e6acbeaa3"}, + {file = "MarkupSafe-2.1.1-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:e1c0b87e09fa55a220f058d1d49d3fb8df88fbfab58558f1198e08c1e1de842a"}, + {file = "MarkupSafe-2.1.1-cp37-cp37m-win32.whl", hash = "sha256:8dc1c72a69aa7e082593c4a203dcf94ddb74bb5c8a731e4e1eb68d031e8498ff"}, + {file = "MarkupSafe-2.1.1-cp37-cp37m-win_amd64.whl", hash = "sha256:97a68e6ada378df82bc9f16b800ab77cbf4b2fada0081794318520138c088e4a"}, + {file = "MarkupSafe-2.1.1-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:e8c843bbcda3a2f1e3c2ab25913c80a3c5376cd00c6e8c4a86a89a28c8dc5452"}, + {file = "MarkupSafe-2.1.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:0212a68688482dc52b2d45013df70d169f542b7394fc744c02a57374a4207003"}, + {file = "MarkupSafe-2.1.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8e576a51ad59e4bfaac456023a78f6b5e6e7651dcd383bcc3e18d06f9b55d6d1"}, + {file = "MarkupSafe-2.1.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4b9fe39a2ccc108a4accc2676e77da025ce383c108593d65cc909add5c3bd601"}, + {file = "MarkupSafe-2.1.1-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:96e37a3dc86e80bf81758c152fe66dbf60ed5eca3d26305edf01892257049925"}, + {file = "MarkupSafe-2.1.1-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:6d0072fea50feec76a4c418096652f2c3238eaa014b2f94aeb1d56a66b41403f"}, + {file = "MarkupSafe-2.1.1-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:089cf3dbf0cd6c100f02945abeb18484bd1ee57a079aefd52cffd17fba910b88"}, + {file = "MarkupSafe-2.1.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:6a074d34ee7a5ce3effbc526b7083ec9731bb3cbf921bbe1d3005d4d2bdb3a63"}, + {file = "MarkupSafe-2.1.1-cp38-cp38-win32.whl", hash = "sha256:421be9fbf0ffe9ffd7a378aafebbf6f4602d564d34be190fc19a193232fd12b1"}, + {file = "MarkupSafe-2.1.1-cp38-cp38-win_amd64.whl", hash = "sha256:fc7b548b17d238737688817ab67deebb30e8073c95749d55538ed473130ec0c7"}, + {file = "MarkupSafe-2.1.1-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:e04e26803c9c3851c931eac40c695602c6295b8d432cbe78609649ad9bd2da8a"}, + {file = "MarkupSafe-2.1.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:b87db4360013327109564f0e591bd2a3b318547bcef31b468a92ee504d07ae4f"}, + {file = "MarkupSafe-2.1.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:99a2a507ed3ac881b975a2976d59f38c19386d128e7a9a18b7df6fff1fd4c1d6"}, + {file = "MarkupSafe-2.1.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:56442863ed2b06d19c37f94d999035e15ee982988920e12a5b4ba29b62ad1f77"}, + {file = "MarkupSafe-2.1.1-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3ce11ee3f23f79dbd06fb3d63e2f6af7b12db1d46932fe7bd8afa259a5996603"}, + {file = "MarkupSafe-2.1.1-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:33b74d289bd2f5e527beadcaa3f401e0df0a89927c1559c8566c066fa4248ab7"}, + {file = "MarkupSafe-2.1.1-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:43093fb83d8343aac0b1baa75516da6092f58f41200907ef92448ecab8825135"}, + {file = "MarkupSafe-2.1.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:8e3dcf21f367459434c18e71b2a9532d96547aef8a871872a5bd69a715c15f96"}, + {file = "MarkupSafe-2.1.1-cp39-cp39-win32.whl", hash = "sha256:d4306c36ca495956b6d568d276ac11fdd9c30a36f1b6eb928070dc5360b22e1c"}, + {file = "MarkupSafe-2.1.1-cp39-cp39-win_amd64.whl", hash = "sha256:46d00d6cfecdde84d40e572d63735ef81423ad31184100411e6e3388d405e247"}, + {file = "MarkupSafe-2.1.1.tar.gz", hash = "sha256:7f91197cc9e48f989d12e4e6fbc46495c446636dfc81b9ccf50bb0ec74b91d4b"}, +] +matplotlib = [ + {file = "matplotlib-3.6.1-cp310-cp310-macosx_10_12_universal2.whl", hash = "sha256:7730e60e751cfcfe7fcb223cf03c0b979e9a064c239783ad37929d340a364cef"}, + {file = "matplotlib-3.6.1-cp310-cp310-macosx_10_12_x86_64.whl", hash = "sha256:9dd40505ccc526acaf9a5db1b3029e237c64b58f1249983b28a291c2d6a1d0fa"}, + {file = "matplotlib-3.6.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:85948b303534b69fd771126764cf883fde2af9b003eb5778cb60f3b46f93d3f6"}, + {file = "matplotlib-3.6.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:71eced071825005011cdc64efbae2e2c76b8209c18aa487dedf69796fe4b1e40"}, + {file = "matplotlib-3.6.1-cp310-cp310-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:220314c2d6b9ca11570d7cd4b841c9f3137546f188336003b9fb8def4dcb804d"}, + {file = "matplotlib-3.6.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2cc5d726d4d42865f909c5208a7841109d76584950dd0587b01a77cc279d4ab7"}, + {file = "matplotlib-3.6.1-cp310-cp310-win32.whl", hash = "sha256:183bf3ac6a6023ee590aa4b677f391ceed65ec0d6b930901a8483c267bd12995"}, + {file = "matplotlib-3.6.1-cp310-cp310-win_amd64.whl", hash = "sha256:a68b91ac7e6bb26100a540a033f54c95fe06d9c0aa51312c2a52d07d1bde78f4"}, + {file = "matplotlib-3.6.1-cp311-cp311-macosx_10_12_universal2.whl", hash = "sha256:4648f0d79a87bf50ee740058305c91091ee5e1fbb71a7d2f5fe6707bfe328d1c"}, + {file = "matplotlib-3.6.1-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:9403764017d20ff570f7ce973a8b9637f08a6109118f4e0ce6c7493d8849a0d3"}, + {file = "matplotlib-3.6.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:e4c8b5a243dd29d50289d694e931bd6cb6ae0b5bd654d12c647543d63862540c"}, + {file = "matplotlib-3.6.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c1effccef0cea2d4da9feeed22079adf6786f92c800a7d0d2ef2104318a1c66c"}, + {file = "matplotlib-3.6.1-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:8dc25473319afabe49150267e54648ac559c33b0fc2a80c8caecfbbc2948a820"}, + {file = "matplotlib-3.6.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:47cb088bbce82ae9fc2edf3c25e56a5c6142ce2553fea2b781679f960a70c207"}, + {file = "matplotlib-3.6.1-cp311-cp311-win32.whl", hash = "sha256:4d3b0e0a4611bd22065bbf47e9b2f689ac9e575bcb850a9f0ae2bbed75cab956"}, + {file = "matplotlib-3.6.1-cp311-cp311-win_amd64.whl", hash = "sha256:e3c116e779fbbf421a9e4d3060db259a9bb486d98f4e3c5a0877c599bd173582"}, + {file = "matplotlib-3.6.1-cp38-cp38-macosx_10_12_universal2.whl", hash = "sha256:565f514dec81a41cbed10eb6011501879695087fc2787fb89423a466508abbbd"}, + {file = "matplotlib-3.6.1-cp38-cp38-macosx_10_12_x86_64.whl", hash = "sha256:05e86446562063d6186ff6d700118c0dbd5dccc403a6187351ee526c48878f10"}, + {file = "matplotlib-3.6.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:8245e85fd793f58edf29b8a9e3be47e8ecf76ea1a1e8240545f2746181ca5787"}, + {file = "matplotlib-3.6.1-cp38-cp38-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:1e2c75d5d1ff6b7ef9870360bfa23bea076b8dc0945a60d19453d7619ed9ea8f"}, + {file = "matplotlib-3.6.1-cp38-cp38-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:c9756a8e69f6e1f76d47eb42132175b6814da1fbeae0545304c6d0fc2aae252a"}, + {file = "matplotlib-3.6.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6f5788168da2661b42f7468063b725cc73fdbeeb80f2704cb2d8c415e9a57c50"}, + {file = "matplotlib-3.6.1-cp38-cp38-win32.whl", hash = "sha256:0bab7564aafd5902128d54b68dca04f5755413fb6b502100bb0235a545882c48"}, + {file = "matplotlib-3.6.1-cp38-cp38-win_amd64.whl", hash = "sha256:3c53486278a0629fd892783271dc994b962fba8dfe207445d039e14f1928ea46"}, + {file = "matplotlib-3.6.1-cp39-cp39-macosx_10_12_universal2.whl", hash = "sha256:27337bcb38d5db7430c14f350924542d75416ec1546d5d9d9f39b362b71db3fb"}, + {file = "matplotlib-3.6.1-cp39-cp39-macosx_10_12_x86_64.whl", hash = "sha256:fad858519bd6d52dbfeebdbe04d00dd8e932ed436f1c535e61bcc970a96c11e4"}, + {file = "matplotlib-3.6.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:4a3d903588b519b38ed085d0ae762a1dcd4b70164617292175cfd91b90d6c415"}, + {file = "matplotlib-3.6.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:87bdbd37d0a41e025879863fe9b17bab15c0421313bc33e77e5e1aa54215c9c5"}, + {file = "matplotlib-3.6.1-cp39-cp39-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e632f66218811d4cf8b7a2a649e25ec15406c3c498f72d19e2bcf8377f38445d"}, + {file = "matplotlib-3.6.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8ddd58324dc9a77e2e56d7b7aea7dbd0575b6f7cd1333c3ca9d388ac70978344"}, + {file = "matplotlib-3.6.1-cp39-cp39-win32.whl", hash = "sha256:12ab21d0cad122f5b23688d453a0280676e7c42f634f0dbd093d15d42d142b1f"}, + {file = "matplotlib-3.6.1-cp39-cp39-win_amd64.whl", hash = "sha256:563896ba269324872ace436a57775dcc8322678a9496b28a8c25cdafa5ec2b92"}, + {file = "matplotlib-3.6.1-pp38-pypy38_pp73-macosx_10_12_x86_64.whl", hash = "sha256:52935b7d4ccbf0dbc9cf454dbb10ca99c11cbe8da9467596b96e5e21fd4dfc5c"}, + {file = "matplotlib-3.6.1-pp38-pypy38_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:87027ff7b2edeb14476900261ef04d4beae949e1dfa0a3eb3ad6a6efbf9d0e1d"}, + {file = "matplotlib-3.6.1-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a4de03085afb3b80fab341afaf8e60dfe06ce439b6dfed55d657cf34a7bc3c40"}, + {file = "matplotlib-3.6.1-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:b53387d4e59432ff221540a4ffb5ee9669c69417805e4faf0148a00d701c61f9"}, + {file = "matplotlib-3.6.1-pp39-pypy39_pp73-macosx_10_12_x86_64.whl", hash = "sha256:02561141c434154f7bae8e5449909d152367cb40aa57bfb2a27f2748b9c5f95f"}, + {file = "matplotlib-3.6.1-pp39-pypy39_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d0161ebf87518ecfe0980c942d5f0d5df0e080c1746ebaab2027a969967014b7"}, + {file = "matplotlib-3.6.1-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2469f57e4c5cc0e85eddc7b30995ea9c404a78c0b1856da75d1a5887156ca350"}, + {file = "matplotlib-3.6.1-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:5f97141e05baf160c3ec125f06ceb2a44c9bb62f42fcb8ee1c05313c73e99432"}, + {file = "matplotlib-3.6.1.tar.gz", hash = "sha256:e2d1b7225666f7e1bcc94c0bc9c587a82e3e8691da4757e357e5c2515222ee37"}, +] +matplotlib-inline = [ + {file = "matplotlib-inline-0.1.6.tar.gz", hash = "sha256:f887e5f10ba98e8d2b150ddcf4702c1e5f8b3a20005eb0f74bfdbd360ee6f304"}, + {file = "matplotlib_inline-0.1.6-py3-none-any.whl", hash = "sha256:f1f41aab5328aa5aaea9b16d083b128102f8712542f819fe7e6a420ff581b311"}, +] +mccabe = [ + {file = "mccabe-0.6.1-py2.py3-none-any.whl", hash = "sha256:ab8a6258860da4b6677da4bd2fe5dc2c659cff31b3ee4f7f5d64e79735b80d42"}, + {file = "mccabe-0.6.1.tar.gz", hash = "sha256:dd8d182285a0fe56bace7f45b5e7d1a6ebcbf524e8f3bd87eb0f125271b8831f"}, +] +mdit-py-plugins = [ + {file = "mdit-py-plugins-0.3.1.tar.gz", hash = "sha256:3fc13298497d6e04fe96efdd41281bfe7622152f9caa1815ea99b5c893de9441"}, + {file = "mdit_py_plugins-0.3.1-py3-none-any.whl", hash = "sha256:606a7f29cf56dbdfaf914acb21709b8f8ee29d857e8f29dcc33d8cb84c57bfa1"}, +] +mdurl = [ + {file = "mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8"}, + {file = "mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba"}, +] +mistune = [ + {file = "mistune-2.0.4-py2.py3-none-any.whl", hash = "sha256:182cc5ee6f8ed1b807de6b7bb50155df7b66495412836b9a74c8fbdfc75fe36d"}, + {file = "mistune-2.0.4.tar.gz", hash = "sha256:9ee0a66053e2267aba772c71e06891fa8f1af6d4b01d5e84e267b4570d4d9808"}, +] +more-itertools = [ + {file = "more-itertools-9.0.0.tar.gz", hash = "sha256:5a6257e40878ef0520b1803990e3e22303a41b5714006c32a3fd8304b26ea1ab"}, + {file = "more_itertools-9.0.0-py3-none-any.whl", hash = "sha256:250e83d7e81d0c87ca6bd942e6aeab8cc9daa6096d12c5308f3f92fa5e5c1f41"}, +] +mpld3 = [ + {file = "mpld3-0.5.8-py3-none-any.whl", hash = "sha256:41938e65de4ba41a1b53d92e7c8609e7172e09b33ef5db42bb6f73701106c8b7"}, + {file = "mpld3-0.5.8.tar.gz", hash = "sha256:1a167dbef836dd7c66d8aa71c06a32d50bffa18725f304d93cb74fdb3545043b"}, +] +mpmath = [ + {file = "mpmath-1.2.1-py3-none-any.whl", hash = "sha256:604bc21bd22d2322a177c73bdb573994ef76e62edd595d17e00aff24b0667e5c"}, + {file = "mpmath-1.2.1.tar.gz", hash = "sha256:79ffb45cf9f4b101a807595bcb3e72e0396202e0b1d25d689134b48c4216a81a"}, +] +msal = [ + {file = "msal-1.20.0b1-py2.py3-none-any.whl", hash = "sha256:07805ade58ce76bdaa4f6a3f7e61477901d5145abd7959a850eb6c49a2fbaea6"}, + {file = "msal-1.20.0b1.tar.gz", hash = "sha256:8c0d7238b7bc5abe86515568c4fd59e53c5ccca159ef02b369f867b951480c4d"}, +] +msal-extensions = [ + {file = "msal-extensions-1.0.0.tar.gz", hash = "sha256:c676aba56b0cce3783de1b5c5ecfe828db998167875126ca4b47dc6436451354"}, + {file = "msal_extensions-1.0.0-py2.py3-none-any.whl", hash = "sha256:91e3db9620b822d0ed2b4d1850056a0f133cba04455e62f11612e40f5502f2ee"}, +] +msgpack = [ + {file = "msgpack-1.0.4-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:4ab251d229d10498e9a2f3b1e68ef64cb393394ec477e3370c457f9430ce9250"}, + {file = "msgpack-1.0.4-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:112b0f93202d7c0fef0b7810d465fde23c746a2d482e1e2de2aafd2ce1492c88"}, + {file = "msgpack-1.0.4-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:002b5c72b6cd9b4bafd790f364b8480e859b4712e91f43014fe01e4f957b8467"}, + {file = "msgpack-1.0.4-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:35bc0faa494b0f1d851fd29129b2575b2e26d41d177caacd4206d81502d4c6a6"}, + {file = "msgpack-1.0.4-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4733359808c56d5d7756628736061c432ded018e7a1dff2d35a02439043321aa"}, + {file = "msgpack-1.0.4-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:eb514ad14edf07a1dbe63761fd30f89ae79b42625731e1ccf5e1f1092950eaa6"}, + {file = "msgpack-1.0.4-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:c23080fdeec4716aede32b4e0ef7e213c7b1093eede9ee010949f2a418ced6ba"}, + {file = "msgpack-1.0.4-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:49565b0e3d7896d9ea71d9095df15b7f75a035c49be733051c34762ca95bbf7e"}, + {file = "msgpack-1.0.4-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:aca0f1644d6b5a73eb3e74d4d64d5d8c6c3d577e753a04c9e9c87d07692c58db"}, + {file = "msgpack-1.0.4-cp310-cp310-win32.whl", hash = "sha256:0dfe3947db5fb9ce52aaea6ca28112a170db9eae75adf9339a1aec434dc954ef"}, + {file = "msgpack-1.0.4-cp310-cp310-win_amd64.whl", hash = "sha256:4dea20515f660aa6b7e964433b1808d098dcfcabbebeaaad240d11f909298075"}, + {file = "msgpack-1.0.4-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:e83f80a7fec1a62cf4e6c9a660e39c7f878f603737a0cdac8c13131d11d97f52"}, + {file = "msgpack-1.0.4-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3c11a48cf5e59026ad7cb0dc29e29a01b5a66a3e333dc11c04f7e991fc5510a9"}, + {file = "msgpack-1.0.4-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1276e8f34e139aeff1c77a3cefb295598b504ac5314d32c8c3d54d24fadb94c9"}, + {file = "msgpack-1.0.4-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6c9566f2c39ccced0a38d37c26cc3570983b97833c365a6044edef3574a00c08"}, + {file = "msgpack-1.0.4-cp36-cp36m-musllinux_1_1_aarch64.whl", hash = "sha256:fcb8a47f43acc113e24e910399376f7277cf8508b27e5b88499f053de6b115a8"}, + {file = "msgpack-1.0.4-cp36-cp36m-musllinux_1_1_i686.whl", hash = "sha256:76ee788122de3a68a02ed6f3a16bbcd97bc7c2e39bd4d94be2f1821e7c4a64e6"}, + {file = "msgpack-1.0.4-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:0a68d3ac0104e2d3510de90a1091720157c319ceeb90d74f7b5295a6bee51bae"}, + {file = "msgpack-1.0.4-cp36-cp36m-win32.whl", hash = "sha256:85f279d88d8e833ec015650fd15ae5eddce0791e1e8a59165318f371158efec6"}, + {file = "msgpack-1.0.4-cp36-cp36m-win_amd64.whl", hash = "sha256:c1683841cd4fa45ac427c18854c3ec3cd9b681694caf5bff04edb9387602d661"}, + {file = "msgpack-1.0.4-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:a75dfb03f8b06f4ab093dafe3ddcc2d633259e6c3f74bb1b01996f5d8aa5868c"}, + {file = "msgpack-1.0.4-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9667bdfdf523c40d2511f0e98a6c9d3603be6b371ae9a238b7ef2dc4e7a427b0"}, + {file = "msgpack-1.0.4-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:11184bc7e56fd74c00ead4f9cc9a3091d62ecb96e97653add7a879a14b003227"}, + {file = "msgpack-1.0.4-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ac5bd7901487c4a1dd51a8c58f2632b15d838d07ceedaa5e4c080f7190925bff"}, + {file = "msgpack-1.0.4-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:1e91d641d2bfe91ba4c52039adc5bccf27c335356055825c7f88742c8bb900dd"}, + {file = "msgpack-1.0.4-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:2a2df1b55a78eb5f5b7d2a4bb221cd8363913830145fad05374a80bf0877cb1e"}, + {file = "msgpack-1.0.4-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:545e3cf0cf74f3e48b470f68ed19551ae6f9722814ea969305794645da091236"}, + {file = "msgpack-1.0.4-cp37-cp37m-win32.whl", hash = "sha256:2cc5ca2712ac0003bcb625c96368fd08a0f86bbc1a5578802512d87bc592fe44"}, + {file = "msgpack-1.0.4-cp37-cp37m-win_amd64.whl", hash = "sha256:eba96145051ccec0ec86611fe9cf693ce55f2a3ce89c06ed307de0e085730ec1"}, + {file = "msgpack-1.0.4-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:7760f85956c415578c17edb39eed99f9181a48375b0d4a94076d84148cf67b2d"}, + {file = "msgpack-1.0.4-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:449e57cc1ff18d3b444eb554e44613cffcccb32805d16726a5494038c3b93dab"}, + {file = "msgpack-1.0.4-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:d603de2b8d2ea3f3bcb2efe286849aa7a81531abc52d8454da12f46235092bcb"}, + {file = "msgpack-1.0.4-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:48f5d88c99f64c456413d74a975bd605a9b0526293218a3b77220a2c15458ba9"}, + {file = "msgpack-1.0.4-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6916c78f33602ecf0509cc40379271ba0f9ab572b066bd4bdafd7434dee4bc6e"}, + {file = "msgpack-1.0.4-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:81fc7ba725464651190b196f3cd848e8553d4d510114a954681fd0b9c479d7e1"}, + {file = "msgpack-1.0.4-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:d5b5b962221fa2c5d3a7f8133f9abffc114fe218eb4365e40f17732ade576c8e"}, + {file = "msgpack-1.0.4-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:77ccd2af37f3db0ea59fb280fa2165bf1b096510ba9fe0cc2bf8fa92a22fdb43"}, + {file = "msgpack-1.0.4-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:b17be2478b622939e39b816e0aa8242611cc8d3583d1cd8ec31b249f04623243"}, + {file = "msgpack-1.0.4-cp38-cp38-win32.whl", hash = "sha256:2bb8cdf50dd623392fa75525cce44a65a12a00c98e1e37bf0fb08ddce2ff60d2"}, + {file = "msgpack-1.0.4-cp38-cp38-win_amd64.whl", hash = "sha256:26b8feaca40a90cbe031b03d82b2898bf560027160d3eae1423f4a67654ec5d6"}, + {file = "msgpack-1.0.4-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:462497af5fd4e0edbb1559c352ad84f6c577ffbbb708566a0abaaa84acd9f3ae"}, + {file = "msgpack-1.0.4-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:2999623886c5c02deefe156e8f869c3b0aaeba14bfc50aa2486a0415178fce55"}, + {file = "msgpack-1.0.4-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:f0029245c51fd9473dc1aede1160b0a29f4a912e6b1dd353fa6d317085b219da"}, + {file = "msgpack-1.0.4-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ed6f7b854a823ea44cf94919ba3f727e230da29feb4a99711433f25800cf747f"}, + {file = "msgpack-1.0.4-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0df96d6eaf45ceca04b3f3b4b111b86b33785683d682c655063ef8057d61fd92"}, + {file = "msgpack-1.0.4-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6a4192b1ab40f8dca3f2877b70e63799d95c62c068c84dc028b40a6cb03ccd0f"}, + {file = "msgpack-1.0.4-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:0e3590f9fb9f7fbc36df366267870e77269c03172d086fa76bb4eba8b2b46624"}, + {file = "msgpack-1.0.4-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:1576bd97527a93c44fa856770197dec00d223b0b9f36ef03f65bac60197cedf8"}, + {file = "msgpack-1.0.4-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:63e29d6e8c9ca22b21846234913c3466b7e4ee6e422f205a2988083de3b08cae"}, + {file = "msgpack-1.0.4-cp39-cp39-win32.whl", hash = "sha256:fb62ea4b62bfcb0b380d5680f9a4b3f9a2d166d9394e9bbd9666c0ee09a3645c"}, + {file = "msgpack-1.0.4-cp39-cp39-win_amd64.whl", hash = "sha256:4d5834a2a48965a349da1c5a79760d94a1a0172fbb5ab6b5b33cbf8447e109ce"}, + {file = "msgpack-1.0.4.tar.gz", hash = "sha256:f5d869c18f030202eb412f08b28d2afeea553d6613aee89e200d7aca7ef01f5f"}, +] +msgpack-numpy = [ + {file = "msgpack-numpy-0.4.8.tar.gz", hash = "sha256:c667d3180513422f9c7545be5eec5d296dcbb357e06f72ed39cc683797556e69"}, + {file = "msgpack_numpy-0.4.8-py2.py3-none-any.whl", hash = "sha256:773c19d4dfbae1b3c7b791083e2caf66983bb19b40901646f61d8731554ae3da"}, +] +msgpack-python = [ + {file = "msgpack-python-0.5.6.tar.gz", hash = "sha256:378cc8a6d3545b532dfd149da715abae4fda2a3adb6d74e525d0d5e51f46909b"}, +] +msrest = [ + {file = "msrest-0.7.1-py3-none-any.whl", hash = "sha256:21120a810e1233e5e6cc7fe40b474eeb4ec6f757a15d7cf86702c369f9567c32"}, + {file = "msrest-0.7.1.zip", hash = "sha256:6e7661f46f3afd88b75667b7187a92829924446c7ea1d169be8c4bb7eeb788b9"}, +] +msrestazure = [ + {file = "msrestazure-0.6.4-py2.py3-none-any.whl", hash = "sha256:3de50f56147ef529b31e099a982496690468ecef33f0544cb0fa0cfe1e1de5b9"}, + {file = "msrestazure-0.6.4.tar.gz", hash = "sha256:a06f0dabc9a6f5efe3b6add4bd8fb623aeadacf816b7a35b0f89107e0544d189"}, +] +multidict = [ + {file = "multidict-6.0.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:0b9e95a740109c6047602f4db4da9949e6c5945cefbad34a1299775ddc9a62e2"}, + {file = "multidict-6.0.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:ac0e27844758d7177989ce406acc6a83c16ed4524ebc363c1f748cba184d89d3"}, + {file = "multidict-6.0.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:041b81a5f6b38244b34dc18c7b6aba91f9cdaf854d9a39e5ff0b58e2b5773b9c"}, + {file = "multidict-6.0.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5fdda29a3c7e76a064f2477c9aab1ba96fd94e02e386f1e665bca1807fc5386f"}, + {file = "multidict-6.0.2-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3368bf2398b0e0fcbf46d85795adc4c259299fec50c1416d0f77c0a843a3eed9"}, + {file = "multidict-6.0.2-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f4f052ee022928d34fe1f4d2bc743f32609fb79ed9c49a1710a5ad6b2198db20"}, + {file = "multidict-6.0.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:225383a6603c086e6cef0f2f05564acb4f4d5f019a4e3e983f572b8530f70c88"}, + {file = "multidict-6.0.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:50bd442726e288e884f7be9071016c15a8742eb689a593a0cac49ea093eef0a7"}, + {file = "multidict-6.0.2-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:47e6a7e923e9cada7c139531feac59448f1f47727a79076c0b1ee80274cd8eee"}, + {file = "multidict-6.0.2-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:0556a1d4ea2d949efe5fd76a09b4a82e3a4a30700553a6725535098d8d9fb672"}, + {file = "multidict-6.0.2-cp310-cp310-musllinux_1_1_ppc64le.whl", hash = "sha256:626fe10ac87851f4cffecee161fc6f8f9853f0f6f1035b59337a51d29ff3b4f9"}, + {file = "multidict-6.0.2-cp310-cp310-musllinux_1_1_s390x.whl", hash = "sha256:8064b7c6f0af936a741ea1efd18690bacfbae4078c0c385d7c3f611d11f0cf87"}, + {file = "multidict-6.0.2-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:2d36e929d7f6a16d4eb11b250719c39560dd70545356365b494249e2186bc389"}, + {file = "multidict-6.0.2-cp310-cp310-win32.whl", hash = "sha256:fcb91630817aa8b9bc4a74023e4198480587269c272c58b3279875ed7235c293"}, + {file = "multidict-6.0.2-cp310-cp310-win_amd64.whl", hash = "sha256:8cbf0132f3de7cc6c6ce00147cc78e6439ea736cee6bca4f068bcf892b0fd658"}, + {file = "multidict-6.0.2-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:05f6949d6169878a03e607a21e3b862eaf8e356590e8bdae4227eedadacf6e51"}, + {file = "multidict-6.0.2-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e2c2e459f7050aeb7c1b1276763364884595d47000c1cddb51764c0d8976e608"}, + {file = "multidict-6.0.2-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d0509e469d48940147e1235d994cd849a8f8195e0bca65f8f5439c56e17872a3"}, + {file = "multidict-6.0.2-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:514fe2b8d750d6cdb4712346a2c5084a80220821a3e91f3f71eec11cf8d28fd4"}, + {file = "multidict-6.0.2-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:19adcfc2a7197cdc3987044e3f415168fc5dc1f720c932eb1ef4f71a2067e08b"}, + {file = "multidict-6.0.2-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b9d153e7f1f9ba0b23ad1568b3b9e17301e23b042c23870f9ee0522dc5cc79e8"}, + {file = "multidict-6.0.2-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:aef9cc3d9c7d63d924adac329c33835e0243b5052a6dfcbf7732a921c6e918ba"}, + {file = "multidict-6.0.2-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:4571f1beddff25f3e925eea34268422622963cd8dc395bb8778eb28418248e43"}, + {file = "multidict-6.0.2-cp37-cp37m-musllinux_1_1_ppc64le.whl", hash = "sha256:d48b8ee1d4068561ce8033d2c344cf5232cb29ee1a0206a7b828c79cbc5982b8"}, + {file = "multidict-6.0.2-cp37-cp37m-musllinux_1_1_s390x.whl", hash = "sha256:45183c96ddf61bf96d2684d9fbaf6f3564d86b34cb125761f9a0ef9e36c1d55b"}, + {file = "multidict-6.0.2-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:75bdf08716edde767b09e76829db8c1e5ca9d8bb0a8d4bd94ae1eafe3dac5e15"}, + {file = "multidict-6.0.2-cp37-cp37m-win32.whl", hash = "sha256:a45e1135cb07086833ce969555df39149680e5471c04dfd6a915abd2fc3f6dbc"}, + {file = "multidict-6.0.2-cp37-cp37m-win_amd64.whl", hash = "sha256:6f3cdef8a247d1eafa649085812f8a310e728bdf3900ff6c434eafb2d443b23a"}, + {file = "multidict-6.0.2-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:0327292e745a880459ef71be14e709aaea2f783f3537588fb4ed09b6c01bca60"}, + {file = "multidict-6.0.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:e875b6086e325bab7e680e4316d667fc0e5e174bb5611eb16b3ea121c8951b86"}, + {file = "multidict-6.0.2-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:feea820722e69451743a3d56ad74948b68bf456984d63c1a92e8347b7b88452d"}, + {file = "multidict-6.0.2-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9cc57c68cb9139c7cd6fc39f211b02198e69fb90ce4bc4a094cf5fe0d20fd8b0"}, + {file = "multidict-6.0.2-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:497988d6b6ec6ed6f87030ec03280b696ca47dbf0648045e4e1d28b80346560d"}, + {file = "multidict-6.0.2-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:89171b2c769e03a953d5969b2f272efa931426355b6c0cb508022976a17fd376"}, + {file = "multidict-6.0.2-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:684133b1e1fe91eda8fa7447f137c9490a064c6b7f392aa857bba83a28cfb693"}, + {file = "multidict-6.0.2-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:fd9fc9c4849a07f3635ccffa895d57abce554b467d611a5009ba4f39b78a8849"}, + {file = "multidict-6.0.2-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:e07c8e79d6e6fd37b42f3250dba122053fddb319e84b55dd3a8d6446e1a7ee49"}, + {file = "multidict-6.0.2-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:4070613ea2227da2bfb2c35a6041e4371b0af6b0be57f424fe2318b42a748516"}, + {file = "multidict-6.0.2-cp38-cp38-musllinux_1_1_ppc64le.whl", hash = "sha256:47fbeedbf94bed6547d3aa632075d804867a352d86688c04e606971595460227"}, + {file = "multidict-6.0.2-cp38-cp38-musllinux_1_1_s390x.whl", hash = "sha256:5774d9218d77befa7b70d836004a768fb9aa4fdb53c97498f4d8d3f67bb9cfa9"}, + {file = "multidict-6.0.2-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:2957489cba47c2539a8eb7ab32ff49101439ccf78eab724c828c1a54ff3ff98d"}, + {file = "multidict-6.0.2-cp38-cp38-win32.whl", hash = "sha256:e5b20e9599ba74391ca0cfbd7b328fcc20976823ba19bc573983a25b32e92b57"}, + {file = "multidict-6.0.2-cp38-cp38-win_amd64.whl", hash = "sha256:8004dca28e15b86d1b1372515f32eb6f814bdf6f00952699bdeb541691091f96"}, + {file = "multidict-6.0.2-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:2e4a0785b84fb59e43c18a015ffc575ba93f7d1dbd272b4cdad9f5134b8a006c"}, + {file = "multidict-6.0.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:6701bf8a5d03a43375909ac91b6980aea74b0f5402fbe9428fc3f6edf5d9677e"}, + {file = "multidict-6.0.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:a007b1638e148c3cfb6bf0bdc4f82776cef0ac487191d093cdc316905e504071"}, + {file = "multidict-6.0.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:07a017cfa00c9890011628eab2503bee5872f27144936a52eaab449be5eaf032"}, + {file = "multidict-6.0.2-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c207fff63adcdf5a485969131dc70e4b194327666b7e8a87a97fbc4fd80a53b2"}, + {file = "multidict-6.0.2-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:373ba9d1d061c76462d74e7de1c0c8e267e9791ee8cfefcf6b0b2495762c370c"}, + {file = "multidict-6.0.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bfba7c6d5d7c9099ba21f84662b037a0ffd4a5e6b26ac07d19e423e6fdf965a9"}, + {file = "multidict-6.0.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:19d9bad105dfb34eb539c97b132057a4e709919ec4dd883ece5838bcbf262b80"}, + {file = "multidict-6.0.2-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:de989b195c3d636ba000ee4281cd03bb1234635b124bf4cd89eeee9ca8fcb09d"}, + {file = "multidict-6.0.2-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:7c40b7bbece294ae3a87c1bc2abff0ff9beef41d14188cda94ada7bcea99b0fb"}, + {file = "multidict-6.0.2-cp39-cp39-musllinux_1_1_ppc64le.whl", hash = "sha256:d16cce709ebfadc91278a1c005e3c17dd5f71f5098bfae1035149785ea6e9c68"}, + {file = "multidict-6.0.2-cp39-cp39-musllinux_1_1_s390x.whl", hash = "sha256:a2c34a93e1d2aa35fbf1485e5010337c72c6791407d03aa5f4eed920343dd360"}, + {file = "multidict-6.0.2-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:feba80698173761cddd814fa22e88b0661e98cb810f9f986c54aa34d281e4937"}, + {file = "multidict-6.0.2-cp39-cp39-win32.whl", hash = "sha256:23b616fdc3c74c9fe01d76ce0d1ce872d2d396d8fa8e4899398ad64fb5aa214a"}, + {file = "multidict-6.0.2-cp39-cp39-win_amd64.whl", hash = "sha256:4bae31803d708f6f15fd98be6a6ac0b6958fcf68fda3c77a048a4f9073704aae"}, + {file = "multidict-6.0.2.tar.gz", hash = "sha256:5ff3bd75f38e4c43f1f470f2df7a4d430b821c4ce22be384e1459cb57d6bb013"}, +] +munch = [ + {file = "munch-2.5.0-py2.py3-none-any.whl", hash = "sha256:6f44af89a2ce4ed04ff8de41f70b226b984db10a91dcc7b9ac2efc1c77022fdd"}, + {file = "munch-2.5.0.tar.gz", hash = "sha256:2d735f6f24d4dba3417fa448cae40c6e896ec1fdab6cdb5e6510999758a4dbd2"}, +] +mypy = [ + {file = "mypy-0.961-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:697540876638ce349b01b6786bc6094ccdaba88af446a9abb967293ce6eaa2b0"}, + {file = "mypy-0.961-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:b117650592e1782819829605a193360a08aa99f1fc23d1d71e1a75a142dc7e15"}, + {file = "mypy-0.961-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:bdd5ca340beffb8c44cb9dc26697628d1b88c6bddf5c2f6eb308c46f269bb6f3"}, + {file = "mypy-0.961-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:3e09f1f983a71d0672bbc97ae33ee3709d10c779beb613febc36805a6e28bb4e"}, + {file = "mypy-0.961-cp310-cp310-win_amd64.whl", hash = "sha256:e999229b9f3198c0c880d5e269f9f8129c8862451ce53a011326cad38b9ccd24"}, + {file = "mypy-0.961-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:b24be97351084b11582fef18d79004b3e4db572219deee0212078f7cf6352723"}, + {file = "mypy-0.961-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:f4a21d01fc0ba4e31d82f0fff195682e29f9401a8bdb7173891070eb260aeb3b"}, + {file = "mypy-0.961-cp36-cp36m-win_amd64.whl", hash = "sha256:439c726a3b3da7ca84a0199a8ab444cd8896d95012c4a6c4a0d808e3147abf5d"}, + {file = "mypy-0.961-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:5a0b53747f713f490affdceef835d8f0cb7285187a6a44c33821b6d1f46ed813"}, + {file = "mypy-0.961-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:0e9f70df36405c25cc530a86eeda1e0867863d9471fe76d1273c783df3d35c2e"}, + {file = "mypy-0.961-cp37-cp37m-win_amd64.whl", hash = "sha256:b88f784e9e35dcaa075519096dc947a388319cb86811b6af621e3523980f1c8a"}, + {file = "mypy-0.961-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:d5aaf1edaa7692490f72bdb9fbd941fbf2e201713523bdb3f4038be0af8846c6"}, + {file = "mypy-0.961-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:9f5f5a74085d9a81a1f9c78081d60a0040c3efb3f28e5c9912b900adf59a16e6"}, + {file = "mypy-0.961-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:f4b794db44168a4fc886e3450201365c9526a522c46ba089b55e1f11c163750d"}, + {file = "mypy-0.961-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:64759a273d590040a592e0f4186539858c948302c653c2eac840c7a3cd29e51b"}, + {file = "mypy-0.961-cp38-cp38-win_amd64.whl", hash = "sha256:63e85a03770ebf403291ec50097954cc5caf2a9205c888ce3a61bd3f82e17569"}, + {file = "mypy-0.961-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:5f1332964963d4832a94bebc10f13d3279be3ce8f6c64da563d6ee6e2eeda932"}, + {file = "mypy-0.961-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:006be38474216b833eca29ff6b73e143386f352e10e9c2fbe76aa8549e5554f5"}, + {file = "mypy-0.961-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:9940e6916ed9371809b35b2154baf1f684acba935cd09928952310fbddaba648"}, + {file = "mypy-0.961-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:a5ea0875a049de1b63b972456542f04643daf320d27dc592d7c3d9cd5d9bf950"}, + {file = "mypy-0.961-cp39-cp39-win_amd64.whl", hash = "sha256:1ece702f29270ec6af25db8cf6185c04c02311c6bb21a69f423d40e527b75c56"}, + {file = "mypy-0.961-py3-none-any.whl", hash = "sha256:03c6cc893e7563e7b2949b969e63f02c000b32502a1b4d1314cabe391aa87d66"}, + {file = "mypy-0.961.tar.gz", hash = "sha256:f730d56cb924d371c26b8eaddeea3cc07d78ff51c521c6d04899ac6904b75492"}, +] +mypy-extensions = [ + {file = "mypy_extensions-0.4.3-py2.py3-none-any.whl", hash = "sha256:090fedd75945a69ae91ce1303b5824f428daf5a028d2f6ab8a299250a846f15d"}, + {file = "mypy_extensions-0.4.3.tar.gz", hash = "sha256:2d82818f5bb3e369420cb3c4060a7970edba416647068eb4c5343488a6c604a8"}, +] +myst-parser = [ + {file = "myst-parser-0.18.1.tar.gz", hash = "sha256:79317f4bb2c13053dd6e64f9da1ba1da6cd9c40c8a430c447a7b146a594c246d"}, + {file = "myst_parser-0.18.1-py3-none-any.whl", hash = "sha256:61b275b85d9f58aa327f370913ae1bec26ebad372cc99f3ab85c8ec3ee8d9fb8"}, +] +natsort = [ + {file = "natsort-8.2.0-py3-none-any.whl", hash = "sha256:04fe18fdd2b9e5957f19f687eb117f102ef8dde6b574764e536e91194bed4f5f"}, + {file = "natsort-8.2.0.tar.gz", hash = "sha256:57f85b72c688b09e053cdac302dd5b5b53df5f73ae20b4874fcbffd8bf783d11"}, +] +nbclassic = [ + {file = "nbclassic-0.4.7-py3-none-any.whl", hash = "sha256:d71d18aa6605eaf59e9b99b34c96360af45847f2a30ee2fefbe2f7bed4bc3df2"}, + {file = "nbclassic-0.4.7.tar.gz", hash = "sha256:1e0470583b55089c427940ed31b8a866ffef7ccab101494e409efe5ac7ba9897"}, +] +nbclient = [ + {file = "nbclient-0.7.0-py3-none-any.whl", hash = "sha256:434c91385cf3e53084185334d675a0d33c615108b391e260915d1aa8e86661b8"}, + {file = "nbclient-0.7.0.tar.gz", hash = "sha256:a1d844efd6da9bc39d2209bf996dbd8e07bf0f36b796edfabaa8f8a9ab77c3aa"}, +] +nbconvert = [ + {file = "nbconvert-7.2.2-py3-none-any.whl", hash = "sha256:fc7a3787c927cbd45a52e088e934fbbaab39afe61767522168a724b7483992be"}, + {file = "nbconvert-7.2.2.tar.gz", hash = "sha256:24acfaa466d2c9b7eb524800e4a45afbed862c5d058cfb30fc7aa24d448c95eb"}, +] +nbformat = [ + {file = "nbformat-5.7.0-py3-none-any.whl", hash = "sha256:1b05ec2c552c2f1adc745f4eddce1eac8ca9ffd59bb9fd859e827eaa031319f9"}, + {file = "nbformat-5.7.0.tar.gz", hash = "sha256:1d4760c15c1a04269ef5caf375be8b98dd2f696e5eb9e603ec2bf091f9b0d3f3"}, +] +ncompress = [ + {file = "ncompress-1.0.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:0349d7de11edd70a7efea9ce9dc67f0e47b5774832dd063f7ae68a9e3e36ea31"}, + {file = "ncompress-1.0.0-cp310-cp310-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:af0011bae90e44121f4e4edbff3dccdce7e4c5fc5e354db7eb48410d71f496df"}, + {file = "ncompress-1.0.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e6f5bf381412e9d3847b76e8b6bd1f84dfadcd3d9c25903c8592facb437909a0"}, + {file = "ncompress-1.0.0-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:e0ebd71990ef7909b6627b5341a2fe1977dcce61dd3760a29e19e3f9e4c6a275"}, + {file = "ncompress-1.0.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:8b9acc46cf36bb998ed215d6e76a94e2bd1e827b9a4cb5362982b7004b5a7620"}, + {file = "ncompress-1.0.0-cp310-cp310-win32.whl", hash = "sha256:2a104803fbe3ab0a96edb14927fa22c8142be838aabe7e938b4a52a4e82db56e"}, + {file = "ncompress-1.0.0-cp310-cp310-win_amd64.whl", hash = "sha256:5a2ae8a9170fa1f45df7efa292eb8c437b18c225b63d4adca4f50f9da0e8e0c7"}, + {file = "ncompress-1.0.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:7608fbda43d04d9f476be2dbf4ef3c96e72d83b9557a48b07fbc9ff3ad29cdd2"}, + {file = "ncompress-1.0.0-cp36-cp36m-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:8322482e72ac2802d1dca1007ec06aa281a4d5cf1cf9f8c75bb51e917382b756"}, + {file = "ncompress-1.0.0-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3590e66313041721ae81e72ece06b7048c9293321bb30900358638673608e264"}, + {file = "ncompress-1.0.0-cp36-cp36m-musllinux_1_1_i686.whl", hash = "sha256:736dbae078107742cf6ac7ccc11ae9c5eab77ef2c02aab3ef64802877bb01cab"}, + {file = "ncompress-1.0.0-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:5336a8831a7e587829ce54e9e27d1fb2e04ddbc7d2d983693e35a3a03ac3ce79"}, + {file = "ncompress-1.0.0-cp36-cp36m-win32.whl", hash = "sha256:9cd040ad73a3b0e917e01cdfba507e10e0bb56849daaac3ac3d86382d4d7ad82"}, + {file = "ncompress-1.0.0-cp36-cp36m-win_amd64.whl", hash = "sha256:8eb4a55cbeaeb238a3b412952077be6b3f37b3416cd0211cc22776391ff2fef7"}, + {file = "ncompress-1.0.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:916671d62167191af58d6b4a17b1c09c647e349dcff1fc0b7d764aa64c3773ee"}, + {file = "ncompress-1.0.0-cp37-cp37m-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:15f10fbfa11345ff0af090e3e6ae13a1fe2b52a2bb39d4f2373c2d6aeac75e5d"}, + {file = "ncompress-1.0.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fe0a671a2f7dc1ee0438d278ef30ab425a969536100c4352b5cb6bc0b6210818"}, + {file = "ncompress-1.0.0-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:9d89acf209858e7940223cf35324e1b2effec119bb009a41f039e2ea4db22177"}, + {file = "ncompress-1.0.0-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:66d991155a1655ccd98e8433c4a7e811d63eb649adb55f47d8f9528a30cc4b7a"}, + {file = "ncompress-1.0.0-cp37-cp37m-win32.whl", hash = "sha256:34c6496168fd4dbc13f1fc0c0fcbadded1957639956f8cbc6894c39999817e36"}, + {file = "ncompress-1.0.0-cp37-cp37m-win_amd64.whl", hash = "sha256:94b3f4e851f5b37e1d4cf2d8da911fa10783a59cba3d7f1f2ae5bd2842558077"}, + {file = "ncompress-1.0.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:aaa18a509d9fc173b4b47d53c834e43ced1eda63d2aa7d4613dc59b2f802a31a"}, + {file = "ncompress-1.0.0-cp38-cp38-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6540556d47670a8fb93878a44d0206bbdc87f32e4c5b57d6fe63691efafbb982"}, + {file = "ncompress-1.0.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9da7c81313aed4b6c6e8020442ed8d03d04bff72947f9380ea1ce2c63ffb8ad1"}, + {file = "ncompress-1.0.0-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:d45ec59a8a3ce00613df0c81e5567854574dbbbf01ecd1a5a0929cd8fb04844d"}, + {file = "ncompress-1.0.0-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:393cc3c126b9451fb32fe2bc07773264c90e73afbd37da0df472ac23bfd1a2d5"}, + {file = "ncompress-1.0.0-cp38-cp38-win32.whl", hash = "sha256:78674f246878938387b6f82b10d1aa2192e02544d214541943d12ef1a45e66c6"}, + {file = "ncompress-1.0.0-cp38-cp38-win_amd64.whl", hash = "sha256:da216a53db7cd4c0247376f87367dd71df457443567e55310f6d3d23a9aff2f2"}, + {file = "ncompress-1.0.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:34754041d9bac2d6908ae0d07ba541e4d6d606cca222ddd53f3a57e15f386b0a"}, + {file = "ncompress-1.0.0-cp39-cp39-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ab9fc62baaa55faf8ed8ac67f2c64a7295fec91d7c1f306ac46aa894ca4edf91"}, + {file = "ncompress-1.0.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:070044eab19586a45d1855c3e50e000ce86d6075b122a5ec8cffd480713dffac"}, + {file = "ncompress-1.0.0-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:f9ba6ab2aadd6fd90365fdad5219e4dc7bc2459b94f1e900a733dddaf4e9b2e6"}, + {file = "ncompress-1.0.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:b031e06b42037b181e3514261e1e85a9eae4af990c12b9348a9f22b8042201ff"}, + {file = "ncompress-1.0.0-cp39-cp39-win32.whl", hash = "sha256:13fa26ec8000d786a8079bb265508b5df4b445a4f460481a13549b4bd3c83824"}, + {file = "ncompress-1.0.0-cp39-cp39-win_amd64.whl", hash = "sha256:d11df815d280985dfa660974df11dbe051a1a18dca2f91f9d30fbd6548237b8f"}, + {file = "ncompress-1.0.0.tar.gz", hash = "sha256:e7bbf10cca1376f4f17ae2c447e33a9d4067525abb0c71d488c9a5ced50552f1"}, +] +nest-asyncio = [ + {file = "nest_asyncio-1.5.6-py3-none-any.whl", hash = "sha256:b9a953fb40dceaa587d109609098db21900182b16440652454a146cffb06e8b8"}, + {file = "nest_asyncio-1.5.6.tar.gz", hash = "sha256:d267cc1ff794403f7df692964d1d2a3fa9418ffea2a3f6859a439ff482fef290"}, +] +networkx = [ + {file = "networkx-2.3.zip", hash = "sha256:8311ddef63cf5c5c5e7c1d0212dd141d9a1fe3f474915281b73597ed5f1d4e3d"}, +] +nodeenv = [ + {file = "nodeenv-1.7.0-py2.py3-none-any.whl", hash = "sha256:27083a7b96a25f2f5e1d8cb4b6317ee8aeda3bdd121394e5ac54e498028a042e"}, + {file = "nodeenv-1.7.0.tar.gz", hash = "sha256:e0e7f7dfb85fc5394c6fe1e8fa98131a2473e04311a45afb6508f7cf1836fa2b"}, +] +nose = [ + {file = "nose-1.3.7-py2-none-any.whl", hash = "sha256:dadcddc0aefbf99eea214e0f1232b94f2fa9bd98fa8353711dacb112bfcbbb2a"}, + {file = "nose-1.3.7-py3-none-any.whl", hash = "sha256:9ff7c6cc443f8c51994b34a667bbcf45afd6d945be7477b52e97516fd17c53ac"}, + {file = "nose-1.3.7.tar.gz", hash = "sha256:f1bffef9cbc82628f6e7d7b40d7e255aefaa1adb6a1b1d26c69a8b79e6208a98"}, +] +notebook = [ + {file = "notebook-6.4.12-py3-none-any.whl", hash = "sha256:8c07a3bb7640e371f8a609bdbb2366a1976c6a2589da8ef917f761a61e3ad8b1"}, + {file = "notebook-6.4.12.tar.gz", hash = "sha256:6268c9ec9048cff7a45405c990c29ac9ca40b0bc3ec29263d218c5e01f2b4e86"}, +] +notebook-shim = [ + {file = "notebook_shim-0.2.0-py3-none-any.whl", hash = "sha256:481711abddfb2e5305b83cf0efe18475824eb47d1ba9f87f66a8c574b8b5c9e4"}, + {file = "notebook_shim-0.2.0.tar.gz", hash = "sha256:fdb81febb05932c6d19e44e10382ce05469cac5e1b6e99b49be6159ddb5e4804"}, +] +numpy = [ + {file = "numpy-1.23.4-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:95d79ada05005f6f4f337d3bb9de8a7774f259341c70bc88047a1f7b96a4bcb2"}, + {file = "numpy-1.23.4-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:926db372bc4ac1edf81cfb6c59e2a881606b409ddc0d0920b988174b2e2a767f"}, + {file = "numpy-1.23.4-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c237129f0e732885c9a6076a537e974160482eab8f10db6292e92154d4c67d71"}, + {file = "numpy-1.23.4-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a8365b942f9c1a7d0f0dc974747d99dd0a0cdfc5949a33119caf05cb314682d3"}, + {file = "numpy-1.23.4-cp310-cp310-win32.whl", hash = "sha256:2341f4ab6dba0834b685cce16dad5f9b6606ea8a00e6da154f5dbded70fdc4dd"}, + {file = "numpy-1.23.4-cp310-cp310-win_amd64.whl", hash = "sha256:d331afac87c92373826af83d2b2b435f57b17a5c74e6268b79355b970626e329"}, + {file = "numpy-1.23.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:488a66cb667359534bc70028d653ba1cf307bae88eab5929cd707c761ff037db"}, + {file = "numpy-1.23.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:ce03305dd694c4873b9429274fd41fc7eb4e0e4dea07e0af97a933b079a5814f"}, + {file = "numpy-1.23.4-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8981d9b5619569899666170c7c9748920f4a5005bf79c72c07d08c8a035757b0"}, + {file = "numpy-1.23.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7a70a7d3ce4c0e9284e92285cba91a4a3f5214d87ee0e95928f3614a256a1488"}, + {file = "numpy-1.23.4-cp311-cp311-win32.whl", hash = "sha256:5e13030f8793e9ee42f9c7d5777465a560eb78fa7e11b1c053427f2ccab90c79"}, + {file = "numpy-1.23.4-cp311-cp311-win_amd64.whl", hash = "sha256:7607b598217745cc40f751da38ffd03512d33ec06f3523fb0b5f82e09f6f676d"}, + {file = "numpy-1.23.4-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:7ab46e4e7ec63c8a5e6dbf5c1b9e1c92ba23a7ebecc86c336cb7bf3bd2fb10e5"}, + {file = "numpy-1.23.4-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:a8aae2fb3180940011b4862b2dd3756616841c53db9734b27bb93813cd79fce6"}, + {file = "numpy-1.23.4-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8c053d7557a8f022ec823196d242464b6955a7e7e5015b719e76003f63f82d0f"}, + {file = "numpy-1.23.4-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a0882323e0ca4245eb0a3d0a74f88ce581cc33aedcfa396e415e5bba7bf05f68"}, + {file = "numpy-1.23.4-cp38-cp38-win32.whl", hash = "sha256:dada341ebb79619fe00a291185bba370c9803b1e1d7051610e01ed809ef3a4ba"}, + {file = "numpy-1.23.4-cp38-cp38-win_amd64.whl", hash = "sha256:0fe563fc8ed9dc4474cbf70742673fc4391d70f4363f917599a7fa99f042d5a8"}, + {file = "numpy-1.23.4-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:c67b833dbccefe97cdd3f52798d430b9d3430396af7cdb2a0c32954c3ef73894"}, + {file = "numpy-1.23.4-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:f76025acc8e2114bb664294a07ede0727aa75d63a06d2fae96bf29a81747e4a7"}, + {file = "numpy-1.23.4-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:12ac457b63ec8ded85d85c1e17d85efd3c2b0967ca39560b307a35a6703a4735"}, + {file = "numpy-1.23.4-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:95de7dc7dc47a312f6feddd3da2500826defdccbc41608d0031276a24181a2c0"}, + {file = "numpy-1.23.4-cp39-cp39-win32.whl", hash = "sha256:f2f390aa4da44454db40a1f0201401f9036e8d578a25f01a6e237cea238337ef"}, + {file = "numpy-1.23.4-cp39-cp39-win_amd64.whl", hash = "sha256:f260da502d7441a45695199b4e7fd8ca87db659ba1c78f2bbf31f934fe76ae0e"}, + {file = "numpy-1.23.4-pp38-pypy38_pp73-macosx_10_9_x86_64.whl", hash = "sha256:61be02e3bf810b60ab74e81d6d0d36246dbfb644a462458bb53b595791251911"}, + {file = "numpy-1.23.4-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:296d17aed51161dbad3c67ed6d164e51fcd18dbcd5dd4f9d0a9c6055dce30810"}, + {file = "numpy-1.23.4-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:4d52914c88b4930dafb6c48ba5115a96cbab40f45740239d9f4159c4ba779962"}, + {file = "numpy-1.23.4.tar.gz", hash = "sha256:ed2cc92af0efad20198638c69bb0fc2870a58dabfba6eb722c933b48556c686c"}, +] +nvidia-ml-py3 = [ + {file = "nvidia-ml-py3-7.352.0.tar.gz", hash = "sha256:390f02919ee9d73fe63a98c73101061a6b37fa694a793abf56673320f1f51277"}, +] +oauthlib = [ + {file = "oauthlib-3.2.2-py3-none-any.whl", hash = "sha256:8139f29aac13e25d502680e9e19963e83f16838d48a0d71c287fe40e7067fbca"}, + {file = "oauthlib-3.2.2.tar.gz", hash = "sha256:9859c40929662bec5d64f34d01c99e093149682a3f38915dc0655d5a633dd918"}, +] +onnx = [ + {file = "onnx-1.12.0-cp310-cp310-macosx_10_12_x86_64.whl", hash = "sha256:bdbd2578424c70836f4d0f9dda16c21868ddb07cc8192f9e8a176908b43d694b"}, + {file = "onnx-1.12.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:213e73610173f6b2e99f99a4b0636f80b379c417312079d603806e48ada4ca8b"}, + {file = "onnx-1.12.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9fd2f4e23078df197bb76a59b9cd8f5a43a6ad2edc035edb3ecfb9042093e05a"}, + {file = "onnx-1.12.0-cp310-cp310-win32.whl", hash = "sha256:23781594bb8b7ee985de1005b3c601648d5b0568a81e01365c48f91d1f5648e4"}, + {file = "onnx-1.12.0-cp310-cp310-win_amd64.whl", hash = "sha256:81a3555fd67be2518bf86096299b48fb9154652596219890abfe90bd43a9ec13"}, + {file = "onnx-1.12.0-cp37-cp37m-macosx_10_12_x86_64.whl", hash = "sha256:5578b93dc6c918cec4dee7fb7d9dd3b09d338301ee64ca8b4f28bc217ed42dca"}, + {file = "onnx-1.12.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c11162ffc487167da140f1112f49c4f82d815824f06e58bc3095407699f05863"}, + {file = "onnx-1.12.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:341c7016e23273e9ffa9b6e301eee95b8c37d0f04df7cedbdb169d2c39524c96"}, + {file = "onnx-1.12.0-cp37-cp37m-win32.whl", hash = "sha256:3c6e6bcffc3f5c1e148df3837dc667fa4c51999788c1b76b0b8fbba607e02da8"}, + {file = "onnx-1.12.0-cp37-cp37m-win_amd64.whl", hash = "sha256:8a7aa61aea339bd28f310f4af4f52ce6c4b876386228760b16308efd58f95059"}, + {file = "onnx-1.12.0-cp38-cp38-macosx_10_12_x86_64.whl", hash = "sha256:56ceb7e094c43882b723cfaa107d85ad673cfdf91faeb28d7dcadacca4f43a07"}, + {file = "onnx-1.12.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b3629e8258db15d4e2c9b7f1be91a3186719dd94661c218c6f5fde3cc7de3d4d"}, + {file = "onnx-1.12.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2d9a7db54e75529160337232282a4816cc50667dc7dc34be178fd6f6b79d4705"}, + {file = "onnx-1.12.0-cp38-cp38-win32.whl", hash = "sha256:fea5156a03398fe0e23248042d8651c1eaac5f6637d4dd683b4c1f1320b9f7b4"}, + {file = "onnx-1.12.0-cp38-cp38-win_amd64.whl", hash = "sha256:f66d2996e65f490a57b3ae952e4e9189b53cc9fe3f75e601d50d4db2dc1b1cd9"}, + {file = "onnx-1.12.0-cp39-cp39-macosx_10_12_x86_64.whl", hash = "sha256:c39a7a0352c856f1df30dccf527eb6cb4909052e5eaf6fa2772a637324c526aa"}, + {file = "onnx-1.12.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:fab13feb4d94342aae6d357d480f2e47d41b9f4e584367542b21ca6defda9e0a"}, + {file = "onnx-1.12.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c7a9b3ea02c30efc1d2662337e280266aca491a8e86be0d8a657f874b7cccd1e"}, + {file = "onnx-1.12.0-cp39-cp39-win32.whl", hash = "sha256:f8800f28c746ab06e51ef8449fd1215621f4ddba91be3ffc264658937d38a2af"}, + {file = "onnx-1.12.0-cp39-cp39-win_amd64.whl", hash = "sha256:af90427ca04c6b7b8107c2021e1273227a3ef1a7a01f3073039cae7855a59833"}, + {file = "onnx-1.12.0.tar.gz", hash = "sha256:13b3e77d27523b9dbf4f30dfc9c959455859d5e34e921c44f712d69b8369eff9"}, +] +onnx2torch = [ + {file = "onnx2torch-1.5.4-py3-none-any.whl", hash = "sha256:fd1a0fe05072bfb9f3d86d9330299b130b41f11bd4ae634db17078974e711725"}, +] +onnxoptimizer = [ + {file = "onnxoptimizer-0.3.1-cp37-cp37m-macosx_10_15_x86_64.whl", hash = "sha256:e73a5e2e3ca4db9bff54f7131768749c861677b97ee811a136fcf1a52783cf6e"}, + {file = "onnxoptimizer-0.3.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c8bf2bfe0dc43f0776867688e1759122dec049ff4f45f7221931b687fe7e139e"}, + {file = "onnxoptimizer-0.3.1-cp37-cp37m-win_amd64.whl", hash = "sha256:a9a815bba418abfb23f319838370cfd9450305a2da7d970a2261046889a70730"}, + {file = "onnxoptimizer-0.3.1-cp38-cp38-macosx_10_15_x86_64.whl", hash = "sha256:60f1d3600f03466a451c05e3d12ce97565bae016e46f70396ba22208cfeae6f6"}, + {file = "onnxoptimizer-0.3.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:056a765593d197b2b643bfb35520a66eacebfc682583d9ac0389a56c2a259e6f"}, + {file = "onnxoptimizer-0.3.1-cp38-cp38-win_amd64.whl", hash = "sha256:15da6a036df388c3f08c3fc638b4d313ee6a1b96aaaa1c602fd1b424dd7bbc23"}, + {file = "onnxoptimizer-0.3.1-cp39-cp39-macosx_10_15_x86_64.whl", hash = "sha256:5547203ee3392e3dabcea68a3a4d316ee0269ad3cf8a3504d1f68d467f60a06a"}, + {file = "onnxoptimizer-0.3.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c773b03313e253a60c7d8fe56ea5bba38fb3442ab84a825468a35a739e8fb20b"}, + {file = "onnxoptimizer-0.3.1-cp39-cp39-win_amd64.whl", hash = "sha256:aac4d5c4c5f4c471346dfb28356355b0c54c074a1f2fe1fe122b197f68c08a92"}, + {file = "onnxoptimizer-0.3.1.tar.gz", hash = "sha256:0aa2e873a49f3762822e4400e1e8886236156f9d1dbf20319e2c18f7ebfb6a1d"}, +] +onnxruntime-gpu = [ + {file = "onnxruntime_gpu-1.12.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:42b0393c5122ed90fa2eb76192a486261d86e9526ccb78b2a98923c22791d2d1"}, + {file = "onnxruntime_gpu-1.12.1-cp310-cp310-win_amd64.whl", hash = "sha256:ecfe97335027e569d4f46725ba89316041e562b8c499690e25e11cfee4601cd1"}, + {file = "onnxruntime_gpu-1.12.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e2be6f7f5a1ce0bc8471ce42e10eab92cfb19d0748b857edcb5320b5e98311b7"}, + {file = "onnxruntime_gpu-1.12.1-cp37-cp37m-win_amd64.whl", hash = "sha256:d73204323aefebe4eecab9fcf76e22b1a00394e3d838c2962a28a27301186b73"}, + {file = "onnxruntime_gpu-1.12.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b37872527d03d3df10756408ca44014bd6ac354a044ab1c4286cd42dc138e518"}, + {file = "onnxruntime_gpu-1.12.1-cp38-cp38-win_amd64.whl", hash = "sha256:296bd9733986cb7517d15bef5535c555d3f863963a71e6575e92d2a854aee61d"}, + {file = "onnxruntime_gpu-1.12.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8e46d0724ce54c5908c5760037b78de741fbd48962b370c29ebc20e608b30eda"}, + {file = "onnxruntime_gpu-1.12.1-cp39-cp39-win_amd64.whl", hash = "sha256:fd919373be35b9ba54210688265df38ad5e19a530449385c40dab51da407345d"}, +] +opencv-python-headless = [] +osmium = [ + {file = "osmium-3.4.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:7bf648744dadd3396040ed57332780272356fb4b87dbd17521ba9b8b91c6e665"}, + {file = "osmium-3.4.1-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:a8ee676ed0a0dbd359197ffb42518889af700da29629ac13834c1149a4b83ce6"}, + {file = "osmium-3.4.1-cp310-cp310-win_amd64.whl", hash = "sha256:080345e4be12474da9b1d4f45fbf8214ab316826029f821f8043f1b36e749cc3"}, + {file = "osmium-3.4.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:58b61b72911b7bb87f617ae12872d7c11d360f08fb50927eb769a91be3434d7c"}, + {file = "osmium-3.4.1-cp36-cp36m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:bfee94a25e419923bcb885bf624024a1610f0e1c26ceb1a7c65426420d549c0e"}, + {file = "osmium-3.4.1-cp36-cp36m-win_amd64.whl", hash = "sha256:2ac803d2d1b0097768a8bf0c174349d686d5dc2ec832ec84cadb20937a415d10"}, + {file = "osmium-3.4.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:daa478c951ade8b49348096f5e330bbe39cd2b5057127666a9102094cf7f31fb"}, + {file = "osmium-3.4.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:5453ed8c8c69ab3ed2c17ae1fd3567b9b54036916f0ffe77235fe363e7029b01"}, + {file = "osmium-3.4.1-cp37-cp37m-win_amd64.whl", hash = "sha256:f9776510dbaac32ded5d3bbe31bacdeeefefc79ce8ea54c743e9eb2ce4ace007"}, + {file = "osmium-3.4.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:d49e56225f4e31867e2bbdef000ae3fb9b18ca6697e44c3315d64b46d53fc77e"}, + {file = "osmium-3.4.1-cp38-cp38-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:76e8461ae68c5307f44eb407424b7dcfc7d0d8bb5b52283088d8f549c0d715ba"}, + {file = "osmium-3.4.1-cp38-cp38-win_amd64.whl", hash = "sha256:3f4710b8350d93edc194a466ab4cb42efcc58961be46901cced359f74bed27e5"}, + {file = "osmium-3.4.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:a777eaa408a49f8c2f0f0358a09307c9fa69d4809ae3632f3e40c61bdbf11d17"}, + {file = "osmium-3.4.1-cp39-cp39-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:50a9c94c4856d81c11e68ff327b81d759311974d7fb67618cec3b15e32b7f4c1"}, + {file = "osmium-3.4.1-cp39-cp39-win_amd64.whl", hash = "sha256:e45b7c54ac756e9cb40e2ba68691df635804eb6aa2023088af66936a9c8e3782"}, + {file = "osmium-3.4.1.tar.gz", hash = "sha256:575dad72ab169cf585b9aeefb4f5f99ac250bf7da1986992afcbf169dc70c381"}, +] +packaging = [ + {file = "packaging-21.3-py3-none-any.whl", hash = "sha256:ef103e05f519cdc783ae24ea4e2e0f508a9c99b2d4969652eed6a2e1ea5bd522"}, + {file = "packaging-21.3.tar.gz", hash = "sha256:dd47c42927d89ab911e606518907cc2d3a1f38bbd026385970643f9c5b8ecfeb"}, +] +pandas = [ + {file = "pandas-1.5.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:0a78e05ec09731c5b3bd7a9805927ea631fe6f6cb06f0e7c63191a9a778d52b4"}, + {file = "pandas-1.5.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:5b0c970e2215572197b42f1cff58a908d734503ea54b326412c70d4692256391"}, + {file = "pandas-1.5.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:f340331a3f411910adfb4bbe46c2ed5872d9e473a783d7f14ecf49bc0869c594"}, + {file = "pandas-1.5.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d8c709f4700573deb2036d240d140934df7e852520f4a584b2a8d5443b71f54d"}, + {file = "pandas-1.5.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:32e3d9f65606b3f6e76555bfd1d0b68d94aff0929d82010b791b6254bf5a4b96"}, + {file = "pandas-1.5.1-cp310-cp310-win_amd64.whl", hash = "sha256:a52419d9ba5906db516109660b114faf791136c94c1a636ed6b29cbfff9187ee"}, + {file = "pandas-1.5.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:66a1ad667b56e679e06ba73bb88c7309b3f48a4c279bd3afea29f65a766e9036"}, + {file = "pandas-1.5.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:36aa1f8f680d7584e9b572c3203b20d22d697c31b71189322f16811d4ecfecd3"}, + {file = "pandas-1.5.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:bcf1a82b770b8f8c1e495b19a20d8296f875a796c4fe6e91da5ef107f18c5ecb"}, + {file = "pandas-1.5.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2c25e5c16ee5c0feb6cf9d982b869eec94a22ddfda9aa2fbed00842cbb697624"}, + {file = "pandas-1.5.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:932d2d7d3cab44cfa275601c982f30c2d874722ef6396bb539e41e4dc4618ed4"}, + {file = "pandas-1.5.1-cp311-cp311-win_amd64.whl", hash = "sha256:eb7e8cf2cf11a2580088009b43de84cabbf6f5dae94ceb489f28dba01a17cb77"}, + {file = "pandas-1.5.1-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:cb2a9cf1150302d69bb99861c5cddc9c25aceacb0a4ef5299785d0f5389a3209"}, + {file = "pandas-1.5.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:81f0674fa50b38b6793cd84fae5d67f58f74c2d974d2cb4e476d26eee33343d0"}, + {file = "pandas-1.5.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:17da7035d9e6f9ea9cdc3a513161f8739b8f8489d31dc932bc5a29a27243f93d"}, + {file = "pandas-1.5.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:669c8605dba6c798c1863157aefde959c1796671ffb342b80fcb80a4c0bc4c26"}, + {file = "pandas-1.5.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:683779e5728ac9138406c59a11e09cd98c7d2c12f0a5fc2b9c5eecdbb4a00075"}, + {file = "pandas-1.5.1-cp38-cp38-win32.whl", hash = "sha256:ddf46b940ef815af4e542697eaf071f0531449407a7607dd731bf23d156e20a7"}, + {file = "pandas-1.5.1-cp38-cp38-win_amd64.whl", hash = "sha256:db45b94885000981522fb92349e6b76f5aee0924cc5315881239c7859883117d"}, + {file = "pandas-1.5.1-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:927e59c694e039c75d7023465d311277a1fc29ed7236b5746e9dddf180393113"}, + {file = "pandas-1.5.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:e675f8fe9aa6c418dc8d3aac0087b5294c1a4527f1eacf9fe5ea671685285454"}, + {file = "pandas-1.5.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:04e51b01d5192499390c0015630975f57836cc95c7411415b499b599b05c0c96"}, + {file = "pandas-1.5.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5cee0c74e93ed4f9d39007e439debcaadc519d7ea5c0afc3d590a3a7b2edf060"}, + {file = "pandas-1.5.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b156a971bc451c68c9e1f97567c94fd44155f073e3bceb1b0d195fd98ed12048"}, + {file = "pandas-1.5.1-cp39-cp39-win32.whl", hash = "sha256:05c527c64ee02a47a24031c880ee0ded05af0623163494173204c5b72ddce658"}, + {file = "pandas-1.5.1-cp39-cp39-win_amd64.whl", hash = "sha256:6bb391659a747cf4f181a227c3e64b6d197100d53da98dcd766cc158bdd9ec68"}, + {file = "pandas-1.5.1.tar.gz", hash = "sha256:249cec5f2a5b22096440bd85c33106b6102e0672204abd2d5c014106459804ee"}, +] +pandocfilters = [ + {file = "pandocfilters-1.5.0-py2.py3-none-any.whl", hash = "sha256:33aae3f25fd1a026079f5d27bdd52496f0e0803b3469282162bafdcbdf6ef14f"}, + {file = "pandocfilters-1.5.0.tar.gz", hash = "sha256:0b679503337d233b4339a817bfc8c50064e2eff681314376a47cb582305a7a38"}, +] +parameterized = [ + {file = "parameterized-0.8.1-py2.py3-none-any.whl", hash = "sha256:9cbb0b69a03e8695d68b3399a8a5825200976536fe1cb79db60ed6a4c8c9efe9"}, + {file = "parameterized-0.8.1.tar.gz", hash = "sha256:41bbff37d6186430f77f900d777e5bb6a24928a1c46fb1de692f8b52b8833b5c"}, +] +paramiko = [ + {file = "paramiko-2.11.0-py2.py3-none-any.whl", hash = "sha256:655f25dc8baf763277b933dfcea101d636581df8d6b9774d1fb653426b72c270"}, + {file = "paramiko-2.11.0.tar.gz", hash = "sha256:003e6bee7c034c21fbb051bf83dc0a9ee4106204dd3c53054c71452cc4ec3938"}, +] +parso = [ + {file = "parso-0.8.3-py2.py3-none-any.whl", hash = "sha256:c001d4636cd3aecdaf33cbb40aebb59b094be2a74c556778ef5576c175e19e75"}, + {file = "parso-0.8.3.tar.gz", hash = "sha256:8c07be290bb59f03588915921e29e8a50002acaf2cdc5fa0e0114f91709fafa0"}, +] +pexpect = [ + {file = "pexpect-4.8.0-py2.py3-none-any.whl", hash = "sha256:0b48a55dcb3c05f3329815901ea4fc1537514d6ba867a152b581d69ae3710937"}, + {file = "pexpect-4.8.0.tar.gz", hash = "sha256:fc65a43959d153d0114afe13997d439c22823a27cefceb5ff35c2178c6784c0c"}, +] +pickleshare = [ + {file = "pickleshare-0.7.5-py2.py3-none-any.whl", hash = "sha256:9649af414d74d4df115d5d718f82acb59c9d418196b7b4290ed47a12ce62df56"}, + {file = "pickleshare-0.7.5.tar.gz", hash = "sha256:87683d47965c1da65cdacaf31c8441d12b8044cdec9aca500cd78fc2c683afca"}, +] +pillow = [ + {file = "Pillow-9.2.0-cp310-cp310-macosx_10_10_x86_64.whl", hash = "sha256:a9c9bc489f8ab30906d7a85afac4b4944a572a7432e00698a7239f44a44e6efb"}, + {file = "Pillow-9.2.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:510cef4a3f401c246cfd8227b300828715dd055463cdca6176c2e4036df8bd4f"}, + {file = "Pillow-9.2.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7888310f6214f19ab2b6df90f3f06afa3df7ef7355fc025e78a3044737fab1f5"}, + {file = "Pillow-9.2.0-cp310-cp310-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:831e648102c82f152e14c1a0938689dbb22480c548c8d4b8b248b3e50967b88c"}, + {file = "Pillow-9.2.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1cc1d2451e8a3b4bfdb9caf745b58e6c7a77d2e469159b0d527a4554d73694d1"}, + {file = "Pillow-9.2.0-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:136659638f61a251e8ed3b331fc6ccd124590eeff539de57c5f80ef3a9594e58"}, + {file = "Pillow-9.2.0-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:6e8c66f70fb539301e064f6478d7453e820d8a2c631da948a23384865cd95544"}, + {file = "Pillow-9.2.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:37ff6b522a26d0538b753f0b4e8e164fdada12db6c6f00f62145d732d8a3152e"}, + {file = "Pillow-9.2.0-cp310-cp310-win32.whl", hash = "sha256:c79698d4cd9318d9481d89a77e2d3fcaeff5486be641e60a4b49f3d2ecca4e28"}, + {file = "Pillow-9.2.0-cp310-cp310-win_amd64.whl", hash = "sha256:254164c57bab4b459f14c64e93df11eff5ded575192c294a0c49270f22c5d93d"}, + {file = "Pillow-9.2.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:adabc0bce035467fb537ef3e5e74f2847c8af217ee0be0455d4fec8adc0462fc"}, + {file = "Pillow-9.2.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:336b9036127eab855beec9662ac3ea13a4544a523ae273cbf108b228ecac8437"}, + {file = "Pillow-9.2.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:50dff9cc21826d2977ef2d2a205504034e3a4563ca6f5db739b0d1026658e004"}, + {file = "Pillow-9.2.0-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:cb6259196a589123d755380b65127ddc60f4c64b21fc3bb46ce3a6ea663659b0"}, + {file = "Pillow-9.2.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7b0554af24df2bf96618dac71ddada02420f946be943b181108cac55a7a2dcd4"}, + {file = "Pillow-9.2.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:15928f824870535c85dbf949c09d6ae7d3d6ac2d6efec80f3227f73eefba741c"}, + {file = "Pillow-9.2.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:bdd0de2d64688ecae88dd8935012c4a72681e5df632af903a1dca8c5e7aa871a"}, + {file = "Pillow-9.2.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:d5b87da55a08acb586bad5c3aa3b86505f559b84f39035b233d5bf844b0834b1"}, + {file = "Pillow-9.2.0-cp311-cp311-win32.whl", hash = "sha256:b6d5e92df2b77665e07ddb2e4dbd6d644b78e4c0d2e9272a852627cdba0d75cf"}, + {file = "Pillow-9.2.0-cp311-cp311-win_amd64.whl", hash = "sha256:6bf088c1ce160f50ea40764f825ec9b72ed9da25346216b91361eef8ad1b8f8c"}, + {file = "Pillow-9.2.0-cp37-cp37m-macosx_10_10_x86_64.whl", hash = "sha256:2c58b24e3a63efd22554c676d81b0e57f80e0a7d3a5874a7e14ce90ec40d3069"}, + {file = "Pillow-9.2.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:eef7592281f7c174d3d6cbfbb7ee5984a671fcd77e3fc78e973d492e9bf0eb3f"}, + {file = "Pillow-9.2.0-cp37-cp37m-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:dcd7b9c7139dc8258d164b55696ecd16c04607f1cc33ba7af86613881ffe4ac8"}, + {file = "Pillow-9.2.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a138441e95562b3c078746a22f8fca8ff1c22c014f856278bdbdd89ca36cff1b"}, + {file = "Pillow-9.2.0-cp37-cp37m-manylinux_2_28_aarch64.whl", hash = "sha256:93689632949aff41199090eff5474f3990b6823404e45d66a5d44304e9cdc467"}, + {file = "Pillow-9.2.0-cp37-cp37m-manylinux_2_28_x86_64.whl", hash = "sha256:f3fac744f9b540148fa7715a435d2283b71f68bfb6d4aae24482a890aed18b59"}, + {file = "Pillow-9.2.0-cp37-cp37m-win32.whl", hash = "sha256:fa768eff5f9f958270b081bb33581b4b569faabf8774726b283edb06617101dc"}, + {file = "Pillow-9.2.0-cp37-cp37m-win_amd64.whl", hash = "sha256:69bd1a15d7ba3694631e00df8de65a8cb031911ca11f44929c97fe05eb9b6c1d"}, + {file = "Pillow-9.2.0-cp38-cp38-macosx_10_10_x86_64.whl", hash = "sha256:030e3460861488e249731c3e7ab59b07c7853838ff3b8e16aac9561bb345da14"}, + {file = "Pillow-9.2.0-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:74a04183e6e64930b667d321524e3c5361094bb4af9083db5c301db64cd341f3"}, + {file = "Pillow-9.2.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2d33a11f601213dcd5718109c09a52c2a1c893e7461f0be2d6febc2879ec2402"}, + {file = "Pillow-9.2.0-cp38-cp38-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1fd6f5e3c0e4697fa7eb45b6e93996299f3feee73a3175fa451f49a74d092b9f"}, + {file = "Pillow-9.2.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a647c0d4478b995c5e54615a2e5360ccedd2f85e70ab57fbe817ca613d5e63b8"}, + {file = "Pillow-9.2.0-cp38-cp38-manylinux_2_28_aarch64.whl", hash = "sha256:4134d3f1ba5f15027ff5c04296f13328fecd46921424084516bdb1b2548e66ff"}, + {file = "Pillow-9.2.0-cp38-cp38-manylinux_2_28_x86_64.whl", hash = "sha256:bc431b065722a5ad1dfb4df354fb9333b7a582a5ee39a90e6ffff688d72f27a1"}, + {file = "Pillow-9.2.0-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:1536ad017a9f789430fb6b8be8bf99d2f214c76502becc196c6f2d9a75b01b76"}, + {file = "Pillow-9.2.0-cp38-cp38-win32.whl", hash = "sha256:2ad0d4df0f5ef2247e27fc790d5c9b5a0af8ade9ba340db4a73bb1a4a3e5fb4f"}, + {file = "Pillow-9.2.0-cp38-cp38-win_amd64.whl", hash = "sha256:ec52c351b35ca269cb1f8069d610fc45c5bd38c3e91f9ab4cbbf0aebc136d9c8"}, + {file = "Pillow-9.2.0-cp39-cp39-macosx_10_10_x86_64.whl", hash = "sha256:0ed2c4ef2451de908c90436d6e8092e13a43992f1860275b4d8082667fbb2ffc"}, + {file = "Pillow-9.2.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:4ad2f835e0ad81d1689f1b7e3fbac7b01bb8777d5a985c8962bedee0cc6d43da"}, + {file = "Pillow-9.2.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ea98f633d45f7e815db648fd7ff0f19e328302ac36427343e4432c84432e7ff4"}, + {file = "Pillow-9.2.0-cp39-cp39-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7761afe0126d046974a01e030ae7529ed0ca6a196de3ec6937c11df0df1bc91c"}, + {file = "Pillow-9.2.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9a54614049a18a2d6fe156e68e188da02a046a4a93cf24f373bffd977e943421"}, + {file = "Pillow-9.2.0-cp39-cp39-manylinux_2_28_aarch64.whl", hash = "sha256:5aed7dde98403cd91d86a1115c78d8145c83078e864c1de1064f52e6feb61b20"}, + {file = "Pillow-9.2.0-cp39-cp39-manylinux_2_28_x86_64.whl", hash = "sha256:13b725463f32df1bfeacbf3dd197fb358ae8ebcd8c5548faa75126ea425ccb60"}, + {file = "Pillow-9.2.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:808add66ea764ed97d44dda1ac4f2cfec4c1867d9efb16a33d158be79f32b8a4"}, + {file = "Pillow-9.2.0-cp39-cp39-win32.whl", hash = "sha256:337a74fd2f291c607d220c793a8135273c4c2ab001b03e601c36766005f36885"}, + {file = "Pillow-9.2.0-cp39-cp39-win_amd64.whl", hash = "sha256:fac2d65901fb0fdf20363fbd345c01958a742f2dc62a8dd4495af66e3ff502a4"}, + {file = "Pillow-9.2.0-pp37-pypy37_pp73-macosx_10_10_x86_64.whl", hash = "sha256:ad2277b185ebce47a63f4dc6302e30f05762b688f8dc3de55dbae4651872cdf3"}, + {file = "Pillow-9.2.0-pp37-pypy37_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7c7b502bc34f6e32ba022b4a209638f9e097d7a9098104ae420eb8186217ebbb"}, + {file = "Pillow-9.2.0-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3d1f14f5f691f55e1b47f824ca4fdcb4b19b4323fe43cc7bb105988cad7496be"}, + {file = "Pillow-9.2.0-pp37-pypy37_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:dfe4c1fedfde4e2fbc009d5ad420647f7730d719786388b7de0999bf32c0d9fd"}, + {file = "Pillow-9.2.0-pp38-pypy38_pp73-macosx_10_10_x86_64.whl", hash = "sha256:f07f1f00e22b231dd3d9b9208692042e29792d6bd4f6639415d2f23158a80013"}, + {file = "Pillow-9.2.0-pp38-pypy38_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1802f34298f5ba11d55e5bb09c31997dc0c6aed919658dfdf0198a2fe75d5490"}, + {file = "Pillow-9.2.0-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:17d4cafe22f050b46d983b71c707162d63d796a1235cdf8b9d7a112e97b15bac"}, + {file = "Pillow-9.2.0-pp38-pypy38_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:96b5e6874431df16aee0c1ba237574cb6dff1dcb173798faa6a9d8b399a05d0e"}, + {file = "Pillow-9.2.0-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:0030fdbd926fb85844b8b92e2f9449ba89607231d3dd597a21ae72dc7fe26927"}, + {file = "Pillow-9.2.0.tar.gz", hash = "sha256:75e636fd3e0fb872693f23ccb8a5ff2cd578801251f3a4f6854c6a5d437d3c04"}, +] +pillow-avif-plugin = [ + {file = "pillow-avif-plugin-1.2.2.tar.gz", hash = "sha256:38033ef060b96b2615f5c9e8fa87d4928a4254f0f43081abd89c9017f82c589a"}, + {file = "pillow_avif_plugin-1.2.2-cp27-cp27m-macosx_10_10_x86_64.whl", hash = "sha256:fc542b03ea87f0e832904fe1ff61cb586bafcd5f80e352ae7ca5cac008e9d651"}, + {file = "pillow_avif_plugin-1.2.2-cp27-cp27m-macosx_11_0_arm64.whl", hash = "sha256:c77ed103dc587894e7d707cd4ffc0f5b1c641d09b1fb84245475f02c1db039c9"}, + {file = "pillow_avif_plugin-1.2.2-cp27-cp27m-win_amd64.whl", hash = "sha256:5c0b979acd9a58a5d5f662eb167d65c8e103af0198fcaa200661abf9733dbf9b"}, + {file = "pillow_avif_plugin-1.2.2-cp27-cp27mu-manylinux2010_i686.whl", hash = "sha256:6dade8e87909766a655a88df0a3c0078c9020315e2fefab8cf3496d9940fd0f8"}, + {file = "pillow_avif_plugin-1.2.2-cp27-cp27mu-manylinux2010_x86_64.whl", hash = "sha256:54b1a27610cbf754e332b0f3e7be188cceedcfcdcb4cff92d272aff04082eb1d"}, + {file = "pillow_avif_plugin-1.2.2-cp27-cp27mu-manylinux2014_aarch64.whl", hash = "sha256:887665e08bee4ded0512fe991bbbe7403c90aa9646be8d27295271dcdc10581e"}, + {file = "pillow_avif_plugin-1.2.2-cp27-cp27mu-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:feba13f19bd9381e079e72f088a66a6509caefb52304888751d637c23b1faa00"}, + {file = "pillow_avif_plugin-1.2.2-cp27-cp27mu-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:7238447e395ccee68052c06c0fb824696f5cd1f3050f50466f1889d8356a28f7"}, + {file = "pillow_avif_plugin-1.2.2-cp310-cp310-macosx_10_10_x86_64.whl", hash = "sha256:703f4e15dcfc9335f69ebd09cecb576f3db0c3586af6bd43d0971a591183b0de"}, + {file = "pillow_avif_plugin-1.2.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:9c4665a8d3aa5fb60ed2976eb52ae886f6a276c7ddf346c118b16dc6f1ceec7c"}, + {file = "pillow_avif_plugin-1.2.2-cp310-cp310-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:593006af5569df6f3aefba184a90a5112798859ec8c745bcb495ab8b84d194bc"}, + {file = "pillow_avif_plugin-1.2.2-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:e2fa7245f7544f4ae03ab4efc035a398883b404488806094e661b3438d921b88"}, + {file = "pillow_avif_plugin-1.2.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:017e5e52cb4320414e8ce3e2089eae2cb87c22c73ff6012b17ae326fc5753b20"}, + {file = "pillow_avif_plugin-1.2.2-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:2a57136d4866de5dc80cfb24d66655955fbdd87acf1d11d88c8dc2ab41023e46"}, + {file = "pillow_avif_plugin-1.2.2-cp310-cp310-win_amd64.whl", hash = "sha256:f339511d0fccb69e3a5e3af39f8fe6700b0a07279015006ea56f8f49e7fecff4"}, + {file = "pillow_avif_plugin-1.2.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:05e821ecd90bb0b8d2dc7610625372cc47de9cb893d09662528bad572f669d1c"}, + {file = "pillow_avif_plugin-1.2.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d33886a5f9796fe9a8a3bc25ccfdeba7db119adb50b7004f1928a14b07d0213a"}, + {file = "pillow_avif_plugin-1.2.2-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:75b7ed186c2f740dd26e556f6a966c59a170b70263e429a2c81920fe444da8a7"}, + {file = "pillow_avif_plugin-1.2.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a11aef6b79078b8dad25c928e5871c146ab94424472851d5bf539ba62abde9ac"}, + {file = "pillow_avif_plugin-1.2.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:10696c536d68a14cefea3b98edb8d5a7ae29e8e07458f1d59c5d1cd780a8bf2a"}, + {file = "pillow_avif_plugin-1.2.2-cp36-cp36m-macosx_10_10_x86_64.whl", hash = "sha256:1a7291d6a5fb7336e72685a31d193e0b3a6bee9986c9ac4d8bd4b68dbe6d4f7f"}, + {file = "pillow_avif_plugin-1.2.2-cp36-cp36m-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:14b9c5dbf237e7dc12f69819ea181a457b3bd4f59f8cd71d028d3635fd3bcab4"}, + {file = "pillow_avif_plugin-1.2.2-cp36-cp36m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:799cbfbeee831332d280c80df9ce16b5c3b1224c318264e97e89df8da32e870e"}, + {file = "pillow_avif_plugin-1.2.2-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:c8f64153b2bb8007d00a3ccb32bb374dda185bf1b4a145c2e971fc67b68d015c"}, + {file = "pillow_avif_plugin-1.2.2-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:1b7937a20042fdd4272cdb3f2942d0290a045e6016335eeb79685ee24e8aa652"}, + {file = "pillow_avif_plugin-1.2.2-cp36-cp36m-win_amd64.whl", hash = "sha256:e5aa90fee46584d5958832a47e19fb7c18de059cacdac33494a55b9a064a56dc"}, + {file = "pillow_avif_plugin-1.2.2-cp37-cp37m-macosx_10_10_x86_64.whl", hash = "sha256:1124f4a5e2312663cdb96879dd01a200475bd86626bf4905fca33c6d438e479b"}, + {file = "pillow_avif_plugin-1.2.2-cp37-cp37m-macosx_11_0_arm64.whl", hash = "sha256:a1d2a17a6b133793ad733b33712cdc0bba13acc6fe83d259ef3c735e172550a4"}, + {file = "pillow_avif_plugin-1.2.2-cp37-cp37m-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:eb2f34c093b93dbc05b28fc34715b411ee0a5f30788137b27eb89864375134c8"}, + {file = "pillow_avif_plugin-1.2.2-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:bef5d0f2b198aca6a13ebd77006ecb25e08d2c09deb25dc89ec72d2460da8e67"}, + {file = "pillow_avif_plugin-1.2.2-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:c8ec81be95e14de6e8052cceae593d4ff43ba22938186b44c68964715a85c1f9"}, + {file = "pillow_avif_plugin-1.2.2-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:39cbf7b21392778f1bd3988c97429ff7b86a9a972f033c9c3674544114e612ab"}, + {file = "pillow_avif_plugin-1.2.2-cp37-cp37m-win_amd64.whl", hash = "sha256:c9099647c81ec26b2f92dde414876f000f74588f15f5e60228dbf0494891d817"}, + {file = "pillow_avif_plugin-1.2.2-cp38-cp38-macosx_10_10_x86_64.whl", hash = "sha256:050599ad735e6a3d6c565bc563ced74872acd3e8bd3e7ac9f014dc2e82249611"}, + {file = "pillow_avif_plugin-1.2.2-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:c3adf80a6ee5e895b75bcd3743f81b3ed96cd0c418326f499312b1bde87b41f1"}, + {file = "pillow_avif_plugin-1.2.2-cp38-cp38-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:251f1fc60caedd2c641c9f28c4f5a74610aa6c1d1b54e681ce63d508a8e30c53"}, + {file = "pillow_avif_plugin-1.2.2-cp38-cp38-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:3216e9f28514947fcdecd41782ccb5bb3a73360d758b1a2ff7fbf3831e0f5bf7"}, + {file = "pillow_avif_plugin-1.2.2-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a229d44f8446d6e2515e965d6d066cfd9308d50c6ada22ecb2f13a9b0c492e86"}, + {file = "pillow_avif_plugin-1.2.2-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:529eb2d9e3827acf874c6ddedc28729bfb709c115cc972c77464cc7bacdf2b38"}, + {file = "pillow_avif_plugin-1.2.2-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:9d3ee3b5b66d58c33bc723074e2db7e1256d341ba90edfd2c9ea19c7964836da"}, + {file = "pillow_avif_plugin-1.2.2-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:a34a928ed23508a694b34a14252e178b82db577285d43a1eaf143a6a8a6ddd63"}, + {file = "pillow_avif_plugin-1.2.2-cp38-cp38-win_amd64.whl", hash = "sha256:d40bf89d78da035dea9d5167335f73e71b696509e14513d875ac2605b91ae269"}, + {file = "pillow_avif_plugin-1.2.2-cp39-cp39-macosx_10_10_x86_64.whl", hash = "sha256:ad8958a5ea5e3f6ae2a4ded374fb7b84b3af2176e295ca6c3d1d0b6e9866933e"}, + {file = "pillow_avif_plugin-1.2.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:ab19285161028059dfc6362b7aba6a02ff5371d22492d8a71eade7d7e5ca6f59"}, + {file = "pillow_avif_plugin-1.2.2-cp39-cp39-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:8f70d2787bf9bed4588fedd9e1f149eb7c2a9990df3ee123eb18d86882ca0b8a"}, + {file = "pillow_avif_plugin-1.2.2-cp39-cp39-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:220fc8e8b9e1e3e98cd7f6dcc116cff8ca453b249dba62264ab0dc2a92fc4e1b"}, + {file = "pillow_avif_plugin-1.2.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0514b09d518a699525061160093da58eb3a04649daf98d8e9ee52d739de5be6e"}, + {file = "pillow_avif_plugin-1.2.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:a6314e0144a2b08e39b6842fa5b981383d7932f6e8363b6bbb291a9efc23deb1"}, + {file = "pillow_avif_plugin-1.2.2-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:3bf72f8df4b08b63b183c6368e3bd0cd098bfacc494803383589655607bc1f76"}, + {file = "pillow_avif_plugin-1.2.2-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:0d54543ed9fbb6c18b61c93a2296e2a9bfc85ef559cb6a50b92fe80cc4711db5"}, + {file = "pillow_avif_plugin-1.2.2-cp39-cp39-win_amd64.whl", hash = "sha256:86c62edb830a83a97c2a2f9a262968f12ce32adbf1069fd5fae47a0fae706e16"}, +] +pipenv = [ + {file = "pipenv-2022.10.12-py2.py3-none-any.whl", hash = "sha256:f43972a42411107ade86b6f17dd698dfcd843bd84eb7264163ebb363f6b0ede4"}, + {file = "pipenv-2022.10.12.tar.gz", hash = "sha256:a4d88f6667cbcd9ea432d626a8b373cd3101886b9fb964ea7e7f9650a83fc307"}, +] +pkginfo = [ + {file = "pkginfo-1.8.3-py2.py3-none-any.whl", hash = "sha256:848865108ec99d4901b2f7e84058b6e7660aae8ae10164e015a6dcf5b242a594"}, + {file = "pkginfo-1.8.3.tar.gz", hash = "sha256:a84da4318dd86f870a9447a8c98340aa06216bfc6f2b7bdc4b8766984ae1867c"}, +] +pkgutil-resolve-name = [ + {file = "pkgutil_resolve_name-1.3.10-py3-none-any.whl", hash = "sha256:ca27cc078d25c5ad71a9de0a7a330146c4e014c2462d9af19c6b828280649c5e"}, + {file = "pkgutil_resolve_name-1.3.10.tar.gz", hash = "sha256:357d6c9e6a755653cfd78893817c0853af365dd51ec97f3d358a819373bbd174"}, +] +platformdirs = [ + {file = "platformdirs-2.5.2-py3-none-any.whl", hash = "sha256:027d8e83a2d7de06bbac4e5ef7e023c02b863d7ea5d079477e722bb41ab25788"}, + {file = "platformdirs-2.5.2.tar.gz", hash = "sha256:58c8abb07dcb441e6ee4b11d8df0ac856038f944ab98b7be6b27b2a3c7feef19"}, +] +plotly = [ + {file = "plotly-5.10.0-py2.py3-none-any.whl", hash = "sha256:989b13825cc974390aa0169479485d9257d37848a47bc63957251f8e1a7046ba"}, + {file = "plotly-5.10.0.tar.gz", hash = "sha256:4d36d9859b7a153b273562deeed8c292587a472eb1fd57cd4158ec89d9defadb"}, +] +pluggy = [ + {file = "pluggy-1.0.0-py2.py3-none-any.whl", hash = "sha256:74134bbf457f031a36d68416e1509f34bd5ccc019f0bcc952c7b909d06b37bd3"}, + {file = "pluggy-1.0.0.tar.gz", hash = "sha256:4224373bacce55f955a878bf9cfa763c1e360858e330072059e10bad68531159"}, +] +poetry = [ + {file = "poetry-1.2.2-py3-none-any.whl", hash = "sha256:93ea3c4a622485c2a7b7249f1e34e4ac84f8229ded76153b67506313201b154f"}, + {file = "poetry-1.2.2.tar.gz", hash = "sha256:6d9ed0b1b826a0a79190f2078d7d78483fa24bf2494f3b170e354eaa5e7b5ea1"}, +] +poetry-core = [ + {file = "poetry-core-1.3.2.tar.gz", hash = "sha256:0ab006a40cb38d6a38b97264f6835da2f08a96912f2728ce668e9ac6a34f686f"}, + {file = "poetry_core-1.3.2-py3-none-any.whl", hash = "sha256:ea0f5a90b339cde132b4e43cff78a1b440cd928db864bb67cfc97fdfcefe7218"}, +] +poetry-plugin-export = [ + {file = "poetry-plugin-export-1.1.2.tar.gz", hash = "sha256:5e92525dd63f38ce74a51ed68ea91d753523f21ce5f9ef8d3b793e2a4b2222ef"}, + {file = "poetry_plugin_export-1.1.2-py3-none-any.whl", hash = "sha256:946e3313b3d00c18fb9a50522e9d5e6a7e111beaba8d6ae33297662fc2070ac1"}, +] +portalocker = [ + {file = "portalocker-2.6.0-py2.py3-none-any.whl", hash = "sha256:102ed1f2badd8dec9af3d732ef70e94b215b85ba45a8d7ff3c0003f19b442f4e"}, + {file = "portalocker-2.6.0.tar.gz", hash = "sha256:964f6830fb42a74b5d32bce99ed37d8308c1d7d44ddf18f3dd89f4680de97b39"}, +] +pprofile = [ + {file = "pprofile-2.1.0.tar.gz", hash = "sha256:b2bb56603dadf40c0bc0f61621f22c20e41638425f729945d9b7f8e4ae8cdd4a"}, +] +pre-commit = [ + {file = "pre_commit-2.20.0-py2.py3-none-any.whl", hash = "sha256:51a5ba7c480ae8072ecdb6933df22d2f812dc897d5fe848778116129a681aac7"}, + {file = "pre_commit-2.20.0.tar.gz", hash = "sha256:a978dac7bc9ec0bcee55c18a277d553b0f419d259dadb4b9418ff2d00eb43959"}, +] +pretrainedmodels = [ + {file = "pretrainedmodels-0.7.4.tar.gz", hash = "sha256:7e77ead4619a3e11ab3c41982c8ad5b86edffe37c87fd2a37ec3c2cc6470b98a"}, +] +prometheus-client = [ + {file = "prometheus_client-0.15.0-py3-none-any.whl", hash = "sha256:db7c05cbd13a0f79975592d112320f2605a325969b270a94b71dcabc47b931d2"}, + {file = "prometheus_client-0.15.0.tar.gz", hash = "sha256:be26aa452490cfcf6da953f9436e95a9f2b4d578ca80094b4458930e5f584ab1"}, +] +prompt-toolkit = [ + {file = "prompt_toolkit-3.0.31-py3-none-any.whl", hash = "sha256:9696f386133df0fc8ca5af4895afe5d78f5fcfe5258111c2a79a1c3e41ffa96d"}, + {file = "prompt_toolkit-3.0.31.tar.gz", hash = "sha256:9ada952c9d1787f52ff6d5f3484d0b4df8952787c087edf6a1f7c2cb1ea88148"}, +] +protobuf = [ + {file = "protobuf-3.20.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:3cc797c9d15d7689ed507b165cd05913acb992d78b379f6014e013f9ecb20996"}, + {file = "protobuf-3.20.1-cp310-cp310-manylinux2014_aarch64.whl", hash = "sha256:ff8d8fa42675249bb456f5db06c00de6c2f4c27a065955917b28c4f15978b9c3"}, + {file = "protobuf-3.20.1-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:cd68be2559e2a3b84f517fb029ee611546f7812b1fdd0aa2ecc9bc6ec0e4fdde"}, + {file = "protobuf-3.20.1-cp310-cp310-win32.whl", hash = "sha256:9016d01c91e8e625141d24ec1b20fed584703e527d28512aa8c8707f105a683c"}, + {file = "protobuf-3.20.1-cp310-cp310-win_amd64.whl", hash = "sha256:32ca378605b41fd180dfe4e14d3226386d8d1b002ab31c969c366549e66a2bb7"}, + {file = "protobuf-3.20.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:9be73ad47579abc26c12024239d3540e6b765182a91dbc88e23658ab71767153"}, + {file = "protobuf-3.20.1-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:097c5d8a9808302fb0da7e20edf0b8d4703274d140fd25c5edabddcde43e081f"}, + {file = "protobuf-3.20.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:e250a42f15bf9d5b09fe1b293bdba2801cd520a9f5ea2d7fb7536d4441811d20"}, + {file = "protobuf-3.20.1-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:cdee09140e1cd184ba9324ec1df410e7147242b94b5f8b0c64fc89e38a8ba531"}, + {file = "protobuf-3.20.1-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:af0ebadc74e281a517141daad9d0f2c5d93ab78e9d455113719a45a49da9db4e"}, + {file = "protobuf-3.20.1-cp37-cp37m-win32.whl", hash = "sha256:755f3aee41354ae395e104d62119cb223339a8f3276a0cd009ffabfcdd46bb0c"}, + {file = "protobuf-3.20.1-cp37-cp37m-win_amd64.whl", hash = "sha256:62f1b5c4cd6c5402b4e2d63804ba49a327e0c386c99b1675c8a0fefda23b2067"}, + {file = "protobuf-3.20.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:06059eb6953ff01e56a25cd02cca1a9649a75a7e65397b5b9b4e929ed71d10cf"}, + {file = "protobuf-3.20.1-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:cb29edb9eab15742d791e1025dd7b6a8f6fcb53802ad2f6e3adcb102051063ab"}, + {file = "protobuf-3.20.1-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:69ccfdf3657ba59569c64295b7d51325f91af586f8d5793b734260dfe2e94e2c"}, + {file = "protobuf-3.20.1-cp38-cp38-win32.whl", hash = "sha256:dd5789b2948ca702c17027c84c2accb552fc30f4622a98ab5c51fcfe8c50d3e7"}, + {file = "protobuf-3.20.1-cp38-cp38-win_amd64.whl", hash = "sha256:77053d28427a29987ca9caf7b72ccafee011257561259faba8dd308fda9a8739"}, + {file = "protobuf-3.20.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:6f50601512a3d23625d8a85b1638d914a0970f17920ff39cec63aaef80a93fb7"}, + {file = "protobuf-3.20.1-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:284f86a6207c897542d7e956eb243a36bb8f9564c1742b253462386e96c6b78f"}, + {file = "protobuf-3.20.1-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:7403941f6d0992d40161aa8bb23e12575637008a5a02283a930addc0508982f9"}, + {file = "protobuf-3.20.1-cp39-cp39-win32.whl", hash = "sha256:db977c4ca738dd9ce508557d4fce0f5aebd105e158c725beec86feb1f6bc20d8"}, + {file = "protobuf-3.20.1-cp39-cp39-win_amd64.whl", hash = "sha256:7e371f10abe57cee5021797126c93479f59fccc9693dafd6bd5633ab67808a91"}, + {file = "protobuf-3.20.1-py2.py3-none-any.whl", hash = "sha256:adfc6cf69c7f8c50fd24c793964eef18f0ac321315439d94945820612849c388"}, + {file = "protobuf-3.20.1.tar.gz", hash = "sha256:adc31566d027f45efe3f44eeb5b1f329da43891634d61c75a5944e9be6dd42c9"}, +] +psutil = [ + {file = "psutil-5.9.3-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:b4a247cd3feaae39bb6085fcebf35b3b8ecd9b022db796d89c8f05067ca28e71"}, + {file = "psutil-5.9.3-cp27-cp27m-manylinux2010_i686.whl", hash = "sha256:5fa88e3d5d0b480602553d362c4b33a63e0c40bfea7312a7bf78799e01e0810b"}, + {file = "psutil-5.9.3-cp27-cp27m-manylinux2010_x86_64.whl", hash = "sha256:767ef4fa33acda16703725c0473a91e1832d296c37c63896c7153ba81698f1ab"}, + {file = "psutil-5.9.3-cp27-cp27m-win32.whl", hash = "sha256:9a4af6ed1094f867834f5f07acd1250605a0874169a5fcadbcec864aec2496a6"}, + {file = "psutil-5.9.3-cp27-cp27m-win_amd64.whl", hash = "sha256:fa5e32c7d9b60b2528108ade2929b115167fe98d59f89555574715054f50fa31"}, + {file = "psutil-5.9.3-cp27-cp27mu-manylinux2010_i686.whl", hash = "sha256:fe79b4ad4836e3da6c4650cb85a663b3a51aef22e1a829c384e18fae87e5e727"}, + {file = "psutil-5.9.3-cp27-cp27mu-manylinux2010_x86_64.whl", hash = "sha256:db8e62016add2235cc87fb7ea000ede9e4ca0aa1f221b40cef049d02d5d2593d"}, + {file = "psutil-5.9.3-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:941a6c2c591da455d760121b44097781bc970be40e0e43081b9139da485ad5b7"}, + {file = "psutil-5.9.3-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:71b1206e7909792d16933a0d2c1c7f04ae196186c51ba8567abae1d041f06dcb"}, + {file = "psutil-5.9.3-cp310-cp310-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f57d63a2b5beaf797b87024d018772439f9d3103a395627b77d17a8d72009543"}, + {file = "psutil-5.9.3-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e7507f6c7b0262d3e7b0eeda15045bf5881f4ada70473b87bc7b7c93b992a7d7"}, + {file = "psutil-5.9.3-cp310-cp310-win32.whl", hash = "sha256:1b540599481c73408f6b392cdffef5b01e8ff7a2ac8caae0a91b8222e88e8f1e"}, + {file = "psutil-5.9.3-cp310-cp310-win_amd64.whl", hash = "sha256:547ebb02031fdada635452250ff39942db8310b5c4a8102dfe9384ee5791e650"}, + {file = "psutil-5.9.3-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:d8c3cc6bb76492133474e130a12351a325336c01c96a24aae731abf5a47fe088"}, + {file = "psutil-5.9.3-cp36-cp36m-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:07d880053c6461c9b89cd5d4808f3b8336665fa3acdefd6777662c5ed73a851a"}, + {file = "psutil-5.9.3-cp36-cp36m-manylinux_2_12_x86_64.manylinux2010_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5e8b50241dd3c2ed498507f87a6602825073c07f3b7e9560c58411c14fe1e1c9"}, + {file = "psutil-5.9.3-cp36-cp36m-win32.whl", hash = "sha256:828c9dc9478b34ab96be75c81942d8df0c2bb49edbb481f597314d92b6441d89"}, + {file = "psutil-5.9.3-cp36-cp36m-win_amd64.whl", hash = "sha256:ed15edb14f52925869250b1375f0ff58ca5c4fa8adefe4883cfb0737d32f5c02"}, + {file = "psutil-5.9.3-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:d266cd05bd4a95ca1c2b9b5aac50d249cf7c94a542f47e0b22928ddf8b80d1ef"}, + {file = "psutil-5.9.3-cp37-cp37m-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7e4939ff75149b67aef77980409f156f0082fa36accc475d45c705bb00c6c16a"}, + {file = "psutil-5.9.3-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:68fa227c32240c52982cb931801c5707a7f96dd8927f9102d6c7771ea1ff5698"}, + {file = "psutil-5.9.3-cp37-cp37m-win32.whl", hash = "sha256:beb57d8a1ca0ae0eb3d08ccaceb77e1a6d93606f0e1754f0d60a6ebd5c288837"}, + {file = "psutil-5.9.3-cp37-cp37m-win_amd64.whl", hash = "sha256:12500d761ac091f2426567f19f95fd3f15a197d96befb44a5c1e3cbe6db5752c"}, + {file = "psutil-5.9.3-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:ba38cf9984d5462b506e239cf4bc24e84ead4b1d71a3be35e66dad0d13ded7c1"}, + {file = "psutil-5.9.3-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:46907fa62acaac364fff0b8a9da7b360265d217e4fdeaca0a2397a6883dffba2"}, + {file = "psutil-5.9.3-cp38-cp38-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a04a1836894c8279e5e0a0127c0db8e198ca133d28be8a2a72b4db16f6cf99c1"}, + {file = "psutil-5.9.3-cp38-cp38-manylinux_2_12_x86_64.manylinux2010_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8a4e07611997acf178ad13b842377e3d8e9d0a5bac43ece9bfc22a96735d9a4f"}, + {file = "psutil-5.9.3-cp38-cp38-win32.whl", hash = "sha256:6ced1ad823ecfa7d3ce26fe8aa4996e2e53fb49b7fed8ad81c80958501ec0619"}, + {file = "psutil-5.9.3-cp38-cp38-win_amd64.whl", hash = "sha256:35feafe232d1aaf35d51bd42790cbccb882456f9f18cdc411532902370d660df"}, + {file = "psutil-5.9.3-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:538fcf6ae856b5e12d13d7da25ad67f02113c96f5989e6ad44422cb5994ca7fc"}, + {file = "psutil-5.9.3-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:a3d81165b8474087bb90ec4f333a638ccfd1d69d34a9b4a1a7eaac06648f9fbe"}, + {file = "psutil-5.9.3-cp39-cp39-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3a7826e68b0cf4ce2c1ee385d64eab7d70e3133171376cac53d7c1790357ec8f"}, + {file = "psutil-5.9.3-cp39-cp39-manylinux_2_12_x86_64.manylinux2010_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9ec296f565191f89c48f33d9544d8d82b0d2af7dd7d2d4e6319f27a818f8d1cc"}, + {file = "psutil-5.9.3-cp39-cp39-win32.whl", hash = "sha256:9ec95df684583b5596c82bb380c53a603bb051cf019d5c849c47e117c5064395"}, + {file = "psutil-5.9.3-cp39-cp39-win_amd64.whl", hash = "sha256:4bd4854f0c83aa84a5a40d3b5d0eb1f3c128f4146371e03baed4589fe4f3c931"}, + {file = "psutil-5.9.3.tar.gz", hash = "sha256:7ccfcdfea4fc4b0a02ca2c31de7fcd186beb9cff8207800e14ab66f79c773af6"}, +] +ptyprocess = [ + {file = "ptyprocess-0.7.0-py2.py3-none-any.whl", hash = "sha256:4b41f3967fce3af57cc7e94b888626c18bf37a083e3651ca8feeb66d492fef35"}, + {file = "ptyprocess-0.7.0.tar.gz", hash = "sha256:5c5d0a3b48ceee0b48485e0c26037c0acd7d29765ca3fbb5cb3831d347423220"}, +] +pure-eval = [ + {file = "pure_eval-0.2.2-py3-none-any.whl", hash = "sha256:01eaab343580944bc56080ebe0a674b39ec44a945e6d09ba7db3cb8cec289350"}, + {file = "pure_eval-0.2.2.tar.gz", hash = "sha256:2b45320af6dfaa1750f543d714b6d1c520a1688dec6fd24d339063ce0aaa9ac3"}, +] +py = [ + {file = "py-1.11.0-py2.py3-none-any.whl", hash = "sha256:607c53218732647dff4acdfcd50cb62615cedf612e72d1724fb1a0cc6405b378"}, + {file = "py-1.11.0.tar.gz", hash = "sha256:51c75c4126074b472f746a24399ad32f6053d1b34b68d2fa41e558e6f4a98719"}, +] +pycapnp = [ + {file = "pycapnp-1.1.0-cp37-cp37m-macosx_10_14_x86_64.whl", hash = "sha256:bdd013eae51d190a2426d00cc72d0aaed148a5be778ca86ee1adae3ab7a0613f"}, + {file = "pycapnp-1.1.0-cp37-cp37m-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:b9a1d6306a0e3e0090574aeb08d432bd67f9eb04ab564e89ef34cd1fe320b20f"}, + {file = "pycapnp-1.1.0-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:47c8bc28521312660c95cfc8a552654949407f8b17bc7ed6955ad7dae34d21a4"}, + {file = "pycapnp-1.1.0-cp37-cp37m-win_amd64.whl", hash = "sha256:60adf2674f89f629551171116b8f400b17e9a41a2ef15736767acec405d4ca50"}, + {file = "pycapnp-1.1.0-cp38-cp38-macosx_10_14_x86_64.whl", hash = "sha256:a788a374ccb93354943c89f5b1caf785faf7bb90191cd6265e042aa004f8b206"}, + {file = "pycapnp-1.1.0-cp38-cp38-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:2a1746017079107232faf26af8ef4284ab0b20ce5cbe688d44e7553a67e5e5cb"}, + {file = "pycapnp-1.1.0-cp38-cp38-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:0c770145a4eccfe97f53ab500283aa9bf969d4a37bffc75737a964db4f2af833"}, + {file = "pycapnp-1.1.0-cp38-cp38-win_amd64.whl", hash = "sha256:1774a4fe9db5f094ba40cf00898fa4b437773e7f9c538b779275b9f422a92ebc"}, + {file = "pycapnp-1.1.0-cp39-cp39-macosx_10_14_x86_64.whl", hash = "sha256:2b28d5d951602c0b832bbe63f85ebdd7685b33118b1c11c2c65a243ec9f35a66"}, + {file = "pycapnp-1.1.0-cp39-cp39-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:61b009faba34855c9d29db107e188898c83099347e22ebcbc1d955774403247b"}, + {file = "pycapnp-1.1.0-cp39-cp39-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:2a7aa9af0185e5977a59228db5042dffb048b2d4bf4f665d2105b4781cf2fcbc"}, + {file = "pycapnp-1.1.0-cp39-cp39-win_amd64.whl", hash = "sha256:13badfb644e2eb7f1219aab259d18b262d1512021e4112fa1ad5e74d17bc30cf"}, + {file = "pycapnp-1.1.0.tar.gz", hash = "sha256:786a2e39b79e592a41e8a1eaeea6e41e2015ecb9f5b7f7c20dfc5768ba1ae077"}, +] +pycodestyle = [ + {file = "pycodestyle-2.8.0-py2.py3-none-any.whl", hash = "sha256:720f8b39dde8b293825e7ff02c475f3077124006db4f440dcbc9a20b76548a20"}, + {file = "pycodestyle-2.8.0.tar.gz", hash = "sha256:eddd5847ef438ea1c7870ca7eb78a9d47ce0cdb4851a5523949f2601d0cbbe7f"}, +] +pycparser = [ + {file = "pycparser-2.21-py2.py3-none-any.whl", hash = "sha256:8ee45429555515e1f6b185e78100aea234072576aa43ab53aefcae078162fca9"}, + {file = "pycparser-2.21.tar.gz", hash = "sha256:e644fdec12f7872f86c58ff790da456218b10f863970249516d60a5eaca77206"}, +] +pycryptodome = [ + {file = "pycryptodome-3.15.0-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:ff7ae90e36c1715a54446e7872b76102baa5c63aa980917f4aa45e8c78d1a3ec"}, + {file = "pycryptodome-3.15.0-cp27-cp27m-manylinux1_i686.whl", hash = "sha256:2ffd8b31561455453ca9f62cb4c24e6b8d119d6d531087af5f14b64bee2c23e6"}, + {file = "pycryptodome-3.15.0-cp27-cp27m-manylinux1_x86_64.whl", hash = "sha256:2ea63d46157386c5053cfebcdd9bd8e0c8b7b0ac4a0507a027f5174929403884"}, + {file = "pycryptodome-3.15.0-cp27-cp27m-manylinux2010_i686.whl", hash = "sha256:7c9ed8aa31c146bef65d89a1b655f5f4eab5e1120f55fc297713c89c9e56ff0b"}, + {file = "pycryptodome-3.15.0-cp27-cp27m-manylinux2010_x86_64.whl", hash = "sha256:5099c9ca345b2f252f0c28e96904643153bae9258647585e5e6f649bb7a1844a"}, + {file = "pycryptodome-3.15.0-cp27-cp27m-manylinux2014_aarch64.whl", hash = "sha256:2ec709b0a58b539a4f9d33fb8508264c3678d7edb33a68b8906ba914f71e8c13"}, + {file = "pycryptodome-3.15.0-cp27-cp27m-musllinux_1_1_aarch64.whl", hash = "sha256:2ae53125de5b0d2c95194d957db9bb2681da8c24d0fb0fe3b056de2bcaf5d837"}, + {file = "pycryptodome-3.15.0-cp27-cp27m-win32.whl", hash = "sha256:fd2184aae6ee2a944aaa49113e6f5787cdc5e4db1eb8edb1aea914bd75f33a0c"}, + {file = "pycryptodome-3.15.0-cp27-cp27m-win_amd64.whl", hash = "sha256:7e3a8f6ee405b3bd1c4da371b93c31f7027944b2bcce0697022801db93120d83"}, + {file = "pycryptodome-3.15.0-cp27-cp27mu-manylinux1_i686.whl", hash = "sha256:b9c5b1a1977491533dfd31e01550ee36ae0249d78aae7f632590db833a5012b8"}, + {file = "pycryptodome-3.15.0-cp27-cp27mu-manylinux1_x86_64.whl", hash = "sha256:0926f7cc3735033061ef3cf27ed16faad6544b14666410727b31fea85a5b16eb"}, + {file = "pycryptodome-3.15.0-cp27-cp27mu-manylinux2010_i686.whl", hash = "sha256:2aa55aae81f935a08d5a3c2042eb81741a43e044bd8a81ea7239448ad751f763"}, + {file = "pycryptodome-3.15.0-cp27-cp27mu-manylinux2010_x86_64.whl", hash = "sha256:c3640deff4197fa064295aaac10ab49a0d55ef3d6a54ae1499c40d646655c89f"}, + {file = "pycryptodome-3.15.0-cp27-cp27mu-manylinux2014_aarch64.whl", hash = "sha256:045d75527241d17e6ef13636d845a12e54660aa82e823b3b3341bcf5af03fa79"}, + {file = "pycryptodome-3.15.0-cp27-cp27mu-musllinux_1_1_aarch64.whl", hash = "sha256:eb6fce570869e70cc8ebe68eaa1c26bed56d40ad0f93431ee61d400525433c54"}, + {file = "pycryptodome-3.15.0-cp35-abi3-macosx_10_9_x86_64.whl", hash = "sha256:9ee40e2168f1348ae476676a2e938ca80a2f57b14a249d8fe0d3cdf803e5a676"}, + {file = "pycryptodome-3.15.0-cp35-abi3-manylinux1_i686.whl", hash = "sha256:4c3ccad74eeb7b001f3538643c4225eac398c77d617ebb3e57571a897943c667"}, + {file = "pycryptodome-3.15.0-cp35-abi3-manylinux1_x86_64.whl", hash = "sha256:1b22bcd9ec55e9c74927f6b1f69843cb256fb5a465088ce62837f793d9ffea88"}, + {file = "pycryptodome-3.15.0-cp35-abi3-manylinux2010_i686.whl", hash = "sha256:57f565acd2f0cf6fb3e1ba553d0cb1f33405ec1f9c5ded9b9a0a5320f2c0bd3d"}, + {file = "pycryptodome-3.15.0-cp35-abi3-manylinux2010_x86_64.whl", hash = "sha256:4b52cb18b0ad46087caeb37a15e08040f3b4c2d444d58371b6f5d786d95534c2"}, + {file = "pycryptodome-3.15.0-cp35-abi3-manylinux2014_aarch64.whl", hash = "sha256:092a26e78b73f2530b8bd6b3898e7453ab2f36e42fd85097d705d6aba2ec3e5e"}, + {file = "pycryptodome-3.15.0-cp35-abi3-musllinux_1_1_aarch64.whl", hash = "sha256:50ca7e587b8e541eb6c192acf92449d95377d1f88908c0a32ac5ac2703ebe28b"}, + {file = "pycryptodome-3.15.0-cp35-abi3-win32.whl", hash = "sha256:e244ab85c422260de91cda6379e8e986405b4f13dc97d2876497178707f87fc1"}, + {file = "pycryptodome-3.15.0-cp35-abi3-win_amd64.whl", hash = "sha256:c77126899c4b9c9827ddf50565e93955cb3996813c18900c16b2ea0474e130e9"}, + {file = "pycryptodome-3.15.0-pp27-pypy_73-macosx_10_9_x86_64.whl", hash = "sha256:9eaadc058106344a566dc51d3d3a758ab07f8edde013712bc8d22032a86b264f"}, + {file = "pycryptodome-3.15.0-pp27-pypy_73-manylinux1_x86_64.whl", hash = "sha256:ff287bcba9fbeb4f1cccc1f2e90a08d691480735a611ee83c80a7d74ad72b9d9"}, + {file = "pycryptodome-3.15.0-pp27-pypy_73-manylinux2010_x86_64.whl", hash = "sha256:60b4faae330c3624cc5a546ba9cfd7b8273995a15de94ee4538130d74953ec2e"}, + {file = "pycryptodome-3.15.0-pp27-pypy_73-win32.whl", hash = "sha256:a8f06611e691c2ce45ca09bbf983e2ff2f8f4f87313609d80c125aff9fad6e7f"}, + {file = "pycryptodome-3.15.0-pp36-pypy36_pp73-macosx_10_9_x86_64.whl", hash = "sha256:b9cc96e274b253e47ad33ae1fccc36ea386f5251a823ccb50593a935db47fdd2"}, + {file = "pycryptodome-3.15.0-pp36-pypy36_pp73-manylinux1_x86_64.whl", hash = "sha256:ecaaef2d21b365d9c5ca8427ffc10cebed9d9102749fd502218c23cb9a05feb5"}, + {file = "pycryptodome-3.15.0-pp36-pypy36_pp73-manylinux2010_x86_64.whl", hash = "sha256:d2a39a66057ab191e5c27211a7daf8f0737f23acbf6b3562b25a62df65ffcb7b"}, + {file = "pycryptodome-3.15.0-pp36-pypy36_pp73-win32.whl", hash = "sha256:9c772c485b27967514d0df1458b56875f4b6d025566bf27399d0c239ff1b369f"}, + {file = "pycryptodome-3.15.0.tar.gz", hash = "sha256:9135dddad504592bcc18b0d2d95ce86c3a5ea87ec6447ef25cfedea12d6018b8"}, +] +pycuda = [ + {file = "pycuda-2022.1.tar.gz", hash = "sha256:acd9030d93e76e60b122e33ad16bcf01bb1344f4c304dedff1cd2bffb0f313a3"}, +] +pycurl = [ + {file = "pycurl-7.45.1.tar.gz", hash = "sha256:a863ad18ff478f5545924057887cdae422e1b2746e41674615f687498ea5b88a"}, +] +pyflakes = [ + {file = "pyflakes-2.4.0-py2.py3-none-any.whl", hash = "sha256:3bb3a3f256f4b7968c9c788781e4ff07dce46bdf12339dcda61053375426ee2e"}, + {file = "pyflakes-2.4.0.tar.gz", hash = "sha256:05a85c2872edf37a4ed30b0cce2f6093e1d0581f8c19d7393122da7e25b2b24c"}, +] +pygame = [ + {file = "pygame-2.1.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:f149e182d0eeef15d8a9b4c9dad1b87dc6eba3a99bd3c44a777a3a2b053a3dca"}, + {file = "pygame-2.1.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:dc4444d61d48c5546df5137cdf81554887ddb6e2ef1be7f51eb77ea3b6bdd56f"}, + {file = "pygame-2.1.2-cp310-cp310-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:a0ccf8e3dce7ca67d523a6020b7e3dbf4b26797a9a8db5cc4c7b5ef20fb64701"}, + {file = "pygame-2.1.2-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:7889dce887ec83c9a0bef8d9eb3669d8863fdaf37c45bacec707d8ad90b24a38"}, + {file = "pygame-2.1.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:db2f40d5a75fd9cdda473c58b0d8b294da6e0179f00bb3b1fc2f7f29cac09bea"}, + {file = "pygame-2.1.2-cp310-cp310-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e4b4cd440d50a9f8551b8989e856aab175593af07eb825cad22fd2f8f6f2ffce"}, + {file = "pygame-2.1.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:754c2906f2ef47173a14493e1de116b2a56a2c8e1764f1202ba844d080248a5b"}, + {file = "pygame-2.1.2-cp310-cp310-win32.whl", hash = "sha256:c99b95e62cdda29c2e60235d7763447c168a6a877403e6f9ca5b2e2bb297c2ce"}, + {file = "pygame-2.1.2-cp310-cp310-win_amd64.whl", hash = "sha256:9649419254d3282dae41f23837de4108b17bc62187c3acd8af2ae3801b765cbd"}, + {file = "pygame-2.1.2-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:dcc285ee1f1d0e2672cc52f880fd3f564b1505de710e817f692fbf64a72ca657"}, + {file = "pygame-2.1.2-cp36-cp36m-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:e1bb25986db77a48f632469c6bc61baf7508ce945aa6161c02180d4ee5ac5b8d"}, + {file = "pygame-2.1.2-cp36-cp36m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:e7a8e18677e0064b7a422f6653a622652d932826a27e50f279d55a8b122a1a83"}, + {file = "pygame-2.1.2-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:dd528dbb91eca16f7522c975d0f9e94b95f6b5024c82c3247dc0383d242d33c6"}, + {file = "pygame-2.1.2-cp36-cp36m-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:fcc9586e17875c0cdf8764597955f9daa979098fd4f80be07ed68276ac225480"}, + {file = "pygame-2.1.2-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c9ce7f3d8af14d7e04eb7eb41c5e5313c43508c252bb2b9eb53e51fc87ada9fd"}, + {file = "pygame-2.1.2-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:e09044e9e1aa8512d6a9c7ce5f94b881824bcfc401105f3c24f546dfc3bb4aa5"}, + {file = "pygame-2.1.2-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:40e4d8d65985bb467d9c5a1305fb53fd6820c61d764979600becab973339676f"}, + {file = "pygame-2.1.2-cp36-cp36m-win32.whl", hash = "sha256:50d9a21edd551669862c27c9272747401b20b1939abaacb842c08ea1cdd1c04d"}, + {file = "pygame-2.1.2-cp36-cp36m-win_amd64.whl", hash = "sha256:e18c9466131378421d00fc40b637425229238d506a073d9c537b230b355a25d6"}, + {file = "pygame-2.1.2-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:07ca9f683075aea9bd977af9f09a720ebf747343d3ea8103e4f1735283b02330"}, + {file = "pygame-2.1.2-cp37-cp37m-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:3c8d6637ff75351e581327efefa9d04eeb0f257b533392b6cc6b15ceca4f7c5e"}, + {file = "pygame-2.1.2-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:5ebbefb8b576572c8fc97a3321d37dc2b4afea6b6e3877a67f7158d8c2c4cefe"}, + {file = "pygame-2.1.2-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9d6452419e01a0f848aed0597f69fd10a4c2a7750c15d1b0607f86090a39dcf3"}, + {file = "pygame-2.1.2-cp37-cp37m-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e627300a66a90651fb39e41601d447b1fdbbfffca3f08ef0278d6cc0436b2160"}, + {file = "pygame-2.1.2-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a56a811d8821f7b9a594e3d0e0dd8bd39b25e3eea8963d5963263b90fd2ea5c2"}, + {file = "pygame-2.1.2-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:24b4f7f30fa2b3d092b60be6fcc725fb91d569fc87a9bcc91614ee8b0c005726"}, + {file = "pygame-2.1.2-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:8e87716114e97322fb177e223d889a4be369a0f73212f4f8507fe0cd43253b23"}, + {file = "pygame-2.1.2-cp37-cp37m-win32.whl", hash = "sha256:20676da24e3e3e6b9fc4eecc7ba09d77ef46c3a83a028763ba1d222476c2e3fb"}, + {file = "pygame-2.1.2-cp37-cp37m-win_amd64.whl", hash = "sha256:93c4cbfc942dd00410eaa9e84252129f9f9993f37f683006d7b49ab245342254"}, + {file = "pygame-2.1.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:2405414d8c572668e04739875661e030a0c588e197fa95463fe301c3d0a0510b"}, + {file = "pygame-2.1.2-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:e8632f6b2ddb90f6f3950744bd65d5ef15af615e3034057fa30ff836f48a7179"}, + {file = "pygame-2.1.2-cp38-cp38-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:ca5ef1315fa67c241a657ab077be44f230c05740c95f0b46409457dceefdc7e5"}, + {file = "pygame-2.1.2-cp38-cp38-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:1219a963941bd53aa754e8449364c142004fe706c33a9c22ff2a76521a82d078"}, + {file = "pygame-2.1.2-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3bb0674aa789848ddc264bfc60c54965bf3bb659c141de4f600e379acc9b944c"}, + {file = "pygame-2.1.2-cp38-cp38-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:24254c4244f0d9bdc904f5d3f38e86757ca4c6aa0e44a6d55ef5e016bc7274d6"}, + {file = "pygame-2.1.2-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:97a74ba186deee68318a52637012ef6abf5be6282c659e1d1ba6ad08cf35ec85"}, + {file = "pygame-2.1.2-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:0e97d38308c441942577fea7fcd1326308bc56d6be6c024218e94d075d322e0f"}, + {file = "pygame-2.1.2-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:ea36f4f93524554a35cac2359df63b50af6556ed866830aa1f07f0d8580280ea"}, + {file = "pygame-2.1.2-cp38-cp38-win32.whl", hash = "sha256:4aa3ae32320cc704d63e185864e44f6265c2a6e52c9384afe152cc3d51b3a2ef"}, + {file = "pygame-2.1.2-cp38-cp38-win_amd64.whl", hash = "sha256:9d7b021b8dde5d528363e474bc18bd6f79a9666eef89fb4859bcb8f0a536c9de"}, + {file = "pygame-2.1.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:660c80c0b2e80f1f801715583b759fb4c7bc0c11eb3b534e89c9fc4bfbc38acd"}, + {file = "pygame-2.1.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:dad6bf3fdd3752d7519422f3732be779b98fe7c87d32c3efe2fdffdcbeebb6ca"}, + {file = "pygame-2.1.2-cp39-cp39-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:119dee20c372c85dc47b717119534d15a60c64ceab8b0eb09278866d10486afe"}, + {file = "pygame-2.1.2-cp39-cp39-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:fc2e5db54491e8f27785fc5204c96f540d3557dcf5b0a9a857b6594d6b32561b"}, + {file = "pygame-2.1.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d2d3c50ee9847b743db6cd7b1bb17a94c2c2abc16679d70f5e745cabdf19e655"}, + {file = "pygame-2.1.2-cp39-cp39-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6ecda8dd4583982bb65f9c682f244a5e94524dcf628379766227e9ed97201a49"}, + {file = "pygame-2.1.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0e06ae8e1c830f1b9c36a2bc6bb11de840232e95b78e2c349c6ed803a303be19"}, + {file = "pygame-2.1.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:c5ea87da5fe4b6164c3854f3b0c9146811dbad0dd7fa74297683dfacc485ae1c"}, + {file = "pygame-2.1.2-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:0427c103f741234336e5606d2fad86f5403c1a3d1dc55c309fbff3c984f0c9ae"}, + {file = "pygame-2.1.2-cp39-cp39-win32.whl", hash = "sha256:5e88b0d4338b94960686f59396f23f7f684fed4859fcc3b9f40286d72c1c61af"}, + {file = "pygame-2.1.2-cp39-cp39-win_amd64.whl", hash = "sha256:5d0c14152d0ca8ef5fbcc5ed9981462bdf59a9ae85a291e62d8a8d0b7e5cbe43"}, + {file = "pygame-2.1.2-pp36-pypy36_pp73-win32.whl", hash = "sha256:636f51f56615d67459b11918206bb4da30cd7d7042027bf997c218ccd6c77902"}, + {file = "pygame-2.1.2-pp37-pypy37_pp73-macosx_10_9_x86_64.whl", hash = "sha256:ff961c3280d6ee5f4163f4772f963d7a4dbe42e36c6dd54b79ad436c1f046e5d"}, + {file = "pygame-2.1.2-pp37-pypy37_pp73-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:fc30e834f65b893d1b4c230070183bf98e6b70c41c1511687e8436a33d5ce49d"}, + {file = "pygame-2.1.2-pp37-pypy37_pp73-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:5c7600bf307de1ca1dca0cc7840e34604d5b0b0a5a5dad345c3fa62b054b886d"}, + {file = "pygame-2.1.2-pp37-pypy37_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7fdb93b4282962c9a2ebf1af994ee698be823dd913218ed97a5f2fb372b10b66"}, + {file = "pygame-2.1.2-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1fddec8829e96424800c806582d73a5173b7d48946cccf7d035839ca09850db8"}, + {file = "pygame-2.1.2.tar.gz", hash = "sha256:d6d0eca28f886f0477cd0721ac688189155a587f2bb8eae740e52ca56c3ad23c"}, +] +pygments = [ + {file = "Pygments-2.13.0-py3-none-any.whl", hash = "sha256:f643f331ab57ba3c9d89212ee4a2dabc6e94f117cf4eefde99a0574720d14c42"}, + {file = "Pygments-2.13.0.tar.gz", hash = "sha256:56a8508ae95f98e2b9bdf93a6be5ae3f7d8af858b43e02c5a2ff083726be40c1"}, +] +pyjwt = [ + {file = "PyJWT-2.6.0-py3-none-any.whl", hash = "sha256:d83c3d892a77bbb74d3e1a2cfa90afaadb60945205d1095d9221f04466f64c14"}, + {file = "PyJWT-2.6.0.tar.gz", hash = "sha256:69285c7e31fc44f68a1feb309e948e0df53259d579295e6cfe2b1792329f05fd"}, +] +pylev = [ + {file = "pylev-1.4.0-py2.py3-none-any.whl", hash = "sha256:7b2e2aa7b00e05bb3f7650eb506fc89f474f70493271a35c242d9a92188ad3dd"}, + {file = "pylev-1.4.0.tar.gz", hash = "sha256:9e77e941042ad3a4cc305dcdf2b2dec1aec2fbe3dd9015d2698ad02b173006d1"}, +] +pylint = [ + {file = "pylint-2.15.4-py3-none-any.whl", hash = "sha256:629cf1dbdfb6609d7e7a45815a8bb59300e34aa35783b5ac563acaca2c4022e9"}, + {file = "pylint-2.15.4.tar.gz", hash = "sha256:5441e9294335d354b7bad57c1044e5bd7cce25c433475d76b440e53452fa5cb8"}, +] +pymsalruntime = [ + {file = "pymsalruntime-0.11.2-cp310-cp310-win32.whl", hash = "sha256:a45e35c9fa58c196029bb9f5b8bedd313b2a8ac971d576c57c31cb06139de247"}, + {file = "pymsalruntime-0.11.2-cp310-cp310-win_amd64.whl", hash = "sha256:81bd2502779b1c032d878b3e6bdb64882b8c7f94560cffed62e2555470d1fe45"}, + {file = "pymsalruntime-0.11.2-cp36-cp36m-win32.whl", hash = "sha256:e6f6316128de8f62caeadf2a755e3919cc4532964d77a550974b156f27ae5f33"}, + {file = "pymsalruntime-0.11.2-cp36-cp36m-win_amd64.whl", hash = "sha256:ee139e7222e89f5bda3d6e8f9426b6bc0e8b4ef7c6fc2e6b9bd8b6c11579c3fb"}, + {file = "pymsalruntime-0.11.2-cp37-cp37m-win32.whl", hash = "sha256:6eedca38877cc8718ac273cf796aebed9a25d64258d717599f601bc01f9b7922"}, + {file = "pymsalruntime-0.11.2-cp37-cp37m-win_amd64.whl", hash = "sha256:b0f289e4d3b01bbddf422cd82899295cf5ee4c41eda45752dd3a0733acd0ba0f"}, + {file = "pymsalruntime-0.11.2-cp38-cp38-win32.whl", hash = "sha256:5760a1c1b6fa8c10f15a325815e0315a703106d3984cbc939d17f48d84ab21bb"}, + {file = "pymsalruntime-0.11.2-cp38-cp38-win_amd64.whl", hash = "sha256:e0654d04f54d1cee218a868da77f4a5a2b5369e2cc9bb35f539144256f08b00a"}, + {file = "pymsalruntime-0.11.2-cp39-cp39-win32.whl", hash = "sha256:06501f5a1fcf83ba2edbae34c94df08f50c31290301ac20f1828c4cecc2ae1bc"}, + {file = "pymsalruntime-0.11.2-cp39-cp39-win_amd64.whl", hash = "sha256:c10f8761baa042cba3a502be50fb19d0fe46850de82cb730b836ac3aff7a9b0e"}, + {file = "pymsalruntime-0.11.2.tar.gz", hash = "sha256:636d01c7f6f165b48e288c2af0bd21447649846af00050956ba28a5d4079e98b"}, +] +pymysql = [ + {file = "PyMySQL-0.9.3-py2.py3-none-any.whl", hash = "sha256:3943fbbbc1e902f41daf7f9165519f140c4451c179380677e6a848587042561a"}, + {file = "PyMySQL-0.9.3.tar.gz", hash = "sha256:d8c059dcd81dedb85a9f034d5e22dcb4442c0b201908bede99e306d65ea7c8e7"}, +] +pynacl = [ + {file = "PyNaCl-1.5.0-cp36-abi3-macosx_10_10_universal2.whl", hash = "sha256:401002a4aaa07c9414132aaed7f6836ff98f59277a234704ff66878c2ee4a0d1"}, + {file = "PyNaCl-1.5.0-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:52cb72a79269189d4e0dc537556f4740f7f0a9ec41c1322598799b0bdad4ef92"}, + {file = "PyNaCl-1.5.0-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a36d4a9dda1f19ce6e03c9a784a2921a4b726b02e1c736600ca9c22029474394"}, + {file = "PyNaCl-1.5.0-cp36-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:0c84947a22519e013607c9be43706dd42513f9e6ae5d39d3613ca1e142fba44d"}, + {file = "PyNaCl-1.5.0-cp36-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:06b8f6fa7f5de8d5d2f7573fe8c863c051225a27b61e6860fd047b1775807858"}, + {file = "PyNaCl-1.5.0-cp36-abi3-musllinux_1_1_aarch64.whl", hash = "sha256:a422368fc821589c228f4c49438a368831cb5bbc0eab5ebe1d7fac9dded6567b"}, + {file = "PyNaCl-1.5.0-cp36-abi3-musllinux_1_1_x86_64.whl", hash = "sha256:61f642bf2378713e2c2e1de73444a3778e5f0a38be6fee0fe532fe30060282ff"}, + {file = "PyNaCl-1.5.0-cp36-abi3-win32.whl", hash = "sha256:e46dae94e34b085175f8abb3b0aaa7da40767865ac82c928eeb9e57e1ea8a543"}, + {file = "PyNaCl-1.5.0-cp36-abi3-win_amd64.whl", hash = "sha256:20f42270d27e1b6a29f54032090b972d97f0a1b0948cc52392041ef7831fee93"}, + {file = "PyNaCl-1.5.0.tar.gz", hash = "sha256:8ac7448f09ab85811607bdd21ec2464495ac8b7c66d146bf545b0f08fb9220ba"}, +] +pyopencl = [ + {file = "pyopencl-2022.2.4-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:c270c7090f6bd8a1cc006aca38256936a0b82f70165e8aff873763218f29bf85"}, + {file = "pyopencl-2022.2.4-cp310-cp310-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5a823c2003d2d3754836f7e65f19e553f8ca022f493d0111ea3bacd886853596"}, + {file = "pyopencl-2022.2.4-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4c1d1605eed80f9305251578b41068e1021f140e6d503b22933a4860c43e7cde"}, + {file = "pyopencl-2022.2.4-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:85bf733b73158a66484763ff7bca7b2d5d0187933987a2753cad3f0deeff989f"}, + {file = "pyopencl-2022.2.4-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:b1f4288700717e3f0b0ce7c6663729ea6a1362d86964261fcaa84ca2efcf06b0"}, + {file = "pyopencl-2022.2.4-cp310-cp310-win_amd64.whl", hash = "sha256:dc72723fd7d5041521f9dccece70ab1ab06f2ad74b1738712a49a3b56cea3628"}, + {file = "pyopencl-2022.2.4-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:82b3f13843c034cee54906b2c750a65910c9f28ba58b61abf80b9bc9c1595a1f"}, + {file = "pyopencl-2022.2.4-cp36-cp36m-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e1a0893caf4b522559a233c4d66e7c8a96a01d8f2c038ff7fd5b3d795a1eb2ed"}, + {file = "pyopencl-2022.2.4-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a3a5d59d87d3e271f7d41c80d558cf45f4226003ec3c341d8374d3ef849614b4"}, + {file = "pyopencl-2022.2.4-cp36-cp36m-musllinux_1_1_i686.whl", hash = "sha256:cef4b300b64b58d55364d6d9eb37123907ee1f32f2dc7f0b7d1fcabbaf6fe260"}, + {file = "pyopencl-2022.2.4-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:47f751cfa75d3038ba0aedf587dd42dc447b8e49b88339048b2147cce176e286"}, + {file = "pyopencl-2022.2.4-cp36-cp36m-win_amd64.whl", hash = "sha256:3b82458c982e6eb61691712139fc8cfd69f28ef127db2b0de06e87058e919f96"}, + {file = "pyopencl-2022.2.4-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:28a0df521643644a1d5b521032b7c6617f7d53b09851a21ce9b10b8ed869dfd5"}, + {file = "pyopencl-2022.2.4-cp37-cp37m-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3611fe2f7c219dcf3d3a119873bfe7a837a467aac00c6e53682dda71a060d29f"}, + {file = "pyopencl-2022.2.4-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7a5cfc4459e5c84ecba49b928d2e9a439f0421342e16884a6749aa227efea900"}, + {file = "pyopencl-2022.2.4-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:37001a8b70bde143597f22e79dbac90ae8c997e2136b0ec4391a2824f78eb548"}, + {file = "pyopencl-2022.2.4-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:349e1ff88b2c0ddb343666e1857b86c65fa34545354012382fe84b5d564ffde1"}, + {file = "pyopencl-2022.2.4-cp37-cp37m-win_amd64.whl", hash = "sha256:da4bc9167f04eb47774e30c5cc6b411b970d8b09ea61873b86058dd2d64445d1"}, + {file = "pyopencl-2022.2.4-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:8fae8ba0a020c5db230bba53c39fd8f950983a992fbb1318a19ba06af83bd416"}, + {file = "pyopencl-2022.2.4-cp38-cp38-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:8685df5b6ec23da07751afd589a168825f6fa727634bf957652091ed7c937151"}, + {file = "pyopencl-2022.2.4-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:84f94a99822d81372b16dcdc56ee9f7e3d2268acaf9cca21924e65b4ddefae20"}, + {file = "pyopencl-2022.2.4-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:532d7972d8cc27278761634e5367ff84cacee81f32490ffce9285ea122804768"}, + {file = "pyopencl-2022.2.4-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:d31c4cd0af50aa602b2131a7b5c964e9105291d611f2d4418ed4628094c9336f"}, + {file = "pyopencl-2022.2.4-cp38-cp38-win_amd64.whl", hash = "sha256:ca9d67ca0b072989530c71c4f781acc1efd1adb6a459e742a6d38d2b8ab1d8e8"}, + {file = "pyopencl-2022.2.4-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:c6d2a3d6dfbae423dbf6dce45ca8a1b32cca2ee842aea49d246f8bbf8ab90812"}, + {file = "pyopencl-2022.2.4-cp39-cp39-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e6e7fbacef495944e1ebb1456ac7a4c38562077d50dfd804dca6aef204f6a79a"}, + {file = "pyopencl-2022.2.4-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3735b5d2add089ea02b43ace69b50fb8fb55b11b93f7bc4be5b4249fb3370b64"}, + {file = "pyopencl-2022.2.4-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:d9e88c92569a5bbcbec802dc193be06a19891979fb02f9ca4739239e2cfd5e04"}, + {file = "pyopencl-2022.2.4-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:0b456e153c1ae1f92379680710daa228c9aa0302918e24f12355533bd4b5e1f4"}, + {file = "pyopencl-2022.2.4-cp39-cp39-win_amd64.whl", hash = "sha256:876912cfebfe9aa92a478d0bf737178e7b686d27103d7279cd1dc754b8e6e85d"}, + {file = "pyopencl-2022.2.4-pp37-pypy37_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:72f259595ac26d250f39ffbfcb47cfa81181aff6f24d70e718f67114a452eb43"}, + {file = "pyopencl-2022.2.4-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0caf451084194da8262d6197251cccdac4c2945d0cb8807fe4bd1d7b0b6ecd5c"}, + {file = "pyopencl-2022.2.4-pp38-pypy38_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a1d64d2354fef846fa7e252078c5a4b74a3c302454de6167d6802a9e1d374e60"}, + {file = "pyopencl-2022.2.4-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:912bc9c48c443f5a88e8827ee68e9cb03f6a1d78ac6f64bb7a4d65f849fa7069"}, + {file = "pyopencl-2022.2.4-pp39-pypy39_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ebf8ebabee550849e8d4a21e13487d34b17c89749b38169bba249020f21363cf"}, + {file = "pyopencl-2022.2.4-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3384a1089df1256df00fde4fc87d1f7f500fc640f4ff47adf55a592502a16396"}, + {file = "pyopencl-2022.2.4.tar.gz", hash = "sha256:b57c9ef8bd8e6db07e89106f3091ba236b24f95a38fd40dfb17d2ed7ff6be4ad"}, +] +pyopenssl = [ + {file = "pyOpenSSL-22.0.0-py2.py3-none-any.whl", hash = "sha256:ea252b38c87425b64116f808355e8da644ef9b07e429398bfece610f893ee2e0"}, + {file = "pyOpenSSL-22.0.0.tar.gz", hash = "sha256:660b1b1425aac4a1bea1d94168a85d99f0b3144c869dd4390d27629d0087f1bf"}, +] +pyparsing = [ + {file = "pyparsing-3.0.9-py3-none-any.whl", hash = "sha256:5026bae9a10eeaefb61dab2f09052b9f4307d44aee4eda64b309723d8d206bbc"}, + {file = "pyparsing-3.0.9.tar.gz", hash = "sha256:2b020ecf7d21b687f219b71ecad3631f644a47f01403fa1d1036b0c6416d70fb"}, +] +pyprof2calltree = [ + {file = "pyprof2calltree-1.4.5.tar.gz", hash = "sha256:a635672ff31677486350b2be9a823ef92f740e6354a6aeda8fa4a8a3768e8f2f"}, +] +pyproj = [ + {file = "pyproj-3.4.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:f343725566267a296b09ee7e591894f1fdc90f84f8ad5ec476aeb53bd4479c07"}, + {file = "pyproj-3.4.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:5816807ca0bdc7256558770c6206a6783a3f02bcf844f94ee245f197bb5f7285"}, + {file = "pyproj-3.4.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e7e609903572a56cca758bbaee5c1663c3e829ddce5eec4f368e68277e37022b"}, + {file = "pyproj-3.4.0-cp310-cp310-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4fd425ee8b6781c249c7adb7daa2e6c41ce573afabe4f380f5eecd913b56a3be"}, + {file = "pyproj-3.4.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:954b068136518b3174d0a99448056e97af62b63392a95c420894f7de2229dae6"}, + {file = "pyproj-3.4.0-cp310-cp310-win_amd64.whl", hash = "sha256:4a23d84c5ffc383c7d9f0bde3a06fc1f6697b1b96725597f8f01e7b4bef0a2b5"}, + {file = "pyproj-3.4.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:1f9c100fd0fd80edbc7e4daa303600a8cbef6f0de43d005617acb38276b88dc0"}, + {file = "pyproj-3.4.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:aa5171f700f174777a9e9ed8f4655583243967c0f9cf2c90e3f54e54ff740134"}, + {file = "pyproj-3.4.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9a496d9057b2128db9d733e66b206f2d5954bbae6b800d412f562d780561478c"}, + {file = "pyproj-3.4.0-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:52e54796e2d9554a5eb8f11df4748af1fbbc47f76aa234d6faf09216a84554c5"}, + {file = "pyproj-3.4.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a454a7c4423faa2a14e939d08ef293ee347fa529c9df79022b0585a6e1d8310c"}, + {file = "pyproj-3.4.0-cp311-cp311-win_amd64.whl", hash = "sha256:25a36e297f3e0524694d40259e3e895edc1a47492a0e30608268ffc1328e3f5d"}, + {file = "pyproj-3.4.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:77d5f519f3cdb94b026ecca626f78db4f041afe201cf082079c8c0092a30b087"}, + {file = "pyproj-3.4.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ccb4b70ad25218027f77e0c8934d10f9b7cdf91d5e64080147743d58fddbc3c0"}, + {file = "pyproj-3.4.0-cp38-cp38-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4e161114bc92701647a83c4bbce79489984f12d980cabb365516e953d1450885"}, + {file = "pyproj-3.4.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f80adda8c54b84271a93829477a01aa57bc178c834362e9f74e1de1b5033c74c"}, + {file = "pyproj-3.4.0-cp38-cp38-win_amd64.whl", hash = "sha256:221d8939685e0c43ee594c9f04b6a73a10e8e1cc0e85f28be0b4eb2f1bc8777d"}, + {file = "pyproj-3.4.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:d94afed99f31673d3d19fe750283621e193e2a53ca9e0443bf9d092c3905833b"}, + {file = "pyproj-3.4.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:0fff9c3a991508f16027be27d153f6c5583d03799443639d13c681e60f49e2d7"}, + {file = "pyproj-3.4.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3b85acf09e5a9e35cd9ee72989793adb7089b4e611be02a43d3d0bda50ad116b"}, + {file = "pyproj-3.4.0-cp39-cp39-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:45554f47d1a12a84b0620e4abc08a2a1b5d9f273a4759eaef75e74788ec7162a"}, + {file = "pyproj-3.4.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:12f62c20656ac9b6076ebb213e9a635d52f4f01fef95310121d337e62e910cb6"}, + {file = "pyproj-3.4.0-cp39-cp39-win_amd64.whl", hash = "sha256:65a0bcdbad95b3c00b419e5d75b1f7e450ec17349b5ea16bf7438ac1d50a12a2"}, + {file = "pyproj-3.4.0-pp38-pypy38_pp73-macosx_10_9_x86_64.whl", hash = "sha256:14ad113b5753c6057f9b2f3c85a6497cef7fa237c4328f2943c0223e98c1dde6"}, + {file = "pyproj-3.4.0-pp38-pypy38_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4688b4cd62cbd86b5e855f9e27d90fbb53f2b4c2ea1cd394a46919e1a4151b89"}, + {file = "pyproj-3.4.0-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:47ad53452ae1dc8b0bf1df920a210bb5616989085aa646592f8681f1d741a754"}, + {file = "pyproj-3.4.0-pp39-pypy39_pp73-macosx_10_9_x86_64.whl", hash = "sha256:48787962232109bad8b72e27949037a9b03591228a6955f25dbe451233e8648a"}, + {file = "pyproj-3.4.0-pp39-pypy39_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:2cb8592259ea54e7557523b079d3f2304081680bdb48bfbf0fd879ee6156129c"}, + {file = "pyproj-3.4.0-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:82200b4569d68b421c079d2973475b58d5959306fe758b43366e79fe96facfe5"}, + {file = "pyproj-3.4.0.tar.gz", hash = "sha256:a708445927ace9857f52c3ba67d2915da7b41a8fdcd9b8f99a4c9ed60a75eb33"}, +] +pyreadline3 = [ + {file = "pyreadline3-3.4.1-py3-none-any.whl", hash = "sha256:b0efb6516fd4fb07b45949053826a62fa4cb353db5be2bbb4a7aa1fdd1e345fb"}, + {file = "pyreadline3-3.4.1.tar.gz", hash = "sha256:6f3d1f7b8a31ba32b73917cefc1f28cc660562f39aea8646d30bd6eff21f7bae"}, +] +pyrsistent = [ + {file = "pyrsistent-0.18.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:df46c854f490f81210870e509818b729db4488e1f30f2a1ce1698b2295a878d1"}, + {file = "pyrsistent-0.18.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5d45866ececf4a5fff8742c25722da6d4c9e180daa7b405dc0a2a2790d668c26"}, + {file = "pyrsistent-0.18.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4ed6784ceac462a7d6fcb7e9b663e93b9a6fb373b7f43594f9ff68875788e01e"}, + {file = "pyrsistent-0.18.1-cp310-cp310-win32.whl", hash = "sha256:e4f3149fd5eb9b285d6bfb54d2e5173f6a116fe19172686797c056672689daf6"}, + {file = "pyrsistent-0.18.1-cp310-cp310-win_amd64.whl", hash = "sha256:636ce2dc235046ccd3d8c56a7ad54e99d5c1cd0ef07d9ae847306c91d11b5fec"}, + {file = "pyrsistent-0.18.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:e92a52c166426efbe0d1ec1332ee9119b6d32fc1f0bbfd55d5c1088070e7fc1b"}, + {file = "pyrsistent-0.18.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d7a096646eab884bf8bed965bad63ea327e0d0c38989fc83c5ea7b8a87037bfc"}, + {file = "pyrsistent-0.18.1-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:cdfd2c361b8a8e5d9499b9082b501c452ade8bbf42aef97ea04854f4a3f43b22"}, + {file = "pyrsistent-0.18.1-cp37-cp37m-win32.whl", hash = "sha256:7ec335fc998faa4febe75cc5268a9eac0478b3f681602c1f27befaf2a1abe1d8"}, + {file = "pyrsistent-0.18.1-cp37-cp37m-win_amd64.whl", hash = "sha256:6455fc599df93d1f60e1c5c4fe471499f08d190d57eca040c0ea182301321286"}, + {file = "pyrsistent-0.18.1-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:fd8da6d0124efa2f67d86fa70c851022f87c98e205f0594e1fae044e7119a5a6"}, + {file = "pyrsistent-0.18.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7bfe2388663fd18bd8ce7db2c91c7400bf3e1a9e8bd7d63bf7e77d39051b85ec"}, + {file = "pyrsistent-0.18.1-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0e3e1fcc45199df76053026a51cc59ab2ea3fc7c094c6627e93b7b44cdae2c8c"}, + {file = "pyrsistent-0.18.1-cp38-cp38-win32.whl", hash = "sha256:b568f35ad53a7b07ed9b1b2bae09eb15cdd671a5ba5d2c66caee40dbf91c68ca"}, + {file = "pyrsistent-0.18.1-cp38-cp38-win_amd64.whl", hash = "sha256:d1b96547410f76078eaf66d282ddca2e4baae8964364abb4f4dcdde855cd123a"}, + {file = "pyrsistent-0.18.1-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:f87cc2863ef33c709e237d4b5f4502a62a00fab450c9e020892e8e2ede5847f5"}, + {file = "pyrsistent-0.18.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6bc66318fb7ee012071b2792024564973ecc80e9522842eb4e17743604b5e045"}, + {file = "pyrsistent-0.18.1-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:914474c9f1d93080338ace89cb2acee74f4f666fb0424896fcfb8d86058bf17c"}, + {file = "pyrsistent-0.18.1-cp39-cp39-win32.whl", hash = "sha256:1b34eedd6812bf4d33814fca1b66005805d3640ce53140ab8bbb1e2651b0d9bc"}, + {file = "pyrsistent-0.18.1-cp39-cp39-win_amd64.whl", hash = "sha256:e24a828f57e0c337c8d8bb9f6b12f09dfdf0273da25fda9e314f0b684b415a07"}, + {file = "pyrsistent-0.18.1.tar.gz", hash = "sha256:d4d61f8b993a7255ba714df3aca52700f8125289f84f704cf80916517c46eb96"}, +] +pyserial = [ + {file = "pyserial-3.5-py2.py3-none-any.whl", hash = "sha256:c4451db6ba391ca6ca299fb3ec7bae67a5c55dde170964c7a14ceefec02f2cf0"}, + {file = "pyserial-3.5.tar.gz", hash = "sha256:3c77e014170dfffbd816e6ffc205e9842efb10be9f58ec16d3e8675b4925cddb"}, +] +pysocks = [ + {file = "PySocks-1.7.1-py27-none-any.whl", hash = "sha256:08e69f092cc6dbe92a0fdd16eeb9b9ffbc13cadfe5ca4c7bd92ffb078b293299"}, + {file = "PySocks-1.7.1-py3-none-any.whl", hash = "sha256:2725bd0a9925919b9b51739eea5f9e2bae91e83288108a9ad338b2e3a4435ee5"}, + {file = "PySocks-1.7.1.tar.gz", hash = "sha256:3f8804571ebe159c380ac6de37643bb4685970655d3bba243530d6558b799aa0"}, +] +pytest = [ + {file = "pytest-7.1.3-py3-none-any.whl", hash = "sha256:1377bda3466d70b55e3f5cecfa55bb7cfcf219c7964629b967c37cf0bda818b7"}, + {file = "pytest-7.1.3.tar.gz", hash = "sha256:4f365fec2dff9c1162f834d9f18af1ba13062db0c708bf7b946f8a5c76180c39"}, +] +pytest-forked = [ + {file = "pytest-forked-1.4.0.tar.gz", hash = "sha256:8b67587c8f98cbbadfdd804539ed5455b6ed03802203485dd2f53c1422d7440e"}, + {file = "pytest_forked-1.4.0-py3-none-any.whl", hash = "sha256:bbbb6717efc886b9d64537b41fb1497cfaf3c9601276be8da2cccfea5a3c8ad8"}, +] +pytest-xdist = [ + {file = "pytest-xdist-2.5.0.tar.gz", hash = "sha256:4580deca3ff04ddb2ac53eba39d76cb5dd5edeac050cb6fbc768b0dd712b4edf"}, + {file = "pytest_xdist-2.5.0-py3-none-any.whl", hash = "sha256:6fe5c74fec98906deb8f2d2b616b5c782022744978e7bd4695d39c8f42d0ce65"}, +] +python-dateutil = [ + {file = "python-dateutil-2.8.2.tar.gz", hash = "sha256:0123cacc1627ae19ddf3c27a5de5bd67ee4586fbdd6440d9748f8abb483d3e86"}, + {file = "python_dateutil-2.8.2-py2.py3-none-any.whl", hash = "sha256:961d03dc3453ebbc59dbdea9e4e11c5651520a876d0f4db161e8674aae935da9"}, +] +python-engineio = [ + {file = "python-engineio-4.3.4.tar.gz", hash = "sha256:d8d8b072799c36cadcdcc2b40d2a560ce09797ab3d2d596b2ad519a5e4df19ae"}, + {file = "python_engineio-4.3.4-py3-none-any.whl", hash = "sha256:7454314a529bba20e745928601ffeaf101c1b5aca9a6c4e48ad397803d10ea0c"}, +] +python-logstash = [ + {file = "python-logstash-0.4.8.tar.gz", hash = "sha256:d04e1ce11ecc107e4a4f3b807fc57d96811e964a554081b3bbb44732f74ef5f9"}, +] +python-socketio = [ + {file = "python-socketio-5.7.2.tar.gz", hash = "sha256:92395062d9db3c13d30e7cdedaa0e1330bba78505645db695415f9a3c628d097"}, + {file = "python_socketio-5.7.2-py3-none-any.whl", hash = "sha256:d9a9f047e6fdd306c852fbac36516f4b495c2096f8ad9ceb8803b8e5ff5622e3"}, +] +pytools = [ + {file = "pytools-2022.1.12.tar.gz", hash = "sha256:4d62875e9a2ab2a24e393a9a8b799492f1a721bffa840af3807bfd42871dd1f4"}, +] +pytz = [ + {file = "pytz-2022.5-py2.py3-none-any.whl", hash = "sha256:335ab46900b1465e714b4fda4963d87363264eb662aab5e65da039c25f1f5b22"}, + {file = "pytz-2022.5.tar.gz", hash = "sha256:c4d88f472f54d615e9cd582a5004d1e5f624854a6a27a6211591c251f22a6914"}, +] +pywavelets = [ + {file = "PyWavelets-1.4.1-cp310-cp310-macosx_10_13_x86_64.whl", hash = "sha256:d854411eb5ee9cb4bc5d0e66e3634aeb8f594210f6a1bed96dbed57ec70f181c"}, + {file = "PyWavelets-1.4.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:231b0e0b1cdc1112f4af3c24eea7bf181c418d37922a67670e9bf6cfa2d544d4"}, + {file = "PyWavelets-1.4.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:754fa5085768227c4f4a26c1e0c78bc509a266d9ebd0eb69a278be7e3ece943c"}, + {file = "PyWavelets-1.4.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:da7b9c006171be1f9ddb12cc6e0d3d703b95f7f43cb5e2c6f5f15d3233fcf202"}, + {file = "PyWavelets-1.4.1-cp310-cp310-win32.whl", hash = "sha256:67a0d28a08909f21400cb09ff62ba94c064882ffd9e3a6b27880a111211d59bd"}, + {file = "PyWavelets-1.4.1-cp310-cp310-win_amd64.whl", hash = "sha256:91d3d393cffa634f0e550d88c0e3f217c96cfb9e32781f2960876f1808d9b45b"}, + {file = "PyWavelets-1.4.1-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:64c6bac6204327321db30b775060fbe8e8642316e6bff17f06b9f34936f88875"}, + {file = "PyWavelets-1.4.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:3f19327f2129fb7977bc59b966b4974dfd72879c093e44a7287500a7032695de"}, + {file = "PyWavelets-1.4.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ad987748f60418d5f4138db89d82ba0cb49b086e0cbb8fd5c3ed4a814cfb705e"}, + {file = "PyWavelets-1.4.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:875d4d620eee655346e3589a16a73790cf9f8917abba062234439b594e706784"}, + {file = "PyWavelets-1.4.1-cp311-cp311-win32.whl", hash = "sha256:7231461d7a8eb3bdc7aa2d97d9f67ea5a9f8902522818e7e2ead9c2b3408eeb1"}, + {file = "PyWavelets-1.4.1-cp311-cp311-win_amd64.whl", hash = "sha256:daf0aa79842b571308d7c31a9c43bc99a30b6328e6aea3f50388cd8f69ba7dbc"}, + {file = "PyWavelets-1.4.1-cp38-cp38-macosx_10_13_x86_64.whl", hash = "sha256:ab7da0a17822cd2f6545626946d3b82d1a8e106afc4b50e3387719ba01c7b966"}, + {file = "PyWavelets-1.4.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:578af438a02a86b70f1975b546f68aaaf38f28fb082a61ceb799816049ed18aa"}, + {file = "PyWavelets-1.4.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9cb5ca8d11d3f98e89e65796a2125be98424d22e5ada360a0dbabff659fca0fc"}, + {file = "PyWavelets-1.4.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:058b46434eac4c04dd89aeef6fa39e4b6496a951d78c500b6641fd5b2cc2f9f4"}, + {file = "PyWavelets-1.4.1-cp38-cp38-win32.whl", hash = "sha256:de7cd61a88a982edfec01ea755b0740e94766e00a1ceceeafef3ed4c85c605cd"}, + {file = "PyWavelets-1.4.1-cp38-cp38-win_amd64.whl", hash = "sha256:7ab8d9db0fe549ab2ee0bea61f614e658dd2df419d5b75fba47baa761e95f8f2"}, + {file = "PyWavelets-1.4.1-cp39-cp39-macosx_10_13_x86_64.whl", hash = "sha256:23bafd60350b2b868076d976bdd92f950b3944f119b4754b1d7ff22b7acbf6c6"}, + {file = "PyWavelets-1.4.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:d0e56cd7a53aed3cceca91a04d62feb3a0aca6725b1912d29546c26f6ea90426"}, + {file = "PyWavelets-1.4.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:030670a213ee8fefa56f6387b0c8e7d970c7f7ad6850dc048bd7c89364771b9b"}, + {file = "PyWavelets-1.4.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:71ab30f51ee4470741bb55fc6b197b4a2b612232e30f6ac069106f0156342356"}, + {file = "PyWavelets-1.4.1-cp39-cp39-win32.whl", hash = "sha256:47cac4fa25bed76a45bc781a293c26ac63e8eaae9eb8f9be961758d22b58649c"}, + {file = "PyWavelets-1.4.1-cp39-cp39-win_amd64.whl", hash = "sha256:88aa5449e109d8f5e7f0adef85f7f73b1ab086102865be64421a3a3d02d277f4"}, + {file = "PyWavelets-1.4.1.tar.gz", hash = "sha256:6437af3ddf083118c26d8f97ab43b0724b956c9f958e9ea788659f6a2834ba93"}, +] +pywin32 = [ + {file = "pywin32-304-cp310-cp310-win32.whl", hash = "sha256:3c7bacf5e24298c86314f03fa20e16558a4e4138fc34615d7de4070c23e65af3"}, + {file = "pywin32-304-cp310-cp310-win_amd64.whl", hash = "sha256:4f32145913a2447736dad62495199a8e280a77a0ca662daa2332acf849f0be48"}, + {file = "pywin32-304-cp310-cp310-win_arm64.whl", hash = "sha256:d3ee45adff48e0551d1aa60d2ec066fec006083b791f5c3527c40cd8aefac71f"}, + {file = "pywin32-304-cp311-cp311-win32.whl", hash = "sha256:30c53d6ce44c12a316a06c153ea74152d3b1342610f1b99d40ba2795e5af0269"}, + {file = "pywin32-304-cp311-cp311-win_amd64.whl", hash = "sha256:7ffa0c0fa4ae4077e8b8aa73800540ef8c24530057768c3ac57c609f99a14fd4"}, + {file = "pywin32-304-cp311-cp311-win_arm64.whl", hash = "sha256:cbbe34dad39bdbaa2889a424d28752f1b4971939b14b1bb48cbf0182a3bcfc43"}, + {file = "pywin32-304-cp36-cp36m-win32.whl", hash = "sha256:be253e7b14bc601718f014d2832e4c18a5b023cbe72db826da63df76b77507a1"}, + {file = "pywin32-304-cp36-cp36m-win_amd64.whl", hash = "sha256:de9827c23321dcf43d2f288f09f3b6d772fee11e809015bdae9e69fe13213988"}, + {file = "pywin32-304-cp37-cp37m-win32.whl", hash = "sha256:f64c0377cf01b61bd5e76c25e1480ca8ab3b73f0c4add50538d332afdf8f69c5"}, + {file = "pywin32-304-cp37-cp37m-win_amd64.whl", hash = "sha256:bb2ea2aa81e96eee6a6b79d87e1d1648d3f8b87f9a64499e0b92b30d141e76df"}, + {file = "pywin32-304-cp38-cp38-win32.whl", hash = "sha256:94037b5259701988954931333aafd39cf897e990852115656b014ce72e052e96"}, + {file = "pywin32-304-cp38-cp38-win_amd64.whl", hash = "sha256:ead865a2e179b30fb717831f73cf4373401fc62fbc3455a0889a7ddac848f83e"}, + {file = "pywin32-304-cp39-cp39-win32.whl", hash = "sha256:25746d841201fd9f96b648a248f731c1dec851c9a08b8e33da8b56148e4c65cc"}, + {file = "pywin32-304-cp39-cp39-win_amd64.whl", hash = "sha256:d24a3382f013b21aa24a5cfbfad5a2cd9926610c0affde3e8ab5b3d7dbcf4ac9"}, +] +pywin32-ctypes = [ + {file = "pywin32-ctypes-0.2.0.tar.gz", hash = "sha256:24ffc3b341d457d48e8922352130cf2644024a4ff09762a2261fd34c36ee5942"}, + {file = "pywin32_ctypes-0.2.0-py2.py3-none-any.whl", hash = "sha256:9dc2d991b3479cc2df15930958b674a48a227d5361d413827a4cfd0b5876fc98"}, +] +pywinpty = [ + {file = "pywinpty-2.0.8-cp310-none-win_amd64.whl", hash = "sha256:9cbf89834abc8d4d4c5f295f11e15dd93889a8069db876f2bc10cc64aa4060ac"}, + {file = "pywinpty-2.0.8-cp37-none-win_amd64.whl", hash = "sha256:a2f9a95f3b74262ef73f1be5257c295c8caab1f79f081aa3400ca61c724f9bc6"}, + {file = "pywinpty-2.0.8-cp38-none-win_amd64.whl", hash = "sha256:23389d56258d6a1fbc4b41257bd65e5bdabaf6fde7f30a13806e557ea9ee6865"}, + {file = "pywinpty-2.0.8-cp39-none-win_amd64.whl", hash = "sha256:ea7c1da94eed5ef93e75026c67c60d4dca33ea9a1c212fa89221079a7b463c68"}, + {file = "pywinpty-2.0.8.tar.gz", hash = "sha256:a89b9021c63ef78b1e7d8e14f0fac4748c88a0c2e4f529c84f37f6e72b914280"}, +] +pyyaml = [ + {file = "PyYAML-6.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:d4db7c7aef085872ef65a8fd7d6d09a14ae91f691dec3e87ee5ee0539d516f53"}, + {file = "PyYAML-6.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:9df7ed3b3d2e0ecfe09e14741b857df43adb5a3ddadc919a2d94fbdf78fea53c"}, + {file = "PyYAML-6.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:77f396e6ef4c73fdc33a9157446466f1cff553d979bd00ecb64385760c6babdc"}, + {file = "PyYAML-6.0-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a80a78046a72361de73f8f395f1f1e49f956c6be882eed58505a15f3e430962b"}, + {file = "PyYAML-6.0-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:f84fbc98b019fef2ee9a1cb3ce93e3187a6df0b2538a651bfb890254ba9f90b5"}, + {file = "PyYAML-6.0-cp310-cp310-win32.whl", hash = "sha256:2cd5df3de48857ed0544b34e2d40e9fac445930039f3cfe4bcc592a1f836d513"}, + {file = "PyYAML-6.0-cp310-cp310-win_amd64.whl", hash = "sha256:daf496c58a8c52083df09b80c860005194014c3698698d1a57cbcfa182142a3a"}, + {file = "PyYAML-6.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:d4b0ba9512519522b118090257be113b9468d804b19d63c71dbcf4a48fa32358"}, + {file = "PyYAML-6.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:81957921f441d50af23654aa6c5e5eaf9b06aba7f0a19c18a538dc7ef291c5a1"}, + {file = "PyYAML-6.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:afa17f5bc4d1b10afd4466fd3a44dc0e245382deca5b3c353d8b757f9e3ecb8d"}, + {file = "PyYAML-6.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:dbad0e9d368bb989f4515da330b88a057617d16b6a8245084f1b05400f24609f"}, + {file = "PyYAML-6.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:432557aa2c09802be39460360ddffd48156e30721f5e8d917f01d31694216782"}, + {file = "PyYAML-6.0-cp311-cp311-win32.whl", hash = "sha256:bfaef573a63ba8923503d27530362590ff4f576c626d86a9fed95822a8255fd7"}, + {file = "PyYAML-6.0-cp311-cp311-win_amd64.whl", hash = "sha256:01b45c0191e6d66c470b6cf1b9531a771a83c1c4208272ead47a3ae4f2f603bf"}, + {file = "PyYAML-6.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:897b80890765f037df3403d22bab41627ca8811ae55e9a722fd0392850ec4d86"}, + {file = "PyYAML-6.0-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:50602afada6d6cbfad699b0c7bb50d5ccffa7e46a3d738092afddc1f9758427f"}, + {file = "PyYAML-6.0-cp36-cp36m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:48c346915c114f5fdb3ead70312bd042a953a8ce5c7106d5bfb1a5254e47da92"}, + {file = "PyYAML-6.0-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:98c4d36e99714e55cfbaaee6dd5badbc9a1ec339ebfc3b1f52e293aee6bb71a4"}, + {file = "PyYAML-6.0-cp36-cp36m-win32.whl", hash = "sha256:0283c35a6a9fbf047493e3a0ce8d79ef5030852c51e9d911a27badfde0605293"}, + {file = "PyYAML-6.0-cp36-cp36m-win_amd64.whl", hash = "sha256:07751360502caac1c067a8132d150cf3d61339af5691fe9e87803040dbc5db57"}, + {file = "PyYAML-6.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:819b3830a1543db06c4d4b865e70ded25be52a2e0631ccd2f6a47a2822f2fd7c"}, + {file = "PyYAML-6.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:473f9edb243cb1935ab5a084eb238d842fb8f404ed2193a915d1784b5a6b5fc0"}, + {file = "PyYAML-6.0-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:0ce82d761c532fe4ec3f87fc45688bdd3a4c1dc5e0b4a19814b9009a29baefd4"}, + {file = "PyYAML-6.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:231710d57adfd809ef5d34183b8ed1eeae3f76459c18fb4a0b373ad56bedcdd9"}, + {file = "PyYAML-6.0-cp37-cp37m-win32.whl", hash = "sha256:c5687b8d43cf58545ade1fe3e055f70eac7a5a1a0bf42824308d868289a95737"}, + {file = "PyYAML-6.0-cp37-cp37m-win_amd64.whl", hash = "sha256:d15a181d1ecd0d4270dc32edb46f7cb7733c7c508857278d3d378d14d606db2d"}, + {file = "PyYAML-6.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:0b4624f379dab24d3725ffde76559cff63d9ec94e1736b556dacdfebe5ab6d4b"}, + {file = "PyYAML-6.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:213c60cd50106436cc818accf5baa1aba61c0189ff610f64f4a3e8c6726218ba"}, + {file = "PyYAML-6.0-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9fa600030013c4de8165339db93d182b9431076eb98eb40ee068700c9c813e34"}, + {file = "PyYAML-6.0-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:277a0ef2981ca40581a47093e9e2d13b3f1fbbeffae064c1d21bfceba2030287"}, + {file = "PyYAML-6.0-cp38-cp38-win32.whl", hash = "sha256:d4eccecf9adf6fbcc6861a38015c2a64f38b9d94838ac1810a9023a0609e1b78"}, + {file = "PyYAML-6.0-cp38-cp38-win_amd64.whl", hash = "sha256:1e4747bc279b4f613a09eb64bba2ba602d8a6664c6ce6396a4d0cd413a50ce07"}, + {file = "PyYAML-6.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:055d937d65826939cb044fc8c9b08889e8c743fdc6a32b33e2390f66013e449b"}, + {file = "PyYAML-6.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:e61ceaab6f49fb8bdfaa0f92c4b57bcfbea54c09277b1b4f7ac376bfb7a7c174"}, + {file = "PyYAML-6.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d67d839ede4ed1b28a4e8909735fc992a923cdb84e618544973d7dfc71540803"}, + {file = "PyYAML-6.0-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:cba8c411ef271aa037d7357a2bc8f9ee8b58b9965831d9e51baf703280dc73d3"}, + {file = "PyYAML-6.0-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:40527857252b61eacd1d9af500c3337ba8deb8fc298940291486c465c8b46ec0"}, + {file = "PyYAML-6.0-cp39-cp39-win32.whl", hash = "sha256:b5b9eccad747aabaaffbc6064800670f0c297e52c12754eb1d976c57e4f74dcb"}, + {file = "PyYAML-6.0-cp39-cp39-win_amd64.whl", hash = "sha256:b3d267842bf12586ba6c734f89d1f5b871df0273157918b0ccefa29deb05c21c"}, + {file = "PyYAML-6.0.tar.gz", hash = "sha256:68fb519c14306fec9720a2a5b45bc9f0c8d1b9c72adf45c37baedfcd949c35a2"}, +] +pyzmq = [ + {file = "pyzmq-23.2.1-cp310-cp310-macosx_10_15_universal2.whl", hash = "sha256:a3fd44b5046d247e7f0f1660bcafe7b5fb0db55d0934c05dd57dda9e1f823ce7"}, + {file = "pyzmq-23.2.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:2141e6798d5981be04c08996d27962086a1aa3ea536fe9cf7e89817fd4523f86"}, + {file = "pyzmq-23.2.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9a39ddb0431a68954bd318b923230fa5b649c9c62b0e8340388820c5f1b15bd2"}, + {file = "pyzmq-23.2.1-cp310-cp310-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e06747014a5ad1b28cebf5bc1ddcdaccfb44e9b441d35e6feb1286c8a72e54be"}, + {file = "pyzmq-23.2.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7e0113d70b095339e99bb522fe7294f5ae6a7f3b2b8f52f659469a74b5cc7661"}, + {file = "pyzmq-23.2.1-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:71b32a1e827bdcbf73750e60370d3b07685816ff3d8695f450f0f8c3226503f8"}, + {file = "pyzmq-23.2.1-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:55568a020ad2cae9ae36da6058e7ca332a56df968f601cbdb7cf6efb2a77579a"}, + {file = "pyzmq-23.2.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:8c02a0cd39dc01659b3d6cb70bb3a41aebd9885fd78239acdd8d9c91351c4568"}, + {file = "pyzmq-23.2.1-cp310-cp310-win32.whl", hash = "sha256:e1fe30bcd5aea5948c42685fad910cd285eacb2518ea4dc6c170d6b535bee95d"}, + {file = "pyzmq-23.2.1-cp310-cp310-win_amd64.whl", hash = "sha256:650389bbfca73955b262b2230423d89992f38ec48033307ae80e700eaa2fbb63"}, + {file = "pyzmq-23.2.1-cp311-cp311-macosx_10_15_universal2.whl", hash = "sha256:e753eee6d3b93c5354e8ba0a1d62956ee49355f0a36e00570823ef64e66183f5"}, + {file = "pyzmq-23.2.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:f07016e3cf088dbfc6e7c5a7b3f540db5c23b0190d539e4fd3e2b5e6beffa4b5"}, + {file = "pyzmq-23.2.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4805af9614b0b41b7e57d17673459facf85604dac502a5a9244f6e8c9a4de658"}, + {file = "pyzmq-23.2.1-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:39dd252b683816935702825e5bf775df16090619ced9bb4ba68c2d0b6f0c9b18"}, + {file = "pyzmq-23.2.1-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:84678153432241bcdca2210cf4ff83560b200556867aea913ffbb960f5d5f340"}, + {file = "pyzmq-23.2.1-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:90d88f9d9a2ae6cfb1dc4ea2d1710cdf6456bc1b9a06dd1bb485c5d298f2517e"}, + {file = "pyzmq-23.2.1-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:794871988c34727c7f79bdfe2546e6854ae1fa2e1feb382784f23a9c6c63ecb3"}, + {file = "pyzmq-23.2.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:c56b1a62a1fb87565343c57b6743fd5da6e138b8c6562361d7d9b5ce4acf399a"}, + {file = "pyzmq-23.2.1-cp311-cp311-win32.whl", hash = "sha256:c3ebf1668664d20c8f7d468955f18379b7d1f7bc8946b13243d050fa3888c7ff"}, + {file = "pyzmq-23.2.1-cp311-cp311-win_amd64.whl", hash = "sha256:ec9803aca9491fd6f0d853d2a6147f19f8deaaa23b1b713d05c5d09e56ea7142"}, + {file = "pyzmq-23.2.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:385609812eafd9970c3752c51f2f6c4f224807e3e441bcfd8c8273877d00c8a8"}, + {file = "pyzmq-23.2.1-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b861db65f6b8906c8d6db51dde2448f266f0c66bf28db2c37aea50f58a849859"}, + {file = "pyzmq-23.2.1-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:6b1e79bba24f6df1712e3188d5c32c480d8eda03e8ecff44dc8ecb0805fa62f3"}, + {file = "pyzmq-23.2.1-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:8dc66f109a245653b19df0f44a5af7a3f14cb8ad6c780ead506158a057bd36ce"}, + {file = "pyzmq-23.2.1-cp36-cp36m-musllinux_1_1_aarch64.whl", hash = "sha256:b815991c7d024bf461f358ad871f2be1135576274caed5749c4828859e40354e"}, + {file = "pyzmq-23.2.1-cp36-cp36m-musllinux_1_1_i686.whl", hash = "sha256:29b74774a0bfd3c4d98ac853f0bdca55bd9ec89d5b0def5486407cca54472ef8"}, + {file = "pyzmq-23.2.1-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:4bb798bef181648827019001f6be43e1c48b34b477763b37a8d27d8c06d197b8"}, + {file = "pyzmq-23.2.1-cp36-cp36m-win32.whl", hash = "sha256:565bd5ab81f6964fc4067ccf2e00877ad0fa917308975694bbb54378389215f8"}, + {file = "pyzmq-23.2.1-cp36-cp36m-win_amd64.whl", hash = "sha256:1f368a82b29f80071781b20663c0fc0c8f6b13273f9f5abe1526af939534f90f"}, + {file = "pyzmq-23.2.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:c9cfaf530e6a7ff65f0afe275e99f983f68b54dfb23ea401f0bc297a632766b6"}, + {file = "pyzmq-23.2.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5c558b50402fca1acc94329c5d8f12aa429738904a5cfb32b9ed3c61235221bb"}, + {file = "pyzmq-23.2.1-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:20bafc4095eab00f41a510579363a3f5e1f5c69d7ee10f1d88895c4df0259183"}, + {file = "pyzmq-23.2.1-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:f619fd38fc2641abfb53cca719c165182500600b82c695cc548a0f05f764be05"}, + {file = "pyzmq-23.2.1-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:044447ae4b2016a6b8697571fd633f799f860b19b76c4a2fd9b1140d52ee6745"}, + {file = "pyzmq-23.2.1-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:49d30ba7074f469e8167917abf9eb854c6503ae10153034a6d4df33618f1db5f"}, + {file = "pyzmq-23.2.1-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:48400b96788cdaca647021bf19a9cd668384f46e4d9c55cf045bdd17f65299c8"}, + {file = "pyzmq-23.2.1-cp37-cp37m-win32.whl", hash = "sha256:8a68f57b7a3f7b6b52ada79876be1efb97c8c0952423436e84d70cc139f16f0d"}, + {file = "pyzmq-23.2.1-cp37-cp37m-win_amd64.whl", hash = "sha256:9e5bf6e7239fc9687239de7a283aa8b801ab85371116045b33ae20132a1325d6"}, + {file = "pyzmq-23.2.1-cp38-cp38-macosx_10_15_universal2.whl", hash = "sha256:0ff6294e001129a9f22dcbfba186165c7e6f573c46de2704d76f873c94c65416"}, + {file = "pyzmq-23.2.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:ffc6b1623d0f9affb351db4ca61f432dca3628a5ee015f9bf2bfbe9c6836881c"}, + {file = "pyzmq-23.2.1-cp38-cp38-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:4d6f110c56f7d5b4d64dde3a382ae61b6d48174e30742859d8e971b18b6c9e5c"}, + {file = "pyzmq-23.2.1-cp38-cp38-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:9269fbfe3a4eb2009199120861c4571ef1655fdf6951c3e7f233567c94e8c602"}, + {file = "pyzmq-23.2.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:12e62ff0d5223ec09b597ab6d73858b9f64a51221399f3cb08aa495e1dff7935"}, + {file = "pyzmq-23.2.1-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:6fd5d0d50cbcf4bc376861529a907bed026a4cbe8c22a500ff8243231ef02433"}, + {file = "pyzmq-23.2.1-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:9d0ab2936085c85a1fc6f9fd8f89d5235ae99b051e90ec5baa5e73ad44346e1f"}, + {file = "pyzmq-23.2.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:022cf5ea7bcaa8a06a03c2706e0ae66904b6138b2155577cd34c64bc7cc637ab"}, + {file = "pyzmq-23.2.1-cp38-cp38-win32.whl", hash = "sha256:28dbdb90b2f6b131f8f10e6081012e4e25234213433420e67e0c1162de537113"}, + {file = "pyzmq-23.2.1-cp38-cp38-win_amd64.whl", hash = "sha256:10d1910ec381b851aeb024a042a13db178cb1edf125e76a4e9d2548ad103aadb"}, + {file = "pyzmq-23.2.1-cp39-cp39-macosx_10_15_universal2.whl", hash = "sha256:99a5a77a10863493a1ee8dece02578c6b32025fb3afff91b40476bc489e81648"}, + {file = "pyzmq-23.2.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:aecd6ceaccc4b594e0092d6513ef3f1c0fa678dd89f86bb8ff1a47014b8fca35"}, + {file = "pyzmq-23.2.1-cp39-cp39-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:415ff62ac525d9add1e3550430a09b9928d2d24a20cc4ce809e67caac41219ab"}, + {file = "pyzmq-23.2.1-cp39-cp39-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:67975a9e1237b9ccc78f457bef17691bbdd2055a9d26e81ee914ba376846d0ce"}, + {file = "pyzmq-23.2.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:38e106b64bad744fe469dc3dd864f2764d66399178c1bf39d45294cc7980f14f"}, + {file = "pyzmq-23.2.1-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:8c842109d31a9281d678f668629241c405928afbebd913c48a5a8e7aee61f63d"}, + {file = "pyzmq-23.2.1-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:fefdf9b685fda4141b95ebec975946076a5e0723ff70b037032b2085c5317684"}, + {file = "pyzmq-23.2.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:79a87831b47a9f6161ad23fa5e89d5469dc585abc49f90b9b07fea8905ae1234"}, + {file = "pyzmq-23.2.1-cp39-cp39-win32.whl", hash = "sha256:342ca3077f47ec2ee41b9825142b614e03e026347167cbc72a59b618c4f6106c"}, + {file = "pyzmq-23.2.1-cp39-cp39-win_amd64.whl", hash = "sha256:5e05492be125dce279721d6b54fd1b956546ecc4bcdfcf8e7b4c413bc0874c10"}, + {file = "pyzmq-23.2.1-pp37-pypy37_pp73-macosx_10_9_x86_64.whl", hash = "sha256:07ed8aaf7ffe150af873269690cc654ffeca7491f62aae0f3821baa181f8d5fe"}, + {file = "pyzmq-23.2.1-pp37-pypy37_pp73-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:ad28ddb40db8e450d7d4bf8a1d765d3f87b63b10e7e9a825a3c130c6371a8c03"}, + {file = "pyzmq-23.2.1-pp37-pypy37_pp73-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:2f67b63f53c6994d601404fd1a329e6d940ac3dd1d92946a93b2b9c70df67b9f"}, + {file = "pyzmq-23.2.1-pp37-pypy37_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c890309296f53f9aa32ffcfc51d805705e1982bffd27c9692a8f1e1b8de279f4"}, + {file = "pyzmq-23.2.1-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:624fd38071a817644acdae075b92a23ea0bdd126a58148288e8284d23ec361ce"}, + {file = "pyzmq-23.2.1-pp38-pypy38_pp73-macosx_10_9_x86_64.whl", hash = "sha256:a114992a193577cb62233abf8cb2832970f9975805a64740e325d2f895e7f85a"}, + {file = "pyzmq-23.2.1-pp38-pypy38_pp73-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:c780acddd2934c6831ff832ecbf78a45a7b62d4eb216480f863854a8b7d54fa7"}, + {file = "pyzmq-23.2.1-pp38-pypy38_pp73-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:d904f6595acfaaf99a1a61881fea068500c40374d263e5e073aa4005e5f9c28a"}, + {file = "pyzmq-23.2.1-pp38-pypy38_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:929d548b74c0f82f7f95b54e4a43f9e4ce2523cfb8a54d3f7141e45652304b2a"}, + {file = "pyzmq-23.2.1-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:f392cbea531b7142d1958c0d4a0c9c8d760dc451e5848d8dd3387804d3e3e62c"}, + {file = "pyzmq-23.2.1-pp39-pypy39_pp73-macosx_10_9_x86_64.whl", hash = "sha256:a0f09d85c45f58aa8e715b42f8b26beba68b3b63a8f7049113478aca26efbc30"}, + {file = "pyzmq-23.2.1-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:23e708fbfdf4ee3107422b69ca65da1b9f056b431fc0888096a8c1d6cd908e8f"}, + {file = "pyzmq-23.2.1-pp39-pypy39_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:35e635343ff367f697d00fa1484262bb68e36bc74c9b80737eac5a1e04c4e1b1"}, + {file = "pyzmq-23.2.1-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:efb9e38b2a590282704269585de7eb33bf43dc294cad092e1b172e23d4c217e5"}, + {file = "pyzmq-23.2.1-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:407f909c4e8fde62fbdad9ebd448319792258cc0550c2815567a4d9d8d9e6d18"}, + {file = "pyzmq-23.2.1.tar.gz", hash = "sha256:2b381aa867ece7d0a82f30a0c7f3d4387b7cf2e0697e33efaa5bed6c5784abcd"}, +] +qtconsole = [ + {file = "qtconsole-5.3.2-py3-none-any.whl", hash = "sha256:c29d24464f57cdbaa17d6f6060be6e6d5e29126e7feb57eebc1747433382b3d1"}, + {file = "qtconsole-5.3.2.tar.gz", hash = "sha256:8eadf012e83ab018295803c247c6ab7eacd3d5ab1e1d88a0f37fdcfdab9295a3"}, +] +qtpy = [ + {file = "QtPy-2.2.1-py3-none-any.whl", hash = "sha256:268cf5328f41353be1b127e04a81bc74ec9a9b54c9ac75dd8fe0ff48d8ad6ead"}, + {file = "QtPy-2.2.1.tar.gz", hash = "sha256:7d5231133b772e40b4ee514b6673aca558331e4b88ca038b26c9e16c5c95524f"}, +] +qudida = [ + {file = "qudida-0.0.4-py3-none-any.whl", hash = "sha256:4519714c40cd0f2e6c51e1735edae8f8b19f4efe1f33be13e9d644ca5f736dd6"}, + {file = "qudida-0.0.4.tar.gz", hash = "sha256:db198e2887ab0c9aa0023e565afbff41dfb76b361f85fd5e13f780d75ba18cc8"}, +] +reactivex = [ + {file = "reactivex-4.0.4-py3-none-any.whl", hash = "sha256:0004796c420bd9e68aad8e65627d85a8e13f293de76656165dffbcb3a0e3fb6a"}, + {file = "reactivex-4.0.4.tar.gz", hash = "sha256:e912e6591022ab9176df8348a653fe8c8fa7a301f26f9931c9d8c78a650e04e8"}, +] +redis = [ + {file = "redis-4.3.4-py3-none-any.whl", hash = "sha256:a52d5694c9eb4292770084fa8c863f79367ca19884b329ab574d5cb2036b3e54"}, + {file = "redis-4.3.4.tar.gz", hash = "sha256:ddf27071df4adf3821c4f2ca59d67525c3a82e5f268bed97b813cb4fabf87880"}, +] +requests = [ + {file = "requests-2.28.1-py3-none-any.whl", hash = "sha256:8fefa2a1a1365bf5520aac41836fbee479da67864514bdb821f31ce07ce65349"}, + {file = "requests-2.28.1.tar.gz", hash = "sha256:7c5599b102feddaa661c826c56ab4fee28bfd17f5abca1ebbe3e7f19d7c97983"}, +] +requests-oauthlib = [ + {file = "requests-oauthlib-1.3.1.tar.gz", hash = "sha256:75beac4a47881eeb94d5ea5d6ad31ef88856affe2332b9aafb52c6452ccf0d7a"}, + {file = "requests_oauthlib-1.3.1-py2.py3-none-any.whl", hash = "sha256:2577c501a2fb8d05a304c09d090d6e47c306fef15809d102b327cf8364bddab5"}, +] +requests-toolbelt = [ + {file = "requests-toolbelt-0.9.1.tar.gz", hash = "sha256:968089d4584ad4ad7c171454f0a5c6dac23971e9472521ea3b6d49d610aa6fc0"}, + {file = "requests_toolbelt-0.9.1-py2.py3-none-any.whl", hash = "sha256:380606e1d10dc85c3bd47bf5a6095f815ec007be7a8b69c878507068df059e6f"}, +] +reverse-geocoder = [ + {file = "reverse_geocoder-1.5.1.tar.gz", hash = "sha256:2a2e781b5f69376d922b78fe8978f1350c84fce0ddb07e02c834ecf98b57c75c"}, +] +s2sphere = [ + {file = "s2sphere-0.2.5-py2.py3-none-any.whl", hash = "sha256:d2340c9cf458ddc9a89afd1d8048a4195ce6fa6b0095ab900d4be5271e537401"}, + {file = "s2sphere-0.2.5.tar.gz", hash = "sha256:c2478c1ff7c601a59a7151a57b605435897514578fa6bdb8730721c182adbbaf"}, +] +scikit-image = [ + {file = "scikit-image-0.19.3.tar.gz", hash = "sha256:24b5367de1762da6ee126dd8f30cc4e7efda474e0d7d70685433f0e3aa2ec450"}, + {file = "scikit_image-0.19.3-cp310-cp310-macosx_10_13_x86_64.whl", hash = "sha256:3a01372ae4bca223873304b0bff79b9d92446ac6d6177f73d89b45561e2d09d8"}, + {file = "scikit_image-0.19.3-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:fdf48d9b1f13af69e4e2c78e05067e322e9c8c97463c315cd0ecb47a94e259fc"}, + {file = "scikit_image-0.19.3-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6b6a8f98f2ac9bb73706461fd1dec875f6a5141759ed526850a5a49e90003d19"}, + {file = "scikit_image-0.19.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cfbb073f23deb48e0e60c47f8741d8089121d89cc78629ea8c5b51096efc5be7"}, + {file = "scikit_image-0.19.3-cp310-cp310-win_amd64.whl", hash = "sha256:cc24177de3fdceca5d04807ad9c87d665f0bf01032ed94a9055cd1ed2b3f33e9"}, + {file = "scikit_image-0.19.3-cp37-cp37m-macosx_10_13_x86_64.whl", hash = "sha256:fd9dd3994bb6f9f7a35f228323f3c4dc44b3cf2ff15fd72d895216e9333550c6"}, + {file = "scikit_image-0.19.3-cp37-cp37m-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:ad5d8000207a264d1a55681a9276e6a739d3f05cf4429004ad00d61d1892235f"}, + {file = "scikit_image-0.19.3-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:84baa3179f3ae983c3a5d81c1e404bc92dcf7daeb41bfe9369badcda3fb22b92"}, + {file = "scikit_image-0.19.3-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7f9f8a1387afc6c70f2bed007c3854a2d7489f9f7713c242f16f32ee05934bc2"}, + {file = "scikit_image-0.19.3-cp37-cp37m-win32.whl", hash = "sha256:9fb0923a3bfa99457c5e17888f27b3b8a83a3600b4fef317992e7b7234764732"}, + {file = "scikit_image-0.19.3-cp37-cp37m-win_amd64.whl", hash = "sha256:ce3d2207f253b8eb2c824e30d145a9f07a34a14212d57f3beca9f7e03c383cbe"}, + {file = "scikit_image-0.19.3-cp38-cp38-macosx_10_13_x86_64.whl", hash = "sha256:2a02d1bd0e2b53e36b952bd5fd6118d9ccc3ee51de35705d63d8eb1f2e86adef"}, + {file = "scikit_image-0.19.3-cp38-cp38-macosx_12_0_arm64.whl", hash = "sha256:03779a7e1736fdf89d83c0ba67d44110496edd736a3bfce61a2b5177a1c8a099"}, + {file = "scikit_image-0.19.3-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:19a21a101a20c587a3b611a2cf6f86c35aae9f8d9563279b987e83ee1c9a9790"}, + {file = "scikit_image-0.19.3-cp38-cp38-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:2f50b923f8099c1045fcde7418d86b206c87e333e43da980f41d8577b9605245"}, + {file = "scikit_image-0.19.3-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e207c6ce5ce121d7d9b9d2b61b9adca57d1abed112c902d8ffbfdc20fb42c12b"}, + {file = "scikit_image-0.19.3-cp38-cp38-win32.whl", hash = "sha256:a7c3985c68bfe05f7571167ee021d14f5b8d1a4a250c91f0b13be7fb07e6af34"}, + {file = "scikit_image-0.19.3-cp38-cp38-win_amd64.whl", hash = "sha256:651de1c2ce1fbee834753b46b8e7d81cb12a5594898babba63ac82b30ddad49d"}, + {file = "scikit_image-0.19.3-cp39-cp39-macosx_10_13_x86_64.whl", hash = "sha256:8d8917fcf85b987b1f287f823f3a1a7dac38b70aaca759bc0200f3bc292d5ced"}, + {file = "scikit_image-0.19.3-cp39-cp39-macosx_12_0_arm64.whl", hash = "sha256:0b0a199157ce8487c77de4fde0edc0b42d6d42818881c11f459262351d678b2d"}, + {file = "scikit_image-0.19.3-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:33dfd463ee6cc509defa279b963829f2230c9e0639ccd3931045be055878eea6"}, + {file = "scikit_image-0.19.3-cp39-cp39-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a8714348ddd671f819457a797c97d4c672166f093def66d66c3254cbd1d43f83"}, + {file = "scikit_image-0.19.3-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ff3b1025356508d41f4fe48528e509d95f9e4015e90cf158cd58c56dc63e0ac5"}, + {file = "scikit_image-0.19.3-cp39-cp39-win32.whl", hash = "sha256:9439e5294de3f18d6e82ec8eee2c46590231cf9c690da80545e83a0733b7a69e"}, + {file = "scikit_image-0.19.3-cp39-cp39-win_amd64.whl", hash = "sha256:32fb88cc36203b99c9672fb972c9ef98635deaa5fc889fe969f3e11c44f22919"}, +] +scikit-learn = [ + {file = "scikit-learn-1.1.2.tar.gz", hash = "sha256:7c22d1305b16f08d57751a4ea36071e2215efb4c09cb79183faa4e8e82a3dbf8"}, + {file = "scikit_learn-1.1.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:6c840f662b5d3377c4ccb8be1fc21bb52cb5d8b8790f8d6bf021739f84e543cf"}, + {file = "scikit_learn-1.1.2-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:2b8db962360c93554cab7bb3c096c4a24695da394dd4b3c3f13409f409b425bc"}, + {file = "scikit_learn-1.1.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3e7d1fc817867a350133f937aaebcafbc06192517cbdf0cf7e5774ad4d1adb9f"}, + {file = "scikit_learn-1.1.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5ec3ea40d467966821843210c02117d82b097b54276fdcfb50f4dfb5c60dbe39"}, + {file = "scikit_learn-1.1.2-cp310-cp310-win_amd64.whl", hash = "sha256:bbef6ea1c012ff9f3e6f6e9ca006b8772d8383e177b898091e68fbd9b3f840f9"}, + {file = "scikit_learn-1.1.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:a90ca42fe8242fd6ff56cda2fecc5fca586a88a24ab602d275d2d0dcc0b928fb"}, + {file = "scikit_learn-1.1.2-cp38-cp38-macosx_12_0_arm64.whl", hash = "sha256:a682ec0f82b6f30fb07486daed1c8001b6683cc66b51877644dfc532bece6a18"}, + {file = "scikit_learn-1.1.2-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c33e16e9a165af6012f5be530ccfbb672e2bc5f9b840238a05eb7f6694304e3f"}, + {file = "scikit_learn-1.1.2-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f94c0146bad51daef919c402a3da8c1c6162619653e1c00c92baa168fda292f2"}, + {file = "scikit_learn-1.1.2-cp38-cp38-win32.whl", hash = "sha256:2f46c6e3ff1054a5ec701646dcfd61d43b8ecac4d416014daed8843cf4c33d4d"}, + {file = "scikit_learn-1.1.2-cp38-cp38-win_amd64.whl", hash = "sha256:b1e706deca9b2ad87ae27dafd5ac4e8eff01b6db492ed5c12cef4735ec5f21ea"}, + {file = "scikit_learn-1.1.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:567417dbbe6a6278399c3e6daf1654414a5a1a4d818d28f251fa7fc28730a1bf"}, + {file = "scikit_learn-1.1.2-cp39-cp39-macosx_12_0_arm64.whl", hash = "sha256:d6f232779023c3b060b80b5c82e5823723bc424dcac1d1a148aa2492c54d245d"}, + {file = "scikit_learn-1.1.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:589d46f28460469f444b898223b13d99db9463e1038dc581ba698111f612264b"}, + {file = "scikit_learn-1.1.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:76800652fb6d6bf527bce36ecc2cc25738b28fe1a17bd294a218fff8e8bd6d50"}, + {file = "scikit_learn-1.1.2-cp39-cp39-win32.whl", hash = "sha256:1c8fecb7c9984d9ec2ea48898229f98aad681a0873e0935f2b7f724fbce4a047"}, + {file = "scikit_learn-1.1.2-cp39-cp39-win_amd64.whl", hash = "sha256:407e9a1cb9e6ba458a539986a9bd25546a757088095b3aab91d465b79a760d37"}, +] +scipy = [ + {file = "scipy-1.9.3-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:1884b66a54887e21addf9c16fb588720a8309a57b2e258ae1c7986d4444d3bc0"}, + {file = "scipy-1.9.3-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:83b89e9586c62e787f5012e8475fbb12185bafb996a03257e9675cd73d3736dd"}, + {file = "scipy-1.9.3-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1a72d885fa44247f92743fc20732ae55564ff2a519e8302fb7e18717c5355a8b"}, + {file = "scipy-1.9.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d01e1dd7b15bd2449c8bfc6b7cc67d630700ed655654f0dfcf121600bad205c9"}, + {file = "scipy-1.9.3-cp310-cp310-win_amd64.whl", hash = "sha256:68239b6aa6f9c593da8be1509a05cb7f9efe98b80f43a5861cd24c7557e98523"}, + {file = "scipy-1.9.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:b41bc822679ad1c9a5f023bc93f6d0543129ca0f37c1ce294dd9d386f0a21096"}, + {file = "scipy-1.9.3-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:90453d2b93ea82a9f434e4e1cba043e779ff67b92f7a0e85d05d286a3625df3c"}, + {file = "scipy-1.9.3-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:83c06e62a390a9167da60bedd4575a14c1f58ca9dfde59830fc42e5197283dab"}, + {file = "scipy-1.9.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:abaf921531b5aeaafced90157db505e10345e45038c39e5d9b6c7922d68085cb"}, + {file = "scipy-1.9.3-cp311-cp311-win_amd64.whl", hash = "sha256:06d2e1b4c491dc7d8eacea139a1b0b295f74e1a1a0f704c375028f8320d16e31"}, + {file = "scipy-1.9.3-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:5a04cd7d0d3eff6ea4719371cbc44df31411862b9646db617c99718ff68d4840"}, + {file = "scipy-1.9.3-cp38-cp38-macosx_12_0_arm64.whl", hash = "sha256:545c83ffb518094d8c9d83cce216c0c32f8c04aaf28b92cc8283eda0685162d5"}, + {file = "scipy-1.9.3-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0d54222d7a3ba6022fdf5773931b5d7c56efe41ede7f7128c7b1637700409108"}, + {file = "scipy-1.9.3-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cff3a5295234037e39500d35316a4c5794739433528310e117b8a9a0c76d20fc"}, + {file = "scipy-1.9.3-cp38-cp38-win_amd64.whl", hash = "sha256:2318bef588acc7a574f5bfdff9c172d0b1bf2c8143d9582e05f878e580a3781e"}, + {file = "scipy-1.9.3-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:d644a64e174c16cb4b2e41dfea6af722053e83d066da7343f333a54dae9bc31c"}, + {file = "scipy-1.9.3-cp39-cp39-macosx_12_0_arm64.whl", hash = "sha256:da8245491d73ed0a994ed9c2e380fd058ce2fa8a18da204681f2fe1f57f98f95"}, + {file = "scipy-1.9.3-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4db5b30849606a95dcf519763dd3ab6fe9bd91df49eba517359e450a7d80ce2e"}, + {file = "scipy-1.9.3-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c68db6b290cbd4049012990d7fe71a2abd9ffbe82c0056ebe0f01df8be5436b0"}, + {file = "scipy-1.9.3-cp39-cp39-win_amd64.whl", hash = "sha256:5b88e6d91ad9d59478fafe92a7c757d00c59e3bdc3331be8ada76a4f8d683f58"}, + {file = "scipy-1.9.3.tar.gz", hash = "sha256:fbc5c05c85c1a02be77b1ff591087c83bc44579c6d2bd9fb798bb64ea5e1a027"}, +] +scons = [ + {file = "SCons-4.4.0-py3-none-any.whl", hash = "sha256:cbbd73b83cf85f1aaaf986370359de1bbfd3af97a765cb3554734f6dcec734e1"}, + {file = "SCons-4.4.0.tar.gz", hash = "sha256:7703c4e9d2200b4854a31800c1dbd4587e1fa86e75f58795c740bcfa7eca7eaa"}, +] +secretstorage = [ + {file = "SecretStorage-3.3.3-py3-none-any.whl", hash = "sha256:f356e6628222568e3af06f2eba8df495efa13b3b63081dafd4f7d9a7b7bc9f99"}, + {file = "SecretStorage-3.3.3.tar.gz", hash = "sha256:2403533ef369eca6d2ba81718576c5e0f564d5cca1b58f73a8b23e7d4eeebd77"}, +] +segmentation-models-pytorch = [ + {file = "segmentation_models_pytorch-0.2.1-py3-none-any.whl", hash = "sha256:98822571470867fb0f416c112c32f7f1d21702dd32195ec8f7736932c2de0486"}, + {file = "segmentation_models_pytorch-0.2.1.tar.gz", hash = "sha256:86744552b04c6bedf7e10f7928791894d8d9b399b9ed58ed1a3236d2bf69ead6"}, +] +send2trash = [ + {file = "Send2Trash-1.8.0-py3-none-any.whl", hash = "sha256:f20eaadfdb517eaca5ce077640cb261c7d2698385a6a0f072a4a5447fd49fa08"}, + {file = "Send2Trash-1.8.0.tar.gz", hash = "sha256:d2c24762fd3759860a0aff155e45871447ea58d2be6bdd39b5c8f966a0c99c2d"}, +] +sentry-sdk = [ + {file = "sentry-sdk-1.10.0.tar.gz", hash = "sha256:1b965bcdbfe52321bb1307c7c93c74035afdbfceb5f585f01a963327c5befc4e"}, + {file = "sentry_sdk-1.10.0-py2.py3-none-any.whl", hash = "sha256:8c648e96e0e2ec5e17ca75a28c442e2f523453fa7cf761ec093f4a656153490e"}, +] +setproctitle = [ + {file = "setproctitle-1.3.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:288943dec88e178bb2fd868adf491197cc0fc8b6810416b1c6775e686bab87fe"}, + {file = "setproctitle-1.3.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:630f6fe5e24a619ccf970c78e084319ee8be5be253ecc9b5b216b0f474f5ef18"}, + {file = "setproctitle-1.3.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6c877691b90026670e5a70adfbcc735460a9f4c274d35ec5e8a43ce3f8443005"}, + {file = "setproctitle-1.3.2-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7a55fe05f15c10e8c705038777656fe45e3bd676d49ad9ac8370b75c66dd7cd7"}, + {file = "setproctitle-1.3.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ab45146c71ca6592c9cc8b354a2cc9cc4843c33efcbe1d245d7d37ce9696552d"}, + {file = "setproctitle-1.3.2-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e00c9d5c541a2713ba0e657e0303bf96ddddc412ef4761676adc35df35d7c246"}, + {file = "setproctitle-1.3.2-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:265ecbe2c6eafe82e104f994ddd7c811520acdd0647b73f65c24f51374cf9494"}, + {file = "setproctitle-1.3.2-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:c2c46200656280a064073447ebd363937562debef329482fd7e570c8d498f806"}, + {file = "setproctitle-1.3.2-cp310-cp310-musllinux_1_1_ppc64le.whl", hash = "sha256:fa2f50678f04fda7a75d0fe5dd02bbdd3b13cbe6ed4cf626e4472a7ccf47ae94"}, + {file = "setproctitle-1.3.2-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:7f2719a398e1a2c01c2a63bf30377a34d0b6ef61946ab9cf4d550733af8f1ef1"}, + {file = "setproctitle-1.3.2-cp310-cp310-win32.whl", hash = "sha256:e425be62524dc0c593985da794ee73eb8a17abb10fe692ee43bb39e201d7a099"}, + {file = "setproctitle-1.3.2-cp310-cp310-win_amd64.whl", hash = "sha256:e85e50b9c67854f89635a86247412f3ad66b132a4d8534ac017547197c88f27d"}, + {file = "setproctitle-1.3.2-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:92c626edc66169a1b09e9541b9c0c9f10488447d8a2b1d87c8f0672e771bc927"}, + {file = "setproctitle-1.3.2-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:710e16fa3bade3b026907e4a5e841124983620046166f355bbb84be364bf2a02"}, + {file = "setproctitle-1.3.2-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1f29b75e86260b0ab59adb12661ef9f113d2f93a59951373eb6d68a852b13e83"}, + {file = "setproctitle-1.3.2-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1c8d9650154afaa86a44ff195b7b10d683c73509d085339d174e394a22cccbb9"}, + {file = "setproctitle-1.3.2-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f0452282258dfcc01697026a8841258dd2057c4438b43914b611bccbcd048f10"}, + {file = "setproctitle-1.3.2-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:e49ae693306d7624015f31cb3e82708916759d592c2e5f72a35c8f4cc8aef258"}, + {file = "setproctitle-1.3.2-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:1ff863a20d1ff6ba2c24e22436a3daa3cd80be1dfb26891aae73f61b54b04aca"}, + {file = "setproctitle-1.3.2-cp37-cp37m-musllinux_1_1_ppc64le.whl", hash = "sha256:55ce1e9925ce1765865442ede9dca0ba9bde10593fcd570b1f0fa25d3ec6b31c"}, + {file = "setproctitle-1.3.2-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:7fe9df7aeb8c64db6c34fc3b13271a363475d77bc157d3f00275a53910cb1989"}, + {file = "setproctitle-1.3.2-cp37-cp37m-win32.whl", hash = "sha256:e5c50e164cd2459bc5137c15288a9ef57160fd5cbf293265ea3c45efe7870865"}, + {file = "setproctitle-1.3.2-cp37-cp37m-win_amd64.whl", hash = "sha256:a499fff50387c1520c085a07578a000123f519e5f3eee61dd68e1d301659651f"}, + {file = "setproctitle-1.3.2-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:5b932c3041aa924163f4aab970c2f0e6b4d9d773f4d50326e0ea1cd69240e5c5"}, + {file = "setproctitle-1.3.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:f4bfc89bd33ebb8e4c0e9846a09b1f5a4a86f5cb7a317e75cc42fee1131b4f4f"}, + {file = "setproctitle-1.3.2-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:fcd3cf4286a60fdc95451d8d14e0389a6b4f5cebe02c7f2609325eb016535963"}, + {file = "setproctitle-1.3.2-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5fb4f769c02f63fac90989711a3fee83919f47ae9afd4758ced5d86596318c65"}, + {file = "setproctitle-1.3.2-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5194b4969f82ea842a4f6af2f82cd16ebdc3f1771fb2771796e6add9835c1973"}, + {file = "setproctitle-1.3.2-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1f0cde41857a644b7353a0060b5f94f7ba7cf593ebde5a1094da1be581ac9a31"}, + {file = "setproctitle-1.3.2-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:9124bedd8006b0e04d4e8a71a0945da9b67e7a4ab88fdad7b1440dc5b6122c42"}, + {file = "setproctitle-1.3.2-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:c8a09d570b39517de10ee5b718730e171251ce63bbb890c430c725c8c53d4484"}, + {file = "setproctitle-1.3.2-cp38-cp38-musllinux_1_1_ppc64le.whl", hash = "sha256:8ff3c8cb26afaed25e8bca7b9dd0c1e36de71f35a3a0706b5c0d5172587a3827"}, + {file = "setproctitle-1.3.2-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:589be87172b238f839e19f146b9ea47c71e413e951ef0dc6db4218ddacf3c202"}, + {file = "setproctitle-1.3.2-cp38-cp38-win32.whl", hash = "sha256:4749a2b0c9ac52f864d13cee94546606f92b981b50e46226f7f830a56a9dc8e1"}, + {file = "setproctitle-1.3.2-cp38-cp38-win_amd64.whl", hash = "sha256:e43f315c68aa61cbdef522a2272c5a5b9b8fd03c301d3167b5e1343ef50c676c"}, + {file = "setproctitle-1.3.2-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:de3a540cd1817ede31f530d20e6a4935bbc1b145fd8f8cf393903b1e02f1ae76"}, + {file = "setproctitle-1.3.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:4058564195b975ddc3f0462375c533cce310ccdd41b80ac9aed641c296c3eff4"}, + {file = "setproctitle-1.3.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1c5d5dad7c28bdd1ec4187d818e43796f58a845aa892bb4481587010dc4d362b"}, + {file = "setproctitle-1.3.2-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ffc61a388a5834a97953d6444a2888c24a05f2e333f9ed49f977a87bb1ad4761"}, + {file = "setproctitle-1.3.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1fa1a0fbee72b47dc339c87c890d3c03a72ea65c061ade3204f285582f2da30f"}, + {file = "setproctitle-1.3.2-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fe8a988c7220c002c45347430993830666e55bc350179d91fcee0feafe64e1d4"}, + {file = "setproctitle-1.3.2-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:bae283e85fc084b18ffeb92e061ff7ac5af9e183c9d1345c93e178c3e5069cbe"}, + {file = "setproctitle-1.3.2-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:fed18e44711c5af4b681c2b3b18f85e6f0f1b2370a28854c645d636d5305ccd8"}, + {file = "setproctitle-1.3.2-cp39-cp39-musllinux_1_1_ppc64le.whl", hash = "sha256:b34baef93bfb20a8ecb930e395ccd2ae3268050d8cf4fe187de5e2bd806fd796"}, + {file = "setproctitle-1.3.2-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:7f0bed90a216ef28b9d227d8d73e28a8c9b88c0f48a082d13ab3fa83c581488f"}, + {file = "setproctitle-1.3.2-cp39-cp39-win32.whl", hash = "sha256:4d8938249a7cea45ab7e1e48b77685d0f2bab1ebfa9dde23e94ab97968996a7c"}, + {file = "setproctitle-1.3.2-cp39-cp39-win_amd64.whl", hash = "sha256:a47d97a75fd2d10c37410b180f67a5835cb1d8fdea2648fd7f359d4277f180b9"}, + {file = "setproctitle-1.3.2-pp37-pypy37_pp73-macosx_10_9_x86_64.whl", hash = "sha256:dad42e676c5261eb50fdb16bdf3e2771cf8f99a79ef69ba88729aeb3472d8575"}, + {file = "setproctitle-1.3.2-pp37-pypy37_pp73-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c91b9bc8985d00239f7dc08a49927a7ca1ca8a6af2c3890feec3ed9665b6f91e"}, + {file = "setproctitle-1.3.2-pp37-pypy37_pp73-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e8579a43eafd246e285eb3a5b939e7158073d5087aacdd2308f23200eac2458b"}, + {file = "setproctitle-1.3.2-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:2fbd8187948284293f43533c150cd69a0e4192c83c377da837dbcd29f6b83084"}, + {file = "setproctitle-1.3.2-pp38-pypy38_pp73-macosx_10_9_x86_64.whl", hash = "sha256:faec934cfe5fd6ac1151c02e67156c3f526e82f96b24d550b5d51efa4a5527c6"}, + {file = "setproctitle-1.3.2-pp38-pypy38_pp73-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e1aafc91cbdacc9e5fe712c52077369168e6b6c346f3a9d51bf600b53eae56bb"}, + {file = "setproctitle-1.3.2-pp38-pypy38_pp73-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b617f12c9be61e8f4b2857be4a4319754756845dbbbd9c3718f468bbb1e17bcb"}, + {file = "setproctitle-1.3.2-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:b2c9cb2705fc84cb8798f1ba74194f4c080aaef19d9dae843591c09b97678e98"}, + {file = "setproctitle-1.3.2-pp39-pypy39_pp73-macosx_10_9_x86_64.whl", hash = "sha256:a149a5f7f2c5a065d4e63cb0d7a4b6d3b66e6e80f12e3f8827c4f63974cbf122"}, + {file = "setproctitle-1.3.2-pp39-pypy39_pp73-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:2e3ac25bfc4a0f29d2409650c7532d5ddfdbf29f16f8a256fc31c47d0dc05172"}, + {file = "setproctitle-1.3.2-pp39-pypy39_pp73-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:65d884e22037b23fa25b2baf1a3316602ed5c5971eb3e9d771a38c3a69ce6e13"}, + {file = "setproctitle-1.3.2-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:7aa0aac1711fadffc1d51e9d00a3bea61f68443d6ac0241a224e4d622489d665"}, + {file = "setproctitle-1.3.2.tar.gz", hash = "sha256:b9fb97907c830d260fa0658ed58afd48a86b2b88aac521135c352ff7fd3477fd"}, +] +setuptools = [ + {file = "setuptools-65.5.0-py3-none-any.whl", hash = "sha256:f62ea9da9ed6289bfe868cd6845968a2c854d1427f8548d52cae02a42b4f0356"}, + {file = "setuptools-65.5.0.tar.gz", hash = "sha256:512e5536220e38146176efb833d4a62aa726b7bbff82cfbc8ba9eaa3996e0b17"}, +] +setuptools-scm = [ + {file = "setuptools_scm-7.0.5-py3-none-any.whl", hash = "sha256:7930f720905e03ccd1e1d821db521bff7ec2ac9cf0ceb6552dd73d24a45d3b02"}, + {file = "setuptools_scm-7.0.5.tar.gz", hash = "sha256:031e13af771d6f892b941adb6ea04545bbf91ebc5ce68c78aaf3fff6e1fb4844"}, +] +shellingham = [ + {file = "shellingham-1.5.0-py2.py3-none-any.whl", hash = "sha256:a8f02ba61b69baaa13facdba62908ca8690a94b8119b69f5ec5873ea85f7391b"}, + {file = "shellingham-1.5.0.tar.gz", hash = "sha256:72fb7f5c63103ca2cb91b23dee0c71fe8ad6fbfd46418ef17dbe40db51592dad"}, +] +simplejson = [ + {file = "simplejson-3.17.6-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:a89acae02b2975b1f8e4974cb8cdf9bf9f6c91162fb8dec50c259ce700f2770a"}, + {file = "simplejson-3.17.6-cp27-cp27m-manylinux1_i686.whl", hash = "sha256:82ff356ff91be0ab2293fc6d8d262451eb6ac4fd999244c4b5f863e049ba219c"}, + {file = "simplejson-3.17.6-cp27-cp27m-manylinux1_x86_64.whl", hash = "sha256:0de783e9c2b87bdd75b57efa2b6260c24b94605b5c9843517577d40ee0c3cc8a"}, + {file = "simplejson-3.17.6-cp27-cp27m-manylinux2010_i686.whl", hash = "sha256:d24a9e61df7a7787b338a58abfba975414937b609eb6b18973e25f573bc0eeeb"}, + {file = "simplejson-3.17.6-cp27-cp27m-manylinux2010_x86_64.whl", hash = "sha256:e8603e691580487f11306ecb066c76f1f4a8b54fb3bdb23fa40643a059509366"}, + {file = "simplejson-3.17.6-cp27-cp27mu-manylinux1_i686.whl", hash = "sha256:9b01e7b00654115965a206e3015f0166674ec1e575198a62a977355597c0bef5"}, + {file = "simplejson-3.17.6-cp27-cp27mu-manylinux1_x86_64.whl", hash = "sha256:37bc0cf0e5599f36072077e56e248f3336917ded1d33d2688624d8ed3cefd7d2"}, + {file = "simplejson-3.17.6-cp27-cp27mu-manylinux2010_i686.whl", hash = "sha256:cf6e7d5fe2aeb54898df18db1baf479863eae581cce05410f61f6b4188c8ada1"}, + {file = "simplejson-3.17.6-cp27-cp27mu-manylinux2010_x86_64.whl", hash = "sha256:bdfc54b4468ed4cd7415928cbe782f4d782722a81aeb0f81e2ddca9932632211"}, + {file = "simplejson-3.17.6-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:dd16302d39c4d6f4afde80edd0c97d4db643327d355a312762ccd9bd2ca515ed"}, + {file = "simplejson-3.17.6-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:deac4bdafa19bbb89edfb73b19f7f69a52d0b5bd3bb0c4ad404c1bbfd7b4b7fd"}, + {file = "simplejson-3.17.6-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:a8bbdb166e2fb816e43ab034c865147edafe28e1b19c72433147789ac83e2dda"}, + {file = "simplejson-3.17.6-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a7854326920d41c3b5d468154318fe6ba4390cb2410480976787c640707e0180"}, + {file = "simplejson-3.17.6-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:04e31fa6ac8e326480703fb6ded1488bfa6f1d3f760d32e29dbf66d0838982ce"}, + {file = "simplejson-3.17.6-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:f63600ec06982cdf480899026f4fda622776f5fabed9a869fdb32d72bc17e99a"}, + {file = "simplejson-3.17.6-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:e03c3b8cc7883a54c3f34a6a135c4a17bc9088a33f36796acdb47162791b02f6"}, + {file = "simplejson-3.17.6-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:a2d30d6c1652140181dc6861f564449ad71a45e4f165a6868c27d36745b65d40"}, + {file = "simplejson-3.17.6-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:a1aa6e4cae8e3b8d5321be4f51c5ce77188faf7baa9fe1e78611f93a8eed2882"}, + {file = "simplejson-3.17.6-cp310-cp310-win32.whl", hash = "sha256:97202f939c3ff341fc3fa84d15db86156b1edc669424ba20b0a1fcd4a796a045"}, + {file = "simplejson-3.17.6-cp310-cp310-win_amd64.whl", hash = "sha256:80d3bc9944be1d73e5b1726c3bbfd2628d3d7fe2880711b1eb90b617b9b8ac70"}, + {file = "simplejson-3.17.6-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:9fa621b3c0c05d965882c920347b6593751b7ab20d8fa81e426f1735ca1a9fc7"}, + {file = "simplejson-3.17.6-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:dd2fb11922f58df8528adfca123f6a84748ad17d066007e7ac977720063556bd"}, + {file = "simplejson-3.17.6-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:724c1fe135aa437d5126138d977004d165a3b5e2ee98fc4eb3e7c0ef645e7e27"}, + {file = "simplejson-3.17.6-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:4ff4ac6ff3aa8f814ac0f50bf218a2e1a434a17aafad4f0400a57a8cc62ef17f"}, + {file = "simplejson-3.17.6-cp36-cp36m-musllinux_1_1_aarch64.whl", hash = "sha256:67093a526e42981fdd954868062e56c9b67fdd7e712616cc3265ad0c210ecb51"}, + {file = "simplejson-3.17.6-cp36-cp36m-musllinux_1_1_i686.whl", hash = "sha256:5d6b4af7ad7e4ac515bc6e602e7b79e2204e25dbd10ab3aa2beef3c5a9cad2c7"}, + {file = "simplejson-3.17.6-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:1c9b1ed7ed282b36571638297525f8ef80f34b3e2d600a56f962c6044f24200d"}, + {file = "simplejson-3.17.6-cp36-cp36m-win32.whl", hash = "sha256:632ecbbd2228575e6860c9e49ea3cc5423764d5aa70b92acc4e74096fb434044"}, + {file = "simplejson-3.17.6-cp36-cp36m-win_amd64.whl", hash = "sha256:4c09868ddb86bf79b1feb4e3e7e4a35cd6e61ddb3452b54e20cf296313622566"}, + {file = "simplejson-3.17.6-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:4b6bd8144f15a491c662f06814bd8eaa54b17f26095bb775411f39bacaf66837"}, + {file = "simplejson-3.17.6-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5decdc78849617917c206b01e9fc1d694fd58caa961be816cb37d3150d613d9a"}, + {file = "simplejson-3.17.6-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:521877c7bd060470806eb6335926e27453d740ac1958eaf0d8c00911bc5e1802"}, + {file = "simplejson-3.17.6-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:65b998193bd7b0c7ecdfffbc825d808eac66279313cb67d8892bb259c9d91494"}, + {file = "simplejson-3.17.6-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:ac786f6cb7aa10d44e9641c7a7d16d7f6e095b138795cd43503769d4154e0dc2"}, + {file = "simplejson-3.17.6-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:3ff5b3464e1ce86a8de8c88e61d4836927d5595c2162cab22e96ff551b916e81"}, + {file = "simplejson-3.17.6-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:69bd56b1d257a91e763256d63606937ae4eb890b18a789b66951c00062afec33"}, + {file = "simplejson-3.17.6-cp37-cp37m-win32.whl", hash = "sha256:b81076552d34c27e5149a40187a8f7e2abb2d3185576a317aaf14aeeedad862a"}, + {file = "simplejson-3.17.6-cp37-cp37m-win_amd64.whl", hash = "sha256:07ecaafc1b1501f275bf5acdee34a4ad33c7c24ede287183ea77a02dc071e0c0"}, + {file = "simplejson-3.17.6-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:068670af975247acbb9fc3d5393293368cda17026db467bf7a51548ee8f17ee1"}, + {file = "simplejson-3.17.6-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:4d1c135af0c72cb28dd259cf7ba218338f4dc027061262e46fe058b4e6a4c6a3"}, + {file = "simplejson-3.17.6-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:23fe704da910ff45e72543cbba152821685a889cf00fc58d5c8ee96a9bad5f94"}, + {file = "simplejson-3.17.6-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f444762fed1bc1fd75187ef14a20ed900c1fbb245d45be9e834b822a0223bc81"}, + {file = "simplejson-3.17.6-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:681eb4d37c9a9a6eb9b3245a5e89d7f7b2b9895590bb08a20aa598c1eb0a1d9d"}, + {file = "simplejson-3.17.6-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:8e8607d8f6b4f9d46fee11447e334d6ab50e993dd4dbfb22f674616ce20907ab"}, + {file = "simplejson-3.17.6-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:b10556817f09d46d420edd982dd0653940b90151d0576f09143a8e773459f6fe"}, + {file = "simplejson-3.17.6-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:e1ec8a9ee0987d4524ffd6299e778c16cc35fef6d1a2764e609f90962f0b293a"}, + {file = "simplejson-3.17.6-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:0b4126cac7d69ac06ff22efd3e0b3328a4a70624fcd6bca4fc1b4e6d9e2e12bf"}, + {file = "simplejson-3.17.6-cp38-cp38-win32.whl", hash = "sha256:35a49ebef25f1ebdef54262e54ae80904d8692367a9f208cdfbc38dbf649e00a"}, + {file = "simplejson-3.17.6-cp38-cp38-win_amd64.whl", hash = "sha256:743cd768affaa508a21499f4858c5b824ffa2e1394ed94eb85caf47ac0732198"}, + {file = "simplejson-3.17.6-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:fb62d517a516128bacf08cb6a86ecd39fb06d08e7c4980251f5d5601d29989ba"}, + {file = "simplejson-3.17.6-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:12133863178a8080a3dccbf5cb2edfab0001bc41e5d6d2446af2a1131105adfe"}, + {file = "simplejson-3.17.6-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:5540fba2d437edaf4aa4fbb80f43f42a8334206ad1ad3b27aef577fd989f20d9"}, + {file = "simplejson-3.17.6-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d74ee72b5071818a1a5dab47338e87f08a738cb938a3b0653b9e4d959ddd1fd9"}, + {file = "simplejson-3.17.6-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:28221620f4dcabdeac310846629b976e599a13f59abb21616356a85231ebd6ad"}, + {file = "simplejson-3.17.6-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:b09bc62e5193e31d7f9876220fb429ec13a6a181a24d897b9edfbbdbcd678851"}, + {file = "simplejson-3.17.6-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:7255a37ff50593c9b2f1afa8fafd6ef5763213c1ed5a9e2c6f5b9cc925ab979f"}, + {file = "simplejson-3.17.6-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:401d40969cee3df7bda211e57b903a534561b77a7ade0dd622a8d1a31eaa8ba7"}, + {file = "simplejson-3.17.6-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:a649d0f66029c7eb67042b15374bd93a26aae202591d9afd71e111dd0006b198"}, + {file = "simplejson-3.17.6-cp39-cp39-win32.whl", hash = "sha256:522fad7be85de57430d6d287c4b635813932946ebf41b913fe7e880d154ade2e"}, + {file = "simplejson-3.17.6-cp39-cp39-win_amd64.whl", hash = "sha256:3fe87570168b2ae018391e2b43fbf66e8593a86feccb4b0500d134c998983ccc"}, + {file = "simplejson-3.17.6.tar.gz", hash = "sha256:cf98038d2abf63a1ada5730e91e84c642ba6c225b0198c3684151b1f80c5f8a6"}, +] +six = [ + {file = "six-1.16.0-py2.py3-none-any.whl", hash = "sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254"}, + {file = "six-1.16.0.tar.gz", hash = "sha256:1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926"}, +] +smbus2 = [ + {file = "smbus2-0.4.2-py2.py3-none-any.whl", hash = "sha256:50f3c78e436b42a9583948be06961a8104cf020ebad5edfaaf2657528bef0818"}, + {file = "smbus2-0.4.2.tar.gz", hash = "sha256:634541ed794068a822fe7499f1577468b9d4641b68dd9bfb6d0eb7270f4d2a32"}, +] +sniffio = [ + {file = "sniffio-1.3.0-py3-none-any.whl", hash = "sha256:eecefdce1e5bbfb7ad2eeaabf7c1eeb404d7757c379bd1f7e5cce9d8bf425384"}, + {file = "sniffio-1.3.0.tar.gz", hash = "sha256:e60305c5e5d314f5389259b7f22aaa33d8f7dee49763119234af3755c55b9101"}, +] +snowballstemmer = [ + {file = "snowballstemmer-2.2.0-py2.py3-none-any.whl", hash = "sha256:c8e1716e83cc398ae16824e5572ae04e0d9fc2c6b985fb0f900f5f0c96ecba1a"}, + {file = "snowballstemmer-2.2.0.tar.gz", hash = "sha256:09b16deb8547d3412ad7b590689584cd0fe25ec8db3be37788be3810cbf19cb1"}, +] +sortedcontainers = [ + {file = "sortedcontainers-2.4.0-py2.py3-none-any.whl", hash = "sha256:a163dcaede0f1c021485e957a39245190e74249897e2ae4b2aa38595db237ee0"}, + {file = "sortedcontainers-2.4.0.tar.gz", hash = "sha256:25caa5a06cc30b6b83d11423433f65d1f9d76c4c6a0c90e3379eaa43b9bfdb88"}, +] +sounddevice = [ + {file = "sounddevice-0.4.5-py3-none-any.whl", hash = "sha256:5cea4afd9412e731f50ae09a54d68b10628a604cfd56b42a976c54d424c6c39d"}, + {file = "sounddevice-0.4.5-py3-none-macosx_10_6_x86_64.macosx_10_6_universal2.whl", hash = "sha256:0875173595a8bd5a66b5a03a3d958e7b89c3b956b8befbe4491a24a3ce7784c0"}, + {file = "sounddevice-0.4.5-py3-none-win32.whl", hash = "sha256:442adf53850916374a58f902200aaf9412227378181264e60c966da64be47d41"}, + {file = "sounddevice-0.4.5-py3-none-win_amd64.whl", hash = "sha256:d3216c5d3d678c3301058e9aac7000879e255140c524c9ef98730091b67ea676"}, + {file = "sounddevice-0.4.5.tar.gz", hash = "sha256:2fe0d41299e4f3037dad2acede4eff0666b34a1fa3da5335e47120373964bef5"}, +] +soupsieve = [ + {file = "soupsieve-2.3.2.post1-py3-none-any.whl", hash = "sha256:3b2503d3c7084a42b1ebd08116e5f81aadfaea95863628c80a3b774a11b7c759"}, + {file = "soupsieve-2.3.2.post1.tar.gz", hash = "sha256:fc53893b3da2c33de295667a0e19f078c14bf86544af307354de5fcf12a3f30d"}, +] +sphinx = [ + {file = "Sphinx-5.3.0.tar.gz", hash = "sha256:51026de0a9ff9fc13c05d74913ad66047e104f56a129ff73e174eb5c3ee794b5"}, + {file = "sphinx-5.3.0-py3-none-any.whl", hash = "sha256:060ca5c9f7ba57a08a1219e547b269fadf125ae25b06b9fa7f66768efb652d6d"}, +] +sphinx-rtd-theme = [ + {file = "sphinx_rtd_theme-1.0.0-py2.py3-none-any.whl", hash = "sha256:4d35a56f4508cfee4c4fb604373ede6feae2a306731d533f409ef5c3496fdbd8"}, + {file = "sphinx_rtd_theme-1.0.0.tar.gz", hash = "sha256:eec6d497e4c2195fa0e8b2016b337532b8a699a68bcb22a512870e16925c6a5c"}, +] +sphinx-sitemap = [ + {file = "sphinx-sitemap-2.2.0.tar.gz", hash = "sha256:65adda39233cb17c0da10ba1cebaa2df73e271cdb6f8efd5cec8eef3b3cf7737"}, +] +sphinxcontrib-applehelp = [ + {file = "sphinxcontrib-applehelp-1.0.2.tar.gz", hash = "sha256:a072735ec80e7675e3f432fcae8610ecf509c5f1869d17e2eecff44389cdbc58"}, + {file = "sphinxcontrib_applehelp-1.0.2-py2.py3-none-any.whl", hash = "sha256:806111e5e962be97c29ec4c1e7fe277bfd19e9652fb1a4392105b43e01af885a"}, +] +sphinxcontrib-devhelp = [ + {file = "sphinxcontrib-devhelp-1.0.2.tar.gz", hash = "sha256:ff7f1afa7b9642e7060379360a67e9c41e8f3121f2ce9164266f61b9f4b338e4"}, + {file = "sphinxcontrib_devhelp-1.0.2-py2.py3-none-any.whl", hash = "sha256:8165223f9a335cc1af7ffe1ed31d2871f325254c0423bc0c4c7cd1c1e4734a2e"}, +] +sphinxcontrib-htmlhelp = [ + {file = "sphinxcontrib-htmlhelp-2.0.0.tar.gz", hash = "sha256:f5f8bb2d0d629f398bf47d0d69c07bc13b65f75a81ad9e2f71a63d4b7a2f6db2"}, + {file = "sphinxcontrib_htmlhelp-2.0.0-py2.py3-none-any.whl", hash = "sha256:d412243dfb797ae3ec2b59eca0e52dac12e75a241bf0e4eb861e450d06c6ed07"}, +] +sphinxcontrib-jsmath = [ + {file = "sphinxcontrib-jsmath-1.0.1.tar.gz", hash = "sha256:a9925e4a4587247ed2191a22df5f6970656cb8ca2bd6284309578f2153e0c4b8"}, + {file = "sphinxcontrib_jsmath-1.0.1-py2.py3-none-any.whl", hash = "sha256:2ec2eaebfb78f3f2078e73666b1415417a116cc848b72e5172e596c871103178"}, +] +sphinxcontrib-qthelp = [ + {file = "sphinxcontrib-qthelp-1.0.3.tar.gz", hash = "sha256:4c33767ee058b70dba89a6fc5c1892c0d57a54be67ddd3e7875a18d14cba5a72"}, + {file = "sphinxcontrib_qthelp-1.0.3-py2.py3-none-any.whl", hash = "sha256:bd9fc24bcb748a8d51fd4ecaade681350aa63009a347a8c14e637895444dfab6"}, +] +sphinxcontrib-serializinghtml = [ + {file = "sphinxcontrib-serializinghtml-1.1.5.tar.gz", hash = "sha256:aa5f6de5dfdf809ef505c4895e51ef5c9eac17d0f287933eb49ec495280b6952"}, + {file = "sphinxcontrib_serializinghtml-1.1.5-py2.py3-none-any.whl", hash = "sha256:352a9a00ae864471d3a7ead8d7d79f5fc0b57e8b3f95e9867eb9eb28999b92fd"}, +] +spidev = [ + {file = "spidev-3.6-cp39-cp39-linux_armv7l.whl", hash = "sha256:280abc00a1ef7780ef62c3f294f52a2527b6c47d8c269fea98664970bcaf6da5"}, + {file = "spidev-3.6.tar.gz", hash = "sha256:14dbc37594a4aaef85403ab617985d3c3ef464d62bc9b769ef552db53701115b"}, +] +sqlalchemy = [ + {file = "SQLAlchemy-1.4.42-cp27-cp27m-macosx_10_14_x86_64.whl", hash = "sha256:28e881266a172a4d3c5929182fde6bb6fba22ac93f137d5380cc78a11a9dd124"}, + {file = "SQLAlchemy-1.4.42-cp27-cp27m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:ca9389a00f639383c93ed00333ed763812f80b5ae9e772ea32f627043f8c9c88"}, + {file = "SQLAlchemy-1.4.42-cp27-cp27m-win32.whl", hash = "sha256:1d0c23ecf7b3bc81e29459c34a3f4c68ca538de01254e24718a7926810dc39a6"}, + {file = "SQLAlchemy-1.4.42-cp27-cp27m-win_amd64.whl", hash = "sha256:6c9d004eb78c71dd4d3ce625b80c96a827d2e67af9c0d32b1c1e75992a7916cc"}, + {file = "SQLAlchemy-1.4.42-cp27-cp27mu-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:9e3a65ce9ed250b2f096f7b559fe3ee92e6605fab3099b661f0397a9ac7c8d95"}, + {file = "SQLAlchemy-1.4.42-cp310-cp310-macosx_10_15_x86_64.whl", hash = "sha256:2e56dfed0cc3e57b2f5c35719d64f4682ef26836b81067ee6cfad062290fd9e2"}, + {file = "SQLAlchemy-1.4.42-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b42c59ffd2d625b28cdb2ae4cde8488543d428cba17ff672a543062f7caee525"}, + {file = "SQLAlchemy-1.4.42-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:22459fc1718785d8a86171bbe7f01b5c9d7297301ac150f508d06e62a2b4e8d2"}, + {file = "SQLAlchemy-1.4.42-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:df76e9c60879fdc785a34a82bf1e8691716ffac32e7790d31a98d7dec6e81545"}, + {file = "SQLAlchemy-1.4.42-cp310-cp310-win32.whl", hash = "sha256:e7e740453f0149437c101ea4fdc7eea2689938c5760d7dcc436c863a12f1f565"}, + {file = "SQLAlchemy-1.4.42-cp310-cp310-win_amd64.whl", hash = "sha256:effc89e606165ca55f04f3f24b86d3e1c605e534bf1a96e4e077ce1b027d0b71"}, + {file = "SQLAlchemy-1.4.42-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:97ff50cd85bb907c2a14afb50157d0d5486a4b4639976b4a3346f34b6d1b5272"}, + {file = "SQLAlchemy-1.4.42-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e12c6949bae10f1012ab5c0ea52ab8db99adcb8c7b717938252137cdf694c775"}, + {file = "SQLAlchemy-1.4.42-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:11b2ec26c5d2eefbc3e6dca4ec3d3d95028be62320b96d687b6e740424f83b7d"}, + {file = "SQLAlchemy-1.4.42-cp311-cp311-win32.whl", hash = "sha256:6045b3089195bc008aee5c273ec3ba9a93f6a55bc1b288841bd4cfac729b6516"}, + {file = "SQLAlchemy-1.4.42-cp311-cp311-win_amd64.whl", hash = "sha256:0501f74dd2745ec38f44c3a3900fb38b9db1ce21586b691482a19134062bf049"}, + {file = "SQLAlchemy-1.4.42-cp36-cp36m-macosx_10_14_x86_64.whl", hash = "sha256:6e39e97102f8e26c6c8550cb368c724028c575ec8bc71afbbf8faaffe2b2092a"}, + {file = "SQLAlchemy-1.4.42-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:15d878929c30e41fb3d757a5853b680a561974a0168cd33a750be4ab93181628"}, + {file = "SQLAlchemy-1.4.42-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:fa5b7eb2051e857bf83bade0641628efe5a88de189390725d3e6033a1fff4257"}, + {file = "SQLAlchemy-1.4.42-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4e1c5f8182b4f89628d782a183d44db51b5af84abd6ce17ebb9804355c88a7b5"}, + {file = "SQLAlchemy-1.4.42-cp36-cp36m-win32.whl", hash = "sha256:a7dd5b7b34a8ba8d181402d824b87c5cee8963cb2e23aa03dbfe8b1f1e417cde"}, + {file = "SQLAlchemy-1.4.42-cp36-cp36m-win_amd64.whl", hash = "sha256:5ede1495174e69e273fad68ad45b6d25c135c1ce67723e40f6cf536cb515e20b"}, + {file = "SQLAlchemy-1.4.42-cp37-cp37m-macosx_10_15_x86_64.whl", hash = "sha256:9256563506e040daddccaa948d055e006e971771768df3bb01feeb4386c242b0"}, + {file = "SQLAlchemy-1.4.42-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4948b6c5f4e56693bbeff52f574279e4ff972ea3353f45967a14c30fb7ae2beb"}, + {file = "SQLAlchemy-1.4.42-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:1811a0b19a08af7750c0b69e38dec3d46e47c4ec1d74b6184d69f12e1c99a5e0"}, + {file = "SQLAlchemy-1.4.42-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9b01d9cd2f9096f688c71a3d0f33f3cd0af8549014e66a7a7dee6fc214a7277d"}, + {file = "SQLAlchemy-1.4.42-cp37-cp37m-win32.whl", hash = "sha256:bd448b262544b47a2766c34c0364de830f7fb0772d9959c1c42ad61d91ab6565"}, + {file = "SQLAlchemy-1.4.42-cp37-cp37m-win_amd64.whl", hash = "sha256:04f2598c70ea4a29b12d429a80fad3a5202d56dce19dd4916cc46a965a5ca2e9"}, + {file = "SQLAlchemy-1.4.42-cp38-cp38-macosx_10_15_x86_64.whl", hash = "sha256:3ab7c158f98de6cb4f1faab2d12973b330c2878d0c6b689a8ca424c02d66e1b3"}, + {file = "SQLAlchemy-1.4.42-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0ee377eb5c878f7cefd633ab23c09e99d97c449dd999df639600f49b74725b80"}, + {file = "SQLAlchemy-1.4.42-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:934472bb7d8666727746a75670a1f8d91a9cae8c464bba79da30a0f6faccd9e1"}, + {file = "SQLAlchemy-1.4.42-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fdb94a3d1ba77ff2ef11912192c066f01e68416f554c194d769391638c8ad09a"}, + {file = "SQLAlchemy-1.4.42-cp38-cp38-win32.whl", hash = "sha256:f0f574465b78f29f533976c06b913e54ab4980b9931b69aa9d306afff13a9471"}, + {file = "SQLAlchemy-1.4.42-cp38-cp38-win_amd64.whl", hash = "sha256:a85723c00a636eed863adb11f1e8aaa36ad1c10089537823b4540948a8429798"}, + {file = "SQLAlchemy-1.4.42-cp39-cp39-macosx_10_15_x86_64.whl", hash = "sha256:5ce6929417d5dce5ad1d3f147db81735a4a0573b8fb36e3f95500a06eaddd93e"}, + {file = "SQLAlchemy-1.4.42-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:723e3b9374c1ce1b53564c863d1a6b2f1dc4e97b1c178d9b643b191d8b1be738"}, + {file = "SQLAlchemy-1.4.42-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:876eb185911c8b95342b50a8c4435e1c625944b698a5b4a978ad2ffe74502908"}, + {file = "SQLAlchemy-1.4.42-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2fd49af453e590884d9cdad3586415922a8e9bb669d874ee1dc55d2bc425aacd"}, + {file = "SQLAlchemy-1.4.42-cp39-cp39-win32.whl", hash = "sha256:e4ef8cb3c5b326f839bfeb6af5f406ba02ad69a78c7aac0fbeeba994ad9bb48a"}, + {file = "SQLAlchemy-1.4.42-cp39-cp39-win_amd64.whl", hash = "sha256:5f966b64c852592469a7eb759615bbd351571340b8b344f1d3fa2478b5a4c934"}, + {file = "SQLAlchemy-1.4.42.tar.gz", hash = "sha256:177e41914c476ed1e1b77fd05966ea88c094053e17a85303c4ce007f88eff363"}, +] +stack-data = [ + {file = "stack_data-0.5.1-py3-none-any.whl", hash = "sha256:5120731a18ba4c82cefcf84a945f6f3e62319ef413bfc210e32aca3a69310ba2"}, + {file = "stack_data-0.5.1.tar.gz", hash = "sha256:95eb784942e861a3d80efd549ff9af6cf847d88343a12eb681d7157cfcb6e32b"}, +] +subprocess32 = [ + {file = "subprocess32-3.5.4-cp27-cp27m-macosx_10_6_intel.whl", hash = "sha256:88e37c1aac5388df41cc8a8456bb49ebffd321a3ad4d70358e3518176de3a56b"}, + {file = "subprocess32-3.5.4-cp27-cp27mu-manylinux2014_x86_64.whl", hash = "sha256:e45d985aef903c5b7444d34350b05da91a9e0ea015415ab45a21212786c649d0"}, + {file = "subprocess32-3.5.4.tar.gz", hash = "sha256:eb2937c80497978d181efa1b839ec2d9622cf9600a039a79d0e108d1f9aec79d"}, +] +sympy = [ + {file = "sympy-1.11.1-py3-none-any.whl", hash = "sha256:938f984ee2b1e8eae8a07b884c8b7a1146010040fccddc6539c54f401c8f6fcf"}, + {file = "sympy-1.11.1.tar.gz", hash = "sha256:e32380dce63cb7c0108ed525570092fd45168bdae2faa17e528221ef72e88658"}, +] +tabulate = [ + {file = "tabulate-0.8.10-py3-none-any.whl", hash = "sha256:0ba055423dbaa164b9e456abe7920c5e8ed33fcc16f6d1b2f2d152c8e1e8b4fc"}, + {file = "tabulate-0.8.10.tar.gz", hash = "sha256:6c57f3f3dd7ac2782770155f3adb2db0b1a269637e42f27599925e64b114f519"}, +] +tenacity = [ + {file = "tenacity-8.1.0-py3-none-any.whl", hash = "sha256:35525cd47f82830069f0d6b73f7eb83bc5b73ee2fff0437952cedf98b27653ac"}, + {file = "tenacity-8.1.0.tar.gz", hash = "sha256:e48c437fdf9340f5666b92cd7990e96bc5fc955e1298baf4a907e3972067a445"}, +] +terminado = [ + {file = "terminado-0.16.0-py3-none-any.whl", hash = "sha256:3e995072a7178a104c41134548ce9b03e4e7f0a538e9c29df4f1fbc81c7cfc75"}, + {file = "terminado-0.16.0.tar.gz", hash = "sha256:fac14374eb5498bdc157ed32e510b1f60d5c3c7981a9f5ba018bb9a64cec0c25"}, +] +threadpoolctl = [ + {file = "threadpoolctl-3.1.0-py3-none-any.whl", hash = "sha256:8b99adda265feb6773280df41eece7b2e6561b772d21ffd52e372f999024907b"}, + {file = "threadpoolctl-3.1.0.tar.gz", hash = "sha256:a335baacfaa4400ae1f0d8e3a58d6674d2f8828e3716bb2802c44955ad391380"}, +] +tifffile = [ + {file = "tifffile-2022.10.10-py3-none-any.whl", hash = "sha256:87f3aee8a0d06b74655269a105de75c1958a24653e1930d523eb516100043503"}, + {file = "tifffile-2022.10.10.tar.gz", hash = "sha256:50b61ba943b866d191295bc38a00191c9fdab23ece063544c7f1a264e3f6aa8e"}, +] +timezonefinder = [ + {file = "timezonefinder-6.1.3-cp38-cp38-manylinux_2_31_x86_64.whl", hash = "sha256:96c96db94e75e072187843152e6c5dc0718500a9a91986032365abe09162d0e7"}, + {file = "timezonefinder-6.1.3.tar.gz", hash = "sha256:f2ee561b1e7692b933fcd914df38800e93db7caf278e7328de7328829b04f275"}, +] +timm = [ + {file = "timm-0.4.12-py3-none-any.whl", hash = "sha256:dba6b1702b7d24bf9f0f1c2fc394b4ee28f93cde5404f1dc732d63ccd00533b6"}, + {file = "timm-0.4.12.tar.gz", hash = "sha256:b14be70dbd4528b5ca8657cf5bc2672c7918c3d9ebfbffe80f4785b54e884b1e"}, +] +tinycss2 = [ + {file = "tinycss2-1.2.1-py3-none-any.whl", hash = "sha256:2b80a96d41e7c3914b8cda8bc7f705a4d9c49275616e886103dd839dfc847847"}, + {file = "tinycss2-1.2.1.tar.gz", hash = "sha256:8cff3a8f066c2ec677c06dbc7b45619804a6938478d9d73c284b29d14ecb0627"}, +] +toml = [ + {file = "toml-0.10.2-py2.py3-none-any.whl", hash = "sha256:806143ae5bfb6a3c6e736a764057db0e6a0e05e338b5630894a5f779cabb4f9b"}, + {file = "toml-0.10.2.tar.gz", hash = "sha256:b3bda1d108d5dd99f4a20d24d9c348e91c4db7ab1b749200bded2f839ccbe68f"}, +] +tomli = [ + {file = "tomli-2.0.1-py3-none-any.whl", hash = "sha256:939de3e7a6161af0c887ef91b7d41a53e7c5a1ca976325f429cb46ea9bc30ecc"}, + {file = "tomli-2.0.1.tar.gz", hash = "sha256:de526c12914f0c550d15924c62d72abc48d6fe7364aa87328337a31007fe8a4f"}, +] +tomlkit = [ + {file = "tomlkit-0.11.5-py3-none-any.whl", hash = "sha256:f2ef9da9cef846ee027947dc99a45d6b68a63b0ebc21944649505bf2e8bc5fe7"}, + {file = "tomlkit-0.11.5.tar.gz", hash = "sha256:571854ebbb5eac89abcb4a2e47d7ea27b89bf29e09c35395da6f03dd4ae23d1c"}, +] +torch = [] +torchsummary = [ + {file = "torchsummary-1.5.1-py3-none-any.whl", hash = "sha256:10f41d1743fb918f83293f13183f532ab1bb8f6639a1b89e5f8592ec1919a976"}, + {file = "torchsummary-1.5.1.tar.gz", hash = "sha256:981bf689e22e0cf7f95c746002f20a24ad26aa6b9d861134a14bc6ce92230590"}, +] +torchvision = [] +tornado = [ + {file = "tornado-6.2-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:20f638fd8cc85f3cbae3c732326e96addff0a15e22d80f049e00121651e82e72"}, + {file = "tornado-6.2-cp37-abi3-macosx_10_9_x86_64.whl", hash = "sha256:87dcafae3e884462f90c90ecc200defe5e580a7fbbb4365eda7c7c1eb809ebc9"}, + {file = "tornado-6.2-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ba09ef14ca9893954244fd872798b4ccb2367c165946ce2dd7376aebdde8e3ac"}, + {file = "tornado-6.2-cp37-abi3-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b8150f721c101abdef99073bf66d3903e292d851bee51910839831caba341a75"}, + {file = "tornado-6.2-cp37-abi3-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d3a2f5999215a3a06a4fc218026cd84c61b8b2b40ac5296a6db1f1451ef04c1e"}, + {file = "tornado-6.2-cp37-abi3-musllinux_1_1_aarch64.whl", hash = "sha256:5f8c52d219d4995388119af7ccaa0bcec289535747620116a58d830e7c25d8a8"}, + {file = "tornado-6.2-cp37-abi3-musllinux_1_1_i686.whl", hash = "sha256:6fdfabffd8dfcb6cf887428849d30cf19a3ea34c2c248461e1f7d718ad30b66b"}, + {file = "tornado-6.2-cp37-abi3-musllinux_1_1_x86_64.whl", hash = "sha256:1d54d13ab8414ed44de07efecb97d4ef7c39f7438cf5e976ccd356bebb1b5fca"}, + {file = "tornado-6.2-cp37-abi3-win32.whl", hash = "sha256:5c87076709343557ef8032934ce5f637dbb552efa7b21d08e89ae7619ed0eb23"}, + {file = "tornado-6.2-cp37-abi3-win_amd64.whl", hash = "sha256:e5f923aa6a47e133d1cf87d60700889d7eae68988704e20c75fb2d65677a8e4b"}, + {file = "tornado-6.2.tar.gz", hash = "sha256:9b630419bde84ec666bfd7ea0a4cb2a8a651c2d5cccdbdd1972a0c859dfc3c13"}, +] +tqdm = [ + {file = "tqdm-4.64.1-py2.py3-none-any.whl", hash = "sha256:6fee160d6ffcd1b1c68c65f14c829c22832bc401726335ce92c52d395944a6a1"}, + {file = "tqdm-4.64.1.tar.gz", hash = "sha256:5f4f682a004951c1b450bc753c710e9280c5746ce6ffedee253ddbcbf54cf1e4"}, +] +traitlets = [ + {file = "traitlets-5.5.0-py3-none-any.whl", hash = "sha256:1201b2c9f76097195989cdf7f65db9897593b0dfd69e4ac96016661bb6f0d30f"}, + {file = "traitlets-5.5.0.tar.gz", hash = "sha256:b122f9ff2f2f6c1709dab289a05555be011c87828e911c0cf4074b85cb780a79"}, +] +triton = [ + {file = "triton-1.1.1-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8441e6f44517aef8f6345f621c003926cbe970892802411a949ccda516cbd5ba"}, + {file = "triton-1.1.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:840776bc1f4757fb2d6af974694c5e5313220ceec238ee6118b9728bc2aa9ade"}, + {file = "triton-1.1.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:97d42cdaa7d56de463d762c18cc876bfd0828a2b6a706263393fe7e10d1c83ca"}, + {file = "triton-1.1.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ebc19c0e902bbf7d29de4d444455608065a2c56e3524f4bc94e724511ca518f3"}, + {file = "triton-1.1.1-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f02f798cd2dd922228082ce1a4e9d81badb9a6217a9aac6d783e95bf7055974d"}, +] +types-atomicwrites = [ + {file = "types-atomicwrites-1.4.5.1.tar.gz", hash = "sha256:9e9f0923ebf93524b28bcece5a23ac8c3820f39b060df29f671936d2e4bc04bc"}, + {file = "types_atomicwrites-1.4.5.1-py3-none-any.whl", hash = "sha256:2f1febbdc78b55453b189fa5b136dce34bab7d1d82319163d470e404aab55c83"}, +] +types-certifi = [ + {file = "types-certifi-2021.10.8.3.tar.gz", hash = "sha256:72cf7798d165bc0b76e1c10dd1ea3097c7063c42c21d664523b928e88b554a4f"}, + {file = "types_certifi-2021.10.8.3-py3-none-any.whl", hash = "sha256:b2d1e325e69f71f7c78e5943d410e650b4707bb0ef32e4ddf3da37f54176e88a"}, +] +types-pycurl = [ + {file = "types-pycurl-7.45.1.tar.gz", hash = "sha256:82e00aa2981595bfa55e5a3bac42221eb3435b0026dffbe1177f6ac9f2d51200"}, + {file = "types_pycurl-7.45.1-py3-none-any.whl", hash = "sha256:9eab3414da4a1b1e9a628bd288fc5172b8c182e1d9fb6d8d082441b0fd64baed"}, +] +types-pyyaml = [ + {file = "types-PyYAML-6.0.12.tar.gz", hash = "sha256:f6f350418125872f3f0409d96a62a5a5ceb45231af5cc07ee0034ec48a3c82fa"}, + {file = "types_PyYAML-6.0.12-py3-none-any.whl", hash = "sha256:29228db9f82df4f1b7febee06bbfb601677882e98a3da98132e31c6874163e15"}, +] +types-requests = [ + {file = "types-requests-2.28.11.2.tar.gz", hash = "sha256:fdcd7bd148139fb8eef72cf4a41ac7273872cad9e6ada14b11ff5dfdeee60ed3"}, + {file = "types_requests-2.28.11.2-py3-none-any.whl", hash = "sha256:14941f8023a80b16441b3b46caffcbfce5265fd14555844d6029697824b5a2ef"}, +] +types-urllib3 = [ + {file = "types-urllib3-1.26.25.1.tar.gz", hash = "sha256:a948584944b2412c9a74b9cf64f6c48caf8652cb88b38361316f6d15d8a184cd"}, + {file = "types_urllib3-1.26.25.1-py3-none-any.whl", hash = "sha256:f6422596cc9ee5fdf68f9d547f541096a20c2dcfd587e37c804c9ea720bf5cb2"}, +] +typing-extensions = [ + {file = "typing_extensions-4.4.0-py3-none-any.whl", hash = "sha256:16fa4864408f655d35ec496218b85f79b3437c829e93320c7c9215ccfd92489e"}, + {file = "typing_extensions-4.4.0.tar.gz", hash = "sha256:1511434bb92bf8dd198c12b1cc812e800d4181cfcb867674e0f8279cc93087aa"}, +] +urllib3 = [ + {file = "urllib3-1.26.12-py2.py3-none-any.whl", hash = "sha256:b930dd878d5a8afb066a637fbb35144fe7901e3b209d1cd4f524bd0e9deee997"}, + {file = "urllib3-1.26.12.tar.gz", hash = "sha256:3fa96cf423e6987997fc326ae8df396db2a8b7c667747d47ddd8ecba91f4a74e"}, +] +utm = [ + {file = "utm-0.7.0.tar.gz", hash = "sha256:3c9a3650e98bb6eecec535418d0dfd4db8f88c8ceaca112a0ff0787e116566e2"}, +] +virtualenv = [ + {file = "virtualenv-20.16.5-py3-none-any.whl", hash = "sha256:d07dfc5df5e4e0dbc92862350ad87a36ed505b978f6c39609dc489eadd5b0d27"}, + {file = "virtualenv-20.16.5.tar.gz", hash = "sha256:227ea1b9994fdc5ea31977ba3383ef296d7472ea85be9d6732e42a91c04e80da"}, +] +virtualenv-clone = [ + {file = "virtualenv-clone-0.5.7.tar.gz", hash = "sha256:418ee935c36152f8f153c79824bb93eaf6f0f7984bae31d3f48f350b9183501a"}, + {file = "virtualenv_clone-0.5.7-py3-none-any.whl", hash = "sha256:44d5263bceed0bac3e1424d64f798095233b64def1c5689afa43dc3223caf5b0"}, +] +wcwidth = [ + {file = "wcwidth-0.2.5-py2.py3-none-any.whl", hash = "sha256:beb4802a9cebb9144e99086eff703a642a13d6a0052920003a230f3294bbe784"}, + {file = "wcwidth-0.2.5.tar.gz", hash = "sha256:c4d647b99872929fdb7bdcaa4fbe7f01413ed3d98077df798530e5b04f116c83"}, +] +webencodings = [ + {file = "webencodings-0.5.1-py2.py3-none-any.whl", hash = "sha256:a0af1213f3c2226497a97e2b3aa01a7e4bee4f403f95be16fc9acd2947514a78"}, + {file = "webencodings-0.5.1.tar.gz", hash = "sha256:b36a1c245f2d304965eb4e0a82848379241dc04b865afcc4aab16748587e1923"}, +] +websocket-client = [ + {file = "websocket-client-1.4.1.tar.gz", hash = "sha256:f9611eb65c8241a67fb373bef040b3cf8ad377a9f6546a12b620b6511e8ea9ef"}, + {file = "websocket_client-1.4.1-py3-none-any.whl", hash = "sha256:398909eb7e261f44b8f4bd474785b6ec5f5b499d4953342fe9755e01ef624090"}, +] +werkzeug = [ + {file = "Werkzeug-2.2.2-py3-none-any.whl", hash = "sha256:f979ab81f58d7318e064e99c4506445d60135ac5cd2e177a2de0089bfd4c9bd5"}, + {file = "Werkzeug-2.2.2.tar.gz", hash = "sha256:7ea2d48322cc7c0f8b3a215ed73eabd7b5d75d0b50e31ab006286ccff9e00b8f"}, +] +widgetsnbextension = [ + {file = "widgetsnbextension-4.0.3-py3-none-any.whl", hash = "sha256:7f3b0de8fda692d31ef03743b598620e31c2668b835edbd3962d080ccecf31eb"}, + {file = "widgetsnbextension-4.0.3.tar.gz", hash = "sha256:34824864c062b0b3030ad78210db5ae6a3960dfb61d5b27562d6631774de0286"}, +] +wrapt = [ + {file = "wrapt-1.14.1-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:1b376b3f4896e7930f1f772ac4b064ac12598d1c38d04907e696cc4d794b43d3"}, + {file = "wrapt-1.14.1-cp27-cp27m-manylinux1_i686.whl", hash = "sha256:903500616422a40a98a5a3c4ff4ed9d0066f3b4c951fa286018ecdf0750194ef"}, + {file = "wrapt-1.14.1-cp27-cp27m-manylinux1_x86_64.whl", hash = "sha256:5a9a0d155deafd9448baff28c08e150d9b24ff010e899311ddd63c45c2445e28"}, + {file = "wrapt-1.14.1-cp27-cp27m-manylinux2010_i686.whl", hash = "sha256:ddaea91abf8b0d13443f6dac52e89051a5063c7d014710dcb4d4abb2ff811a59"}, + {file = "wrapt-1.14.1-cp27-cp27m-manylinux2010_x86_64.whl", hash = "sha256:36f582d0c6bc99d5f39cd3ac2a9062e57f3cf606ade29a0a0d6b323462f4dd87"}, + {file = "wrapt-1.14.1-cp27-cp27mu-manylinux1_i686.whl", hash = "sha256:7ef58fb89674095bfc57c4069e95d7a31cfdc0939e2a579882ac7d55aadfd2a1"}, + {file = "wrapt-1.14.1-cp27-cp27mu-manylinux1_x86_64.whl", hash = "sha256:e2f83e18fe2f4c9e7db597e988f72712c0c3676d337d8b101f6758107c42425b"}, + {file = "wrapt-1.14.1-cp27-cp27mu-manylinux2010_i686.whl", hash = "sha256:ee2b1b1769f6707a8a445162ea16dddf74285c3964f605877a20e38545c3c462"}, + {file = "wrapt-1.14.1-cp27-cp27mu-manylinux2010_x86_64.whl", hash = "sha256:833b58d5d0b7e5b9832869f039203389ac7cbf01765639c7309fd50ef619e0b1"}, + {file = "wrapt-1.14.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:80bb5c256f1415f747011dc3604b59bc1f91c6e7150bd7db03b19170ee06b320"}, + {file = "wrapt-1.14.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:07f7a7d0f388028b2df1d916e94bbb40624c59b48ecc6cbc232546706fac74c2"}, + {file = "wrapt-1.14.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:02b41b633c6261feff8ddd8d11c711df6842aba629fdd3da10249a53211a72c4"}, + {file = "wrapt-1.14.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:2fe803deacd09a233e4762a1adcea5db5d31e6be577a43352936179d14d90069"}, + {file = "wrapt-1.14.1-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:257fd78c513e0fb5cdbe058c27a0624c9884e735bbd131935fd49e9fe719d310"}, + {file = "wrapt-1.14.1-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:4fcc4649dc762cddacd193e6b55bc02edca674067f5f98166d7713b193932b7f"}, + {file = "wrapt-1.14.1-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:11871514607b15cfeb87c547a49bca19fde402f32e2b1c24a632506c0a756656"}, + {file = "wrapt-1.14.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:8ad85f7f4e20964db4daadcab70b47ab05c7c1cf2a7c1e51087bfaa83831854c"}, + {file = "wrapt-1.14.1-cp310-cp310-win32.whl", hash = "sha256:a9a52172be0b5aae932bef82a79ec0a0ce87288c7d132946d645eba03f0ad8a8"}, + {file = "wrapt-1.14.1-cp310-cp310-win_amd64.whl", hash = "sha256:6d323e1554b3d22cfc03cd3243b5bb815a51f5249fdcbb86fda4bf62bab9e164"}, + {file = "wrapt-1.14.1-cp35-cp35m-manylinux1_i686.whl", hash = "sha256:43ca3bbbe97af00f49efb06e352eae40434ca9d915906f77def219b88e85d907"}, + {file = "wrapt-1.14.1-cp35-cp35m-manylinux1_x86_64.whl", hash = "sha256:6b1a564e6cb69922c7fe3a678b9f9a3c54e72b469875aa8018f18b4d1dd1adf3"}, + {file = "wrapt-1.14.1-cp35-cp35m-manylinux2010_i686.whl", hash = "sha256:00b6d4ea20a906c0ca56d84f93065b398ab74b927a7a3dbd470f6fc503f95dc3"}, + {file = "wrapt-1.14.1-cp35-cp35m-manylinux2010_x86_64.whl", hash = "sha256:a85d2b46be66a71bedde836d9e41859879cc54a2a04fad1191eb50c2066f6e9d"}, + {file = "wrapt-1.14.1-cp35-cp35m-win32.whl", hash = "sha256:dbcda74c67263139358f4d188ae5faae95c30929281bc6866d00573783c422b7"}, + {file = "wrapt-1.14.1-cp35-cp35m-win_amd64.whl", hash = "sha256:b21bb4c09ffabfa0e85e3a6b623e19b80e7acd709b9f91452b8297ace2a8ab00"}, + {file = "wrapt-1.14.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:9e0fd32e0148dd5dea6af5fee42beb949098564cc23211a88d799e434255a1f4"}, + {file = "wrapt-1.14.1-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9736af4641846491aedb3c3f56b9bc5568d92b0692303b5a305301a95dfd38b1"}, + {file = "wrapt-1.14.1-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5b02d65b9ccf0ef6c34cba6cf5bf2aab1bb2f49c6090bafeecc9cd81ad4ea1c1"}, + {file = "wrapt-1.14.1-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:21ac0156c4b089b330b7666db40feee30a5d52634cc4560e1905d6529a3897ff"}, + {file = "wrapt-1.14.1-cp36-cp36m-musllinux_1_1_aarch64.whl", hash = "sha256:9f3e6f9e05148ff90002b884fbc2a86bd303ae847e472f44ecc06c2cd2fcdb2d"}, + {file = "wrapt-1.14.1-cp36-cp36m-musllinux_1_1_i686.whl", hash = "sha256:6e743de5e9c3d1b7185870f480587b75b1cb604832e380d64f9504a0535912d1"}, + {file = "wrapt-1.14.1-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:d79d7d5dc8a32b7093e81e97dad755127ff77bcc899e845f41bf71747af0c569"}, + {file = "wrapt-1.14.1-cp36-cp36m-win32.whl", hash = "sha256:81b19725065dcb43df02b37e03278c011a09e49757287dca60c5aecdd5a0b8ed"}, + {file = "wrapt-1.14.1-cp36-cp36m-win_amd64.whl", hash = "sha256:b014c23646a467558be7da3d6b9fa409b2c567d2110599b7cf9a0c5992b3b471"}, + {file = "wrapt-1.14.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:88bd7b6bd70a5b6803c1abf6bca012f7ed963e58c68d76ee20b9d751c74a3248"}, + {file = "wrapt-1.14.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b5901a312f4d14c59918c221323068fad0540e34324925c8475263841dbdfe68"}, + {file = "wrapt-1.14.1-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d77c85fedff92cf788face9bfa3ebaa364448ebb1d765302e9af11bf449ca36d"}, + {file = "wrapt-1.14.1-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8d649d616e5c6a678b26d15ece345354f7c2286acd6db868e65fcc5ff7c24a77"}, + {file = "wrapt-1.14.1-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:7d2872609603cb35ca513d7404a94d6d608fc13211563571117046c9d2bcc3d7"}, + {file = "wrapt-1.14.1-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:ee6acae74a2b91865910eef5e7de37dc6895ad96fa23603d1d27ea69df545015"}, + {file = "wrapt-1.14.1-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:2b39d38039a1fdad98c87279b48bc5dce2c0ca0d73483b12cb72aa9609278e8a"}, + {file = "wrapt-1.14.1-cp37-cp37m-win32.whl", hash = "sha256:60db23fa423575eeb65ea430cee741acb7c26a1365d103f7b0f6ec412b893853"}, + {file = "wrapt-1.14.1-cp37-cp37m-win_amd64.whl", hash = "sha256:709fe01086a55cf79d20f741f39325018f4df051ef39fe921b1ebe780a66184c"}, + {file = "wrapt-1.14.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:8c0ce1e99116d5ab21355d8ebe53d9460366704ea38ae4d9f6933188f327b456"}, + {file = "wrapt-1.14.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:e3fb1677c720409d5f671e39bac6c9e0e422584e5f518bfd50aa4cbbea02433f"}, + {file = "wrapt-1.14.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:642c2e7a804fcf18c222e1060df25fc210b9c58db7c91416fb055897fc27e8cc"}, + {file = "wrapt-1.14.1-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7b7c050ae976e286906dd3f26009e117eb000fb2cf3533398c5ad9ccc86867b1"}, + {file = "wrapt-1.14.1-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ef3f72c9666bba2bab70d2a8b79f2c6d2c1a42a7f7e2b0ec83bb2f9e383950af"}, + {file = "wrapt-1.14.1-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:01c205616a89d09827986bc4e859bcabd64f5a0662a7fe95e0d359424e0e071b"}, + {file = "wrapt-1.14.1-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:5a0f54ce2c092aaf439813735584b9537cad479575a09892b8352fea5e988dc0"}, + {file = "wrapt-1.14.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:2cf71233a0ed05ccdabe209c606fe0bac7379fdcf687f39b944420d2a09fdb57"}, + {file = "wrapt-1.14.1-cp38-cp38-win32.whl", hash = "sha256:aa31fdcc33fef9eb2552cbcbfee7773d5a6792c137b359e82879c101e98584c5"}, + {file = "wrapt-1.14.1-cp38-cp38-win_amd64.whl", hash = "sha256:d1967f46ea8f2db647c786e78d8cc7e4313dbd1b0aca360592d8027b8508e24d"}, + {file = "wrapt-1.14.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:3232822c7d98d23895ccc443bbdf57c7412c5a65996c30442ebe6ed3df335383"}, + {file = "wrapt-1.14.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:988635d122aaf2bdcef9e795435662bcd65b02f4f4c1ae37fbee7401c440b3a7"}, + {file = "wrapt-1.14.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9cca3c2cdadb362116235fdbd411735de4328c61425b0aa9f872fd76d02c4e86"}, + {file = "wrapt-1.14.1-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d52a25136894c63de15a35bc0bdc5adb4b0e173b9c0d07a2be9d3ca64a332735"}, + {file = "wrapt-1.14.1-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:40e7bc81c9e2b2734ea4bc1aceb8a8f0ceaac7c5299bc5d69e37c44d9081d43b"}, + {file = "wrapt-1.14.1-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:b9b7a708dd92306328117d8c4b62e2194d00c365f18eff11a9b53c6f923b01e3"}, + {file = "wrapt-1.14.1-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:6a9a25751acb379b466ff6be78a315e2b439d4c94c1e99cb7266d40a537995d3"}, + {file = "wrapt-1.14.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:34aa51c45f28ba7f12accd624225e2b1e5a3a45206aa191f6f9aac931d9d56fe"}, + {file = "wrapt-1.14.1-cp39-cp39-win32.whl", hash = "sha256:dee0ce50c6a2dd9056c20db781e9c1cfd33e77d2d569f5d1d9321c641bb903d5"}, + {file = "wrapt-1.14.1-cp39-cp39-win_amd64.whl", hash = "sha256:dee60e1de1898bde3b238f18340eec6148986da0455d8ba7848d50470a7a32fb"}, + {file = "wrapt-1.14.1.tar.gz", hash = "sha256:380a85cf89e0e69b7cfbe2ea9f765f004ff419f34194018a6827ac0e3edfed4d"}, +] +xattr = [ + {file = "xattr-0.9.9-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:58a9fb4fd19b467e88f4b75b5243706caa57e312d3aee757b53b57c7fd0f4ba9"}, + {file = "xattr-0.9.9-cp27-cp27m-manylinux1_i686.whl", hash = "sha256:e71efca59705c7abde5b7f76323ebe00ed2977f10cba4204b9421dada036b5ca"}, + {file = "xattr-0.9.9-cp27-cp27m-manylinux1_x86_64.whl", hash = "sha256:1aad96b6603961c3d1ca1aaa8369b1a8d684a7b37357b2428087c286bf0e561c"}, + {file = "xattr-0.9.9-cp27-cp27m-manylinux2010_i686.whl", hash = "sha256:46cb74f98d31d9d70f975ec3e6554360a9bdcbb4b9fb50a69fabe54f9f928c97"}, + {file = "xattr-0.9.9-cp27-cp27m-manylinux2010_x86_64.whl", hash = "sha256:80c2db56058a687d7439be041f916cbeb2943fbe2623e53d5da721a4552d8991"}, + {file = "xattr-0.9.9-cp27-cp27mu-manylinux1_i686.whl", hash = "sha256:c360d1cc42e885b64d84f64de3c501dd7bce576248327ef583b4625ee63aa023"}, + {file = "xattr-0.9.9-cp27-cp27mu-manylinux1_x86_64.whl", hash = "sha256:debd87afe6bdf88c3689bde52eecf2b166388b13ef7388259d23223374db417d"}, + {file = "xattr-0.9.9-cp27-cp27mu-manylinux2010_i686.whl", hash = "sha256:4280c9f33a8678828f1bbc3d3dc8b823b5e4a113ee5ecb0fb98bff60cc2b9ad1"}, + {file = "xattr-0.9.9-cp27-cp27mu-manylinux2010_x86_64.whl", hash = "sha256:e0916ec1656d2071cd3139d1f52426825985d8ed076f981ef7f0bc13dfa8e96c"}, + {file = "xattr-0.9.9-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:a517916fbf2f58a3222bb2048fe1eeff4e23e07a4ce6228a27de004c80bf53ab"}, + {file = "xattr-0.9.9-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:e886c882b3b28c7a684c3e3daf46347da5428a46b88bc6d62c4867d574b90c54"}, + {file = "xattr-0.9.9-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:373e3d1fd9258438fc38d1438142d3659f36743f374a20457346ef26741ed441"}, + {file = "xattr-0.9.9-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1a7beeb54ca140273b2f6320bb98b701ec30628af2ebe4eb30f7051419eb4ef3"}, + {file = "xattr-0.9.9-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ef3ca29cdaae9c47c625d84bb6c9046f7275cccde0ea805caa23ca58d3671f3f"}, + {file = "xattr-0.9.9-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5c381d890931cd18b137ce3fb5c5f08b672c3c61e2e47b1a7442ee46e827abfe"}, + {file = "xattr-0.9.9-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:59c5783ccf57cf2700ce57d51a92134900ed26f6ab20d209f383fb898903fea6"}, + {file = "xattr-0.9.9-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:966b885b69d95362e2a12d39f84889cf857090e57263b5ac33409498aa00c160"}, + {file = "xattr-0.9.9-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:efaaf0cb1ea8e9febb7baad301ae8cc9ad7a96fdfc5c6399d165e7a19e3e61ce"}, + {file = "xattr-0.9.9-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:f19fa75ed1e9db86354efab29869cb2be6976d456bd7c89e67b118d5384a1d98"}, + {file = "xattr-0.9.9-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7ca28ad06828244b315214ee35388f57e81e90aac2ceac3f32e42ae394e31b9c"}, + {file = "xattr-0.9.9-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:532c7f1656dd2fe937116b9e210229f716d7fc7ac142f9cdace7da92266d32e8"}, + {file = "xattr-0.9.9-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:11c28033c17e98c67e0def9d6ebd415ad3c006a7bc3fee6bad79c5e52d0dff49"}, + {file = "xattr-0.9.9-cp36-cp36m-musllinux_1_1_aarch64.whl", hash = "sha256:473cabb30e544ea08c8c01c1ef18053147cdc8552d443ac97815e46fbb13c7d4"}, + {file = "xattr-0.9.9-cp36-cp36m-musllinux_1_1_i686.whl", hash = "sha256:c4a308522b444d090fbd66a385c9519b6b977818226921b0d2fc403667c93564"}, + {file = "xattr-0.9.9-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:82493434488aca72d88b5129dac8f212e7b8bdca7ceffe7bb977c850f2452e4e"}, + {file = "xattr-0.9.9-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:e41d289706c7e8940f4d08e865da6a8ae988123e40a44f9a97ddc09e67795d7d"}, + {file = "xattr-0.9.9-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ef08698e360cf43688dca3db3421b156b29948a714d5d089348073f463c11646"}, + {file = "xattr-0.9.9-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4eb10ac16ca8d534c0395425d52121e0c1981f808e1b3f577f6a5ec33d3853e4"}, + {file = "xattr-0.9.9-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5605fec07b0e964bd980cc70ec335b9eb1b7ac7c6f314c7c2d8f54b09104fe4c"}, + {file = "xattr-0.9.9-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:974e7d577ddb15e4552fb0ec10a4cfe09bdf6267365aa2b8394bb04637785aad"}, + {file = "xattr-0.9.9-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:ad6777de922c638bfa87a0d7faebc5722ddef04a1210b2a8909289b58b769af0"}, + {file = "xattr-0.9.9-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:3887e70873ebf0efbde32f9929ec1c7e45ec0013561743e2cc0406a91e51113b"}, + {file = "xattr-0.9.9-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:83caa8e93a45a0f25f91b92d9b45f490c87bff74f02555df6312efeba0dacc31"}, + {file = "xattr-0.9.9-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:e33ec0a1d913d946d1ab7509f37ee37306c45af735347f13b963df34ffe6e029"}, + {file = "xattr-0.9.9-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:263c58dca83372260c5c195e0b59959e38e1f107f0b7350de82e3db38479036c"}, + {file = "xattr-0.9.9-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:125dfb9905428162349d3b8b825d9a18280893f0cb0db2a2467d5ef253fa6ce2"}, + {file = "xattr-0.9.9-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e243524e0dde16d7a2e1b52512ad2c6964df2143dd1c79b820dcb4c6c0822c20"}, + {file = "xattr-0.9.9-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:01ec07d24a14406bdc6a123041c63a88e1c4a3f820e4a7d30f7609d57311b499"}, + {file = "xattr-0.9.9-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:85c1df5f1d209345ea96de137419e886a27bb55076b3ae01faacf35aafcf3a61"}, + {file = "xattr-0.9.9-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:ca74d3eff92d6dc16e271fbad9cbab547fb9a0c983189c4031c3ff3d150dd871"}, + {file = "xattr-0.9.9-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:7d17505e49ac70c0e71939c5aac96417a863583fb30a2d6304d5ac881230548f"}, + {file = "xattr-0.9.9-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:1ae47a6398d3c04623fa386a4aa2f66e5cd3cdb1a7e69d1bfaeb8c73983bf271"}, + {file = "xattr-0.9.9-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:809e2537d0aff9fca97dacf3245cbbaf711bbced5d1b0235a8d1906b04e26114"}, + {file = "xattr-0.9.9-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:de3af84364f06d67b3662ccf7c1a73e1d389d8d274394e952651e7bf1bbd2718"}, + {file = "xattr-0.9.9-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3b62cdad232d2d2dedd39b543701db8e3883444ec0d57ce3fab8f75e5f8b0301"}, + {file = "xattr-0.9.9-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6b11d2eda397d47f7075743409683c233519ca52aa1dac109b413a4d8c15b740"}, + {file = "xattr-0.9.9-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:661c0a939aefdf071887121f534bb10588d69c7b2dfca5c486af2fc81a0786e8"}, + {file = "xattr-0.9.9-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:5db7c2db320a8d5264d437d71f1eb7270a7e4a6545296e7766161d17752590b7"}, + {file = "xattr-0.9.9-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:83203e60cbaca9536d297e5039b285a600ff84e6e9e8536fe2d521825eeeb437"}, + {file = "xattr-0.9.9-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:42bfb4e4da06477e739770ac6942edbdc71e9fc3b497b67db5fba712fa8109c2"}, + {file = "xattr-0.9.9-pp37-pypy37_pp73-macosx_10_9_x86_64.whl", hash = "sha256:67047d04d1c56ad4f0f5886085e91b0077238ab3faaec6492c3c21920c6566eb"}, + {file = "xattr-0.9.9-pp37-pypy37_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:885782bc82ded1a3f684d54a1af259ae9fcc347fa54b5a05b8aad82b8a42044c"}, + {file = "xattr-0.9.9-pp37-pypy37_pp73-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5bc84ccec618b5aa089e7cee8b07fcc92d4069aac4053da604c8143a0d6b1381"}, + {file = "xattr-0.9.9-pp37-pypy37_pp73-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:baeff3e5dda8ea7e9424cfaee51829f46afe3836c30d02f343f9049c685681ca"}, + {file = "xattr-0.9.9.tar.gz", hash = "sha256:09cb7e1efb3aa1b4991d6be4eb25b73dc518b4fe894f0915f5b0dcede972f346"}, +] +yarl = [ + {file = "yarl-1.8.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:abc06b97407868ef38f3d172762f4069323de52f2b70d133d096a48d72215d28"}, + {file = "yarl-1.8.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:07b21e274de4c637f3e3b7104694e53260b5fc10d51fb3ec5fed1da8e0f754e3"}, + {file = "yarl-1.8.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:9de955d98e02fab288c7718662afb33aab64212ecb368c5dc866d9a57bf48880"}, + {file = "yarl-1.8.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7ec362167e2c9fd178f82f252b6d97669d7245695dc057ee182118042026da40"}, + {file = "yarl-1.8.1-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:20df6ff4089bc86e4a66e3b1380460f864df3dd9dccaf88d6b3385d24405893b"}, + {file = "yarl-1.8.1-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:5999c4662631cb798496535afbd837a102859568adc67d75d2045e31ec3ac497"}, + {file = "yarl-1.8.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ed19b74e81b10b592084a5ad1e70f845f0aacb57577018d31de064e71ffa267a"}, + {file = "yarl-1.8.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1e4808f996ca39a6463f45182e2af2fae55e2560be586d447ce8016f389f626f"}, + {file = "yarl-1.8.1-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:2d800b9c2eaf0684c08be5f50e52bfa2aa920e7163c2ea43f4f431e829b4f0fd"}, + {file = "yarl-1.8.1-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:6628d750041550c5d9da50bb40b5cf28a2e63b9388bac10fedd4f19236ef4957"}, + {file = "yarl-1.8.1-cp310-cp310-musllinux_1_1_ppc64le.whl", hash = "sha256:f5af52738e225fcc526ae64071b7e5342abe03f42e0e8918227b38c9aa711e28"}, + {file = "yarl-1.8.1-cp310-cp310-musllinux_1_1_s390x.whl", hash = "sha256:76577f13333b4fe345c3704811ac7509b31499132ff0181f25ee26619de2c843"}, + {file = "yarl-1.8.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:0c03f456522d1ec815893d85fccb5def01ffaa74c1b16ff30f8aaa03eb21e453"}, + {file = "yarl-1.8.1-cp310-cp310-win32.whl", hash = "sha256:ea30a42dc94d42f2ba4d0f7c0ffb4f4f9baa1b23045910c0c32df9c9902cb272"}, + {file = "yarl-1.8.1-cp310-cp310-win_amd64.whl", hash = "sha256:9130ddf1ae9978abe63808b6b60a897e41fccb834408cde79522feb37fb72fb0"}, + {file = "yarl-1.8.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:0ab5a138211c1c366404d912824bdcf5545ccba5b3ff52c42c4af4cbdc2c5035"}, + {file = "yarl-1.8.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a0fb2cb4204ddb456a8e32381f9a90000429489a25f64e817e6ff94879d432fc"}, + {file = "yarl-1.8.1-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:85cba594433915d5c9a0d14b24cfba0339f57a2fff203a5d4fd070e593307d0b"}, + {file = "yarl-1.8.1-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:1ca7e596c55bd675432b11320b4eacc62310c2145d6801a1f8e9ad160685a231"}, + {file = "yarl-1.8.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d0f77539733e0ec2475ddcd4e26777d08996f8cd55d2aef82ec4d3896687abda"}, + {file = "yarl-1.8.1-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:29e256649f42771829974e742061c3501cc50cf16e63f91ed8d1bf98242e5507"}, + {file = "yarl-1.8.1-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:7fce6cbc6c170ede0221cc8c91b285f7f3c8b9fe28283b51885ff621bbe0f8ee"}, + {file = "yarl-1.8.1-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:59ddd85a1214862ce7c7c66457f05543b6a275b70a65de366030d56159a979f0"}, + {file = "yarl-1.8.1-cp37-cp37m-musllinux_1_1_ppc64le.whl", hash = "sha256:12768232751689c1a89b0376a96a32bc7633c08da45ad985d0c49ede691f5c0d"}, + {file = "yarl-1.8.1-cp37-cp37m-musllinux_1_1_s390x.whl", hash = "sha256:b19255dde4b4f4c32e012038f2c169bb72e7f081552bea4641cab4d88bc409dd"}, + {file = "yarl-1.8.1-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:6c8148e0b52bf9535c40c48faebb00cb294ee577ca069d21bd5c48d302a83780"}, + {file = "yarl-1.8.1-cp37-cp37m-win32.whl", hash = "sha256:de839c3a1826a909fdbfe05f6fe2167c4ab033f1133757b5936efe2f84904c07"}, + {file = "yarl-1.8.1-cp37-cp37m-win_amd64.whl", hash = "sha256:dd032e8422a52e5a4860e062eb84ac94ea08861d334a4bcaf142a63ce8ad4802"}, + {file = "yarl-1.8.1-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:19cd801d6f983918a3f3a39f3a45b553c015c5aac92ccd1fac619bd74beece4a"}, + {file = "yarl-1.8.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:6347f1a58e658b97b0a0d1ff7658a03cb79bdbda0331603bed24dd7054a6dea1"}, + {file = "yarl-1.8.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:7c0da7e44d0c9108d8b98469338705e07f4bb7dab96dbd8fa4e91b337db42548"}, + {file = "yarl-1.8.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5587bba41399854703212b87071c6d8638fa6e61656385875f8c6dff92b2e461"}, + {file = "yarl-1.8.1-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:31a9a04ecccd6b03e2b0e12e82131f1488dea5555a13a4d32f064e22a6003cfe"}, + {file = "yarl-1.8.1-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:205904cffd69ae972a1707a1bd3ea7cded594b1d773a0ce66714edf17833cdae"}, + {file = "yarl-1.8.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ea513a25976d21733bff523e0ca836ef1679630ef4ad22d46987d04b372d57fc"}, + {file = "yarl-1.8.1-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d0b51530877d3ad7a8d47b2fff0c8df3b8f3b8deddf057379ba50b13df2a5eae"}, + {file = "yarl-1.8.1-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:d2b8f245dad9e331540c350285910b20dd913dc86d4ee410c11d48523c4fd546"}, + {file = "yarl-1.8.1-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:ab2a60d57ca88e1d4ca34a10e9fb4ab2ac5ad315543351de3a612bbb0560bead"}, + {file = "yarl-1.8.1-cp38-cp38-musllinux_1_1_ppc64le.whl", hash = "sha256:449c957ffc6bc2309e1fbe67ab7d2c1efca89d3f4912baeb8ead207bb3cc1cd4"}, + {file = "yarl-1.8.1-cp38-cp38-musllinux_1_1_s390x.whl", hash = "sha256:a165442348c211b5dea67c0206fc61366212d7082ba8118c8c5c1c853ea4d82e"}, + {file = "yarl-1.8.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:b3ded839a5c5608eec8b6f9ae9a62cb22cd037ea97c627f38ae0841a48f09eae"}, + {file = "yarl-1.8.1-cp38-cp38-win32.whl", hash = "sha256:c1445a0c562ed561d06d8cbc5c8916c6008a31c60bc3655cdd2de1d3bf5174a0"}, + {file = "yarl-1.8.1-cp38-cp38-win_amd64.whl", hash = "sha256:56c11efb0a89700987d05597b08a1efcd78d74c52febe530126785e1b1a285f4"}, + {file = "yarl-1.8.1-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:e80ed5a9939ceb6fda42811542f31c8602be336b1fb977bccb012e83da7e4936"}, + {file = "yarl-1.8.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:6afb336e23a793cd3b6476c30f030a0d4c7539cd81649683b5e0c1b0ab0bf350"}, + {file = "yarl-1.8.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:4c322cbaa4ed78a8aac89b2174a6df398faf50e5fc12c4c191c40c59d5e28357"}, + {file = "yarl-1.8.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:fae37373155f5ef9b403ab48af5136ae9851151f7aacd9926251ab26b953118b"}, + {file = "yarl-1.8.1-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5395da939ffa959974577eff2cbfc24b004a2fb6c346918f39966a5786874e54"}, + {file = "yarl-1.8.1-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:076eede537ab978b605f41db79a56cad2e7efeea2aa6e0fa8f05a26c24a034fb"}, + {file = "yarl-1.8.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3d1a50e461615747dd93c099f297c1994d472b0f4d2db8a64e55b1edf704ec1c"}, + {file = "yarl-1.8.1-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7de89c8456525650ffa2bb56a3eee6af891e98f498babd43ae307bd42dca98f6"}, + {file = "yarl-1.8.1-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:4a88510731cd8d4befaba5fbd734a7dd914de5ab8132a5b3dde0bbd6c9476c64"}, + {file = "yarl-1.8.1-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:2d93a049d29df172f48bcb09acf9226318e712ce67374f893b460b42cc1380ae"}, + {file = "yarl-1.8.1-cp39-cp39-musllinux_1_1_ppc64le.whl", hash = "sha256:21ac44b763e0eec15746a3d440f5e09ad2ecc8b5f6dcd3ea8cb4773d6d4703e3"}, + {file = "yarl-1.8.1-cp39-cp39-musllinux_1_1_s390x.whl", hash = "sha256:d0272228fabe78ce00a3365ffffd6f643f57a91043e119c289aaba202f4095b0"}, + {file = "yarl-1.8.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:99449cd5366fe4608e7226c6cae80873296dfa0cde45d9b498fefa1de315a09e"}, + {file = "yarl-1.8.1-cp39-cp39-win32.whl", hash = "sha256:8b0af1cf36b93cee99a31a545fe91d08223e64390c5ecc5e94c39511832a4bb6"}, + {file = "yarl-1.8.1-cp39-cp39-win_amd64.whl", hash = "sha256:de49d77e968de6626ba7ef4472323f9d2e5a56c1d85b7c0e2a190b2173d3b9be"}, + {file = "yarl-1.8.1.tar.gz", hash = "sha256:af887845b8c2e060eb5605ff72b6f2dd2aab7a761379373fd89d314f4752abbf"}, +] +zerorpc = [] +zipp = [ + {file = "zipp-3.9.0-py3-none-any.whl", hash = "sha256:972cfa31bc2fedd3fa838a51e9bc7e64b7fb725a8c00e7431554311f180e9980"}, + {file = "zipp-3.9.0.tar.gz", hash = "sha256:3a7af91c3db40ec72dd9d154ae18e008c69efe8ca88dde4f9a731bb82fe2f9eb"}, +] +zope-event = [ + {file = "zope.event-4.5.0-py2.py3-none-any.whl", hash = "sha256:2666401939cdaa5f4e0c08cf7f20c9b21423b95e88f4675b1443973bdb080c42"}, + {file = "zope.event-4.5.0.tar.gz", hash = "sha256:5e76517f5b9b119acf37ca8819781db6c16ea433f7e2062c4afc2b6fbedb1330"}, +] +zope-interface = [ + {file = "zope.interface-5.5.0-cp27-cp27m-macosx_10_14_x86_64.whl", hash = "sha256:2cb3003941f5f4fa577479ac6d5db2b940acb600096dd9ea9bf07007f5cab46f"}, + {file = "zope.interface-5.5.0-cp27-cp27m-win32.whl", hash = "sha256:8c791f4c203ccdbcda588ea4c8a6e4353e10435ea48ddd3d8734a26fe9714cba"}, + {file = "zope.interface-5.5.0-cp27-cp27m-win_amd64.whl", hash = "sha256:3eedf3d04179774d750e8bb4463e6da350956a50ed44d7b86098e452d7ec385e"}, + {file = "zope.interface-5.5.0-cp310-cp310-macosx_11_0_x86_64.whl", hash = "sha256:58a66c2020a347973168a4a9d64317bac52f9fdfd3e6b80b252be30da881a64e"}, + {file = "zope.interface-5.5.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:da7912ae76e1df6a1fb841b619110b1be4c86dfb36699d7fd2f177105cdea885"}, + {file = "zope.interface-5.5.0-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:423c074e404f13e6fa07f4454f47fdbb38d358be22945bc812b94289d9142374"}, + {file = "zope.interface-5.5.0-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:7bdcec93f152e0e1942102537eed7b166d6661ae57835b20a52a2a3d6a3e1bf3"}, + {file = "zope.interface-5.5.0-cp310-cp310-win32.whl", hash = "sha256:03f5ae315db0d0de668125d983e2a819a554f3fdb2d53b7e934e3eb3c3c7375d"}, + {file = "zope.interface-5.5.0-cp310-cp310-win_amd64.whl", hash = "sha256:8b9f153208d74ccfa25449a0c6cb756ab792ce0dc99d9d771d935f039b38740c"}, + {file = "zope.interface-5.5.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:aeac590cce44e68ee8ad0b8ecf4d7bf15801f102d564ca1b0eb1f12f584ee656"}, + {file = "zope.interface-5.5.0-cp35-cp35m-win32.whl", hash = "sha256:7d9ec1e6694af39b687045712a8ad14ddcb568670d5eb1b66b48b98b9312afba"}, + {file = "zope.interface-5.5.0-cp35-cp35m-win_amd64.whl", hash = "sha256:d18fb0f6c8169d26044128a2e7d3c39377a8a151c564e87b875d379dbafd3930"}, + {file = "zope.interface-5.5.0-cp36-cp36m-macosx_10_14_x86_64.whl", hash = "sha256:0eb2b3e84f48dd9cfc8621c80fba905d7e228615c67f76c7df7c716065669bb6"}, + {file = "zope.interface-5.5.0-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:df6593e150d13cfcce69b0aec5df7bc248cb91e4258a7374c129bb6d56b4e5ca"}, + {file = "zope.interface-5.5.0-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:9dc4493aa3d87591e3d2bf1453e25b98038c839ca8e499df3d7106631b66fe83"}, + {file = "zope.interface-5.5.0-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:5c6023ae7defd052cf76986ce77922177b0c2f3913bea31b5b28fbdf6cb7099e"}, + {file = "zope.interface-5.5.0-cp36-cp36m-win32.whl", hash = "sha256:a69c28d85bb7cf557751a5214cb3f657b2b035c8c96d71080c1253b75b79b69b"}, + {file = "zope.interface-5.5.0-cp36-cp36m-win_amd64.whl", hash = "sha256:85dd6dd9aaae7a176948d8bb62e20e2968588fd787c29c5d0d964ab475168d3d"}, + {file = "zope.interface-5.5.0-cp37-cp37m-macosx_10_15_x86_64.whl", hash = "sha256:970661ece2029915b8f7f70892e88404340fbdefd64728380cad41c8dce14ff4"}, + {file = "zope.interface-5.5.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1e3495bb0cdcea212154e558082c256f11b18031f05193ae2fb85d048848db14"}, + {file = "zope.interface-5.5.0-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:3f68404edb1a4fb6aa8a94675521ca26c83ebbdbb90e894f749ae0dc4ca98418"}, + {file = "zope.interface-5.5.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:740f3c1b44380658777669bcc42f650f5348e53797f2cee0d93dc9b0f9d7cc69"}, + {file = "zope.interface-5.5.0-cp37-cp37m-win32.whl", hash = "sha256:006f8dd81fae28027fc28ada214855166712bf4f0bfbc5a8788f9b70982b9437"}, + {file = "zope.interface-5.5.0-cp37-cp37m-win_amd64.whl", hash = "sha256:43490ad65d4c64e45a30e51a2beb7a6b63e1ff395302ad22392224eb618476d6"}, + {file = "zope.interface-5.5.0-cp38-cp38-macosx_10_15_x86_64.whl", hash = "sha256:f70726b60009433111fe9928f5d89cbb18962411d33c45fb19eb81b9bbd26fcd"}, + {file = "zope.interface-5.5.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cfa614d049667bed1c737435c609c0956c5dc0dbafdc1145ee7935e4658582cb"}, + {file = "zope.interface-5.5.0-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:58a975f89e4584d0223ab813c5ba4787064c68feef4b30d600f5e01de90ae9ce"}, + {file = "zope.interface-5.5.0-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:37ec9ade9902f412cc7e7a32d71f79dec3035bad9bd0170226252eed88763c48"}, + {file = "zope.interface-5.5.0-cp38-cp38-win32.whl", hash = "sha256:be11fce0e6af6c0e8d93c10ef17b25aa7c4acb7ec644bff2596c0d639c49e20f"}, + {file = "zope.interface-5.5.0-cp38-cp38-win_amd64.whl", hash = "sha256:cbbf83914b9a883ab324f728de869f4e406e0cbcd92df7e0a88decf6f9ab7d5a"}, + {file = "zope.interface-5.5.0-cp39-cp39-macosx_10_15_x86_64.whl", hash = "sha256:26c1456520fdcafecc5765bec4783eeafd2e893eabc636908f50ee31fe5c738c"}, + {file = "zope.interface-5.5.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:47ff078734a1030c48103422a99e71a7662d20258c00306546441adf689416f7"}, + {file = "zope.interface-5.5.0-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:687cab7f9ae18d2c146f315d0ca81e5ffe89a139b88277afa70d52f632515854"}, + {file = "zope.interface-5.5.0-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:d80f6236b57a95eb19d5e47eb68d0296119e1eff6deaa2971ab8abe3af918420"}, + {file = "zope.interface-5.5.0-cp39-cp39-win32.whl", hash = "sha256:9cdc4e898d3b1547d018829fd4a9f403e52e51bba24be0fbfa37f3174e1ef797"}, + {file = "zope.interface-5.5.0-cp39-cp39-win_amd64.whl", hash = "sha256:6566b3d2657e7609cd8751bcb1eab1202b1692a7af223035a5887d64bb3a2f3b"}, + {file = "zope.interface-5.5.0.tar.gz", hash = "sha256:700ebf9662cf8df70e2f0cb4988e078c53f65ee3eefd5c9d80cf988c4175c8e3"}, +] diff --git a/pyextra/acados_template/acados_layout.json b/pyextra/acados_template/acados_layout.json index 16fd452337..c9f0b90c73 100644 --- a/pyextra/acados_template/acados_layout.json +++ b/pyextra/acados_template/acados_layout.json @@ -5,6 +5,9 @@ "acados_include_path": [ "str" ], + "cython_include_dirs": [ + "str" + ], "model": { "name" : [ "str" @@ -23,7 +26,15 @@ ], "dyn_disc_fun" : [ "str" - ] + ], + "gnsf" : { + "nontrivial_f_LO": [ + "int" + ], + "purely_linear": [ + "int" + ] + } }, "parameter_values": [ "ndarray", @@ -657,6 +668,9 @@ "hessian_approx": [ "str" ], + "hpipm_mode": [ + "str" + ], "regularize_method": [ "str" ], @@ -693,6 +707,18 @@ "alpha_reduction": [ "float" ], + "line_search_use_sufficient_descent": [ + "int" + ], + "globalization_use_SOC": [ + "int" + ], + "full_step_dual": [ + "int" + ], + "eps_sufficient_descent": [ + "float" + ], "sim_method_num_stages": [ "ndarray", [ diff --git a/pyextra/acados_template/acados_model.py b/pyextra/acados_template/acados_model.py index 4871a2c0d5..e292cc7477 100644 --- a/pyextra/acados_template/acados_model.py +++ b/pyextra/acados_template/acados_model.py @@ -78,6 +78,13 @@ class AcadosModel(): self.dyn_disc_fun_jac = None #: name of function discrete dyanamics + jacobian; Default: :code:`None` self.dyn_disc_fun = None #: name of function discrete dyanamics; Default: :code:`None` + # for GNSF models + self.gnsf = {'nontrivial_f_LO': 1, 'purely_linear': 0} + """ + dictionary containing information on GNSF structure needed when rendering templates. + Contains integers `nontrivial_f_LO`, `purely_linear`. + """ + ## for OCP # constraints self.con_h_expr = None #: CasADi expression for the constraint :math:`h`; Default: :code:`None` diff --git a/pyextra/acados_template/acados_ocp.py b/pyextra/acados_template/acados_ocp.py index 198ab033dc..80970239eb 100644 --- a/pyextra/acados_template/acados_ocp.py +++ b/pyextra/acados_template/acados_ocp.py @@ -270,28 +270,28 @@ class AcadosOcpDims: @nx.setter def nx(self, nx): - if type(nx) == int and nx > 0: + if isinstance(nx, int) and nx > 0: self.__nx = nx else: raise Exception('Invalid nx value, expected positive integer. Exiting.') @nz.setter def nz(self, nz): - if type(nz) == int and nz > -1: + if isinstance(nz, int) and nz > -1: self.__nz = nz else: raise Exception('Invalid nz value, expected nonnegative integer. Exiting.') @nu.setter def nu(self, nu): - if type(nu) == int and nu > -1: + if isinstance(nu, int) and nu > -1: self.__nu = nu else: raise Exception('Invalid nu value, expected nonnegative integer. Exiting.') @np.setter def np(self, np): - if type(np) == int and np > -1: + if isinstance(np, int) and np > -1: self.__np = np else: raise Exception('Invalid np value, expected nonnegative integer. Exiting.') @@ -312,49 +312,49 @@ class AcadosOcpDims: @ny_e.setter def ny_e(self, ny_e): - if type(ny_e) == int and ny_e > -1: + if isinstance(ny_e, int) and ny_e > -1: self.__ny_e = ny_e else: raise Exception('Invalid ny_e value, expected nonnegative integer. Exiting.') @nr.setter def nr(self, nr): - if type(nr) == int and nr > -1: + if isinstance(nr, int) and nr > -1: self.__nr = nr else: raise Exception('Invalid nr value, expected nonnegative integer. Exiting.') @nr_e.setter def nr_e(self, nr_e): - if type(nr_e) == int and nr_e > -1: + if isinstance(nr_e, int) and nr_e > -1: self.__nr_e = nr_e else: raise Exception('Invalid nr_e value, expected nonnegative integer. Exiting.') @nh.setter def nh(self, nh): - if type(nh) == int and nh > -1: + if isinstance(nh, int) and nh > -1: self.__nh = nh else: raise Exception('Invalid nh value, expected nonnegative integer. Exiting.') @nh_e.setter def nh_e(self, nh_e): - if type(nh_e) == int and nh_e > -1: + if isinstance(nh_e, int) and nh_e > -1: self.__nh_e = nh_e else: raise Exception('Invalid nh_e value, expected nonnegative integer. Exiting.') @nphi.setter def nphi(self, nphi): - if type(nphi) == int and nphi > -1: + if isinstance(nphi, int) and nphi > -1: self.__nphi = nphi else: raise Exception('Invalid nphi value, expected nonnegative integer. Exiting.') @nphi_e.setter def nphi_e(self, nphi_e): - if type(nphi_e) == int and nphi_e > -1: + if isinstance(nphi_e, int) and nphi_e > -1: self.__nphi_e = nphi_e else: raise Exception('Invalid nphi_e value, expected nonnegative integer. Exiting.') @@ -375,42 +375,42 @@ class AcadosOcpDims: @nbx_0.setter def nbx_0(self, nbx_0): - if type(nbx_0) == int and nbx_0 > -1: + if isinstance(nbx_0, int) and nbx_0 > -1: self.__nbx_0 = nbx_0 else: raise Exception('Invalid nbx_0 value, expected nonnegative integer. Exiting.') @nbx_e.setter def nbx_e(self, nbx_e): - if type(nbx_e) == int and nbx_e > -1: + if isinstance(nbx_e, int) and nbx_e > -1: self.__nbx_e = nbx_e else: raise Exception('Invalid nbx_e value, expected nonnegative integer. Exiting.') @nbu.setter def nbu(self, nbu): - if type(nbu) == int and nbu > -1: + if isinstance(nbu, int) and nbu > -1: self.__nbu = nbu else: raise Exception('Invalid nbu value, expected nonnegative integer. Exiting.') @nsbx.setter def nsbx(self, nsbx): - if type(nsbx) == int and nsbx > -1: + if isinstance(nsbx, int) and nsbx > -1: self.__nsbx = nsbx else: raise Exception('Invalid nsbx value, expected nonnegative integer. Exiting.') @nsbx_e.setter def nsbx_e(self, nsbx_e): - if type(nsbx_e) == int and nsbx_e > -1: + if isinstance(nsbx_e, int) and nsbx_e > -1: self.__nsbx_e = nsbx_e else: raise Exception('Invalid nsbx_e value, expected nonnegative integer. Exiting.') @nsbu.setter def nsbu(self, nsbu): - if type(nsbu) == int and nsbu > -1: + if isinstance(nsbu, int) and nsbu > -1: self.__nsbu = nsbu else: raise Exception('Invalid nsbu value, expected nonnegative integer. Exiting.') @@ -1592,14 +1592,14 @@ class AcadosOcpConstraints: # initial x @lbx_0.setter def lbx_0(self, lbx_0): - if type(lbx_0) == np.ndarray: + if isinstance(lbx_0, np.ndarray): self.__lbx_0 = lbx_0 else: raise Exception('Invalid lbx_0 value. Exiting.') @ubx_0.setter def ubx_0(self, ubx_0): - if type(ubx_0) == np.ndarray: + if isinstance(ubx_0, np.ndarray): self.__ubx_0 = ubx_0 else: raise Exception('Invalid ubx_0 value. Exiting.') @@ -1613,7 +1613,7 @@ class AcadosOcpConstraints: @Jbx_0.setter def Jbx_0(self, Jbx_0): - if type(Jbx_0) == np.ndarray: + if isinstance(Jbx_0, np.ndarray): self.__idxbx_0 = J_to_idx(Jbx_0) else: raise Exception('Invalid Jbx_0 value. Exiting.') @@ -1639,28 +1639,28 @@ class AcadosOcpConstraints: # bounds on x @lbx.setter def lbx(self, lbx): - if type(lbx) == np.ndarray: + if isinstance(lbx, np.ndarray): self.__lbx = lbx else: raise Exception('Invalid lbx value. Exiting.') @ubx.setter def ubx(self, ubx): - if type(ubx) == np.ndarray: + if isinstance(ubx, np.ndarray): self.__ubx = ubx else: raise Exception('Invalid ubx value. Exiting.') @idxbx.setter def idxbx(self, idxbx): - if type(idxbx) == np.ndarray: + if isinstance(idxbx, np.ndarray): self.__idxbx = idxbx else: raise Exception('Invalid idxbx value. Exiting.') @Jbx.setter def Jbx(self, Jbx): - if type(Jbx) == np.ndarray: + if isinstance(Jbx, np.ndarray): self.__idxbx = J_to_idx(Jbx) else: raise Exception('Invalid Jbx value. Exiting.') @@ -1668,28 +1668,28 @@ class AcadosOcpConstraints: # bounds on u @lbu.setter def lbu(self, lbu): - if type(lbu) == np.ndarray: + if isinstance(lbu, np.ndarray): self.__lbu = lbu else: raise Exception('Invalid lbu value. Exiting.') @ubu.setter def ubu(self, ubu): - if type(ubu) == np.ndarray: + if isinstance(ubu, np.ndarray): self.__ubu = ubu else: raise Exception('Invalid ubu value. Exiting.') @idxbu.setter def idxbu(self, idxbu): - if type(idxbu) == np.ndarray: + if isinstance(idxbu, np.ndarray): self.__idxbu = idxbu else: raise Exception('Invalid idxbu value. Exiting.') @Jbu.setter def Jbu(self, Jbu): - if type(Jbu) == np.ndarray: + if isinstance(Jbu, np.ndarray): self.__idxbu = J_to_idx(Jbu) else: raise Exception('Invalid Jbu value. Exiting.') @@ -1697,28 +1697,28 @@ class AcadosOcpConstraints: # bounds on x at shooting node N @lbx_e.setter def lbx_e(self, lbx_e): - if type(lbx_e) == np.ndarray: + if isinstance(lbx_e, np.ndarray): self.__lbx_e = lbx_e else: raise Exception('Invalid lbx_e value. Exiting.') @ubx_e.setter def ubx_e(self, ubx_e): - if type(ubx_e) == np.ndarray: + if isinstance(ubx_e, np.ndarray): self.__ubx_e = ubx_e else: raise Exception('Invalid ubx_e value. Exiting.') @idxbx_e.setter def idxbx_e(self, idxbx_e): - if type(idxbx_e) == np.ndarray: + if isinstance(idxbx_e, np.ndarray): self.__idxbx_e = idxbx_e else: raise Exception('Invalid idxbx_e value. Exiting.') @Jbx_e.setter def Jbx_e(self, Jbx_e): - if type(Jbx_e) == np.ndarray: + if isinstance(Jbx_e, np.ndarray): self.__idxbx_e = J_to_idx(Jbx_e) else: raise Exception('Invalid Jbx_e value. Exiting.') @@ -1742,14 +1742,14 @@ class AcadosOcpConstraints: @lg.setter def lg(self, lg): - if type(lg) == np.ndarray: + if isinstance(lg, np.ndarray): self.__lg = lg else: raise Exception('Invalid lg value. Exiting.') @ug.setter def ug(self, ug): - if type(ug) == np.ndarray: + if isinstance(ug, np.ndarray): self.__ug = ug else: raise Exception('Invalid ug value. Exiting.') @@ -1765,14 +1765,14 @@ class AcadosOcpConstraints: @lg_e.setter def lg_e(self, lg_e): - if type(lg_e) == np.ndarray: + if isinstance(lg_e, np.ndarray): self.__lg_e = lg_e else: raise Exception('Invalid lg_e value. Exiting.') @ug_e.setter def ug_e(self, ug_e): - if type(ug_e) == np.ndarray: + if isinstance(ug_e, np.ndarray): self.__ug_e = ug_e else: raise Exception('Invalid ug_e value. Exiting.') @@ -1780,14 +1780,14 @@ class AcadosOcpConstraints: # nonlinear constraints @lh.setter def lh(self, lh): - if type(lh) == np.ndarray: + if isinstance(lh, np.ndarray): self.__lh = lh else: raise Exception('Invalid lh value. Exiting.') @uh.setter def uh(self, uh): - if type(uh) == np.ndarray: + if isinstance(uh, np.ndarray): self.__uh = uh else: raise Exception('Invalid uh value. Exiting.') @@ -1795,14 +1795,14 @@ class AcadosOcpConstraints: # convex-over-nonlinear constraints @lphi.setter def lphi(self, lphi): - if type(lphi) == np.ndarray: + if isinstance(lphi, np.ndarray): self.__lphi = lphi else: raise Exception('Invalid lphi value. Exiting.') @uphi.setter def uphi(self, uphi): - if type(uphi) == np.ndarray: + if isinstance(uphi, np.ndarray): self.__uphi = uphi else: raise Exception('Invalid uphi value. Exiting.') @@ -1810,14 +1810,14 @@ class AcadosOcpConstraints: # nonlinear constraints at shooting node N @lh_e.setter def lh_e(self, lh_e): - if type(lh_e) == np.ndarray: + if isinstance(lh_e, np.ndarray): self.__lh_e = lh_e else: raise Exception('Invalid lh_e value. Exiting.') @uh_e.setter def uh_e(self, uh_e): - if type(uh_e) == np.ndarray: + if isinstance(uh_e, np.ndarray): self.__uh_e = uh_e else: raise Exception('Invalid uh_e value. Exiting.') @@ -1825,14 +1825,14 @@ class AcadosOcpConstraints: # convex-over-nonlinear constraints at shooting node N @lphi_e.setter def lphi_e(self, lphi_e): - if type(lphi_e) == np.ndarray: + if isinstance(lphi_e, np.ndarray): self.__lphi_e = lphi_e else: raise Exception('Invalid lphi_e value. Exiting.') @uphi_e.setter def uphi_e(self, uphi_e): - if type(uphi_e) == np.ndarray: + if isinstance(uphi_e, np.ndarray): self.__uphi_e = uphi_e else: raise Exception('Invalid uphi_e value. Exiting.') @@ -1841,21 +1841,21 @@ class AcadosOcpConstraints: # soft bounds on x @lsbx.setter def lsbx(self, lsbx): - if type(lsbx) == np.ndarray: + if isinstance(lsbx, np.ndarray): self.__lsbx = lsbx else: raise Exception('Invalid lsbx value. Exiting.') @usbx.setter def usbx(self, usbx): - if type(usbx) == np.ndarray: + if isinstance(usbx, np.ndarray): self.__usbx = usbx else: raise Exception('Invalid usbx value. Exiting.') @idxsbx.setter def idxsbx(self, idxsbx): - if type(idxsbx) == np.ndarray: + if isinstance(idxsbx, np.ndarray): self.__idxsbx = idxsbx else: raise Exception('Invalid idxsbx value. Exiting.') @@ -1870,28 +1870,28 @@ class AcadosOcpConstraints: # soft bounds on u @lsbu.setter def lsbu(self, lsbu): - if type(lsbu) == np.ndarray: + if isinstance(lsbu, np.ndarray): self.__lsbu = lsbu else: raise Exception('Invalid lsbu value. Exiting.') @usbu.setter def usbu(self, usbu): - if type(usbu) == np.ndarray: + if isinstance(usbu, np.ndarray): self.__usbu = usbu else: raise Exception('Invalid usbu value. Exiting.') @idxsbu.setter def idxsbu(self, idxsbu): - if type(idxsbu) == np.ndarray: + if isinstance(idxsbu, np.ndarray): self.__idxsbu = idxsbu else: raise Exception('Invalid idxsbu value. Exiting.') @Jsbu.setter def Jsbu(self, Jsbu): - if type(Jsbu) == np.ndarray: + if isinstance(Jsbu, np.ndarray): self.__idxsbu = J_to_idx_slack(Jsbu) else: raise Exception('Invalid Jsbu value. Exiting.') @@ -1899,28 +1899,28 @@ class AcadosOcpConstraints: # soft bounds on x at shooting node N @lsbx_e.setter def lsbx_e(self, lsbx_e): - if type(lsbx_e) == np.ndarray: + if isinstance(lsbx_e, np.ndarray): self.__lsbx_e = lsbx_e else: raise Exception('Invalid lsbx_e value. Exiting.') @usbx_e.setter def usbx_e(self, usbx_e): - if type(usbx_e) == np.ndarray: + if isinstance(usbx_e, np.ndarray): self.__usbx_e = usbx_e else: raise Exception('Invalid usbx_e value. Exiting.') @idxsbx_e.setter def idxsbx_e(self, idxsbx_e): - if type(idxsbx_e) == np.ndarray: + if isinstance(idxsbx_e, np.ndarray): self.__idxsbx_e = idxsbx_e else: raise Exception('Invalid idxsbx_e value. Exiting.') @Jsbx_e.setter def Jsbx_e(self, Jsbx_e): - if type(Jsbx_e) == np.ndarray: + if isinstance(Jsbx_e, np.ndarray): self.__idxsbx_e = J_to_idx_slack(Jsbx_e) else: raise Exception('Invalid Jsbx_e value. Exiting.') @@ -1959,21 +1959,21 @@ class AcadosOcpConstraints: # soft bounds on nonlinear constraints @lsh.setter def lsh(self, lsh): - if type(lsh) == np.ndarray: + if isinstance(lsh, np.ndarray): self.__lsh = lsh else: raise Exception('Invalid lsh value. Exiting.') @ush.setter def ush(self, ush): - if type(ush) == np.ndarray: + if isinstance(ush, np.ndarray): self.__ush = ush else: raise Exception('Invalid ush value. Exiting.') @idxsh.setter def idxsh(self, idxsh): - if type(idxsh) == np.ndarray: + if isinstance(idxsh, np.ndarray): self.__idxsh = idxsh else: raise Exception('Invalid idxsh value. Exiting.') @@ -1989,21 +1989,21 @@ class AcadosOcpConstraints: # soft bounds on convex-over-nonlinear constraints @lsphi.setter def lsphi(self, lsphi): - if type(lsphi) == np.ndarray: + if isinstance(lsphi, np.ndarray): self.__lsphi = lsphi else: raise Exception('Invalid lsphi value. Exiting.') @usphi.setter def usphi(self, usphi): - if type(usphi) == np.ndarray: + if isinstance(usphi, np.ndarray): self.__usphi = usphi else: raise Exception('Invalid usphi value. Exiting.') @idxsphi.setter def idxsphi(self, idxsphi): - if type(idxsphi) == np.ndarray: + if isinstance(idxsphi, np.ndarray): self.__idxsphi = idxsphi else: raise Exception('Invalid idxsphi value. Exiting.') @@ -2151,6 +2151,11 @@ class AcadosOcpOptions: self.__ext_cost_num_hess = 0 self.__alpha_min = 0.05 self.__alpha_reduction = 0.7 + self.__line_search_use_sufficient_descent = 0 + self.__globalization_use_SOC = 0 + self.__full_step_dual = 0 + self.__eps_sufficient_descent = 1e-4 + self.__hpipm_mode = 'BALANCE' @property @@ -2161,6 +2166,21 @@ class AcadosOcpOptions: """ return self.__qp_solver + @property + def hpipm_mode(self): + """ + Mode of HPIPM to be used, + + String in ('BALANCE', 'SPEED_ABS', 'SPEED', 'ROBUST'). + + Default: 'BALANCE'. + + see https://cdn.syscop.de/publications/Frison2020a.pdf + and the HPIPM code: + https://github.com/giaf/hpipm/blob/master/ocp_qp/x_ocp_qp_ipm.c#L69 + """ + return self.__hpipm_mode + @property def hessian_approx(self): """Hessian approximation. @@ -2367,6 +2387,43 @@ class AcadosOcpOptions: """Step size reduction factor for globalization MERIT_BACKTRACKING, default: 0.7.""" return self.__alpha_reduction + @property + def line_search_use_sufficient_descent(self): + """ + Determines if sufficient descent (Armijo) condition is used in line search. + Type: int; 0 or 1; + default: 0. + """ + return self.__line_search_use_sufficient_descent + + @property + def eps_sufficient_descent(self): + """ + Factor for sufficient descent (Armijo) conditon, see line_search_use_sufficient_descent. + Type: float, + default: 1e-4. + """ + return self.__eps_sufficient_descent + + @property + def globalization_use_SOC(self): + """ + Determines if second order correction (SOC) is done when using MERIT_BACKTRACKING. + SOC is done if preliminary line search does not return full step. + Type: int; 0 or 1; + default: 0. + """ + return self.__globalization_use_SOC + + @property + def full_step_dual(self): + """ + Determines if dual variables are updated with full steps (alpha=1.0) when primal variables are updated with smaller step. + Type: int; 0 or 1; + default: 0. + """ + return self.__full_step_dual + @property def nlp_solver_tol_ineq(self): """NLP solver inequality tolerance""" @@ -2500,6 +2557,15 @@ class AcadosOcpOptions: raise Exception('Invalid collocation_type value. Possible values are:\n\n' \ + ',\n'.join(collocation_types) + '.\n\nYou have: ' + collocation_type + '.\n\nExiting.') + @hpipm_mode.setter + def hpipm_mode(self, hpipm_mode): + hpipm_modes = ('BALANCE', 'SPEED_ABS', 'SPEED', 'ROBUST') + if hpipm_mode in hpipm_modes: + self.__hpipm_mode = hpipm_mode + else: + raise Exception('Invalid hpipm_mode value. Possible values are:\n\n' \ + + ',\n'.join(hpipm_modes) + '.\n\nYou have: ' + hpipm_mode + '.\n\nExiting.') + @hessian_approx.setter def hessian_approx(self, hessian_approx): hessian_approxs = ('GAUSS_NEWTON', 'EXACT') @@ -2524,12 +2590,23 @@ class AcadosOcpOptions: @time_steps.setter def time_steps(self, time_steps): - self.__time_steps = time_steps + if isinstance(time_steps, np.ndarray): + if len(time_steps.shape) == 1: + self.__time_steps = time_steps + else: + raise Exception('Invalid time_steps, expected np.ndarray of shape (N,).') + else: + raise Exception('Invalid time_steps, expected np.ndarray.') @shooting_nodes.setter def shooting_nodes(self, shooting_nodes): - self.__shooting_nodes = shooting_nodes - + if isinstance(shooting_nodes, np.ndarray): + if len(shooting_nodes.shape) == 1: + self.__shooting_nodes = shooting_nodes + else: + raise Exception('Invalid shooting_nodes, expected np.ndarray of shape (N+1,).') + else: + raise Exception('Invalid shooting_nodes, expected np.ndarray.') @Tsim.setter def Tsim(self, Tsim): @@ -2537,7 +2614,12 @@ class AcadosOcpOptions: @globalization.setter def globalization(self, globalization): - self.__globalization = globalization + globalization_types = ('MERIT_BACKTRACKING', 'FIXED_STEP') + if globalization in globalization_types: + self.__globalization = globalization + else: + raise Exception('Invalid globalization value. Possible values are:\n\n' \ + + ',\n'.join(globalization_types) + '.\n\nYou have: ' + globalization + '.\n\nExiting.') @alpha_min.setter def alpha_min(self, alpha_min): @@ -2547,10 +2629,38 @@ class AcadosOcpOptions: def alpha_reduction(self, alpha_reduction): self.__alpha_reduction = alpha_reduction + @line_search_use_sufficient_descent.setter + def line_search_use_sufficient_descent(self, line_search_use_sufficient_descent): + if line_search_use_sufficient_descent in [0, 1]: + self.__line_search_use_sufficient_descent = line_search_use_sufficient_descent + else: + raise Exception(f'Invalid value for line_search_use_sufficient_descent. Possible values are 0, 1, got {line_search_use_sufficient_descent}') + + @globalization_use_SOC.setter + def globalization_use_SOC(self, globalization_use_SOC): + if globalization_use_SOC in [0, 1]: + self.__globalization_use_SOC = globalization_use_SOC + else: + raise Exception(f'Invalid value for globalization_use_SOC. Possible values are 0, 1, got {globalization_use_SOC}') + + @full_step_dual.setter + def full_step_dual(self, full_step_dual): + if full_step_dual in [0, 1]: + self.__full_step_dual = full_step_dual + else: + raise Exception(f'Invalid value for full_step_dual. Possible values are 0, 1, got {full_step_dual}') + + @eps_sufficient_descent.setter + def eps_sufficient_descent(self, eps_sufficient_descent): + if isinstance(eps_sufficient_descent, float) and eps_sufficient_descent > 0: + self.__eps_sufficient_descent = eps_sufficient_descent + else: + raise Exception('Invalid eps_sufficient_descent value. eps_sufficient_descent must be a positive float. Exiting') + @sim_method_num_stages.setter def sim_method_num_stages(self, sim_method_num_stages): - # if type(sim_method_num_stages) == int: + # if isinstance(sim_method_num_stages, int): # self.__sim_method_num_stages = sim_method_num_stages # else: # raise Exception('Invalid sim_method_num_stages value. sim_method_num_stages must be an integer. Exiting.') @@ -2560,7 +2670,7 @@ class AcadosOcpOptions: @sim_method_num_steps.setter def sim_method_num_steps(self, sim_method_num_steps): - # if type(sim_method_num_steps) == int: + # if isinstance(sim_method_num_steps, int): # self.__sim_method_num_steps = sim_method_num_steps # else: # raise Exception('Invalid sim_method_num_steps value. sim_method_num_steps must be an integer. Exiting.') @@ -2570,7 +2680,7 @@ class AcadosOcpOptions: @sim_method_newton_iter.setter def sim_method_newton_iter(self, sim_method_newton_iter): - if type(sim_method_newton_iter) == int: + if isinstance(sim_method_newton_iter, int): self.__sim_method_newton_iter = sim_method_newton_iter else: raise Exception('Invalid sim_method_newton_iter value. sim_method_newton_iter must be an integer. Exiting.') @@ -2593,7 +2703,7 @@ class AcadosOcpOptions: @nlp_solver_step_length.setter def nlp_solver_step_length(self, nlp_solver_step_length): - if type(nlp_solver_step_length) == float and nlp_solver_step_length > 0: + if isinstance(nlp_solver_step_length, float) and nlp_solver_step_length > 0: self.__nlp_solver_step_length = nlp_solver_step_length else: raise Exception('Invalid nlp_solver_step_length value. nlp_solver_step_length must be a positive float. Exiting') @@ -2614,7 +2724,7 @@ class AcadosOcpOptions: @qp_solver_cond_N.setter def qp_solver_cond_N(self, qp_solver_cond_N): - if isinstance(qp_solver_cond_N, int) and qp_solver_cond_N > 0: + if isinstance(qp_solver_cond_N, int) and qp_solver_cond_N >= 0: self.__qp_solver_cond_N = qp_solver_cond_N else: raise Exception('Invalid qp_solver_cond_N value. qp_solver_cond_N must be a positive int. Exiting') @@ -2705,21 +2815,21 @@ class AcadosOcpOptions: @nlp_solver_max_iter.setter def nlp_solver_max_iter(self, nlp_solver_max_iter): - if type(nlp_solver_max_iter) == int and nlp_solver_max_iter > 0: + if isinstance(nlp_solver_max_iter, int) and nlp_solver_max_iter > 0: self.__nlp_solver_max_iter = nlp_solver_max_iter else: raise Exception('Invalid nlp_solver_max_iter value. nlp_solver_max_iter must be a positive int. Exiting') @print_level.setter def print_level(self, print_level): - if type(print_level) == int and print_level >= 0: + if isinstance(print_level, int) and print_level >= 0: self.__print_level = print_level else: raise Exception('Invalid print_level value. print_level takes one of the values >=0. Exiting') @model_external_shared_lib_dir.setter def model_external_shared_lib_dir(self, model_external_shared_lib_dir): - if type(model_external_shared_lib_dir) == str : + if isinstance(model_external_shared_lib_dir, str) : self.__model_external_shared_lib_dir = model_external_shared_lib_dir else: raise Exception('Invalid model_external_shared_lib_dir value. Str expected.' \ @@ -2727,7 +2837,7 @@ class AcadosOcpOptions: @model_external_shared_lib_name.setter def model_external_shared_lib_name(self, model_external_shared_lib_name): - if type(model_external_shared_lib_name) == str : + if isinstance(model_external_shared_lib_name, str) : if model_external_shared_lib_name[-3:] == '.so' : raise Exception('Invalid model_external_shared_lib_name value. Remove the .so extension.' \ + '.\n\nYou have: ' + type(model_external_shared_lib_name) + '.\n\nExiting.') @@ -2805,10 +2915,13 @@ class AcadosOcp: self.solver_options = AcadosOcpOptions() """Solver Options, type :py:class:`acados_template.acados_ocp.AcadosOcpOptions`""" - self.acados_include_path = f'{acados_path}/include' - """Path to acados include directory, type: string""" - self.acados_lib_path = f'{acados_path}/lib' - """Path to where acados library is located, type: string""" + self.acados_include_path = os.path.join(acados_path, 'include').replace(os.sep, '/') # the replace part is important on Windows for CMake + """Path to acados include directory (set automatically), type: `string`""" + self.acados_lib_path = os.path.join(acados_path, 'lib').replace(os.sep, '/') # the replace part is important on Windows for CMake + """Path to where acados library is located, type: `string`""" + + import numpy + self.cython_include_dirs = numpy.get_include() self.__parameter_values = np.array([]) self.__problem_class = 'OCP' diff --git a/pyextra/acados_template/acados_ocp_solver.py b/pyextra/acados_template/acados_ocp_solver.py index b34b8fa84a..beeda2cb0c 100644 --- a/pyextra/acados_template/acados_ocp_solver.py +++ b/pyextra/acados_template/acados_ocp_solver.py @@ -37,7 +37,7 @@ import os import json import numpy as np from datetime import datetime -import ctypes +import importlib from ctypes import POINTER, cast, CDLL, c_void_p, c_char_p, c_double, c_int, c_int64, byref from copy import deepcopy @@ -51,9 +51,10 @@ from .generate_c_code_nls_cost import generate_c_code_nls_cost from .generate_c_code_external_cost import generate_c_code_external_cost from .acados_ocp import AcadosOcp from .acados_model import acados_model_strip_casadi_symbolics -from .utils import is_column, is_empty, casadi_length, render_template, acados_class2dict,\ +from .utils import is_column, is_empty, casadi_length, render_template,\ format_class_dict, ocp_check_against_layout, np_array_to_list, make_model_consistent,\ - set_up_imported_gnsf_model, get_acados_path, get_ocp_nlp_layout, get_python_interface_path + set_up_imported_gnsf_model, get_ocp_nlp_layout, get_python_interface_path +from .builders import CMakeBuilder def make_ocp_dims_consistent(acados_ocp): @@ -90,7 +91,7 @@ def make_ocp_dims_consistent(acados_ocp): raise Exception('inconsistent dimension np, regarding model.p and parameter_values.' + \ f'\nGot np = {dims.np}, acados_ocp.parameter_values.shape = {acados_ocp.parameter_values.shape[0]}\n') - # cost + ## cost # initial stage - if not set, copy fields from path constraints if cost.cost_type_0 is None: cost.cost_type_0 = cost.cost_type @@ -132,6 +133,15 @@ def make_ocp_dims_consistent(acados_ocp): f'\nGot W_0[{cost.W.shape}], yref_0[{cost.yref_0.shape}]\n') dims.ny_0 = ny_0 + elif cost.cost_type_0 == 'EXTERNAL': + if opts.hessian_approx == 'GAUSS_NEWTON' and opts.ext_cost_num_hess == 0 and model.cost_expr_ext_cost_custom_hess_0 is None: + print("\nWARNING: Gauss-Newton Hessian approximation with EXTERNAL cost type not possible!\n" + "got cost_type_0: EXTERNAL, hessian_approx: 'GAUSS_NEWTON.'\n" + "GAUSS_NEWTON hessian is only supported for cost_types [NON]LINEAR_LS.\n" + "If you continue, acados will proceed computing the exact hessian for the cost term.\n" + "Note: There is also the option to use the external cost module with a numerical hessian approximation (see `ext_cost_num_hess`).\n" + "OR the option to provide a symbolic custom hessian approximation (see `cost_expr_ext_cost_custom_hess`).\n") + # path if cost.cost_type == 'LINEAR_LS': ny = cost.W.shape[0] @@ -161,6 +171,15 @@ def make_ocp_dims_consistent(acados_ocp): f'\nGot W[{cost.W.shape}], yref[{cost.yref.shape}]\n') dims.ny = ny + elif cost.cost_type == 'EXTERNAL': + if opts.hessian_approx == 'GAUSS_NEWTON' and opts.ext_cost_num_hess == 0 and model.cost_expr_ext_cost_custom_hess is None: + print("\nWARNING: Gauss-Newton Hessian approximation with EXTERNAL cost type not possible!\n" + "got cost_type: EXTERNAL, hessian_approx: 'GAUSS_NEWTON.'\n" + "GAUSS_NEWTON hessian is only supported for cost_types [NON]LINEAR_LS.\n" + "If you continue, acados will proceed computing the exact hessian for the cost term.\n" + "Note: There is also the option to use the external cost module with a numerical hessian approximation (see `ext_cost_num_hess`).\n" + "OR the option to provide a symbolic custom hessian approximation (see `cost_expr_ext_cost_custom_hess`).\n") + # terminal if cost.cost_type_e == 'LINEAR_LS': ny_e = cost.W_e.shape[0] @@ -183,6 +202,14 @@ def make_ocp_dims_consistent(acados_ocp): raise Exception('inconsistent dimension: regarding W_e, yref_e.') dims.ny_e = ny_e + elif cost.cost_type_e == 'EXTERNAL': + if opts.hessian_approx == 'GAUSS_NEWTON' and opts.ext_cost_num_hess == 0 and model.cost_expr_ext_cost_custom_hess_e is None: + print("\nWARNING: Gauss-Newton Hessian approximation with EXTERNAL cost type not possible!\n" + "got cost_type_e: EXTERNAL, hessian_approx: 'GAUSS_NEWTON.'\n" + "GAUSS_NEWTON hessian is only supported for cost_types [NON]LINEAR_LS.\n" + "If you continue, acados will proceed computing the exact hessian for the cost term.\n" + "Note: There is also the option to use the external cost module with a numerical hessian approximation (see `ext_cost_num_hess`).\n" + "OR the option to provide a symbolic custom hessian approximation (see `cost_expr_ext_cost_custom_hess`).\n") ## constraints # initial @@ -434,18 +461,14 @@ def make_ocp_dims_consistent(acados_ocp): if np.shape(opts.shooting_nodes)[0] != dims.N+1: raise Exception('inconsistent dimension N, regarding shooting_nodes.') - # time_steps = opts.shooting_nodes[1:] - opts.shooting_nodes[0:-1] - # # identify constant time-steps: due to numerical reasons the content of time_steps might vary a bit - # delta_time_steps = time_steps[1:] - time_steps[0:-1] - # avg_time_steps = np.average(time_steps) - # # criterion for constant time-step detection: the min/max difference in values normalized by the average - # check_const_time_step = np.max(delta_time_steps)-np.min(delta_time_steps) / avg_time_steps - # # if the criterion is small, we have a constant time-step - # if check_const_time_step < 1e-9: - # time_steps[:] = avg_time_steps # if we have a constant time-step: apply the average time-step - time_steps = np.zeros((dims.N,)) - for i in range(dims.N): - time_steps[i] = opts.shooting_nodes[i+1] - opts.shooting_nodes[i] # TODO use commented code above + time_steps = opts.shooting_nodes[1:] - opts.shooting_nodes[0:-1] + # identify constant time_steps: due to numerical reasons the content of time_steps might vary a bit + avg_time_steps = np.average(time_steps) + # criterion for constant time step detection: the min/max difference in values normalized by the average + check_const_time_step = (np.max(time_steps)-np.min(time_steps)) / avg_time_steps + # if the criterion is small, we have a constant time_step + if check_const_time_step < 1e-9: + time_steps[:] = avg_time_steps # if we have a constant time_step: apply the average time_step opts.time_steps = time_steps @@ -525,8 +548,7 @@ def ocp_formulation_json_dump(acados_ocp, simulink_opts, json_file='acados_ocp_n # strip shooting_nodes ocp_nlp_dict['solver_options'].pop('shooting_nodes', None) - - dims_dict = acados_class2dict(acados_ocp.dims) + dims_dict = format_class_dict(acados_ocp.dims.__dict__) ocp_check_against_layout(ocp_nlp_dict, dims_dict) @@ -627,15 +649,25 @@ def ocp_generate_external_functions(acados_ocp, model): generate_c_code_external_cost(model, 'terminal', opts) -def ocp_render_templates(acados_ocp, json_file): +def ocp_get_default_cmake_builder() -> CMakeBuilder: + """ + If :py:class:`~acados_template.acados_ocp_solver.AcadosOcpSolver` is used with `CMake` this function returns a good first setting. + :return: default :py:class:`~acados_template.builders.CMakeBuilder` + """ + cmake_builder = CMakeBuilder() + cmake_builder.options_on = ['BUILD_ACADOS_OCP_SOLVER_LIB'] + return cmake_builder + + +def ocp_render_templates(acados_ocp, json_file, cmake_builder=None): name = acados_ocp.model.name # setting up loader and environment - json_path = os.path.join(os.getcwd(), json_file) + json_path = os.path.abspath(json_file) if not os.path.exists(json_path): - raise Exception('{} not found!'.format(json_path)) + raise Exception(f'Path "{json_path}" not found!') code_export_dir = acados_ocp.code_export_directory template_dir = code_export_dir @@ -657,9 +689,14 @@ def ocp_render_templates(acados_ocp, json_file): out_file = f'acados_solver.pxd' render_template(in_file, out_file, template_dir, json_path) - in_file = 'Makefile.in' - out_file = 'Makefile' - render_template(in_file, out_file, template_dir, json_path) + if cmake_builder is not None: + in_file = 'CMakeLists.in.txt' + out_file = 'CMakeLists.txt' + render_template(in_file, out_file, template_dir, json_path) + else: + in_file = 'Makefile.in' + out_file = 'Makefile' + render_template(in_file, out_file, template_dir, json_path) in_file = 'acados_solver_sfun.in.c' out_file = f'acados_solver_sfunction_{name}.c' @@ -769,21 +806,33 @@ class AcadosOcpSolver: """ Class to interact with the acados ocp solver C object. - :param acados_ocp: type AcadosOcp - description of the OCP for acados + :param acados_ocp: type :py:class:`~acados_template.acados_ocp.AcadosOcp` - description of the OCP for acados :param json_file: name for the json file used to render the templated code - default: acados_ocp_nlp.json :param simulink_opts: Options to configure Simulink S-function blocks, mainly to activate possible Inputs and Outputs """ if sys.platform=="win32": from ctypes import wintypes - dlclose = ctypes.WinDLL('kernel32', use_last_error=True).FreeLibrary + from ctypes import WinDLL + dlclose = WinDLL('kernel32', use_last_error=True).FreeLibrary dlclose.argtypes = [wintypes.HMODULE] else: dlclose = CDLL(None).dlclose dlclose.argtypes = [c_void_p] @classmethod - def generate(cls, acados_ocp, json_file='acados_ocp_nlp.json', simulink_opts=None, build=True): + def generate(cls, acados_ocp, json_file='acados_ocp_nlp.json', simulink_opts=None, cmake_builder: CMakeBuilder = None): + """ + Generates the code for an acados OCP solver, given the description in acados_ocp. + :param acados_ocp: type AcadosOcp - description of the OCP for acados + :param json_file: name for the json file used to render the templated code - default: `acados_ocp_nlp.json` + :param simulink_opts: Options to configure Simulink S-function blocks, mainly to activate possible inputs and + outputs; default: `None` + :param cmake_builder: type :py:class:`~acados_template.builders.CMakeBuilder` generate a `CMakeLists.txt` and use + the `CMake` pipeline instead of a `Makefile` (`CMake` seems to be the better option in conjunction with + `MS Visual Studio`); default: `None` + """ model = acados_ocp.model + acados_ocp.code_export_directory = os.path.abspath(acados_ocp.code_export_directory) if simulink_opts is None: simulink_opts = get_simulink_default_opts() @@ -807,24 +856,106 @@ class AcadosOcpSolver: # dump to json ocp_formulation_json_dump(acados_ocp, simulink_opts, json_file) - code_export_dir = acados_ocp.code_export_directory # render templates - ocp_render_templates(acados_ocp, json_file) + ocp_render_templates(acados_ocp, json_file, cmake_builder=cmake_builder) + acados_ocp.json_file = json_file - if build: - ## Compile solver - cwd=os.getcwd() - os.chdir(code_export_dir) - os.system('make clean_ocp_shared_lib') - os.system('make ocp_shared_lib') - os.chdir(cwd) - - def __init__(self, model_name, N, code_export_dir): - self.model_name = model_name - self.N = N + + @classmethod + def build(cls, code_export_dir, with_cython=False, cmake_builder: CMakeBuilder = None): + """ + Builds the code for an acados OCP solver, that has been generated in code_export_dir + :param code_export_dir: directory in which acados OCP solver has been generated, see generate() + :param with_cython: option indicating if the cython interface is build, default: False. + :param cmake_builder: type :py:class:`~acados_template.builders.CMakeBuilder` generate a `CMakeLists.txt` and use + the `CMake` pipeline instead of a `Makefile` (`CMake` seems to be the better option in conjunction with + `MS Visual Studio`); default: `None` + """ + code_export_dir = os.path.abspath(code_export_dir) + cwd=os.getcwd() + os.chdir(code_export_dir) + if with_cython: + os.system('make clean_ocp_cython') + os.system('make ocp_cython') + else: + if cmake_builder is not None: + cmake_builder.exec(code_export_dir) + else: + os.system('make clean_ocp_shared_lib') + os.system('make ocp_shared_lib') + os.chdir(cwd) + + + @classmethod + def create_cython_solver(cls, json_file): + """ + Returns an `AcadosOcpSolverCython` object. + + This is an alternative Cython based Python wrapper to the acados OCP solver in C. + This offers faster interaction with the solver, because getter and setter calls, which include shape checking are done in compiled C code. + + The default wrapper `AcadosOcpSolver` is based on ctypes. + """ + with open(json_file, 'r') as f: + acados_ocp_json = json.load(f) + code_export_directory = acados_ocp_json['code_export_directory'] + + importlib.invalidate_caches() + rel_code_export_directory = os.path.relpath(code_export_directory) + acados_ocp_solver_pyx = importlib.import_module(f'{rel_code_export_directory}.acados_ocp_solver_pyx') + + AcadosOcpSolverCython = getattr(acados_ocp_solver_pyx, 'AcadosOcpSolverCython') + return AcadosOcpSolverCython(acados_ocp_json['model']['name'], + acados_ocp_json['solver_options']['nlp_solver_type'], + acados_ocp_json['dims']['N']) + + + def __init__(self, acados_ocp, json_file='acados_ocp_nlp.json', simulink_opts=None, build=True, generate=True, cmake_builder: CMakeBuilder = None): self.solver_created = False - self.shared_lib_name = f'{code_export_dir}/libacados_ocp_solver_{self.model_name}.so' + if generate: + self.generate(acados_ocp, json_file=json_file, simulink_opts=simulink_opts, cmake_builder=cmake_builder) + + # load json, store options in object + with open(json_file, 'r') as f: + acados_ocp_json = json.load(f) + self.N = acados_ocp_json['dims']['N'] + self.model_name = acados_ocp_json['model']['name'] + self.solver_options = acados_ocp_json['solver_options'] + + acados_lib_path = acados_ocp_json['acados_lib_path'] + code_export_directory = acados_ocp_json['code_export_directory'] + + if build: + self.build(code_export_directory, with_cython=False, cmake_builder=cmake_builder) + + # prepare library loading + lib_prefix = 'lib' + lib_ext = '.so' + if os.name == 'nt': + lib_prefix = '' + lib_ext = '' + # ToDo: check for mac + + # Load acados library to avoid unloading the library. + # This is necessary if acados was compiled with OpenMP, since the OpenMP threads can't be destroyed. + # Unloading a library which uses OpenMP results in a segfault (on any platform?). + # see [https://stackoverflow.com/questions/34439956/vc-crash-when-freeing-a-dll-built-with-openmp] + # or [https://python.hotexamples.com/examples/_ctypes/-/dlclose/python-dlclose-function-examples.html] + libacados_name = f'{lib_prefix}acados{lib_ext}' + libacados_filepath = os.path.join(acados_lib_path, libacados_name) + self.__acados_lib = CDLL(libacados_filepath) + # find out if acados was compiled with OpenMP + try: + self.__acados_lib_uses_omp = getattr(self.__acados_lib, 'omp_get_thread_num') is not None + except AttributeError as e: + self.__acados_lib_uses_omp = False + if self.__acados_lib_uses_omp: + print('acados was compiled with OpenMP.') + else: + print('acados was compiled without OpenMP.') + libacados_ocp_solver_name = f'{lib_prefix}acados_ocp_solver_{self.model_name}{lib_ext}' + self.shared_lib_name = os.path.join(code_export_directory, libacados_ocp_solver_name) # get shared_lib self.shared_lib = CDLL(self.shared_lib_name) @@ -842,6 +973,8 @@ class AcadosOcpSolver: # get pointers solver self.__get_pointers_solver() + self.status = 0 + def __get_pointers_solver(self): """ @@ -864,6 +997,10 @@ class AcadosOcpSolver: getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_out").restype = c_void_p self.nlp_out = getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_out")(self.capsule) + getattr(self.shared_lib, f"{self.model_name}_acados_get_sens_out").argtypes = [c_void_p] + getattr(self.shared_lib, f"{self.model_name}_acados_get_sens_out").restype = c_void_p + self.sens_out = getattr(self.shared_lib, f"{self.model_name}_acados_get_sens_out")(self.capsule) + getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_in").argtypes = [c_void_p] getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_in").restype = c_void_p self.nlp_in = getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_in")(self.capsule) @@ -872,46 +1009,37 @@ class AcadosOcpSolver: getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_solver").restype = c_void_p self.nlp_solver = getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_solver")(self.capsule) - # treat parameters separately - getattr(self.shared_lib, f"{self.model_name}_acados_update_params").argtypes = [c_void_p, c_int, POINTER(c_double)] - getattr(self.shared_lib, f"{self.model_name}_acados_update_params").restype = c_int - self._set_param = getattr(self.shared_lib, f"{self.model_name}_acados_update_params") - - self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, POINTER(c_int)] - self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.restype = c_int - - self.shared_lib.ocp_nlp_cost_dims_get_from_attr.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, POINTER(c_int)] - self.shared_lib.ocp_nlp_cost_dims_get_from_attr.restype = c_int - - self.shared_lib.ocp_nlp_constraints_model_set.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_cost_model_set.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_out_set.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_set.argtypes = \ - [c_void_p, c_void_p, c_int, c_char_p, c_void_p] def solve(self): """ Solve the ocp with current input. """ - getattr(self.shared_lib, f"{self.model_name}_acados_solve").argtypes = [c_void_p] getattr(self.shared_lib, f"{self.model_name}_acados_solve").restype = c_int - status = getattr(self.shared_lib, f"{self.model_name}_acados_solve")(self.capsule) - return status + self.status = getattr(self.shared_lib, f"{self.model_name}_acados_solve")(self.capsule) + + return self.status + + + def reset(self): + """ + Sets current iterate to all zeros. + """ + getattr(self.shared_lib, f"{self.model_name}_acados_reset").argtypes = [c_void_p] + getattr(self.shared_lib, f"{self.model_name}_acados_reset").restype = c_int + getattr(self.shared_lib, f"{self.model_name}_acados_reset")(self.capsule) + + return def set_new_time_steps(self, new_time_steps): """ - Set new time steps before solving. Only reload library without code generation but with new time steps. + Set new time steps. + Recreates the solver if N changes. - :param new_time_steps: vector of new time steps for the solver + :param new_time_steps: 1 dimensional np array of new time steps for the solver - .. note:: This allows for different use-cases: either set a new size of time-steps or a new distribution of + .. note:: This allows for different use-cases: either set a new size of time_steps or a new distribution of the shooting nodes without changing the number, e.g., to reach a different final time. Both cases do not require a new code export and compilation. """ @@ -921,15 +1049,14 @@ class AcadosOcpSolver: raise Exception('Solver was not yet created!') # check if time steps really changed in value - if np.array_equal(self.acados_ocp.solver_options.time_steps, new_time_steps): + if np.array_equal(self.solver_options['time_steps'], new_time_steps): return N = new_time_steps.size - model = self.acados_ocp.model new_time_steps_data = cast(new_time_steps.ctypes.data, POINTER(c_double)) # check if recreation of acados is necessary (no need to recreate acados if sizes are identical) - if self.acados_ocp.solver_options.time_steps.size == N: + if len(self.solver_options['time_steps']) == N: getattr(self.shared_lib, f"{self.model_name}_acados_update_time_steps").argtypes = [c_void_p, c_int, c_void_p] getattr(self.shared_lib, f"{self.model_name}_acados_update_time_steps").restype = c_int assert getattr(self.shared_lib, f"{self.model_name}_acados_update_time_steps")(self.capsule, N, new_time_steps_data) == 0 @@ -941,11 +1068,6 @@ class AcadosOcpSolver: getattr(self.shared_lib, f"{self.model_name}_acados_free").restype = c_int getattr(self.shared_lib, f"{self.model_name}_acados_free")(self.capsule) - # store N and new time steps - self.N = self.acados_ocp.dims.N = N - self.acados_ocp.solver_options.time_steps = new_time_steps - self.acados_ocp.solver_options.Tsim = self.acados_ocp.solver_options.time_steps[0] - # create solver with new time steps getattr(self.shared_lib, f"{self.model_name}_acados_create_with_discretization").argtypes = [c_void_p, c_int, c_void_p] getattr(self.shared_lib, f"{self.model_name}_acados_create_with_discretization").restype = c_int @@ -956,6 +1078,75 @@ class AcadosOcpSolver: # get pointers solver self.__get_pointers_solver() + # store time_steps, N + self.solver_options['time_steps'] = new_time_steps + self.N = N + self.solver_options['Tsim'] = self.solver_options['time_steps'][0] + + + def update_qp_solver_cond_N(self, qp_solver_cond_N: int): + """ + Recreate solver with new value `qp_solver_cond_N` with a partial condensing QP solver. + This function is relevant for code reuse, i.e., if either `set_new_time_steps(...)` is used or + the influence of a different `qp_solver_cond_N` is studied without code export and compilation. + :param qp_solver_cond_N: new number of condensing stages for the solver + + .. note:: This function can only be used in combination with a partial condensing QP solver. + + .. note:: After `set_new_time_steps(...)` is used and depending on the new number of time steps it might be + necessary to change `qp_solver_cond_N` as well (using this function), i.e., typically + `qp_solver_cond_N < N`. + """ + # unlikely but still possible + if not self.solver_created: + raise Exception('Solver was not yet created!') + if self.N < qp_solver_cond_N: + raise Exception('Setting qp_solver_cond_N to be larger than N does not work!') + if self.solver_options['qp_solver_cond_N'] != qp_solver_cond_N: + self.solver_created = False + + # recreate the solver + fun_name = f'{self.model_name}_acados_update_qp_solver_cond_N' + getattr(self.shared_lib, fun_name).argtypes = [c_void_p, c_int] + getattr(self.shared_lib, fun_name).restype = c_int + assert getattr(self.shared_lib, fun_name)(self.capsule, qp_solver_cond_N) == 0 + + # store the new value + self.solver_options['qp_solver_cond_N'] = qp_solver_cond_N + self.solver_created = True + + # get pointers solver + self.__get_pointers_solver() + + + def eval_param_sens(self, index, stage=0, field="ex"): + """ + Calculate the sensitivity of the curent solution with respect to the initial state component of index + + :param index: integer corresponding to initial state index in range(nx) + """ + + field_ = field + field = field_.encode('utf-8') + + # checks + if not isinstance(index, int): + raise Exception('AcadosOcpSolver.eval_param_sens(): index must be Integer.') + + self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes = [c_void_p, c_void_p, c_void_p, c_int, c_char_p] + self.shared_lib.ocp_nlp_dims_get_from_attr.restype = c_int + nx = self.shared_lib.ocp_nlp_dims_get_from_attr(self.nlp_config, self.nlp_dims, self.nlp_out, 0, "x".encode('utf-8')) + + if index < 0 or index > nx: + raise Exception(f'AcadosOcpSolver.eval_param_sens(): index must be in [0, nx-1], got: {index}.') + + # actual eval_param + self.shared_lib.ocp_nlp_eval_param_sens.argtypes = [c_void_p, c_char_p, c_int, c_int, c_void_p] + self.shared_lib.ocp_nlp_eval_param_sens.restype = None + self.shared_lib.ocp_nlp_eval_param_sens(self.nlp_solver, field, stage, index, self.sens_out) + + return + def get(self, stage_, field_): """ @@ -978,23 +1169,30 @@ class AcadosOcpSolver: out_fields = ['x', 'u', 'z', 'pi', 'lam', 't', 'sl', 'su'] # mem_fields = ['sl', 'su'] + sens_fields = ['sens_u', "sens_x"] + all_fields = out_fields + sens_fields + field = field_ - field = field.encode('utf-8') - if (field_ not in out_fields): + if (field_ not in all_fields): raise Exception('AcadosOcpSolver.get(): {} is an invalid argument.\ - \n Possible values are {}. Exiting.'.format(field_, out_fields)) + \n Possible values are {}. Exiting.'.format(field_, all_fields)) if not isinstance(stage_, int): raise Exception('AcadosOcpSolver.get(): stage index must be Integer.') if stage_ < 0 or stage_ > self.N: - raise Exception('AcadosOcpSolver.get(): stage index must be in [0, N], got: {}.'.format(self.N)) + raise Exception('AcadosOcpSolver.get(): stage index must be in [0, N], got: {}.'.format(stage_)) if stage_ == self.N and field_ == 'pi': raise Exception('AcadosOcpSolver.get(): field {} does not exist at final stage {}.'\ .format(field_, stage_)) + if field_ in sens_fields: + field = field_.replace('sens_', '') + + field = field.encode('utf-8') + self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes = \ [c_void_p, c_void_p, c_void_p, c_int, c_char_p] self.shared_lib.ocp_nlp_dims_get_from_attr.restype = c_int @@ -1015,6 +1213,11 @@ class AcadosOcpSolver: # [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] # self.shared_lib.ocp_nlp_get_at_stage(self.nlp_config, \ # self.nlp_dims, self.nlp_solver, stage_, field, out_data) + elif field_ in sens_fields: + self.shared_lib.ocp_nlp_out_get.argtypes = \ + [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] + self.shared_lib.ocp_nlp_out_get(self.nlp_config, \ + self.nlp_dims, self.sens_out, stage_, field, out_data) return out @@ -1029,6 +1232,7 @@ class AcadosOcpSolver: - res_comp: residual wrt complementarity conditions - qp_stat: status of QP solver - qp_iter: number of QP iterations + - alpha: SQP step size - qp_res_stat: stationarity residual of the last QP solution - qp_res_eq: residual wrt equality constraints (dynamics) of the last QP solution - qp_res_ineq: residual wrt inequality constraints (constraints) of the last QP solution @@ -1036,19 +1240,18 @@ class AcadosOcpSolver: """ stat = self.get_stats("statistics") - if self.acados_ocp.solver_options.nlp_solver_type == 'SQP': - print('\niter\tres_stat\tres_eq\t\tres_ineq\tres_comp\tqp_stat\tqp_iter') - if stat.shape[0]>7: + if self.solver_options['nlp_solver_type'] == 'SQP': + print('\niter\tres_stat\tres_eq\t\tres_ineq\tres_comp\tqp_stat\tqp_iter\talpha') + if stat.shape[0]>8: print('\tqp_res_stat\tqp_res_eq\tqp_res_ineq\tqp_res_comp') for jj in range(stat.shape[1]): - print('{:d}\t{:e}\t{:e}\t{:e}\t{:e}\t{:d}\t{:d}'.format( \ - int(stat[0][jj]), stat[1][jj], stat[2][jj], \ - stat[3][jj], stat[4][jj], int(stat[5][jj]), int(stat[6][jj]))) - if stat.shape[0]>7: + print(f'{int(stat[0][jj]):d}\t{stat[1][jj]:e}\t{stat[2][jj]:e}\t{stat[3][jj]:e}\t' + + f'{stat[4][jj]:e}\t{int(stat[5][jj]):d}\t{int(stat[6][jj]):d}\t{stat[7][jj]:e}\t') + if stat.shape[0]>8: print('\t{:e}\t{:e}\t{:e}\t{:e}'.format( \ - stat[7][jj], stat[8][jj], stat[9][jj], stat[10][jj])) + stat[8][jj], stat[9][jj], stat[10][jj], stat[11][jj])) print('\n') - elif self.acados_ocp.solver_options.nlp_solver_type == 'SQP_RTI': + elif self.solver_options['nlp_solver_type'] == 'SQP_RTI': print('\niter\tqp_stat\tqp_iter') if stat.shape[0]>3: print('\tqp_res_stat\tqp_res_eq\tqp_res_ineq\tqp_res_comp') @@ -1108,6 +1311,7 @@ class AcadosOcpSolver: with open(filename, 'r') as f: solution = json.load(f) + print(f"loading iterate {filename}") for key in solution.keys(): (field, stage) = key.split('_') self.set(int(stage), field, np.array(solution[key])) @@ -1117,62 +1321,99 @@ class AcadosOcpSolver: """ Get the information of the last solver call. - :param field: string in ['statistics', 'time_tot', 'time_lin', 'time_sim', 'time_sim_ad', 'time_sim_la', 'time_qp', 'time_qp_solver_call', 'time_reg', 'sqp_iter'] + :param field: string in ['statistics', 'time_tot', 'time_lin', 'time_sim', 'time_sim_ad', 'time_sim_la', 'time_qp', 'time_qp_solver_call', 'time_reg', 'sqp_iter', 'residuals', 'qp_iter', 'alpha'] + + Available fileds: + - time_tot: total CPU time previous call + - time_lin: CPU time for linearization + - time_sim: CPU time for integrator + - time_sim_ad: CPU time for integrator contribution of external function calls + - time_sim_la: CPU time for integrator contribution of linear algebra + - time_qp: CPU time qp solution + - time_qp_solver_call: CPU time inside qp solver (without converting the QP) + - time_qp_xcond: time_glob: CPU time globalization + - time_solution_sensitivities: CPU time for previous call to eval_param_sens + - time_reg: CPU time regularization + - sqp_iter: number of SQP iterations + - qp_iter: vector of QP iterations for last SQP call + - statistics: table with info about last iteration + - stat_m: number of rows in statistics matrix + - stat_n: number of columns in statistics matrix + - residuals: residuals of last iterate + - alpha: step sizes of SQP iterations """ - fields = ['time_tot', # total cpu time previous call - 'time_lin', # cpu time for linearization - 'time_sim', # cpu time for integrator - 'time_sim_ad', # cpu time for integrator contribution of external function calls - 'time_sim_la', # cpu time for integrator contribution of linear algebra - 'time_qp', # cpu time qp solution - 'time_qp_solver_call', # cpu time inside qp solver (without converting the QP) + double_fields = ['time_tot', + 'time_lin', + 'time_sim', + 'time_sim_ad', + 'time_sim_la', + 'time_qp', + 'time_qp_solver_call', 'time_qp_xcond', - 'time_glob', # cpu time globalization - 'time_reg', # cpu time regularization - 'sqp_iter', # number of SQP iterations - 'qp_iter', # vector of QP iterations for last SQP call - 'statistics', # table with info about last iteration + 'time_glob', + 'time_solution_sensitivities', + 'time_reg' + ] + fields = double_fields + [ + 'sqp_iter', + 'qp_iter', + 'statistics', 'stat_m', - 'stat_n',] + 'stat_n', + 'residuals', + 'alpha', + ] + field = field_.encode('utf-8') - field = field_ - field = field.encode('utf-8') - if (field_ not in fields): - raise Exception('AcadosOcpSolver.get_stats(): {} is not a valid argument.\ - \n Possible values are {}. Exiting.'.format(fields, fields)) if field_ in ['sqp_iter', 'stat_m', 'stat_n']: out = np.ascontiguousarray(np.zeros((1,)), dtype=np.int64) out_data = cast(out.ctypes.data, POINTER(c_int64)) + self.shared_lib.ocp_nlp_get.argtypes = [c_void_p, c_void_p, c_char_p, c_void_p] + self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) + return out + + # TODO: just return double instead of np. + elif field_ in double_fields: + out = np.zeros((1,)) + out_data = cast(out.ctypes.data, POINTER(c_double)) + self.shared_lib.ocp_nlp_get.argtypes = [c_void_p, c_void_p, c_char_p, c_void_p] + self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) + return out elif field_ == 'statistics': sqp_iter = self.get_stats("sqp_iter") stat_m = self.get_stats("stat_m") stat_n = self.get_stats("stat_n") - min_size = min([stat_m, sqp_iter+1]) - out = np.ascontiguousarray( np.zeros((stat_n[0]+1, min_size[0])), dtype=np.float64) out_data = cast(out.ctypes.data, POINTER(c_double)) + self.shared_lib.ocp_nlp_get.argtypes = [c_void_p, c_void_p, c_char_p, c_void_p] + self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) + return out elif field_ == 'qp_iter': full_stats = self.get_stats('statistics') - if self.acados_ocp.solver_options.nlp_solver_type == 'SQP': - out = full_stats[6, :] - elif self.acados_ocp.solver_options.nlp_solver_type == 'SQP_RTI': - out = full_stats[2, :] + if self.solver_options['nlp_solver_type'] == 'SQP': + return full_stats[6, :] + elif self.solver_options['nlp_solver_type'] == 'SQP_RTI': + return full_stats[2, :] - else: - out = np.ascontiguousarray(np.zeros((1,)), dtype=np.float64) - out_data = cast(out.ctypes.data, POINTER(c_double)) + elif field_ == 'alpha': + full_stats = self.get_stats('statistics') + if self.solver_options['nlp_solver_type'] == 'SQP': + return full_stats[7, :] + else: # self.solver_options['nlp_solver_type'] == 'SQP_RTI': + raise Exception("alpha values are not available for SQP_RTI") - if not field_ == 'qp_iter': - self.shared_lib.ocp_nlp_get.argtypes = [c_void_p, c_void_p, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) + elif field_ == 'residuals': + return self.get_residuals() - return out + else: + raise Exception(f'AcadosOcpSolver.get_stats(): {field} is not a valid argument.' + + f'\n Possible values are {fields}.') def get_cost(self): @@ -1196,12 +1437,12 @@ class AcadosOcpSolver: return out[0] - def get_residuals(self): + def get_residuals(self, recompute=False): """ Returns an array of the form [res_stat, res_eq, res_ineq, res_comp]. """ # compute residuals if RTI - if self.acados_ocp.solver_options.nlp_solver_type == 'SQP_RTI': + if self.solver_options['nlp_solver_type'] == 'SQP_RTI' or recompute: self.shared_lib.ocp_nlp_eval_residuals.argtypes = [c_void_p, c_void_p, c_void_p] self.shared_lib.ocp_nlp_eval_residuals(self.nlp_solver, self.nlp_in, self.nlp_out) @@ -1230,14 +1471,12 @@ class AcadosOcpSolver: # Note: this function should not be used anymore, better use cost_set, constraints_set - def set(self, stage_, field_, value_): - """ Set numerical data inside the solver. :param stage: integer corresponding to shooting node - :param field: string in ['x', 'u', 'pi', 'lam', 't', 'p'] + :param field: string in ['x', 'u', 'pi', 'lam', 't', 'p', 'xdot_guess', 'z_guess'] .. note:: regarding lam, t: \n the inequalities are internally organized in the following order: \n @@ -1253,6 +1492,7 @@ class AcadosOcpSolver: cost_fields = ['y_ref', 'yref'] constraints_fields = ['lbx', 'ubx', 'lbu', 'ubu'] out_fields = ['x', 'u', 'pi', 'lam', 't', 'z', 'sl', 'su'] + mem_fields = ['xdot_guess', 'z_guess'] # cast value_ to avoid conversion issues if isinstance(value_, (float, int)): @@ -1294,18 +1534,25 @@ class AcadosOcpSolver: value_data_p = cast((value_data), c_void_p) if field_ in constraints_fields: + self.shared_lib.ocp_nlp_constraints_model_set.argtypes = \ + [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_constraints_model_set(self.nlp_config, \ self.nlp_dims, self.nlp_in, stage, field, value_data_p) elif field_ in cost_fields: + self.shared_lib.ocp_nlp_cost_model_set.argtypes = \ + [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_cost_model_set(self.nlp_config, \ self.nlp_dims, self.nlp_in, stage, field, value_data_p) elif field_ in out_fields: + self.shared_lib.ocp_nlp_out_set.argtypes = \ + [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] self.shared_lib.ocp_nlp_out_set(self.nlp_config, \ self.nlp_dims, self.nlp_out, stage, field, value_data_p) - # elif field_ in mem_fields: - # self.shared_lib.ocp_nlp_set(self.nlp_config, \ - # self.nlp_solver, stage, field, value_data_p) - + elif field_ in mem_fields: + self.shared_lib.ocp_nlp_set.argtypes = \ + [c_void_p, c_void_p, c_int, c_char_p, c_void_p] + self.shared_lib.ocp_nlp_set(self.nlp_config, \ + self.nlp_solver, stage, field, value_data_p) return @@ -1364,9 +1611,8 @@ class AcadosOcpSolver: raise Exception("Unknown api: '{}'".format(api)) if value_shape != tuple(dims): - raise Exception('AcadosOcpSolver.cost_set(): mismatching dimension', \ - ' for field "{}" with dimension {} (you have {})'.format( \ - field_, tuple(dims), value_shape)) + raise Exception('AcadosOcpSolver.cost_set(): mismatching dimension' + + f' for field "{field_}" at stage {stage} with dimension {tuple(dims)} (you have {value_shape})') value_data = cast(value_.ctypes.data, POINTER(c_double)) value_data_p = cast((value_data), c_void_p) @@ -1433,8 +1679,8 @@ class AcadosOcpSolver: raise Exception("Unknown api: '{}'".format(api)) if value_shape != tuple(dims): - raise Exception('AcadosOcpSolver.constraints_set(): mismatching dimension' \ - ' for field "{}" with dimension {} (you have {})'.format(field_, tuple(dims), value_shape)) + raise Exception(f'AcadosOcpSolver.constraints_set(): mismatching dimension' + + f' for field "{field_}" at stage {stage} with dimension {tuple(dims)} (you have {value_shape})') value_data = cast(value_.ctypes.data, POINTER(c_double)) value_data_p = cast((value_data), c_void_p) @@ -1490,11 +1736,21 @@ class AcadosOcpSolver: """ Set options of the solver. - :param field: string, e.g. 'print_level', 'rti_phase', 'initialize_t_slacks', 'step_length', 'alpha_min', 'alpha_reduction' - :param value: of type int, float + :param field: string, e.g. 'print_level', 'rti_phase', 'initialize_t_slacks', 'step_length', 'alpha_min', 'alpha_reduction', 'qp_warm_start', 'line_search_use_sufficient_descent', 'full_step_dual', 'globalization_use_SOC', 'qp_tol_stat', 'qp_tol_eq', 'qp_tol_ineq', 'qp_tol_comp', 'qp_tau_min', 'qp_mu0' + + :param value: of type int, float, string + + - qp_tol_stat: QP solver tolerance stationarity + - qp_tol_eq: QP solver tolerance equalities + - qp_tol_ineq: QP solver tolerance inequalities + - qp_tol_comp: QP solver tolerance complementarity + - qp_tau_min: for HPIPM QP solvers: minimum value of barrier parameter in HPIPM + - qp_mu0: for HPIPM QP solvers: initial value for complementarity slackness + - warm_start_first_qp: indicates if first QP in SQP is warm_started """ - int_fields = ['print_level', 'rti_phase', 'initialize_t_slacks'] - double_fields = ['step_length', 'tol_eq', 'tol_stat', 'tol_ineq', 'tol_comp', 'alpha_min', 'alpha_reduction'] + int_fields = ['print_level', 'rti_phase', 'initialize_t_slacks', 'qp_warm_start', 'line_search_use_sufficient_descent', 'full_step_dual', 'globalization_use_SOC', 'warm_start_first_qp'] + double_fields = ['step_length', 'tol_eq', 'tol_stat', 'tol_ineq', 'tol_comp', 'alpha_min', 'alpha_reduction', 'eps_sufficient_descent', + 'qp_tol_stat', 'qp_tol_eq', 'qp_tol_ineq', 'qp_tol_comp', 'qp_tau_min', 'qp_mu0'] string_fields = ['globalization'] # check field availability and type @@ -1522,10 +1778,10 @@ class AcadosOcpSolver: if field_ == 'rti_phase': if value_ < 0 or value_ > 2: - raise Exception('AcadosOcpSolver.solve(): argument \'rti_phase\' can ' + raise Exception('AcadosOcpSolver.options_set(): argument \'rti_phase\' can ' 'take only values 0, 1, 2 for SQP-RTI-type solvers') - if self.acados_ocp.solver_options.nlp_solver_type != 'SQP_RTI' and value_ > 0: - raise Exception('AcadosOcpSolver.solve(): argument \'rti_phase\' can ' + if self.solver_options['nlp_solver_type'] != 'SQP_RTI' and value_ > 0: + raise Exception('AcadosOcpSolver.options_set(): argument \'rti_phase\' can ' 'take only value 0 for SQP-type solvers') # encode diff --git a/pyextra/acados_template/acados_ocp_solver_fast.py b/pyextra/acados_template/acados_ocp_solver_fast.py deleted file mode 100644 index 656d288f1c..0000000000 --- a/pyextra/acados_template/acados_ocp_solver_fast.py +++ /dev/null @@ -1,402 +0,0 @@ -import sys -import os -import json -import numpy as np -from datetime import datetime - -from ctypes import POINTER, CDLL, c_void_p, c_int, cast, c_double, c_char_p - -from copy import deepcopy - -from .generate_c_code_explicit_ode import generate_c_code_explicit_ode -from .generate_c_code_implicit_ode import generate_c_code_implicit_ode -from .generate_c_code_gnsf import generate_c_code_gnsf -from .generate_c_code_discrete_dynamics import generate_c_code_discrete_dynamics -from .generate_c_code_constraint import generate_c_code_constraint -from .generate_c_code_nls_cost import generate_c_code_nls_cost -from .generate_c_code_external_cost import generate_c_code_external_cost -from .acados_ocp import AcadosOcp -from .acados_model import acados_model_strip_casadi_symbolics -from .utils import is_column, is_empty, casadi_length, render_template, acados_class2dict,\ - format_class_dict, ocp_check_against_layout, np_array_to_list, make_model_consistent,\ - set_up_imported_gnsf_model, get_acados_path - - -class AcadosOcpSolverFast: - dlclose = CDLL(None).dlclose - dlclose.argtypes = [c_void_p] - - def __init__(self, model_name, N, code_export_dir): - - self.solver_created = False - self.N = N - self.model_name = model_name - - self.shared_lib_name = f'{code_export_dir}/libacados_ocp_solver_{model_name}.so' - - # get shared_lib - self.shared_lib = CDLL(self.shared_lib_name) - - # create capsule - getattr(self.shared_lib, f"{model_name}_acados_create_capsule").restype = c_void_p - self.capsule = getattr(self.shared_lib, f"{model_name}_acados_create_capsule")() - - # create solver - getattr(self.shared_lib, f"{model_name}_acados_create").argtypes = [c_void_p] - getattr(self.shared_lib, f"{model_name}_acados_create").restype = c_int - assert getattr(self.shared_lib, f"{model_name}_acados_create")(self.capsule)==0 - self.solver_created = True - - # get pointers solver - getattr(self.shared_lib, f"{model_name}_acados_get_nlp_opts").argtypes = [c_void_p] - getattr(self.shared_lib, f"{model_name}_acados_get_nlp_opts").restype = c_void_p - self.nlp_opts = getattr(self.shared_lib, f"{model_name}_acados_get_nlp_opts")(self.capsule) - - getattr(self.shared_lib, f"{model_name}_acados_get_nlp_dims").argtypes = [c_void_p] - getattr(self.shared_lib, f"{model_name}_acados_get_nlp_dims").restype = c_void_p - self.nlp_dims = getattr(self.shared_lib, f"{model_name}_acados_get_nlp_dims")(self.capsule) - - getattr(self.shared_lib, f"{model_name}_acados_get_nlp_config").argtypes = [c_void_p] - getattr(self.shared_lib, f"{model_name}_acados_get_nlp_config").restype = c_void_p - self.nlp_config = getattr(self.shared_lib, f"{model_name}_acados_get_nlp_config")(self.capsule) - - getattr(self.shared_lib, f"{model_name}_acados_get_nlp_out").argtypes = [c_void_p] - getattr(self.shared_lib, f"{model_name}_acados_get_nlp_out").restype = c_void_p - self.nlp_out = getattr(self.shared_lib, f"{model_name}_acados_get_nlp_out")(self.capsule) - - getattr(self.shared_lib, f"{model_name}_acados_get_nlp_in").argtypes = [c_void_p] - getattr(self.shared_lib, f"{model_name}_acados_get_nlp_in").restype = c_void_p - self.nlp_in = getattr(self.shared_lib, f"{model_name}_acados_get_nlp_in")(self.capsule) - - getattr(self.shared_lib, f"{model_name}_acados_get_nlp_solver").argtypes = [c_void_p] - getattr(self.shared_lib, f"{model_name}_acados_get_nlp_solver").restype = c_void_p - self.nlp_solver = getattr(self.shared_lib, f"{model_name}_acados_get_nlp_solver")(self.capsule) - - - def solve(self): - """ - Solve the ocp with current input. - """ - model_name = self.model_name - - getattr(self.shared_lib, f"{model_name}_acados_solve").argtypes = [c_void_p] - getattr(self.shared_lib, f"{model_name}_acados_solve").restype = c_int - status = getattr(self.shared_lib, f"{model_name}_acados_solve")(self.capsule) - return status - - def cost_set(self, start_stage_, field_, value_, api='warn'): - self.cost_set_slice(start_stage_, start_stage_+1, field_, value_[None], api='warn') - return - - def cost_set_slice(self, start_stage_, end_stage_, field_, value_, api='warn'): - """ - Set numerical data in the cost module of the solver. - - :param stage: integer corresponding to shooting node - :param field: string, e.g. 'yref', 'W', 'ext_cost_num_hess' - :param value: of appropriate size - """ - # cast value_ to avoid conversion issues - if isinstance(value_, (float, int)): - value_ = np.array([value_]) - value_ = np.ascontiguousarray(np.copy(value_), dtype=np.float64) - field = field_ - field = field.encode('utf-8') - dim = np.product(value_.shape[1:]) - - start_stage = c_int(start_stage_) - end_stage = c_int(end_stage_) - self.shared_lib.ocp_nlp_cost_dims_get_from_attr.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, POINTER(c_int)] - self.shared_lib.ocp_nlp_cost_dims_get_from_attr.restype = c_int - - dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) - dims_data = cast(dims.ctypes.data, POINTER(c_int)) - - self.shared_lib.ocp_nlp_cost_dims_get_from_attr(self.nlp_config, - self.nlp_dims, self.nlp_out, start_stage_, field, dims_data) - - value_shape = value_.shape - expected_shape = tuple(np.concatenate([np.array([end_stage_ - start_stage_]), dims])) - if len(value_shape) == 2: - value_shape = (value_shape[0], value_shape[1], 0) - - elif len(value_shape) == 3: - if api=='old': - pass - elif api=='warn': - if not np.all(np.ravel(value_, order='F')==np.ravel(value_, order='K')): - raise Exception("Ambiguity in API detected.\n" - "Are you making an acados model from scrach? Add api='new' to cost_set and carry on.\n" - "Are you seeing this error suddenly in previously running code? Read on.\n" - " You are relying on a now-fixed bug in cost_set for field '{}'.\n".format(field_) + - " acados_template now correctly passes on any matrices to acados in column major format.\n" + - " Two options to fix this error: \n" + - " * Add api='old' to cost_set to restore old incorrect behaviour\n" + - " * Add api='new' to cost_set and remove any unnatural manipulation of the value argument " + - "such as non-mathematical transposes, reshaping, casting to fortran order, etc... " + - "If there is no such manipulation, then you have probably been getting an incorrect solution before.") - # Get elements in column major order - value_ = np.ravel(value_, order='F') - elif api=='new': - # Get elements in column major order - value_ = np.ravel(value_, order='F') - else: - raise Exception("Unknown api: '{}'".format(api)) - - if value_shape != expected_shape: - raise Exception('AcadosOcpSolver.cost_set(): mismatching dimension', - ' for field "{}" with dimension {} (you have {})'.format( - field_, expected_shape, value_shape)) - - - value_data = cast(value_.ctypes.data, POINTER(c_double)) - value_data_p = cast((value_data), c_void_p) - - self.shared_lib.ocp_nlp_cost_model_set_slice.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_int, c_char_p, c_void_p, c_int] - self.shared_lib.ocp_nlp_cost_model_set_slice(self.nlp_config, - self.nlp_dims, self.nlp_in, start_stage, end_stage, field, value_data_p, dim) - return - - def constraints_set(self, start_stage_, field_, value_, api='warn'): - self.constraints_set_slice(start_stage_, start_stage_+1, field_, value_[None], api='warn') - return - - def constraints_set_slice(self, start_stage_, end_stage_, field_, value_, api='warn'): - """ - Set numerical data in the constraint module of the solver. - - :param stage: integer corresponding to shooting node - :param field: string in ['lbx', 'ubx', 'lbu', 'ubu', 'lg', 'ug', 'lh', 'uh', 'uphi'] - :param value: of appropriate size - """ - # cast value_ to avoid conversion issues - if isinstance(value_, (float, int)): - value_ = np.array([value_]) - value_ = value_.astype(float) - - field = field_ - field = field.encode('utf-8') - dim = np.product(value_.shape[1:]) - - start_stage = c_int(start_stage_) - end_stage = c_int(end_stage_) - self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, POINTER(c_int)] - self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.restype = c_int - - dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) - dims_data = cast(dims.ctypes.data, POINTER(c_int)) - - self.shared_lib.ocp_nlp_constraint_dims_get_from_attr(self.nlp_config, \ - self.nlp_dims, self.nlp_out, start_stage_, field, dims_data) - - value_shape = value_.shape - expected_shape = tuple(np.concatenate([np.array([end_stage_ - start_stage_]), dims])) - if len(value_shape) == 2: - value_shape = (value_shape[0], value_shape[1], 0) - elif len(value_shape) == 3: - if api=='old': - pass - elif api=='warn': - if not np.all(np.ravel(value_, order='F')==np.ravel(value_, order='K')): - raise Exception("Ambiguity in API detected.\n" - "Are you making an acados model from scrach? Add api='new' to constraints_set and carry on.\n" - "Are you seeing this error suddenly in previously running code? Read on.\n" - " You are relying on a now-fixed bug in constraints_set for field '{}'.\n".format(field_) + - " acados_template now correctly passes on any matrices to acados in column major format.\n" + - " Two options to fix this error: \n" + - " * Add api='old' to constraints_set to restore old incorrect behaviour\n" + - " * Add api='new' to constraints_set and remove any unnatural manipulation of the value argument " + - "such as non-mathematical transposes, reshaping, casting to fortran order, etc... " + - "If there is no such manipulation, then you have probably been getting an incorrect solution before.") - # Get elements in column major order - value_ = np.ravel(value_, order='F') - elif api=='new': - # Get elements in column major order - value_ = np.ravel(value_, order='F') - else: - raise Exception("Unknown api: '{}'".format(api)) - if value_shape != expected_shape: - raise Exception('AcadosOcpSolver.constraints_set(): mismatching dimension' \ - ' for field "{}" with dimension {} (you have {})'.format(field_, expected_shape, value_shape)) - - value_data = cast(value_.ctypes.data, POINTER(c_double)) - value_data_p = cast((value_data), c_void_p) - - self.shared_lib.ocp_nlp_constraints_model_set_slice.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_int, c_char_p, c_void_p, c_int] - self.shared_lib.ocp_nlp_constraints_model_set_slice(self.nlp_config, \ - self.nlp_dims, self.nlp_in, start_stage, end_stage, field, value_data_p, dim) - return - - # Note: this function should not be used anymore, better use cost_set, constraints_set - def set(self, stage_, field_, value_): - """ - Set numerical data inside the solver. - - :param stage: integer corresponding to shooting node - :param field: string in ['x', 'u', 'pi', 'lam', 't', 'p'] - - .. note:: regarding lam, t: \n - the inequalities are internally organized in the following order: \n - [ lbu lbx lg lh lphi ubu ubx ug uh uphi; \n - lsbu lsbx lsg lsh lsphi usbu usbx usg ush usphi] - - .. note:: pi: multipliers for dynamics equality constraints \n - lam: multipliers for inequalities \n - t: slack variables corresponding to evaluation of all inequalities (at the solution) \n - sl: slack variables of soft lower inequality constraints \n - su: slack variables of soft upper inequality constraints \n - """ - cost_fields = ['y_ref', 'yref'] - constraints_fields = ['lbx', 'ubx', 'lbu', 'ubu'] - out_fields = ['x', 'u', 'pi', 'lam', 't', 'z'] - mem_fields = ['sl', 'su'] - - # cast value_ to avoid conversion issues - if isinstance(value_, (float, int)): - value_ = np.array([value_]) - value_ = value_.astype(float) - - model_name = self.model_name - - field = field_ - field = field.encode('utf-8') - - stage = c_int(stage_) - - # treat parameters separately - if field_ == 'p': - getattr(self.shared_lib, f"{model_name}_acados_update_params").argtypes = [c_void_p, c_int, POINTER(c_double)] - getattr(self.shared_lib, f"{model_name}_acados_update_params").restype = c_int - - value_data = cast(value_.ctypes.data, POINTER(c_double)) - - assert getattr(self.shared_lib, f"{model_name}_acados_update_params")(self.capsule, stage, value_data, value_.shape[0])==0 - else: - if field_ not in constraints_fields + cost_fields + out_fields + mem_fields: - raise Exception("AcadosOcpSolver.set(): {} is not a valid argument.\ - \nPossible values are {}. Exiting.".format(field, \ - constraints_fields + cost_fields + out_fields + ['p'])) - - self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p] - self.shared_lib.ocp_nlp_dims_get_from_attr.restype = c_int - - dims = self.shared_lib.ocp_nlp_dims_get_from_attr(self.nlp_config, \ - self.nlp_dims, self.nlp_out, stage_, field) - - if value_.shape[0] != dims: - msg = 'AcadosOcpSolver.set(): mismatching dimension for field "{}" '.format(field_) - msg += 'with dimension {} (you have {})'.format(dims, value_.shape) - raise Exception(msg) - - value_data = cast(value_.ctypes.data, POINTER(c_double)) - value_data_p = cast((value_data), c_void_p) - - if field_ in constraints_fields: - self.shared_lib.ocp_nlp_constraints_model_set.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_constraints_model_set(self.nlp_config, \ - self.nlp_dims, self.nlp_in, stage, field, value_data_p) - elif field_ in cost_fields: - self.shared_lib.ocp_nlp_cost_model_set.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_cost_model_set(self.nlp_config, \ - self.nlp_dims, self.nlp_in, stage, field, value_data_p) - elif field_ in out_fields: - self.shared_lib.ocp_nlp_out_set.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_out_set(self.nlp_config, \ - self.nlp_dims, self.nlp_out, stage, field, value_data_p) - elif field_ in mem_fields: - self.shared_lib.ocp_nlp_set.argtypes = \ - [c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_set(self.nlp_config, \ - self.nlp_solver, stage, field, value_data_p) - return - - - def get_slice(self, start_stage_, end_stage_, field_): - """ - Get the last solution of the solver: - - :param start_stage: integer corresponding to shooting node that indicates start of slice - :param end_stage: integer corresponding to shooting node that indicates end of slice - :param field: string in ['x', 'u', 'z', 'pi', 'lam', 't', 'sl', 'su',] - - .. note:: regarding lam, t: \n - the inequalities are internally organized in the following order: \n - [ lbu lbx lg lh lphi ubu ubx ug uh uphi; \n - lsbu lsbx lsg lsh lsphi usbu usbx usg ush usphi] - - .. note:: pi: multipliers for dynamics equality constraints \n - lam: multipliers for inequalities \n - t: slack variables corresponding to evaluation of all inequalities (at the solution) \n - sl: slack variables of soft lower inequality constraints \n - su: slack variables of soft upper inequality constraints \n - """ - out_fields = ['x', 'u', 'z', 'pi', 'lam', 't'] - mem_fields = ['sl', 'su'] - field = field_ - field = field.encode('utf-8') - - if (field_ not in out_fields + mem_fields): - raise Exception('AcadosOcpSolver.get_slice(): {} is an invalid argument.\ - \n Possible values are {}. Exiting.'.format(field_, out_fields)) - - if not isinstance(start_stage_, int): - raise Exception('AcadosOcpSolver.get_slice(): stage index must be Integer.') - - if not isinstance(end_stage_, int): - raise Exception('AcadosOcpSolver.get_slice(): stage index must be Integer.') - - if start_stage_ >= end_stage_: - raise Exception('AcadosOcpSolver.get_slice(): end stage index must be larger than start stage index') - - if start_stage_ < 0 or end_stage_ > self.N + 1: - raise Exception('AcadosOcpSolver.get_slice(): stage index must be in [0, N], got: {}.'.format(self.N)) - self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p] - self.shared_lib.ocp_nlp_dims_get_from_attr.restype = c_int - - dims = self.shared_lib.ocp_nlp_dims_get_from_attr(self.nlp_config, \ - self.nlp_dims, self.nlp_out, start_stage_, field) - - out = np.ascontiguousarray(np.zeros((end_stage_ - start_stage_, dims)), dtype=np.float64) - out_data = cast(out.ctypes.data, POINTER(c_double)) - - if (field_ in out_fields): - self.shared_lib.ocp_nlp_out_get_slice.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_out_get_slice(self.nlp_config, \ - self.nlp_dims, self.nlp_out, start_stage_, end_stage_, field, out_data) - elif field_ in mem_fields: - self.shared_lib.ocp_nlp_get_at_stage.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_get_at_stage(self.nlp_config, \ - self.nlp_dims, self.nlp_solver, start_stage_, end_stage_, field, out_data) - - return out - - def get_cost(self): - """ - Returns the cost value of the current solution. - """ - # compute cost internally - self.shared_lib.ocp_nlp_eval_cost.argtypes = [c_void_p, c_void_p, c_void_p] - self.shared_lib.ocp_nlp_eval_cost(self.nlp_solver, self.nlp_in, self.nlp_out) - - # create output array - out = np.ascontiguousarray(np.zeros((1,)), dtype=np.float64) - out_data = cast(out.ctypes.data, POINTER(c_double)) - - # call getter - self.shared_lib.ocp_nlp_get.argtypes = [c_void_p, c_void_p, c_char_p, c_void_p] - - field = "cost_value".encode('utf-8') - self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) - - return out[0] diff --git a/pyextra/acados_template/acados_ocp_solver_pyx.pyx b/pyextra/acados_template/acados_ocp_solver_pyx.pyx index 9bcf5bb46a..fe7fa8425a 100644 --- a/pyextra/acados_template/acados_ocp_solver_pyx.pyx +++ b/pyextra/acados_template/acados_ocp_solver_pyx.pyx @@ -39,21 +39,19 @@ cimport cython from libc cimport string cimport acados_solver_common +# TODO: make this import more clear? it is not a general solver, but problem specific. cimport acados_solver cimport numpy as cnp import os +from datetime import datetime import numpy as np -cdef class AcadosOcpSolverFast: +cdef class AcadosOcpSolverCython: """ Class to interact with the acados ocp solver C object. - - :param acados_ocp: type AcadosOcp - description of the OCP for acados - :param json_file: name for the json file used to render the templated code - default: acados_ocp_nlp.json - :param simulink_opts: Options to configure Simulink S-function blocks, mainly to activate possible Inputs and Outputs """ cdef acados_solver.nlp_solver_capsule *capsule @@ -61,19 +59,26 @@ cdef class AcadosOcpSolverFast: cdef acados_solver_common.ocp_nlp_dims *nlp_dims cdef acados_solver_common.ocp_nlp_config *nlp_config cdef acados_solver_common.ocp_nlp_out *nlp_out + cdef acados_solver_common.ocp_nlp_out *sens_out cdef acados_solver_common.ocp_nlp_in *nlp_in cdef acados_solver_common.ocp_nlp_solver *nlp_solver + cdef int status + cdef bint solver_created + cdef str model_name cdef int N - cdef bint solver_created - def __cinit__(self, str model_name, int N, str code_export_dir): - self.model_name = model_name - self.N = N + cdef str nlp_solver_type + + def __cinit__(self, model_name, nlp_solver_type, N): self.solver_created = False + self.N = N + self.model_name = model_name + self.nlp_solver_type = nlp_solver_type + # create capsule self.capsule = acados_solver.acados_create_capsule() @@ -81,11 +86,21 @@ cdef class AcadosOcpSolverFast: assert acados_solver.acados_create(self.capsule) == 0 self.solver_created = True + # get pointers solver + self.__get_pointers_solver() + self.status = 0 + + + def __get_pointers_solver(self): + """ + Private function to get the pointers for solver + """ # get pointers solver self.nlp_opts = acados_solver.acados_get_nlp_opts(self.capsule) self.nlp_dims = acados_solver.acados_get_nlp_dims(self.capsule) self.nlp_config = acados_solver.acados_get_nlp_config(self.capsule) self.nlp_out = acados_solver.acados_get_nlp_out(self.capsule) + self.sens_out = acados_solver.acados_get_sens_out(self.capsule) self.nlp_in = acados_solver.acados_get_nlp_in(self.capsule) self.nlp_solver = acados_solver.acados_get_nlp_solver(self.capsule) @@ -97,17 +112,121 @@ cdef class AcadosOcpSolverFast: return acados_solver.acados_solve(self.capsule) + def reset(self): + """ + Sets current iterate to all zeros. + """ + return acados_solver.acados_reset(self.capsule) + + def set_new_time_steps(self, new_time_steps): """ - Set new time steps before solving. Only reload library without code generation but with new time steps. + Set new time steps. + Recreates the solver if N changes. - :param new_time_steps: vector of new time steps for the solver + :param new_time_steps: 1 dimensional np array of new time steps for the solver .. note:: This allows for different use-cases: either set a new size of time-steps or a new distribution of the shooting nodes without changing the number, e.g., to reach a different final time. Both cases do not require a new code export and compilation. """ - raise NotImplementedError() + + raise NotImplementedError("AcadosOcpSolverCython: does not support set_new_time_steps() since it is only a prototyping feature") + # # unlikely but still possible + # if not self.solver_created: + # raise Exception('Solver was not yet created!') + + # ## check if time steps really changed in value + # # get time steps + # cdef cnp.ndarray[cnp.float64_t, ndim=1] old_time_steps = np.ascontiguousarray(np.zeros((self.N,)), dtype=np.float64) + # assert acados_solver.acados_get_time_steps(self.capsule, self.N, old_time_steps.data) + + # if np.array_equal(old_time_steps, new_time_steps): + # return + + # N = new_time_steps.size + # cdef cnp.ndarray[cnp.float64_t, ndim=1] value = np.ascontiguousarray(new_time_steps, dtype=np.float64) + + # # check if recreation of acados is necessary (no need to recreate acados if sizes are identical) + # if len(old_time_steps) == N: + # assert acados_solver.acados_update_time_steps(self.capsule, N, value.data) == 0 + + # else: # recreate the solver with the new time steps + # self.solver_created = False + + # # delete old memory (analog to __del__) + # acados_solver.acados_free(self.capsule) + + # # create solver with new time steps + # assert acados_solver.acados_create_with_discretization(self.capsule, N, value.data) == 0 + + # self.solver_created = True + + # # get pointers solver + # self.__get_pointers_solver() + + # # store time_steps, N + # self.time_steps = new_time_steps + # self.N = N + + + def update_qp_solver_cond_N(self, qp_solver_cond_N: int): + """ + Recreate solver with new value `qp_solver_cond_N` with a partial condensing QP solver. + This function is relevant for code reuse, i.e., if either `set_new_time_steps(...)` is used or + the influence of a different `qp_solver_cond_N` is studied without code export and compilation. + :param qp_solver_cond_N: new number of condensing stages for the solver + + .. note:: This function can only be used in combination with a partial condensing QP solver. + + .. note:: After `set_new_time_steps(...)` is used and depending on the new number of time steps it might be + necessary to change `qp_solver_cond_N` as well (using this function), i.e., typically + `qp_solver_cond_N < N`. + """ + raise NotImplementedError("AcadosOcpSolverCython: does not support update_qp_solver_cond_N() since it is only a prototyping feature") + + # # unlikely but still possible + # if not self.solver_created: + # raise Exception('Solver was not yet created!') + # if self.N < qp_solver_cond_N: + # raise Exception('Setting qp_solver_cond_N to be larger than N does not work!') + # if self.qp_solver_cond_N != qp_solver_cond_N: + # self.solver_created = False + + # # recreate the solver + # acados_solver.acados_update_qp_solver_cond_N(self.capsule, qp_solver_cond_N) + + # # store the new value + # self.qp_solver_cond_N = qp_solver_cond_N + # self.solver_created = True + + # # get pointers solver + # self.__get_pointers_solver() + + + def eval_param_sens(self, index, stage=0, field="ex"): + """ + Calculate the sensitivity of the curent solution with respect to the initial state component of index + + :param index: integer corresponding to initial state index in range(nx) + """ + + field_ = field + field = field_.encode('utf-8') + + # checks + if not isinstance(index, int): + raise Exception('AcadosOcpSolverCython.eval_param_sens(): index must be Integer.') + + cdef int nx = acados_solver_common.ocp_nlp_dims_get_from_attr(self.nlp_config, self.nlp_dims, self.nlp_out, 0, "x".encode('utf-8')) + + if index < 0 or index > nx: + raise Exception(f'AcadosOcpSolverCython.eval_param_sens(): index must be in [0, nx-1], got: {index}.') + + # actual eval_param + acados_solver_common.ocp_nlp_eval_param_sens(self.nlp_solver, field, stage, index, self.sens_out) + + return def get(self, int stage, str field_): @@ -133,14 +252,14 @@ cdef class AcadosOcpSolverFast: field = field_.encode('utf-8') if field_ not in out_fields: - raise Exception('AcadosOcpSolver.get(): {} is an invalid argument.\ + raise Exception('AcadosOcpSolverCython.get(): {} is an invalid argument.\ \n Possible values are {}. Exiting.'.format(field_, out_fields)) if stage < 0 or stage > self.N: - raise Exception('AcadosOcpSolver.get(): stage index must be in [0, N], got: {}.'.format(self.N)) + raise Exception('AcadosOcpSolverCython.get(): stage index must be in [0, N], got: {}.'.format(self.N)) if stage == self.N and field_ == 'pi': - raise Exception('AcadosOcpSolver.get(): field {} does not exist at final stage {}.'\ + raise Exception('AcadosOcpSolverCython.get(): field {} does not exist at final stage {}.'\ .format(field_, stage)) cdef int dims = acados_solver_common.ocp_nlp_dims_get_from_attr(self.nlp_config, @@ -168,7 +287,7 @@ cdef class AcadosOcpSolverFast: - qp_res_ineq: residual wrt inequality constraints (constraints) of the last QP solution - qp_res_comp: residual wrt complementarity conditions of the last QP solution """ - raise NotImplementedError() + acados_solver.acados_print_stats(self.capsule) def store_iterate(self, filename='', overwrite=False): @@ -178,14 +297,50 @@ cdef class AcadosOcpSolverFast: :param filename: if not set, use model_name + timestamp + '.json' :param overwrite: if false and filename exists add timestamp to filename """ - raise NotImplementedError() + import json + if filename == '': + filename += self.model_name + '_' + 'iterate' + '.json' + + if not overwrite: + # append timestamp + if os.path.isfile(filename): + filename = filename[:-5] + filename += datetime.utcnow().strftime('%Y-%m-%d-%H:%M:%S.%f') + '.json' + + # get iterate: + solution = dict() + + for i in range(self.N+1): + solution['x_'+str(i)] = self.get(i,'x') + solution['u_'+str(i)] = self.get(i,'u') + solution['z_'+str(i)] = self.get(i,'z') + solution['lam_'+str(i)] = self.get(i,'lam') + solution['t_'+str(i)] = self.get(i, 't') + solution['sl_'+str(i)] = self.get(i, 'sl') + solution['su_'+str(i)] = self.get(i, 'su') + for i in range(self.N): + solution['pi_'+str(i)] = self.get(i,'pi') + + # save + with open(filename, 'w') as f: + json.dump(solution, f, default=lambda x: x.tolist(), indent=4, sort_keys=True) + print("stored current iterate in ", os.path.join(os.getcwd(), filename)) def load_iterate(self, filename): """ Loads the iterate stored in json file with filename into the ocp solver. """ - raise NotImplementedError() + import json + if not os.path.isfile(filename): + raise Exception('load_iterate: failed, file does not exist: ' + os.path.join(os.getcwd(), filename)) + + with open(filename, 'r') as f: + solution = json.load(f) + + for key in solution.keys(): + (field, stage) = key.split('_') + self.set(int(stage), field, np.array(solution[key])) def get_stats(self, field_): @@ -193,8 +348,97 @@ cdef class AcadosOcpSolverFast: Get the information of the last solver call. :param field: string in ['statistics', 'time_tot', 'time_lin', 'time_sim', 'time_sim_ad', 'time_sim_la', 'time_qp', 'time_qp_solver_call', 'time_reg', 'sqp_iter'] + Available fileds: + - time_tot: total CPU time previous call + - time_lin: CPU time for linearization + - time_sim: CPU time for integrator + - time_sim_ad: CPU time for integrator contribution of external function calls + - time_sim_la: CPU time for integrator contribution of linear algebra + - time_qp: CPU time qp solution + - time_qp_solver_call: CPU time inside qp solver (without converting the QP) + - time_qp_xcond: time_glob: CPU time globalization + - time_solution_sensitivities: CPU time for previous call to eval_param_sens + - time_reg: CPU time regularization + - sqp_iter: number of SQP iterations + - qp_iter: vector of QP iterations for last SQP call + - statistics: table with info about last iteration + - stat_m: number of rows in statistics matrix + - stat_n: number of columns in statistics matrix + - residuals: residuals of last iterate + - alpha: step sizes of SQP iterations """ - raise NotImplementedError() + + double_fields = ['time_tot', + 'time_lin', + 'time_sim', + 'time_sim_ad', + 'time_sim_la', + 'time_qp', + 'time_qp_solver_call', + 'time_qp_xcond', + 'time_glob', + 'time_solution_sensitivities', + 'time_reg' + ] + fields = double_fields + [ + 'sqp_iter', + 'qp_iter', + 'statistics', + 'stat_m', + 'stat_n', + 'residuals', + 'alpha', + ] + field = field_.encode('utf-8') + + if field_ in ['sqp_iter', 'stat_m', 'stat_n']: + return self.__get_stat_int(field) + + elif field_ in double_fields: + return self.__get_stat_double(field) + + elif field_ == 'statistics': + sqp_iter = self.get_stats("sqp_iter") + stat_m = self.get_stats("stat_m") + stat_n = self.get_stats("stat_n") + min_size = min([stat_m, sqp_iter+1]) + return self.__get_stat_matrix(field, stat_n+1, min_size) + + elif field_ == 'qp_iter': + full_stats = self.get_stats('statistics') + if self.nlp_solver_type == 'SQP': + return full_stats[6, :] + elif self.nlp_solver_type == 'SQP_RTI': + return full_stats[2, :] + + elif field_ == 'alpha': + full_stats = self.get_stats('statistics') + if self.nlp_solver_type == 'SQP': + return full_stats[7, :] + else: # self.nlp_solver_type == 'SQP_RTI': + raise Exception("alpha values are not available for SQP_RTI") + + elif field_ == 'residuals': + return self.get_residuals() + + else: + raise NotImplementedError("TODO!") + + + def __get_stat_int(self, field): + cdef int out + acados_solver_common.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, &out) + return out + + def __get_stat_double(self, field): + cdef cnp.ndarray[cnp.float64_t, ndim=1] out = np.zeros((1,)) + acados_solver_common.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out.data) + return out + + def __get_stat_matrix(self, field, n, m): + cdef cnp.ndarray[cnp.float64_t, ndim=2] out_mat = np.ascontiguousarray(np.zeros((n, m)), dtype=np.float64) + acados_solver_common.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_mat.data) + return out_mat def get_cost(self): @@ -213,11 +457,35 @@ cdef class AcadosOcpSolverFast: return out - def get_residuals(self): + def get_residuals(self, recompute=False): """ Returns an array of the form [res_stat, res_eq, res_ineq, res_comp]. """ - raise NotImplementedError() + # compute residuals if RTI + if self.nlp_solver_type == 'SQP_RTI' or recompute: + acados_solver_common.ocp_nlp_eval_residuals(self.nlp_solver, self.nlp_in, self.nlp_out) + + # create output array + cdef cnp.ndarray[cnp.float64_t, ndim=1] out = np.ascontiguousarray(np.zeros((4,), dtype=np.float64)) + cdef double double_value + + field = "res_stat".encode('utf-8') + acados_solver_common.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, &double_value) + out[0] = double_value + + field = "res_eq".encode('utf-8') + acados_solver_common.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, &double_value) + out[1] = double_value + + field = "res_ineq".encode('utf-8') + acados_solver_common.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, &double_value) + out[2] = double_value + + field = "res_comp".encode('utf-8') + acados_solver_common.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, &double_value) + out[3] = double_value + + return out # Note: this function should not be used anymore, better use cost_set, constraints_set @@ -243,18 +511,18 @@ cdef class AcadosOcpSolverFast: cost_fields = ['y_ref', 'yref'] constraints_fields = ['lbx', 'ubx', 'lbu', 'ubu'] out_fields = ['x', 'u', 'pi', 'lam', 't', 'z', 'sl', 'su'] + mem_fields = ['xdot_guess', 'z_guess'] field = field_.encode('utf-8') - cdef double[::1] value + cdef cnp.ndarray[cnp.float64_t, ndim=1] value = np.ascontiguousarray(value_, dtype=np.float64) # treat parameters separately if field_ == 'p': - value = np.ascontiguousarray(value_, dtype=np.double) - assert acados_solver.acados_update_params(self.capsule, stage, &value[0], value.shape[0]) == 0 + assert acados_solver.acados_update_params(self.capsule, stage, value.data, value.shape[0]) == 0 else: if field_ not in constraints_fields + cost_fields + out_fields: - raise Exception("AcadosOcpSolver.set(): {} is not a valid argument.\ + raise Exception("AcadosOcpSolverCython.set(): {} is not a valid argument.\ \nPossible values are {}. Exiting.".format(field, \ constraints_fields + cost_fields + out_fields + ['p'])) @@ -262,20 +530,22 @@ cdef class AcadosOcpSolverFast: self.nlp_dims, self.nlp_out, stage, field) if value_.shape[0] != dims: - msg = 'AcadosOcpSolver.set(): mismatching dimension for field "{}" '.format(field_) + msg = 'AcadosOcpSolverCython.set(): mismatching dimension for field "{}" '.format(field_) msg += 'with dimension {} (you have {})'.format(dims, value_.shape[0]) raise Exception(msg) - value = np.ascontiguousarray(value_, dtype=np.double) if field_ in constraints_fields: acados_solver_common.ocp_nlp_constraints_model_set(self.nlp_config, - self.nlp_dims, self.nlp_in, stage, field, &value[0]) + self.nlp_dims, self.nlp_in, stage, field, value.data) elif field_ in cost_fields: acados_solver_common.ocp_nlp_cost_model_set(self.nlp_config, - self.nlp_dims, self.nlp_in, stage, field, &value[0]) + self.nlp_dims, self.nlp_in, stage, field, value.data) elif field_ in out_fields: acados_solver_common.ocp_nlp_out_set(self.nlp_config, - self.nlp_dims, self.nlp_out, stage, field, &value[0]) + self.nlp_dims, self.nlp_out, stage, field, value.data) + elif field_ in mem_fields: + acados_solver_common.ocp_nlp_set(self.nlp_config, \ + self.nlp_solver, stage, field, value.data) def cost_set(self, int stage, str field_, value_): @@ -304,9 +574,8 @@ cdef class AcadosOcpSolverFast: value = np.asfortranarray(value_) if value_shape[0] != dims[0] or value_shape[1] != dims[1]: - raise Exception('AcadosOcpSolver.cost_set(): mismatching dimension', \ - ' for field "{}" with dimension {} (you have {})'.format( \ - field_, tuple(dims), value_shape)) + raise Exception('AcadosOcpSolverCython.cost_set(): mismatching dimension' + + f' for field "{field_}" at stage {stage} with dimension {tuple(dims)} (you have {value_shape})') acados_solver_common.ocp_nlp_cost_model_set(self.nlp_config, \ self.nlp_dims, self.nlp_in, stage, field, &value[0][0]) @@ -338,8 +607,8 @@ cdef class AcadosOcpSolverFast: value = np.asfortranarray(value_) if value_shape[0] != dims[0] or value_shape[1] != dims[1]: - raise Exception('AcadosOcpSolver.constraints_set(): mismatching dimension' \ - ' for field "{}" with dimension {} (you have {})'.format(field_, tuple(dims), value_shape)) + raise Exception(f'AcadosOcpSolverCython.constraints_set(): mismatching dimension' + + f' for field "{field_}" at stage {stage} with dimension {tuple(dims)} (you have {value_shape})') acados_solver_common.ocp_nlp_constraints_model_set(self.nlp_config, \ self.nlp_dims, self.nlp_in, stage, field, &value[0][0]) @@ -361,7 +630,7 @@ cdef class AcadosOcpSolverFast: acados_solver_common.ocp_nlp_dynamics_dims_get_from_attr(self.nlp_config, self.nlp_dims, self.nlp_out, stage, field, &dims[0]) # create output data - out = np.zeros((dims[0], dims[1]), order='F', dtype=np.float64) + cdef cnp.ndarray[cnp.float64_t, ndim=2] out = np.zeros((dims[0], dims[1]), order='F') # call getter acados_solver_common.ocp_nlp_get_at_stage(self.nlp_config, self.nlp_dims, self.nlp_solver, stage, field, out.data) @@ -373,11 +642,21 @@ cdef class AcadosOcpSolverFast: """ Set options of the solver. - :param field: string, e.g. 'print_level', 'rti_phase', 'initialize_t_slacks', 'step_length', 'alpha_min', 'alpha_reduction' - :param value: of type int, float + :param field: string, e.g. 'print_level', 'rti_phase', 'initialize_t_slacks', 'step_length', 'alpha_min', 'alpha_reduction', 'qp_warm_start', 'line_search_use_sufficient_descent', 'full_step_dual', 'globalization_use_SOC', 'qp_tol_stat', 'qp_tol_eq', 'qp_tol_ineq', 'qp_tol_comp', 'qp_tau_min', 'qp_mu0' + + :param value: of type int, float, string + + - qp_tol_stat: QP solver tolerance stationarity + - qp_tol_eq: QP solver tolerance equalities + - qp_tol_ineq: QP solver tolerance inequalities + - qp_tol_comp: QP solver tolerance complementarity + - qp_tau_min: for HPIPM QP solvers: minimum value of barrier parameter in HPIPM + - qp_mu0: for HPIPM QP solvers: initial value for complementarity slackness + - warm_start_first_qp: indicates if first QP in SQP is warm_started """ - int_fields = ['print_level', 'rti_phase', 'initialize_t_slacks'] - double_fields = ['step_length', 'tol_eq', 'tol_stat', 'tol_ineq', 'tol_comp', 'alpha_min', 'alpha_reduction'] + int_fields = ['print_level', 'rti_phase', 'initialize_t_slacks', 'qp_warm_start', 'line_search_use_sufficient_descent', 'full_step_dual', 'globalization_use_SOC', 'warm_start_first_qp'] + double_fields = ['step_length', 'tol_eq', 'tol_stat', 'tol_ineq', 'tol_comp', 'alpha_min', 'alpha_reduction', 'eps_sufficient_descent', + 'qp_tol_stat', 'qp_tol_eq', 'qp_tol_ineq', 'qp_tol_comp', 'qp_tau_min', 'qp_mu0'] string_fields = ['globalization'] # encode @@ -394,10 +673,10 @@ cdef class AcadosOcpSolverFast: if field_ == 'rti_phase': if value_ < 0 or value_ > 2: - raise Exception('AcadosOcpSolver.solve(): argument \'rti_phase\' can ' + raise Exception('AcadosOcpSolverCython.solve(): argument \'rti_phase\' can ' 'take only values 0, 1, 2 for SQP-RTI-type solvers') - if self.acados_ocp.solver_options.nlp_solver_type != 'SQP_RTI' and value_ > 0: - raise Exception('AcadosOcpSolver.solve(): argument \'rti_phase\' can ' + if self.nlp_solver_type != 'SQP_RTI' and value_ > 0: + raise Exception('AcadosOcpSolverCython.solve(): argument \'rti_phase\' can ' 'take only value 0 for SQP-type solvers') int_value = value_ @@ -418,7 +697,7 @@ cdef class AcadosOcpSolverFast: acados_solver_common.ocp_nlp_solver_opts_set(self.nlp_config, self.nlp_opts, field, &string_value[0]) else: - raise Exception('AcadosOcpSolver.options_set() does not support field {}.'\ + raise Exception('AcadosOcpSolverCython.options_set() does not support field {}.'\ '\n Possible values are {}.'.format(field_, ', '.join(int_fields + double_fields + string_fields))) diff --git a/pyextra/acados_template/acados_sim.py b/pyextra/acados_template/acados_sim.py index d7ad1487dc..93d5f298db 100644 --- a/pyextra/acados_template/acados_sim.py +++ b/pyextra/acados_template/acados_sim.py @@ -70,28 +70,28 @@ class AcadosSimDims: @nx.setter def nx(self, nx): - if type(nx) == int and nx > 0: + if isinstance(nx, int) and nx > 0: self.__nx = nx else: raise Exception('Invalid nx value, expected positive integer. Exiting.') @nz.setter def nz(self, nz): - if type(nz) == int and nz > -1: + if isinstance(nz, int) and nz > -1: self.__nz = nz else: raise Exception('Invalid nz value, expected nonnegative integer. Exiting.') @nu.setter def nu(self, nu): - if type(nu) == int and nu > -1: + if isinstance(nu, int) and nu > -1: self.__nu = nu else: raise Exception('Invalid nu value, expected nonnegative integer. Exiting.') @np.setter def np(self, np): - if type(np) == int and np > -1: + if isinstance(np, int) and np > -1: self.__np = np else: raise Exception('Invalid np value, expected nonnegative integer. Exiting.') @@ -294,14 +294,15 @@ class AcadosSim: self.solver_options = AcadosSimOpts() """Solver Options, type :py:class:`acados_template.acados_sim.AcadosSimOpts`""" - self.acados_include_path = f'{acados_path}/include' - """Path to acados include directors (set automatically), type: `string`""" - self.acados_lib_path = f'{acados_path}/lib' + self.acados_include_path = os.path.join(acados_path, 'include').replace(os.sep, '/') # the replace part is important on Windows for CMake + """Path to acados include directory (set automatically), type: `string`""" + self.acados_lib_path = os.path.join(acados_path, 'lib').replace(os.sep, '/') # the replace part is important on Windows for CMake """Path to where acados library is located (set automatically), type: `string`""" self.code_export_directory = 'c_generated_code' """Path to where code will be exported. Default: `c_generated_code`.""" + self.cython_include_dirs = '' self.__parameter_values = np.array([]) @property diff --git a/pyextra/acados_template/acados_sim_solver.py b/pyextra/acados_template/acados_sim_solver.py index 145f90293e..3588dd38cd 100644 --- a/pyextra/acados_template/acados_sim_solver.py +++ b/pyextra/acados_template/acados_sim_solver.py @@ -47,6 +47,7 @@ from .acados_ocp import AcadosOcp from .acados_model import acados_model_strip_casadi_symbolics from .utils import is_column, render_template, format_class_dict, np_array_to_list,\ make_model_consistent, set_up_imported_gnsf_model, get_python_interface_path +from .builders import CMakeBuilder def make_sim_dims_consistent(acados_sim): @@ -111,7 +112,17 @@ def sim_formulation_json_dump(acados_sim, json_file='acados_sim.json'): json.dump(sim_json, f, default=np_array_to_list, indent=4, sort_keys=True) -def sim_render_templates(json_file, model_name, code_export_dir): +def sim_get_default_cmake_builder() -> CMakeBuilder: + """ + If :py:class:`~acados_template.acados_sim_solver.AcadosSimSolver` is used with `CMake` this function returns a good first setting. + :return: default :py:class:`~acados_template.builders.CMakeBuilder` + """ + cmake_builder = CMakeBuilder() + cmake_builder.options_on = ['BUILD_ACADOS_SIM_SOLVER_LIB'] + return cmake_builder + + +def sim_render_templates(json_file, model_name, code_export_dir, cmake_options: CMakeBuilder = None): # setting up loader and environment json_path = os.path.join(os.getcwd(), json_file) @@ -129,9 +140,15 @@ def sim_render_templates(json_file, model_name, code_export_dir): out_file = f'acados_sim_solver_{model_name}.h' render_template(in_file, out_file, template_dir, json_path) - in_file = 'Makefile.in' - out_file = f'Makefile' - render_template(in_file, out_file, template_dir, json_path) + # Builder + if cmake_options is not None: + in_file = 'CMakeLists.in.txt' + out_file = 'CMakeLists.txt' + render_template(in_file, out_file, template_dir, json_path) + else: + in_file = 'Makefile.in' + out_file = 'Makefile' + render_template(in_file, out_file, template_dir, json_path) in_file = 'main_sim.in.c' out_file = f'main_sim_{model_name}.c' @@ -161,15 +178,19 @@ def sim_generate_casadi_functions(acados_sim): elif integrator_type == 'GNSF': generate_c_code_gnsf(model, opts) + class AcadosSimSolver: """ Class to interact with the acados integrator C object. - :param acados_sim: type :py:class:`acados_template.acados_ocp.AcadosOcp` (takes values to generate an instance :py:class:`acados_template.acados_sim.AcadosSim`) or :py:class:`acados_template.acados_sim.AcadosSim` - :param json_file: Default: 'acados_sim.json' - :param build: Default: True + :param acados_sim: type :py:class:`~acados_template.acados_ocp.AcadosOcp` (takes values to generate an instance :py:class:`~acados_template.acados_sim.AcadosSim`) or :py:class:`~acados_template.acados_sim.AcadosSim` + :param json_file: Default: 'acados_sim.json' + :param build: Default: True + :param cmake_builder: type :py:class:`~acados_template.utils.CMakeBuilder` generate a `CMakeLists.txt` and use + the `CMake` pipeline instead of a `Makefile` (`CMake` seems to be the better option in conjunction with + `MS Visual Studio`); default: `None` """ - def __init__(self, acados_sim_, json_file='acados_sim.json', build=True): + def __init__(self, acados_sim_, json_file='acados_sim.json', build=True, cmake_builder: CMakeBuilder = None): self.solver_created = False @@ -203,21 +224,50 @@ class AcadosSimSolver: code_export_dir = acados_sim.code_export_directory if build: # render templates - sim_render_templates(json_file, model_name, code_export_dir) + sim_render_templates(json_file, model_name, code_export_dir, cmake_builder) - ## Compile solver + # Compile solver cwd = os.getcwd() + code_export_dir = os.path.abspath(code_export_dir) os.chdir(code_export_dir) - os.system('make sim_shared_lib') + if cmake_builder is not None: + cmake_builder.exec(code_export_dir) + else: + os.system('make sim_shared_lib') os.chdir(cwd) self.sim_struct = acados_sim model_name = self.sim_struct.model.name self.model_name = model_name + # Load acados library to avoid unloading the library. + # This is necessary if acados was compiled with OpenMP, since the OpenMP threads can't be destroyed. + # Unloading a library which uses OpenMP results in a segfault (on any platform?). + # see [https://stackoverflow.com/questions/34439956/vc-crash-when-freeing-a-dll-built-with-openmp] + # or [https://python.hotexamples.com/examples/_ctypes/-/dlclose/python-dlclose-function-examples.html] + libacados_name = 'libacados.so' + libacados_filepath = os.path.join(acados_sim.acados_lib_path, libacados_name) + self.__acados_lib = CDLL(libacados_filepath) + # find out if acados was compiled with OpenMP + try: + self.__acados_lib_uses_omp = getattr(self.__acados_lib, 'omp_get_thread_num') is not None + except AttributeError as e: + self.__acados_lib_uses_omp = False + if self.__acados_lib_uses_omp: + print('acados was compiled with OpenMP.') + else: + print('acados was compiled without OpenMP.') + # Ctypes - shared_lib = f'{code_export_dir}/libacados_sim_solver_{model_name}.so' - self.shared_lib = CDLL(shared_lib) + lib_prefix = 'lib' + lib_ext = '.so' + if os.name == 'nt': + lib_prefix = '' + lib_ext = '' + self.shared_lib_name = os.path.join(code_export_dir, f'{lib_prefix}acados_sim_solver_{model_name}{lib_ext}') + print(f'self.shared_lib_name = "{self.shared_lib_name}"') + + self.shared_lib = CDLL(self.shared_lib_name) # create capsule diff --git a/pyextra/acados_template/acados_solver_common.pxd b/pyextra/acados_template/acados_solver_common.pxd index 9314802e61..fedd7190d9 100644 --- a/pyextra/acados_template/acados_solver_common.pxd +++ b/pyextra/acados_template/acados_solver_common.pxd @@ -95,6 +95,7 @@ cdef extern from "acados_c/ocp_nlp_interface.h": # solver void ocp_nlp_eval_residuals(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in, ocp_nlp_out *nlp_out) + void ocp_nlp_eval_param_sens(ocp_nlp_solver *solver, char *field, int stage, int index, ocp_nlp_out *sens_nlp_out) void ocp_nlp_eval_cost(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in_, ocp_nlp_out *nlp_out) # get/set diff --git a/pyextra/acados_template/builders.py b/pyextra/acados_template/builders.py new file mode 100644 index 0000000000..f595033ceb --- /dev/null +++ b/pyextra/acados_template/builders.py @@ -0,0 +1,116 @@ +# -*- coding: future_fstrings -*- +# +# Copyright 2019 Gianluca Frison, Dimitris Kouzoupis, Robin Verschueren, +# Andrea Zanelli, Niels van Duijkeren, Jonathan Frey, Tommaso Sartor, +# Branimir Novoselnik, Rien Quirynen, Rezart Qelibari, Dang Doan, +# Jonas Koenemann, Yutao Chen, Tobias Schöls, Jonas Schlagenhauf, Moritz Diehl +# +# This file is part of acados. +# +# The 2-Clause BSD License +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# +# 2. 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. +# +# 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 AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.; +# + +import os +import sys +from subprocess import call + + +class CMakeBuilder: + """ + Class to work with the `CMake` build system. + """ + def __init__(self): + self._source_dir = None # private source directory, this is set to code_export_dir + self.build_dir = 'build' + self._build_dir = None # private build directory, usually rendered to abspath(build_dir) + self.generator = None + """Defines the generator, options can be found via `cmake --help` under 'Generator'. Type: string. Linux default 'Unix Makefiles', Windows 'Visual Studio 15 2017 Win64'; default value: `None`.""" + # set something for Windows + if os.name == 'nt': + self.generator = 'Visual Studio 15 2017 Win64' + self.build_targets = None + """A comma-separated list of the build targets, if `None` then all targets will be build; type: List of strings; default: `None`.""" + self.options_on = None + """List of strings as CMake options which are translated to '-D Opt[0]=ON -D Opt[1]=ON ...'; default: `None`.""" + + # Generate the command string for handling the cmake command. + def get_cmd1_cmake(self): + defines_str = '' + if self.options_on is not None: + defines_arr = [f' -D{opt}=ON' for opt in self.options_on] + defines_str = ' '.join(defines_arr) + generator_str = '' + if self.generator is not None: + generator_str = f' -G"{self.generator}"' + return f'cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="{self._source_dir}"{defines_str}{generator_str} -Wdev -S"{self._source_dir}" -B"{self._build_dir}"' + + # Generate the command string for handling the build. + def get_cmd2_build(self): + import multiprocessing + cmd = f'cmake --build "{self._build_dir}" --config Release -j{multiprocessing.cpu_count()}' + if self.build_targets is not None: + cmd += f' -t {self.build_targets}' + return cmd + + # Generate the command string for handling the install command. + def get_cmd3_install(self): + return f'cmake --install "{self._build_dir}"' + + def exec(self, code_export_directory): + """ + Execute the compilation using `CMake` with the given settings. + :param code_export_directory: must be the absolute path to the directory where the code was exported to + """ + if(os.path.isabs(code_export_directory) is False): + print(f'(W) the code export directory "{code_export_directory}" is not an absolute path!') + self._source_dir = code_export_directory + self._build_dir = os.path.abspath(self.build_dir) + try: + os.mkdir(self._build_dir) + except FileExistsError as e: + pass + + try: + os.chdir(self._build_dir) + cmd_str = self.get_cmd1_cmake() + print(f'call("{cmd_str})"') + retcode = call(cmd_str, shell=True) + if retcode != 0: + raise RuntimeError(f'CMake command "{cmd_str}" was terminated by signal {retcode}') + cmd_str = self.get_cmd2_build() + print(f'call("{cmd_str}")') + retcode = call(cmd_str, shell=True) + if retcode != 0: + raise RuntimeError(f'Build command "{cmd_str}" was terminated by signal {retcode}') + cmd_str = self.get_cmd3_install() + print(f'call("{cmd_str}")') + retcode = call(cmd_str, shell=True) + if retcode != 0: + raise RuntimeError(f'Install command "{cmd_str}" was terminated by signal {retcode}') + except OSError as e: + print("Execution failed:", e, file=sys.stderr) + except Exception as e: + print("Execution failed:", e, file=sys.stderr) + exit(1) diff --git a/pyextra/acados_template/c_templates_tera/CMakeLists.in.txt b/pyextra/acados_template/c_templates_tera/CMakeLists.in.txt new file mode 100644 index 0000000000..3d6483b5d2 --- /dev/null +++ b/pyextra/acados_template/c_templates_tera/CMakeLists.in.txt @@ -0,0 +1,374 @@ +# +# Copyright 2019 Gianluca Frison, Dimitris Kouzoupis, Robin Verschueren, +# Andrea Zanelli, Niels van Duijkeren, Jonathan Frey, Tommaso Sartor, +# Branimir Novoselnik, Rien Quirynen, Rezart Qelibari, Dang Doan, +# Jonas Koenemann, Yutao Chen, Tobias Schöls, Jonas Schlagenhauf, Moritz Diehl +# +# This file is part of acados. +# +# The 2-Clause BSD License +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# +# 2. 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. +# +# 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 AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.; +# + +{%- if solver_options.qp_solver %} + {%- set qp_solver = solver_options.qp_solver %} +{%- else %} + {%- set qp_solver = "FULL_CONDENSING_HPIPM" %} +{%- endif %} + +{%- if solver_options.hessian_approx %} + {%- set hessian_approx = solver_options.hessian_approx %} +{%- elif solver_options.sens_hess %} + {%- set hessian_approx = "EXACT" %} +{%- else %} + {%- set hessian_approx = "GAUSS_NEWTON" %} +{%- endif %} + +{%- if constraints.constr_type %} + {%- set constr_type = constraints.constr_type %} +{%- else %} + {%- set constr_type = "NONE" %} +{%- endif %} + +{%- if constraints.constr_type_e %} + {%- set constr_type_e = constraints.constr_type_e %} +{%- else %} + {%- set constr_type_e = "NONE" %} +{%- endif %} + +{%- if cost.cost_type %} + {%- set cost_type = cost.cost_type %} +{%- else %} + {%- set cost_type = "NONE" %} +{%- endif %} + +{%- if cost.cost_type_e %} + {%- set cost_type_e = cost.cost_type_e %} +{%- else %} + {%- set cost_type_e = "NONE" %} +{%- endif %} + +{%- if cost.cost_type_0 %} + {%- set cost_type_0 = cost.cost_type_0 %} +{%- else %} + {%- set cost_type_0 = "NONE" %} +{%- endif %} + +{%- if dims.nh %} + {%- set dims_nh = dims.nh %} +{%- else %} + {%- set dims_nh = 0 %} +{%- endif %} + +{%- if dims.nphi %} + {%- set dims_nphi = dims.nphi %} +{%- else %} + {%- set dims_nphi = 0 %} +{%- endif %} + +{%- if dims.nh_e %} + {%- set dims_nh_e = dims.nh_e %} +{%- else %} + {%- set dims_nh_e = 0 %} +{%- endif %} + +{%- if dims.nphi_e %} + {%- set dims_nphi_e = dims.nphi_e %} +{%- else %} + {%- set dims_nphi_e = 0 %} +{%- endif %} + +{%- if solver_options.model_external_shared_lib_dir %} + {%- set model_external_shared_lib_dir = solver_options.model_external_shared_lib_dir %} +{%- endif %} + +{%- if solver_options.model_external_shared_lib_name %} + {%- set model_external_shared_lib_name = solver_options.model_external_shared_lib_name %} +{%- endif %} + +{#- control operator #} +{%- if os and os == "pc" %} + {%- set control = "&" %} +{%- else %} + {%- set control = ";" %} +{%- endif %} + +{%- if acados_link_libs and os and os == "pc" %}{# acados linking libraries and flags #} + {%- set link_libs = acados_link_libs.qpoases ~ " " ~ acados_link_libs.hpmpc ~ " " ~ acados_link_libs.osqp -%} + {%- set openmp_flag = acados_link_libs.openmp %} +{%- else %} + {%- set openmp_flag = " " %} + {%- if qp_solver == "FULL_CONDENSING_QPOASES" %} + {%- set link_libs = "-lqpOASES_e" %} + {%- else %} + {%- set link_libs = "" %} + {%- endif %} +{%- endif %} + +cmake_minimum_required(VERSION 3.10) + +project({{ model.name }}) + +# build options. +option(BUILD_ACADOS_SOLVER_LIB "Should the solver library acados_solver_{{ model.name }} be build?" OFF) +option(BUILD_ACADOS_OCP_SOLVER_LIB "Should the OCP solver library acados_ocp_solver_{{ model.name }} be build?" OFF) +option(BUILD_EXAMPLE "Should the example main_{{ model.name }} be build?" OFF) +{%- if solver_options.integrator_type != "DISCRETE" %} +option(BUILD_SIM_EXAMPLE "Should the simulation example main_sim_{{ model.name }} be build?" OFF) +option(BUILD_ACADOS_SIM_SOLVER_LIB "Should the simulation solver library acados_sim_solver_{{ model.name }} be build?" OFF) +{%- endif %} + +# object target names +set(MODEL_OBJ model_{{ model.name }}) +set(OCP_OBJ ocp_{{ model.name }}) +set(SIM_OBJ sim_{{ model.name }}) + +# model +set(MODEL_SRC +{%- if solver_options.integrator_type == "ERK" %} + {{ model.name }}_model/{{ model.name }}_expl_ode_fun.c + {{ model.name }}_model/{{ model.name }}_expl_vde_forw.c + {%- if hessian_approx == "EXACT" %} + {{ model.name }}_model/{{ model.name }}_expl_ode_hess.c + {%- endif %} +{%- elif solver_options.integrator_type == "IRK" %} + {{ model.name }}_model/{{ model.name }}_impl_dae_fun.c + {{ model.name }}_model/{{ model.name }}_impl_dae_fun_jac_x_xdot_z.c + {{ model.name }}_model/{{ model.name }}_impl_dae_jac_x_xdot_u_z.c + {%- if hessian_approx == "EXACT" %} + {{ model.name }}_model/{{ model.name }}_impl_dae_hess.c + {%- endif %} +{%- elif solver_options.integrator_type == "LIFTED_IRK" %} + {{ model.name }}_model/{{ model.name }}_impl_dae_fun.c + {{ model.name }}_model/{{ model.name }}_impl_dae_fun_jac_x_xdot_u.c + {%- if hessian_approx == "EXACT" %} + {{ model.name }}_model/{{ model.name }}_impl_dae_hess.c + {%- endif %} +{%- elif solver_options.integrator_type == "GNSF" %} + {% if model.gnsf.purely_linear != 1 %} + {{ model.name }}_model/{{ model.name }}_gnsf_phi_fun.c + {{ model.name }}_model/{{ model.name }}_gnsf_phi_fun_jac_y.c + {{ model.name }}_model/{{ model.name }}_gnsf_phi_jac_y_uhat.c + {% if model.gnsf.nontrivial_f_LO == 1 %} + {{ model.name }}_model/{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz.c + {%- endif %} + {%- endif %} + {{ model.name }}_model/{{ model.name }}_gnsf_get_matrices_fun.c +{%- elif solver_options.integrator_type == "DISCRETE" %} + {%- if model.dyn_ext_fun_type == "casadi" %} + {{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun.c + {{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun_jac.c + {%- if hessian_approx == "EXACT" %} + {{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun_jac_hess.c + {%- endif %} + {%- else %} + {{ model.name }}_model/{{ model.dyn_source_discrete }} + {%- endif %} +{%- endif -%} +) +add_library(${MODEL_OBJ} OBJECT ${MODEL_SRC} ) + +# optimal control problem - mostly CasADi exports +if(${BUILD_ACADOS_SOLVER_LIB} OR ${BUILD_ACADOS_OCP_SOLVER_LIB} OR ${BUILD_EXAMPLE}) + set(OCP_SRC +{%- if constr_type == "BGP" and dims_nphi > 0 %} + {{ model.name }}_constraints/{{ model.name }}_phi_constraint.c +{%- endif %} +{%- if constr_type_e == "BGP" and dims_nphi_e > 0 %} + {{ model.name }}_constraints/{{ model.name }}_phi_e_constraint.c +{%- endif %} + +{%- if constr_type == "BGH" and dims_nh > 0 %} + {{ model.name }}_constraints/{{ model.name }}_constr_h_fun_jac_uxt_zt.c + {{ model.name }}_constraints/{{ model.name }}_constr_h_fun.c + {%- if hessian_approx == "EXACT" %} + {{ model.name }}_constraints/{{ model.name }}_constr_h_fun_jac_uxt_zt_hess.c + {%- endif %} +{%- endif %} + +{%- if constr_type_e == "BGH" and dims_nh_e > 0 %} + {{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun_jac_uxt_zt.c + {{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun.c + {%- if hessian_approx == "EXACT" %} + {{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess.c + {%- endif %} +{%- endif %} + +{%- if cost_type_0 == "NONLINEAR_LS" %} + {{ model.name }}_cost/{{ model.name }}_cost_y_0_fun.c + {{ model.name }}_cost/{{ model.name }}_cost_y_0_fun_jac_ut_xt.c + {{ model.name }}_cost/{{ model.name }}_cost_y_0_hess.c +{%- elif cost_type_0 == "EXTERNAL" %} + {%- if cost.cost_ext_fun_type_0 == "casadi" %} + {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun.c + {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun_jac.c + {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun_jac_hess.c + {%- else %} + {{ model.name }}_cost/{{ cost.cost_source_ext_cost_0 }} + {%- endif %} +{%- endif %} +{%- if cost_type == "NONLINEAR_LS" %} + {{ model.name }}_cost/{{ model.name }}_cost_y_fun.c + {{ model.name }}_cost/{{ model.name }}_cost_y_fun_jac_ut_xt.c + {{ model.name }}_cost/{{ model.name }}_cost_y_hess.c +{%- elif cost_type == "EXTERNAL" %} + {%- if cost.cost_ext_fun_type == "casadi" %} + {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun.c + {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun_jac.c + {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun_jac_hess.c + {%- elif cost.cost_source_ext_cost != cost.cost_source_ext_cost_0 %} + {{ model.name }}_cost/{{ cost.cost_source_ext_cost }} + {%- endif %} +{%- endif %} +{%- if cost_type_e == "NONLINEAR_LS" %} + {{ model.name }}_cost/{{ model.name }}_cost_y_e_fun.c + {{ model.name }}_cost/{{ model.name }}_cost_y_e_fun_jac_ut_xt.c + {{ model.name }}_cost/{{ model.name }}_cost_y_e_hess.c +{%- elif cost_type_e == "EXTERNAL" %} + {%- if cost.cost_ext_fun_type_e == "casadi" %} + {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun.c + {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun_jac.c + {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun_jac_hess.c + {%- elif cost.cost_source_ext_cost_e != cost.cost_source_ext_cost_0 %} + {{ model.name }}_cost/{{ cost.cost_source_ext_cost_e }} + {%- endif %} +{%- endif %} + acados_solver_{{ model.name }}.c) + add_library(${OCP_OBJ} OBJECT ${OCP_SRC}) +endif() + +{%- if solver_options.integrator_type != "DISCRETE" %} +# for sim solver +if(${BUILD_ACADOS_SOLVER_LIB} OR ${BUILD_EXAMPLE} + {%- if solver_options.integrator_type != "DISCRETE" %} + OR ${BUILD_SIM_EXAMPLE} OR ${BUILD_ACADOS_SIM_SOLVER_LIB} + {%- endif -%} + ) + set(SIM_SRC acados_sim_solver_{{ model.name }}.c) + add_library(${SIM_OBJ} OBJECT ${SIM_SRC}) +endif() +{%- endif %} + +# for target example +set(EX_SRC main_{{ model.name }}.c) +set(EX_EXE main_{{ model.name }}) + +{%- if model_external_shared_lib_dir and model_external_shared_lib_name %} +set(EXTERNAL_DIR {{ model_external_shared_lib_dir }}) +set(EXTERNAL_LIB {{ model_external_shared_lib_name }}) +{%- else %} +set(EXTERNAL_DIR) +set(EXTERNAL_LIB) +{%- endif %} + +# set some search paths for preprocessor and linker +set(ACADOS_INCLUDE_PATH {{ acados_include_path }} CACHE PATH "Define the path which contains the include directory for acados.") +set(ACADOS_LIB_PATH {{ acados_lib_path }} CACHE PATH "Define the path which contains the lib directory for acados.") + +# c-compiler flags for debugging +set(CMAKE_C_FLAGS_DEBUG "-O0 -ggdb") + +set(CMAKE_C_FLAGS " +{%- if qp_solver == "FULL_CONDENSING_QPOASES" -%} + -DACADOS_WITH_QPOASES +{%- endif -%} +{%- if qp_solver == "PARTIAL_CONDENSING_OSQP" -%} + -DACADOS_WITH_OSQP +{%- endif -%} +{%- if qp_solver == "PARTIAL_CONDENSING_QPDUNES" -%} + -DACADOS_WITH_QPDUNES +{%- endif -%} + -fPIC -std=c99 {{ openmp_flag }}") +#-fno-diagnostics-show-line-numbers -g + +include_directories( + ${ACADOS_INCLUDE_PATH} + ${ACADOS_INCLUDE_PATH}/acados + ${ACADOS_INCLUDE_PATH}/blasfeo/include + ${ACADOS_INCLUDE_PATH}/hpipm/include +{%- if qp_solver == "FULL_CONDENSING_QPOASES" %} + ${ACADOS_INCLUDE_PATH}/qpOASES_e/ +{%- endif %} +) + +# linker flags +link_directories(${ACADOS_LIB_PATH}) + +# link to libraries +if(UNIX) + link_libraries(acados hpipm blasfeo m {{ link_libs }}) +else() + link_libraries(acados hpipm blasfeo {{ link_libs }}) +endif() + +# the targets + +# bundled_shared_lib +if(${BUILD_ACADOS_SOLVER_LIB}) + set(LIB_ACADOS_SOLVER acados_solver_{{ model.name }}) + add_library(${LIB_ACADOS_SOLVER} SHARED $ $ + {%- if solver_options.integrator_type != "DISCRETE" %} + $ + {%- endif -%} + ) + install(TARGETS ${LIB_ACADOS_SOLVER} DESTINATION ${CMAKE_INSTALL_PREFIX}) +endif(${BUILD_ACADOS_SOLVER_LIB}) + +# ocp_shared_lib +if(${BUILD_ACADOS_OCP_SOLVER_LIB}) + set(LIB_ACADOS_OCP_SOLVER acados_ocp_solver_{{ model.name }}) + add_library(${LIB_ACADOS_OCP_SOLVER} SHARED $ $) + # Specify libraries or flags to use when linking a given target and/or its dependents. + target_link_libraries(${LIB_ACADOS_OCP_SOLVER} PRIVATE ${EXTERNAL_LIB}) + target_link_directories(${LIB_ACADOS_OCP_SOLVER} PRIVATE ${EXTERNAL_DIR}) + install(TARGETS ${LIB_ACADOS_OCP_SOLVER} DESTINATION ${CMAKE_INSTALL_PREFIX}) +endif(${BUILD_ACADOS_OCP_SOLVER_LIB}) + +# example +if(${BUILD_EXAMPLE}) + add_executable(${EX_EXE} ${EX_SRC} $ $ + {%- if solver_options.integrator_type != "DISCRETE" %} + $ + {%- endif -%} + ) + install(TARGETS ${EX_EXE} DESTINATION ${CMAKE_INSTALL_PREFIX}) +endif(${BUILD_EXAMPLE}) + +{% if solver_options.integrator_type != "DISCRETE" -%} +# example_sim +if(${BUILD_SIM_EXAMPLE}) + set(EX_SIM_SRC main_sim_{{ model.name }}.c) + set(EX_SIM_EXE main_sim_{{ model.name }}) + add_executable(${EX_SIM_EXE} ${EX_SIM_SRC} $ $) + install(TARGETS ${EX_SIM_EXE} DESTINATION ${CMAKE_INSTALL_PREFIX}) +endif(${BUILD_SIM_EXAMPLE}) + +# sim_shared_lib +if(${BUILD_ACADOS_SIM_SOLVER_LIB}) + set(LIB_ACADOS_SIM_SOLVER acados_sim_solver_{{ model.name }}) + add_library(${LIB_ACADOS_SIM_SOLVER} SHARED $ $) + install(TARGETS ${LIB_ACADOS_SIM_SOLVER} DESTINATION ${CMAKE_INSTALL_PREFIX}) +endif(${BUILD_ACADOS_SIM_SOLVER_LIB}) +{%- endif %} + diff --git a/pyextra/acados_template/c_templates_tera/Makefile.in b/pyextra/acados_template/c_templates_tera/Makefile.in index 487e66ab07..d45be0a9c7 100644 --- a/pyextra/acados_template/c_templates_tera/Makefile.in +++ b/pyextra/acados_template/c_templates_tera/Makefile.in @@ -125,134 +125,134 @@ {%- endif %} {%- endif %} -{# acados flags #} -ACADOS_FLAGS = -fPIC -std=c99 {{ openmp_flag }} #-fno-diagnostics-show-line-numbers -g -{%- if qp_solver == "FULL_CONDENSING_QPOASES" %} -ACADOS_FLAGS += -DACADOS_WITH_QPOASES -{%- endif %} -{%- if qp_solver == "PARTIAL_CONDENSING_OSQP" %} -ACADOS_FLAGS += -DACADOS_WITH_OSQP -{%- endif %} -{%- if qp_solver == "PARTIAL_CONDENSING_QPDUNES" %} -ACADOS_FLAGS += -DACADOS_WITH_QPDUNES -{%- endif %} -# # Debugging -# ACADOS_FLAGS += -g3 +# define sources and use make's implicit rules to generate object files (*.o) -MODEL_OBJ= +# model +MODEL_SRC= {%- if solver_options.integrator_type == "ERK" %} -MODEL_OBJ+= {{ model.name }}_model/{{ model.name }}_expl_ode_fun.o -MODEL_OBJ+= {{ model.name }}_model/{{ model.name }}_expl_vde_forw.o -{%- if hessian_approx == "EXACT" %} -MODEL_OBJ+= {{ model.name }}_model/{{ model.name }}_expl_ode_hess.o -{%- endif %} +MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_expl_ode_fun.c +MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_expl_vde_forw.c + {%- if hessian_approx == "EXACT" %} +MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_expl_ode_hess.c + {%- endif %} {%- elif solver_options.integrator_type == "IRK" %} -MODEL_OBJ+= {{ model.name }}_model/{{ model.name }}_impl_dae_fun.o -MODEL_OBJ+= {{ model.name }}_model/{{ model.name }}_impl_dae_fun_jac_x_xdot_z.o -MODEL_OBJ+= {{ model.name }}_model/{{ model.name }}_impl_dae_jac_x_xdot_u_z.o -{%- if hessian_approx == "EXACT" %} -MODEL_OBJ+= {{ model.name }}_model/{{ model.name }}_impl_dae_hess.o -{%- endif %} +MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_impl_dae_fun.c +MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_impl_dae_fun_jac_x_xdot_z.c +MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_impl_dae_jac_x_xdot_u_z.c + {%- if hessian_approx == "EXACT" %} +MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_impl_dae_hess.c + {%- endif %} {%- elif solver_options.integrator_type == "LIFTED_IRK" %} -MODEL_OBJ+= {{ model.name }}_model/{{ model.name }}_impl_dae_fun.o -MODEL_OBJ+= {{ model.name }}_model/{{ model.name }}_impl_dae_fun_jac_x_xdot_u.o -{%- if hessian_approx == "EXACT" %} -MODEL_OBJ+= {{ model.name }}_model/{{ model.name }}_impl_dae_hess.o -{%- endif %} +MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_impl_dae_fun.c +MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_impl_dae_fun_jac_x_xdot_u.c + {%- if hessian_approx == "EXACT" %} +MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_impl_dae_hess.c + {%- endif %} {%- elif solver_options.integrator_type == "GNSF" %} -MODEL_OBJ+= {{ model.name }}_model/{{ model.name }}_gnsf_phi_fun.o -MODEL_OBJ+= {{ model.name }}_model/{{ model.name }}_gnsf_phi_fun_jac_y.o -MODEL_OBJ+= {{ model.name }}_model/{{ model.name }}_gnsf_phi_jac_y_uhat.o -MODEL_OBJ+= {{ model.name }}_model/{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz.o -MODEL_OBJ+= {{ model.name }}_model/{{ model.name }}_gnsf_get_matrices_fun.o + {% if model.gnsf.purely_linear != 1 %} +MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_gnsf_phi_fun.c +MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_gnsf_phi_fun_jac_y.c +MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_gnsf_phi_jac_y_uhat.c + {% if model.gnsf.nontrivial_f_LO == 1 %} +MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz.c + {%- endif %} + {%- endif %} +MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_gnsf_get_matrices_fun.c {%- elif solver_options.integrator_type == "DISCRETE" %} -{%- if model.dyn_ext_fun_type == "casadi" %} -MODEL_OBJ+= {{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun.o -MODEL_OBJ+= {{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun_jac.o -{%- if hessian_approx == "EXACT" %} -MODEL_OBJ+= {{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun_jac_hess.o -{%- endif %} -{%- else %} -MODEL_OBJ+= {{ model.name }}_model/{{ model.dyn_source_discrete }} -{%- endif %} + {%- if model.dyn_ext_fun_type == "casadi" %} +MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun.c +MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun_jac.c + {%- if hessian_approx == "EXACT" %} +MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun_jac_hess.c + {%- endif %} + {%- else %} +MODEL_SRC+= {{ model.name }}_model/{{ model.dyn_source_discrete }} + {%- endif %} {%- endif %} +MODEL_OBJ := $(MODEL_SRC:.c=.o) - -OCP_OBJ= +# optimal control problem - mostly CasADi exports +OCP_SRC= {%- if constr_type == "BGP" and dims_nphi > 0 %} -OCP_OBJ+= {{ model.name }}_constraints/{{ model.name }}_phi_constraint.o +OCP_SRC+= {{ model.name }}_constraints/{{ model.name }}_phi_constraint.c {%- endif %} {%- if constr_type_e == "BGP" and dims_nphi_e > 0 %} -OCP_OBJ+= {{ model.name }}_constraints/{{ model.name }}_phi_e_constraint.o +OCP_SRC+= {{ model.name }}_constraints/{{ model.name }}_phi_e_constraint.c {%- endif %} {%- if constr_type == "BGH" and dims_nh > 0 %} -OCP_OBJ+= {{ model.name }}_constraints/{{ model.name }}_constr_h_fun_jac_uxt_zt.o -OCP_OBJ+= {{ model.name }}_constraints/{{ model.name }}_constr_h_fun.o -{%- if hessian_approx == "EXACT" %} -OCP_OBJ+= {{ model.name }}_constraints/{{ model.name }}_constr_h_fun_jac_uxt_zt_hess.o -{%- endif %} +OCP_SRC+= {{ model.name }}_constraints/{{ model.name }}_constr_h_fun_jac_uxt_zt.c +OCP_SRC+= {{ model.name }}_constraints/{{ model.name }}_constr_h_fun.c + {%- if hessian_approx == "EXACT" %} +OCP_SRC+= {{ model.name }}_constraints/{{ model.name }}_constr_h_fun_jac_uxt_zt_hess.c + {%- endif %} {%- endif %} {%- if constr_type_e == "BGH" and dims_nh_e > 0 %} -OCP_OBJ+= {{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun_jac_uxt_zt.o -OCP_OBJ+= {{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun.o -{%- if hessian_approx == "EXACT" %} -OCP_OBJ+= {{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess.o -{%- endif %} +OCP_SRC+= {{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun_jac_uxt_zt.c +OCP_SRC+= {{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun.c + {%- if hessian_approx == "EXACT" %} +OCP_SRC+= {{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess.c + {%- endif %} {%- endif %} {%- if cost_type_0 == "NONLINEAR_LS" %} -OCP_OBJ+= {{ model.name }}_cost/{{ model.name }}_cost_y_0_fun.c -OCP_OBJ+= {{ model.name }}_cost/{{ model.name }}_cost_y_0_fun_jac_ut_xt.c -OCP_OBJ+= {{ model.name }}_cost/{{ model.name }}_cost_y_0_hess.c +OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_0_fun.c +OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_0_fun_jac_ut_xt.c +OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_0_hess.c {%- elif cost_type_0 == "EXTERNAL" %} -{% if cost.cost_ext_fun_type_0 == "casadi" %} -OCP_OBJ+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun.c -OCP_OBJ+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun_jac.c -OCP_OBJ+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun_jac_hess.c -{% else %} -OCP_OBJ+= {{ model.name }}_cost/{{ cost.cost_source_ext_cost_0 }} -{% endif %} + {%- if cost.cost_ext_fun_type_0 == "casadi" %} +OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun.c +OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun_jac.c +OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun_jac_hess.c + {%- else %} +OCP_SRC+= {{ model.name }}_cost/{{ cost.cost_source_ext_cost_0 }} + {%- endif %} {%- endif %} {%- if cost_type == "NONLINEAR_LS" %} -OCP_OBJ+= {{ model.name }}_cost/{{ model.name }}_cost_y_fun.c -OCP_OBJ+= {{ model.name }}_cost/{{ model.name }}_cost_y_fun_jac_ut_xt.c -OCP_OBJ+= {{ model.name }}_cost/{{ model.name }}_cost_y_hess.c +OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_fun.c +OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_fun_jac_ut_xt.c +OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_hess.c {%- elif cost_type == "EXTERNAL" %} -{% if cost.cost_ext_fun_type == "casadi" %} -OCP_OBJ+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun.c -OCP_OBJ+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun_jac.c -OCP_OBJ+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun_jac_hess.c -{% elif cost.cost_source_ext_cost != cost.cost_source_ext_cost_0 %} -OCP_OBJ+= {{ model.name }}_cost/{{ cost.cost_source_ext_cost }} -{% endif %} + {%- if cost.cost_ext_fun_type == "casadi" %} +OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun.c +OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun_jac.c +OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun_jac_hess.c + {%- elif cost.cost_source_ext_cost != cost.cost_source_ext_cost_0 %} +OCP_SRC+= {{ model.name }}_cost/{{ cost.cost_source_ext_cost }} + {%- endif %} {%- endif %} {%- if cost_type_e == "NONLINEAR_LS" %} -OCP_OBJ+= {{ model.name }}_cost/{{ model.name }}_cost_y_e_fun.c -OCP_OBJ+= {{ model.name }}_cost/{{ model.name }}_cost_y_e_fun_jac_ut_xt.c -OCP_OBJ+= {{ model.name }}_cost/{{ model.name }}_cost_y_e_hess.c +OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_e_fun.c +OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_e_fun_jac_ut_xt.c +OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_e_hess.c {%- elif cost_type_e == "EXTERNAL" %} -{% if cost.cost_ext_fun_type_e == "casadi" %} -OCP_OBJ+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun.c -OCP_OBJ+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun_jac.c -OCP_OBJ+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun_jac_hess.c -{% elif cost.cost_source_ext_cost_e != cost.cost_source_ext_cost_0 %} -OCP_OBJ+= {{ model.name }}_cost/{{ cost.cost_source_ext_cost_e }} -{% endif %} + {%- if cost.cost_ext_fun_type_e == "casadi" %} +OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun.c +OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun_jac.c +OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun_jac_hess.c + {%- elif cost.cost_source_ext_cost_e != cost.cost_source_ext_cost_0 %} +OCP_SRC+= {{ model.name }}_cost/{{ cost.cost_source_ext_cost_e }} + {%- endif %} {%- endif %} -OCP_OBJ+= acados_solver_{{ model.name }}.o +OCP_SRC+= acados_solver_{{ model.name }}.c +OCP_OBJ := $(OCP_SRC:.c=.o) +# for sim solver +SIM_SRC= acados_sim_solver_{{ model.name }}.c +SIM_OBJ := $(SIM_SRC:.c=.o) -SIM_OBJ= -SIM_OBJ+= acados_sim_solver_{{ model.name }}.o +# for target example +EX_SRC= main_{{ model.name }}.c +EX_OBJ := $(EX_SRC:.c=.o) +EX_EXE := $(EX_SRC:.c=) -EX_OBJ= -EX_OBJ+= main_{{ model.name }}.o - -EX_SIM_OBJ= -EX_SIM_OBJ+= main_sim_{{ model.name }}.o +# for target example_sim +EX_SIM_SRC= main_sim_{{ model.name }}.c +EX_SIM_OBJ := $(EX_SIM_SRC:.c=.o) +EX_SIM_EXE := $(EX_SIM_SRC:.c=) +# combine model, sim and ocp object files OBJ= OBJ+= $(MODEL_OBJ) {%- if solver_options.integrator_type != "DISCRETE" %} @@ -271,233 +271,103 @@ EXTERNAL_LIB+= {{ model_external_shared_lib_name }} INCLUDE_PATH = {{ acados_include_path }} LIB_PATH = {{ acados_lib_path }} -{%- if solver_options.integrator_type == "DISCRETE" %} -all: clean casadi_fun example -shared_lib: ocp_shared_lib -{%- else %} -all: clean casadi_fun example_sim example -shared_lib: bundled_shared_lib ocp_shared_lib sim_shared_lib -{%- endif %} - -CASADI_MODEL_SOURCE= -{%- if solver_options.integrator_type == "ERK" %} -CASADI_MODEL_SOURCE+= {{ model.name }}_expl_ode_fun.c -CASADI_MODEL_SOURCE+= {{ model.name }}_expl_vde_forw.c -{%- if hessian_approx == "EXACT" %} -CASADI_MODEL_SOURCE+= {{ model.name }}_expl_ode_hess.c -{%- endif %} -{%- elif solver_options.integrator_type == "IRK" %} -CASADI_MODEL_SOURCE+= {{ model.name }}_impl_dae_fun.c -CASADI_MODEL_SOURCE+= {{ model.name }}_impl_dae_fun_jac_x_xdot_z.c -CASADI_MODEL_SOURCE+= {{ model.name }}_impl_dae_jac_x_xdot_u_z.c -{%- if hessian_approx == "EXACT" %} -CASADI_MODEL_SOURCE+= {{ model.name }}_impl_dae_hess.c -{%- endif %} -{%- elif solver_options.integrator_type == "LIFTED_IRK" %} -CASADI_MODEL_SOURCE+= {{ model.name }}_impl_dae_fun.c -# CASADI_MODEL_SOURCE+= {{ model.name }}_impl_dae_fun_jac_x_xdot_z.c -# CASADI_MODEL_SOURCE+= {{ model.name }}_impl_dae_jac_x_xdot_u_z.c -CASADI_MODEL_SOURCE+= {{ model.name }}_impl_dae_fun_jac_x_xdot_u.c -{%- if hessian_approx == "EXACT" %} -CASADI_MODEL_SOURCE+= {{ model.name }}_impl_dae_hess.c -{%- endif %} -{%- elif solver_options.integrator_type == "GNSF" %} -CASADI_MODEL_SOURCE+= {{ model.name }}_gnsf_phi_fun.c -CASADI_MODEL_SOURCE+= {{ model.name }}_gnsf_phi_fun_jac_y.c -CASADI_MODEL_SOURCE+= {{ model.name }}_gnsf_phi_jac_y_uhat.c -CASADI_MODEL_SOURCE+= {{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz.c -CASADI_MODEL_SOURCE+= {{ model.name }}_gnsf_get_matrices_fun.c -{%- elif solver_options.integrator_type == "DISCRETE" and model.dyn_ext_fun_type == "casadi" %} -CASADI_MODEL_SOURCE+= {{ model.name }}_dyn_disc_phi_fun.c -CASADI_MODEL_SOURCE+= {{ model.name }}_dyn_disc_phi_fun_jac.c -{%- if hessian_approx == "EXACT" %} -CASADI_MODEL_SOURCE+= {{ model.name }}_dyn_disc_phi_fun_jac_hess.c -{%- endif %} -{%- endif %} -{%- if constr_type == "BGP" and dims_nphi > 0 %} -CASADI_CON_PHI_SOURCE= -CASADI_CON_PHI_SOURCE+= {{ model.name }}_phi_constraint.c -{%- endif %} -{%- if constr_type_e == "BGP" and dims_nphi_e > 0 %} -CASADI_CON_PHI_E_SOURCE= -CASADI_CON_PHI_E_SOURCE+= {{ model.name }}_phi_e_constraint.c -{%- endif %} -{%- if constr_type == "BGH" and dims_nh > 0 %} -CASADI_CON_H_SOURCE= -CASADI_CON_H_SOURCE+= {{ model.name }}_constr_h_fun_jac_uxt_zt.c -CASADI_CON_H_SOURCE+= {{ model.name }}_constr_h_fun.c -{%- if hessian_approx == "EXACT" %} -CASADI_CON_H_SOURCE+= {{ model.name }}_constr_h_fun_jac_uxt_zt_hess.c -{%- endif %} -{%- endif %} - -{%- if dims_nh_e > 0 %} -CASADI_CON_H_E_SOURCE= -CASADI_CON_H_E_SOURCE+= {{ model.name }}_constr_h_e_fun_jac_uxt_zt.c -CASADI_CON_H_E_SOURCE+= {{ model.name }}_constr_h_e_fun.c -{%- if hessian_approx == "EXACT" %} -CASADI_CON_H_E_SOURCE+= {{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess.c -{%- endif %} -{%- endif %} - -{%- if cost_type == "NONLINEAR_LS" %} -CASADI_COST_Y_SOURCE= -CASADI_COST_Y_SOURCE+= {{ model.name }}_cost_y_fun.c -CASADI_COST_Y_SOURCE+= {{ model.name }}_cost_y_fun_jac_ut_xt.c -CASADI_COST_Y_SOURCE+= {{ model.name }}_cost_y_hess.c -{%- endif %} -{%- if cost_type_e == "NONLINEAR_LS" %} -CASADI_COST_Y_E_SOURCE= -CASADI_COST_Y_E_SOURCE+= {{ model.name }}_cost_y_e_fun.c -CASADI_COST_Y_E_SOURCE+= {{ model.name }}_cost_y_e_fun_jac_ut_xt.c -CASADI_COST_Y_E_SOURCE+= {{ model.name }}_cost_y_e_hess.c +# preprocessor flags for make's implicit rules +{%- if qp_solver == "FULL_CONDENSING_QPOASES" %} +CPPFLAGS += -DACADOS_WITH_QPOASES {%- endif %} -{%- if cost_type_0 == "NONLINEAR_LS" %} -CASADI_COST_Y_0_SOURCE= -CASADI_COST_Y_0_SOURCE+= {{ model.name }}_cost_y_0_fun.c -CASADI_COST_Y_0_SOURCE+= {{ model.name }}_cost_y_0_fun_jac_ut_xt.c -CASADI_COST_Y_0_SOURCE+= {{ model.name }}_cost_y_0_hess.c +{%- if qp_solver == "PARTIAL_CONDENSING_OSQP" %} +CPPFLAGS += -DACADOS_WITH_OSQP {%- endif %} +{%- if qp_solver == "PARTIAL_CONDENSING_QPDUNES" %} +CPPFLAGS += -DACADOS_WITH_QPDUNES +{%- endif %} +CPPFLAGS+= -I$(INCLUDE_PATH) +CPPFLAGS+= -I$(INCLUDE_PATH)/acados +CPPFLAGS+= -I$(INCLUDE_PATH)/blasfeo/include +CPPFLAGS+= -I$(INCLUDE_PATH)/hpipm/include + {%- if qp_solver == "FULL_CONDENSING_QPOASES" %} +CPPFLAGS+= -I $(INCLUDE_PATH)/qpOASES_e/ + {%- endif %} + +{# c-compiler flags #} +# define the c-compiler flags for make's implicit rules +CFLAGS = -fPIC -std=c99 {{ openmp_flag }} #-fno-diagnostics-show-line-numbers -g +# # Debugging +# CFLAGS += -g3 -casadi_fun: - {%- if model.dyn_ext_fun_type == "casadi" %} - ( cd {{ model.name }}_model {{ control }} gcc $(ACADOS_FLAGS) -c $(CASADI_MODEL_SOURCE)) - {%- endif %} - {%- if constr_type == "BGP" and dims_nphi > 0 %} - ( cd {{ model.name }}_constraints {{ control }} gcc $(ACADOS_FLAGS) -c $(CASADI_CON_PHI_SOURCE)) - {%- endif %} - {%- if constr_type_e == "BGP" and dims_nphi_e > 0 %} - ( cd {{ model.name }}_constraints {{ control }} gcc $(ACADOS_FLAGS) -c $(CASADI_CON_PHI_E_SOURCE)) - {%- endif %} - {%- if constr_type == "BGH" and dims_nh > 0 %} - ( cd {{ model.name }}_constraints {{ control }} gcc $(ACADOS_FLAGS) -c $(CASADI_CON_H_SOURCE)) - {%- endif %} - {%- if constr_type_e == "BGH" and dims_nh_e > 0 %} - ( cd {{ model.name }}_constraints {{ control }} gcc $(ACADOS_FLAGS) -c $(CASADI_CON_H_E_SOURCE)) - {%- endif %} - {%- if cost_type == "NONLINEAR_LS" %} - ( cd {{ model.name }}_cost {{ control }} gcc $(ACADOS_FLAGS) -c $(CASADI_COST_Y_SOURCE)) - {%- endif %} - {%- if cost_type_e == "NONLINEAR_LS" %} - ( cd {{ model.name }}_cost {{ control }} gcc $(ACADOS_FLAGS) -c $(CASADI_COST_Y_E_SOURCE)) - {%- endif %} - {%- if cost_type_0 == "NONLINEAR_LS" %} - ( cd {{ model.name }}_cost {{ control }} gcc $(ACADOS_FLAGS) -c $(CASADI_COST_Y_0_SOURCE)) - {%- endif %} - -main: - gcc $(ACADOS_FLAGS) -c main_{{ model.name }}.c -I $(INCLUDE_PATH)/blasfeo/include/ -I $(INCLUDE_PATH)/hpipm/include/ \ - -I $(INCLUDE_PATH) -I $(INCLUDE_PATH)/acados/ \ - {%- if qp_solver == "FULL_CONDENSING_QPOASES" %} - -I $(INCLUDE_PATH)/qpOASES_e/ - {%- endif %} +# linker flags +LDFLAGS+= -L$(LIB_PATH) -main_sim: - gcc $(ACADOS_FLAGS) -c main_sim_{{ model.name }}.c -I $(INCLUDE_PATH)/blasfeo/include/ -I $(INCLUDE_PATH)/hpipm/include/ \ - -I $(INCLUDE_PATH) -I $(INCLUDE_PATH)/acados/ +# link to libraries +LDLIBS+= -lacados +LDLIBS+= -lhpipm +LDLIBS+= -lblasfeo +LDLIBS+= -lm +LDLIBS+= {{ link_libs }} -ocp_solver: - gcc $(ACADOS_FLAGS) -c acados_solver_{{ model.name }}.c -I $(INCLUDE_PATH)/blasfeo/include/ -I $(INCLUDE_PATH)/hpipm/include/ \ - -I $(INCLUDE_PATH) -I $(INCLUDE_PATH)/acados/ \ - {%- if qp_solver == "FULL_CONDENSING_QPOASES" %} - -I $(INCLUDE_PATH)/qpOASES_e/ - {%- endif %} +# libraries +LIBACADOS_SOLVER=libacados_solver_{{ model.name }}.so +LIBACADOS_OCP_SOLVER=libacados_ocp_solver_{{ model.name }}.so +LIBACADOS_SIM_SOLVER=lib$(SIM_SRC:.c=.so) -sim_solver: - gcc $(ACADOS_FLAGS) -c acados_sim_solver_{{ model.name }}.c -I $(INCLUDE_PATH)/blasfeo/include/ -I $(INCLUDE_PATH)/hpipm/include/ \ - -I $(INCLUDE_PATH) -I $(INCLUDE_PATH)/acados/ \ - {%- if qp_solver == "FULL_CONDENSING_QPOASES" %} - -I $(INCLUDE_PATH)/qpOASES_e/ - {%- endif %} +# virtual targets +.PHONY : all clean -example: ocp_solver main - gcc $(ACADOS_FLAGS) -o main_{{ model.name }} $(EX_OBJ) $(OBJ) -L $(LIB_PATH) \ - -lacados -lhpipm -lblasfeo \ - {{ link_libs }} \ - -lm \ - -I $(INCLUDE_PATH)/blasfeo/include/ \ - -I $(INCLUDE_PATH)/hpipm/include/ \ - -I $(INCLUDE_PATH) \ - -I $(INCLUDE_PATH)/acados/ \ - {%- if qp_solver == "FULL_CONDENSING_QPOASES" %} - -I $(INCLUDE_PATH)/qpOASES_e/ - {%- endif %} - - -example_sim: sim_solver main_sim - gcc $(ACADOS_FLAGS) -o main_sim_{{ model.name }} $(EX_SIM_OBJ) $(MODEL_OBJ) $(SIM_OBJ) -L $(LIB_PATH) \ - -lacados -lhpipm -lblasfeo \ - {{ link_libs }} \ - -lm \ - -I $(INCLUDE_PATH)/blasfeo/include/ \ - -I $(INCLUDE_PATH)/acados/ \ +#all: clean example_sim example shared_lib +{% if solver_options.integrator_type == "DISCRETE" -%} +all: clean example +shared_lib: ocp_shared_lib +{%- else %} +all: clean example_sim example +shared_lib: bundled_shared_lib ocp_shared_lib sim_shared_lib +{%- endif %} -{%- if solver_options.integrator_type != "DISCRETE" %} +# some linker targets +example: $(EX_OBJ) $(OBJ) + $(CC) $^ -o $(EX_EXE) $(LDFLAGS) $(LDLIBS) -bundled_shared_lib: casadi_fun ocp_solver sim_solver - gcc $(ACADOS_FLAGS) -shared -o libacados_solver_{{ model.name }}.so $(OBJ) \ - -I $(INCLUDE_PATH)/blasfeo/include/ \ - -I $(INCLUDE_PATH)/hpipm/include/ \ - -I $(INCLUDE_PATH) \ - -L $(LIB_PATH) \ - -lacados -lhpipm -lblasfeo \ - {{ link_libs }} \ - -lm \ +example_sim: $(EX_SIM_OBJ) $(MODEL_OBJ) $(SIM_OBJ) + $(CC) $^ -o $(EX_SIM_EXE) $(LDFLAGS) $(LDLIBS) -ocp_shared_lib: casadi_fun ocp_solver - gcc $(ACADOS_FLAGS) -shared -o libacados_ocp_solver_{{ model.name }}.so $(OCP_OBJ) $(MODEL_OBJ) \ - -I $(INCLUDE_PATH)/blasfeo/include/ \ - -I $(INCLUDE_PATH)/hpipm/include/ \ - -I $(INCLUDE_PATH) \ - -L$(EXTERNAL_DIR) -l$(EXTERNAL_LIB) \ - -L $(LIB_PATH) -lacados -lhpipm -lblasfeo \ - {{ link_libs }} \ - -lm \ +{% if solver_options.integrator_type != "DISCRETE" -%} +bundled_shared_lib: $(OBJ) + $(CC) -shared $^ -o $(LIBACADOS_SOLVER) $(LDFLAGS) $(LDLIBS) +{%- endif %} -{%- else %} +ocp_shared_lib: $(OCP_OBJ) $(MODEL_OBJ) + $(CC) -shared $^ -o $(LIBACADOS_OCP_SOLVER) $(LDFLAGS) $(LDLIBS) \ + -L$(EXTERNAL_DIR) -l$(EXTERNAL_LIB) -ocp_shared_lib: casadi_fun ocp_solver - gcc $(ACADOS_FLAGS) -shared -o libacados_ocp_solver_{{ model.name }}.so $(OCP_OBJ) $(MODEL_OBJ) \ - -I $(INCLUDE_PATH)/blasfeo/include/ \ - -I $(INCLUDE_PATH)/hpipm/include/ \ - -I $(INCLUDE_PATH) \ - -L$(EXTERNAL_DIR) -l$(EXTERNAL_LIB) \ - -L $(LIB_PATH) -lacados -lhpipm -lblasfeo \ - {{ link_libs }} \ - -lm \ +sim_shared_lib: $(SIM_OBJ) $(MODEL_OBJ) + $(CC) -shared $^ -o $(LIBACADOS_SIM_SOLVER) $(LDFLAGS) $(LDLIBS) -{%- endif %} +# Cython targets ocp_cython_c: ocp_shared_lib cython \ -o acados_ocp_solver_pyx.c \ -I $(INCLUDE_PATH)/../interfaces/acados_template/acados_template \ $(INCLUDE_PATH)/../interfaces/acados_template/acados_template/acados_ocp_solver_pyx.pyx \ + -I {{ code_export_directory }} \ ocp_cython_o: ocp_cython_c - clang $(ACADOS_FLAGS) -c -O2 \ + $(CC) $(ACADOS_FLAGS) -c -O2 \ + -fPIC \ -o acados_ocp_solver_pyx.o \ -I /usr/include/python3.8 \ -I $(INCLUDE_PATH)/blasfeo/include/ \ -I $(INCLUDE_PATH)/hpipm/include/ \ -I $(INCLUDE_PATH) \ + -I {{ cython_include_dirs }} \ acados_ocp_solver_pyx.c \ ocp_cython: ocp_cython_o - clang $(ACADOS_FLAGS) -shared \ + $(CC) $(ACADOS_FLAGS) -shared \ -o acados_ocp_solver_pyx.so \ -Wl,-rpath=$(LIB_PATH) \ acados_ocp_solver_pyx.o \ $(abspath .)/libacados_ocp_solver_{{ model.name }}.so \ - -L $(LIB_PATH) -lacados -lhpipm -lblasfeo -lqpOASES_e \ - {{ link_libs }} \ - -lm \ - -sim_shared_lib: casadi_fun sim_solver - gcc $(ACADOS_FLAGS) -shared -o libacados_sim_solver_{{ model.name }}.so $(SIM_OBJ) $(MODEL_OBJ) -L$(EXTERNAL_DIR) -l$(EXTERNAL_LIB) \ - -L $(LIB_PATH) -lacados -lhpipm -lblasfeo \ - {{ link_libs }} \ - -lm \ + $(LDFLAGS) $(LDLIBS) {%- if os and os == "pc" %} @@ -510,15 +380,27 @@ clean_ocp_shared_lib: del \Q libacados_ocp_solver_{{ model.name }}.so 2>nul del \Q acados_solver_{{ model.name }}.o 2>nul +clean_ocp_cython: + del \Q libacados_ocp_solver_{{ model.name }}.so 2>nul + del \Q acados_solver_{{ model.name }}.o 2>nul + del \Q acados_ocp_solver_pyx.so 2>nul + del \Q acados_ocp_solver_pyx.o 2>nul + {%- else %} clean: - rm -f *.o - rm -f *.so - rm -f main_{{ model.name }} + $(RM) $(OBJ) $(EX_OBJ) $(EX_SIM_OBJ) + $(RM) $(LIBACADOS_SOLVER) $(LIBACADOS_OCP_SOLVER) $(LIBACADOS_SIM_SOLVER) + $(RM) $(EX_EXE) $(EX_SIM_EXE) clean_ocp_shared_lib: - rm -f libacados_ocp_solver_{{ model.name }}.so - rm -f acados_solver_{{ model.name }}.o + $(RM) $(LIBACADOS_OCP_SOLVER) + $(RM) $(OCP_OBJ) + +clean_ocp_cython: + $(RM) libacados_ocp_solver_{{ model.name }}.so + $(RM) acados_solver_{{ model.name }}.o + $(RM) acados_ocp_solver_pyx.so + $(RM) acados_ocp_solver_pyx.o {%- endif %} diff --git a/pyextra/acados_template/c_templates_tera/acados_mex_create.in.c b/pyextra/acados_template/c_templates_tera/acados_mex_create.in.c index 251b249b2f..e67a51567a 100644 --- a/pyextra/acados_template/c_templates_tera/acados_mex_create.in.c +++ b/pyextra/acados_template/c_templates_tera/acados_mex_create.in.c @@ -63,7 +63,7 @@ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) mexPrintf("{{ model.name }}_acados_create() -> success!\n"); // get pointers to nlp solver related objects - ocp_nlp_plan *nlp_plan = {{ model.name }}_acados_get_nlp_plan(acados_ocp_capsule); + ocp_nlp_plan_t *nlp_plan = {{ model.name }}_acados_get_nlp_plan(acados_ocp_capsule); ocp_nlp_config *nlp_config = {{ model.name }}_acados_get_nlp_config(acados_ocp_capsule); ocp_nlp_dims *nlp_dims = {{ model.name }}_acados_get_nlp_dims(acados_ocp_capsule); ocp_nlp_in *nlp_in = {{ model.name }}_acados_get_nlp_in(acados_ocp_capsule); @@ -238,14 +238,18 @@ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) l_ptr[0] = (long long) acados_ocp_capsule->impl_dae_hess; {%- endif %} {% elif solver_options.integrator_type == "GNSF" %} + {% if model.gnsf.purely_linear != 1 %} l_ptr = mxGetData(gnsf_phi_fun_mat); l_ptr[0] = (long long) acados_ocp_capsule->gnsf_phi_fun; l_ptr = mxGetData(gnsf_phi_fun_jac_y_mat); l_ptr[0] = (long long) acados_ocp_capsule->gnsf_phi_fun_jac_y; l_ptr = mxGetData(gnsf_phi_jac_y_uhat_mat); l_ptr[0] = (long long) acados_ocp_capsule->gnsf_phi_jac_y_uhat; + {% if model.gnsf.nontrivial_f_LO == 1 %} l_ptr = mxGetData(gnsf_f_lo_jac_x1_x1dot_u_z_mat); l_ptr[0] = (long long) acados_ocp_capsule->gnsf_f_lo_jac_x1_x1dot_u_z; + {%- endif %} + {%- endif %} l_ptr = mxGetData(gnsf_get_matrices_fun_mat); l_ptr[0] = (long long) acados_ocp_capsule->gnsf_get_matrices_fun; {% elif solver_options.integrator_type == "DISCRETE" %} diff --git a/pyextra/acados_template/c_templates_tera/acados_mex_set.in.c b/pyextra/acados_template/c_templates_tera/acados_mex_set.in.c index ae8c311557..f8e1e5e445 100644 --- a/pyextra/acados_template/c_templates_tera/acados_mex_set.in.c +++ b/pyextra/acados_template/c_templates_tera/acados_mex_set.in.c @@ -69,7 +69,7 @@ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {{ model.name }}_solver_capsule *capsule = ({{ model.name }}_solver_capsule *) ptr[0]; // plan ptr = (long long *) mxGetData( mxGetField( C_ocp, 0, "plan" ) ); - ocp_nlp_plan *plan = (ocp_nlp_plan *) ptr[0]; + ocp_nlp_plan_t *plan = (ocp_nlp_plan_t *) ptr[0]; // config ptr = (long long *) mxGetData( mxGetField( C_ocp, 0, "config" ) ); ocp_nlp_config *config = (ocp_nlp_config *) ptr[0]; @@ -404,7 +404,7 @@ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) } else if (!strcmp(field, "init_z")) { - sim_solver_plan sim_plan = plan->sim_solver_plan[0]; + sim_solver_plan_t sim_plan = plan->sim_solver_plan[0]; sim_solver_t type = sim_plan.sim_solver; if (type == IRK) { @@ -426,7 +426,7 @@ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) } else if (!strcmp(field, "init_xdot")) { - sim_solver_plan sim_plan = plan->sim_solver_plan[0]; + sim_solver_plan_t sim_plan = plan->sim_solver_plan[0]; sim_solver_t type = sim_plan.sim_solver; if (type == IRK) { @@ -448,7 +448,7 @@ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) } else if (!strcmp(field, "init_gnsf_phi")) { - sim_solver_plan sim_plan = plan->sim_solver_plan[0]; + sim_solver_plan_t sim_plan = plan->sim_solver_plan[0]; sim_solver_t type = sim_plan.sim_solver; if (type == GNSF) { diff --git a/pyextra/acados_template/c_templates_tera/acados_sim_solver.in.c b/pyextra/acados_template/c_templates_tera/acados_sim_solver.in.c index 971fb8a78f..f2e75058c1 100644 --- a/pyextra/acados_template/c_templates_tera/acados_sim_solver.in.c +++ b/pyextra/acados_template/c_templates_tera/acados_sim_solver.in.c @@ -164,12 +164,17 @@ int {{ model.name }}_acados_sim_create(sim_solver_capsule * capsule) {%- endif %} {% elif solver_options.integrator_type == "GNSF" -%} + {% if model.gnsf.purely_linear != 1 %} capsule->sim_gnsf_phi_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)); capsule->sim_gnsf_phi_fun_jac_y = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)); capsule->sim_gnsf_phi_jac_y_uhat = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)); + {% if model.gnsf.nontrivial_f_LO == 1 %} capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)); + {%- endif %} + {%- endif %} capsule->sim_gnsf_get_matrices_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)); + {% if model.gnsf.purely_linear != 1 %} capsule->sim_gnsf_phi_fun->casadi_fun = &{{ model.name }}_gnsf_phi_fun; capsule->sim_gnsf_phi_fun->casadi_n_in = &{{ model.name }}_gnsf_phi_fun_n_in; capsule->sim_gnsf_phi_fun->casadi_n_out = &{{ model.name }}_gnsf_phi_fun_n_out; @@ -194,6 +199,7 @@ int {{ model.name }}_acados_sim_create(sim_solver_capsule * capsule) capsule->sim_gnsf_phi_jac_y_uhat->casadi_work = &{{ model.name }}_gnsf_phi_jac_y_uhat_work; external_function_param_casadi_create(capsule->sim_gnsf_phi_jac_y_uhat, np); + {% if model.gnsf.nontrivial_f_LO == 1 %} capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z->casadi_fun = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz; capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z->casadi_n_in = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_n_in; capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z->casadi_n_out = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_n_out; @@ -201,6 +207,8 @@ int {{ model.name }}_acados_sim_create(sim_solver_capsule * capsule) capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z->casadi_sparsity_out = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_sparsity_out; capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z->casadi_work = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_work; external_function_param_casadi_create(capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z, np); + {%- endif %} + {%- endif %} capsule->sim_gnsf_get_matrices_fun->casadi_fun = &{{ model.name }}_gnsf_get_matrices_fun; capsule->sim_gnsf_get_matrices_fun->casadi_n_in = &{{ model.name }}_gnsf_get_matrices_fun_n_in; @@ -212,7 +220,7 @@ int {{ model.name }}_acados_sim_create(sim_solver_capsule * capsule) {% endif %} // sim plan & config - sim_solver_plan plan; + sim_solver_plan_t plan; plan.sim_solver = {{ solver_options.integrator_type }}; // create correct config based on plan @@ -307,14 +315,18 @@ int {{ model.name }}_acados_sim_create(sim_solver_capsule * capsule) "expl_ode_hess", capsule->sim_expl_ode_hess); {%- endif %} {%- elif solver_options.integrator_type == "GNSF" %} + {% if model.gnsf.purely_linear != 1 %} {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, "phi_fun", capsule->sim_gnsf_phi_fun); {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, "phi_fun_jac_y", capsule->sim_gnsf_phi_fun_jac_y); {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, "phi_jac_y_uhat", capsule->sim_gnsf_phi_jac_y_uhat); + {% if model.gnsf.nontrivial_f_LO == 1 %} {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, "f_lo_jac_x1_x1dot_u_z", capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z); + {%- endif %} + {%- endif %} {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, "gnsf_get_matrices_fun", capsule->sim_gnsf_get_matrices_fun); {%- endif %} @@ -409,10 +421,14 @@ int {{ model.name }}_acados_sim_free(sim_solver_capsule *capsule) external_function_param_casadi_free(capsule->sim_expl_ode_hess); {%- endif %} {%- elif solver_options.integrator_type == "GNSF" %} + {% if model.gnsf.purely_linear != 1 %} external_function_param_casadi_free(capsule->sim_gnsf_phi_fun); external_function_param_casadi_free(capsule->sim_gnsf_phi_fun_jac_y); external_function_param_casadi_free(capsule->sim_gnsf_phi_jac_y_uhat); + {% if model.gnsf.nontrivial_f_LO == 1 %} external_function_param_casadi_free(capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z); + {%- endif %} + {%- endif %} external_function_param_casadi_free(capsule->sim_gnsf_get_matrices_fun); {% endif %} @@ -445,10 +461,14 @@ int {{ model.name }}_acados_sim_update_params(sim_solver_capsule *capsule, doubl capsule->sim_impl_dae_hess[0].set_param(capsule->sim_impl_dae_hess, p); {%- endif %} {%- elif solver_options.integrator_type == "GNSF" %} + {% if model.gnsf.purely_linear != 1 %} capsule->sim_gnsf_phi_fun[0].set_param(capsule->sim_gnsf_phi_fun, p); capsule->sim_gnsf_phi_fun_jac_y[0].set_param(capsule->sim_gnsf_phi_fun_jac_y, p); capsule->sim_gnsf_phi_jac_y_uhat[0].set_param(capsule->sim_gnsf_phi_jac_y_uhat, p); + {% if model.gnsf.nontrivial_f_LO == 1 %} capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z[0].set_param(capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z, p); + {%- endif %} + {%- endif %} capsule->sim_gnsf_get_matrices_fun[0].set_param(capsule->sim_gnsf_get_matrices_fun, p); {% endif %} diff --git a/pyextra/acados_template/c_templates_tera/acados_sim_solver.in.h b/pyextra/acados_template/c_templates_tera/acados_sim_solver.in.h index 4da8202d3c..7306491baf 100644 --- a/pyextra/acados_template/c_templates_tera/acados_sim_solver.in.h +++ b/pyextra/acados_template/c_templates_tera/acados_sim_solver.in.h @@ -80,21 +80,21 @@ typedef struct sim_solver_capsule } sim_solver_capsule; -int {{ model.name }}_acados_sim_create(sim_solver_capsule *capsule); -int {{ model.name }}_acados_sim_solve(sim_solver_capsule *capsule); -int {{ model.name }}_acados_sim_free(sim_solver_capsule *capsule); -int {{ model.name }}_acados_sim_update_params(sim_solver_capsule *capsule, double *value, int np); +ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_sim_create(sim_solver_capsule *capsule); +ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_sim_solve(sim_solver_capsule *capsule); +ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_sim_free(sim_solver_capsule *capsule); +ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_sim_update_params(sim_solver_capsule *capsule, double *value, int np); -sim_config * {{ model.name }}_acados_get_sim_config(sim_solver_capsule *capsule); -sim_in * {{ model.name }}_acados_get_sim_in(sim_solver_capsule *capsule); -sim_out * {{ model.name }}_acados_get_sim_out(sim_solver_capsule *capsule); -void * {{ model.name }}_acados_get_sim_dims(sim_solver_capsule *capsule); -sim_opts * {{ model.name }}_acados_get_sim_opts(sim_solver_capsule *capsule); -sim_solver * {{ model.name }}_acados_get_sim_solver(sim_solver_capsule *capsule); +ACADOS_SYMBOL_EXPORT sim_config * {{ model.name }}_acados_get_sim_config(sim_solver_capsule *capsule); +ACADOS_SYMBOL_EXPORT sim_in * {{ model.name }}_acados_get_sim_in(sim_solver_capsule *capsule); +ACADOS_SYMBOL_EXPORT sim_out * {{ model.name }}_acados_get_sim_out(sim_solver_capsule *capsule); +ACADOS_SYMBOL_EXPORT void * {{ model.name }}_acados_get_sim_dims(sim_solver_capsule *capsule); +ACADOS_SYMBOL_EXPORT sim_opts * {{ model.name }}_acados_get_sim_opts(sim_solver_capsule *capsule); +ACADOS_SYMBOL_EXPORT sim_solver * {{ model.name }}_acados_get_sim_solver(sim_solver_capsule *capsule); -sim_solver_capsule * {{ model.name }}_acados_sim_solver_create_capsule(void); -int {{ model.name }}_acados_sim_solver_free_capsule(sim_solver_capsule *capsule); +ACADOS_SYMBOL_EXPORT sim_solver_capsule * {{ model.name }}_acados_sim_solver_create_capsule(void); +ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_sim_solver_free_capsule(sim_solver_capsule *capsule); #ifdef __cplusplus } diff --git a/pyextra/acados_template/c_templates_tera/acados_sim_solver_sfun.in.c b/pyextra/acados_template/c_templates_tera/acados_sim_solver_sfun.in.c index 234295fa29..68a6a3f80f 100644 --- a/pyextra/acados_template/c_templates_tera/acados_sim_solver_sfun.in.c +++ b/pyextra/acados_template/c_templates_tera/acados_sim_solver_sfun.in.c @@ -37,7 +37,7 @@ #define MDL_START // acados -#include "acados/utils/print.h" +// #include "acados/utils/print.h" #include "acados_c/ocp_nlp_interface.h" #include "acados_c/external_function_interface.h" diff --git a/pyextra/acados_template/c_templates_tera/acados_solver.in.c b/pyextra/acados_template/c_templates_tera/acados_solver.in.c index 6e13242a41..0af8127709 100644 --- a/pyextra/acados_template/c_templates_tera/acados_solver.in.c +++ b/pyextra/acados_template/c_templates_tera/acados_solver.in.c @@ -34,8 +34,9 @@ // standard #include #include +#include // acados -#include "acados/utils/print.h" +// #include "acados/utils/print.h" #include "acados_c/ocp_nlp_interface.h" #include "acados_c/external_function_interface.h" @@ -121,14 +122,15 @@ int {{ model.name }}_acados_free_capsule({{ model.name }}_solver_capsule *capsul } -int {{ model.name }}_acados_create({{ model.name }}_solver_capsule * capsule) +int {{ model.name }}_acados_create({{ model.name }}_solver_capsule* capsule) { int N_shooting_intervals = {{ model.name | upper }}_N; double* new_time_steps = NULL; // NULL -> don't alter the code generated time-steps return {{ model.name }}_acados_create_with_discretization(capsule, N_shooting_intervals, new_time_steps); } -int {{ model.name }}_acados_update_time_steps({{ model.name }}_solver_capsule * capsule, int N, double* new_time_steps) + +int {{ model.name }}_acados_update_time_steps({{ model.name }}_solver_capsule* capsule, int N, double* new_time_steps) { if (N != capsule->nlp_solver_plan->N) { fprintf(stderr, "{{ model.name }}_acados_update_time_steps: given number of time steps (= %d) " \ @@ -151,30 +153,20 @@ int {{ model.name }}_acados_update_time_steps({{ model.name }}_solver_capsule * return 0; } -int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_capsule * capsule, int N, double* new_time_steps) +/** + * Internal function for {{ model.name }}_acados_create: step 1 + */ +void {{ model.name }}_acados_create_1_set_plan(ocp_nlp_plan_t* nlp_solver_plan, const int N) { - int status = 0; - // If N does not match the number of shooting intervals used for code generation, new_time_steps must be given. - if (N != {{ model.name | upper }}_N && !new_time_steps) { - fprintf(stderr, "{{ model.name }}_acados_create_with_discretization: new_time_steps is NULL " \ - "but the number of shooting intervals (= %d) differs from the number of " \ - "shooting intervals (= %d) during code generation! Please provide a new vector of time_stamps!\n", \ - N, {{ model.name | upper }}_N); - return 1; - } - - // number of expected runtime parameters - capsule->nlp_np = NP; + assert(N == nlp_solver_plan->N); /************************************************ - * plan & config + * plan ************************************************/ - ocp_nlp_plan * nlp_solver_plan = ocp_nlp_plan_create(N); - capsule->nlp_solver_plan = nlp_solver_plan; {%- if solver_options.nlp_solver_type == "SQP" %} nlp_solver_plan->nlp_solver = SQP; - {% else %} + {%- else %} nlp_solver_plan->nlp_solver = SQP_RTI; {%- endif %} @@ -188,11 +180,11 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c for (int i = 0; i < N; i++) { - {% if solver_options.integrator_type == "DISCRETE" %} + {%- if solver_options.integrator_type == "DISCRETE" %} nlp_solver_plan->nlp_dynamics[i] = DISCRETE_MODEL; // discrete dynamics does not need sim solver option, this field is ignored nlp_solver_plan->sim_solver_plan[i].sim_solver = INVALID_SIM_SOLVER; - {% else %} + {%- else %} nlp_solver_plan->nlp_dynamics[i] = CONTINUOUS_MODEL; nlp_solver_plan->sim_solver_plan[i].sim_solver = {{ solver_options.integrator_type }}; {%- endif %} @@ -200,7 +192,7 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c for (int i = 0; i < N; i++) { - {% if constraints.constr_type == "BGP" %} + {%- if constraints.constr_type == "BGP" %} nlp_solver_plan->nlp_constraints[i] = BGP; {%- else -%} nlp_solver_plan->nlp_constraints[i] = BGH; @@ -209,7 +201,7 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c {%- if constraints.constr_type_e == "BGP" %} nlp_solver_plan->nlp_constraints[N] = BGP; - {% else %} + {%- else %} nlp_solver_plan->nlp_constraints[N] = BGH; {%- endif %} @@ -226,10 +218,18 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c nlp_solver_plan->regularization = CONVEXIFY; {%- endif %} {%- endif %} - ocp_nlp_config * nlp_config = ocp_nlp_config_create(*nlp_solver_plan); - capsule->nlp_config = nlp_config; +} +/** + * Internal function for {{ model.name }}_acados_create: step 2 + */ +ocp_nlp_dims* {{ model.name }}_acados_create_2_create_and_set_dimensions({{ model.name }}_solver_capsule* capsule) +{ + ocp_nlp_plan_t* nlp_solver_plan = capsule->nlp_solver_plan; + const int N = nlp_solver_plan->N; + ocp_nlp_config* nlp_config = capsule->nlp_config; + /************************************************ * dimensions ************************************************/ @@ -307,7 +307,6 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c /* create and set ocp_nlp_dims */ ocp_nlp_dims * nlp_dims = ocp_nlp_dims_create(nlp_config); - capsule->nlp_dims = nlp_dims; ocp_nlp_dims_set_opt_vars(nlp_config, nlp_dims, "nx", nx); ocp_nlp_dims_set_opt_vars(nlp_config, nlp_dims, "nu", nu); @@ -325,14 +324,14 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nbxe", &nbxe[i]); } - {%- if cost.cost_type_0 == "NONLINEAR_LS" or cost.cost_type_0 == "LINEAR_LS" %} +{%- if cost.cost_type_0 == "NONLINEAR_LS" or cost.cost_type_0 == "LINEAR_LS" %} ocp_nlp_dims_set_cost(nlp_config, nlp_dims, 0, "ny", &ny[0]); - {%- endif %} +{%- endif %} - {%- if cost.cost_type == "NONLINEAR_LS" or cost.cost_type == "LINEAR_LS" %} +{%- if cost.cost_type == "NONLINEAR_LS" or cost.cost_type == "LINEAR_LS" %} for (int i = 1; i < N; i++) ocp_nlp_dims_set_cost(nlp_config, nlp_dims, i, "ny", &ny[i]); - {%- endif %} +{%- endif %} for (int i = 0; i < N; i++) { @@ -346,21 +345,20 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c {%- endif %} } - {%- if constraints.constr_type_e == "BGH" %} +{%- if constraints.constr_type_e == "BGH" %} ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, N, "nh", &nh[N]); ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, N, "nsh", &nsh[N]); - {%- elif constraints.constr_type_e == "BGP" %} +{%- elif constraints.constr_type_e == "BGP" %} ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, N, "nr", &nr[N]); ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, N, "nphi", &nphi[N]); ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, N, "nsphi", &nsphi[N]); - {%- endif %} - {%- if cost.cost_type_e == "NONLINEAR_LS" or cost.cost_type_e == "LINEAR_LS" %} +{%- endif %} +{%- if cost.cost_type_e == "NONLINEAR_LS" or cost.cost_type_e == "LINEAR_LS" %} ocp_nlp_dims_set_cost(nlp_config, nlp_dims, N, "ny", &ny[N]); - {%- endif %} - +{%- endif %} free(intNp1mem); -{% if solver_options.integrator_type == "GNSF" -%} +{%- if solver_options.integrator_type == "GNSF" -%} // GNSF specific dimensions int gnsf_nx1 = {{ dims.gnsf_nx1 }}; int gnsf_nz1 = {{ dims.gnsf_nz1 }}; @@ -380,136 +378,91 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c } } {%- endif %} +return nlp_dims; +} + + +/** + * Internal function for {{ model.name }}_acados_create: step 3 + */ +void {{ model.name }}_acados_create_3_create_and_set_functions({{ model.name }}_solver_capsule* capsule) +{ + const int N = capsule->nlp_solver_plan->N; + ocp_nlp_config* nlp_config = capsule->nlp_config; /************************************************ * external functions ************************************************/ - {%- if constraints.constr_type == "BGP" %} + +#define MAP_CASADI_FNC(__CAPSULE_FNC__, __MODEL_BASE_FNC__) do{ \ + capsule->__CAPSULE_FNC__.casadi_fun = & __MODEL_BASE_FNC__ ;\ + capsule->__CAPSULE_FNC__.casadi_n_in = & __MODEL_BASE_FNC__ ## _n_in; \ + capsule->__CAPSULE_FNC__.casadi_n_out = & __MODEL_BASE_FNC__ ## _n_out; \ + capsule->__CAPSULE_FNC__.casadi_sparsity_in = & __MODEL_BASE_FNC__ ## _sparsity_in; \ + capsule->__CAPSULE_FNC__.casadi_sparsity_out = & __MODEL_BASE_FNC__ ## _sparsity_out; \ + capsule->__CAPSULE_FNC__.casadi_work = & __MODEL_BASE_FNC__ ## _work; \ + external_function_param_casadi_create(&capsule->__CAPSULE_FNC__ , {{ dims.np }}); \ + }while(false) + +{% if constraints.constr_type == "BGP" %} + // constraints.constr_type == "BGP" capsule->phi_constraint = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { // nonlinear part of convex-composite constraint - capsule->phi_constraint[i].casadi_fun = &{{ model.name }}_phi_constraint; - capsule->phi_constraint[i].casadi_n_in = &{{ model.name }}_phi_constraint_n_in; - capsule->phi_constraint[i].casadi_n_out = &{{ model.name }}_phi_constraint_n_out; - capsule->phi_constraint[i].casadi_sparsity_in = &{{ model.name }}_phi_constraint_sparsity_in; - capsule->phi_constraint[i].casadi_sparsity_out = &{{ model.name }}_phi_constraint_sparsity_out; - capsule->phi_constraint[i].casadi_work = &{{ model.name }}_phi_constraint_work; - - external_function_param_casadi_create(&capsule->phi_constraint[i], {{ dims.np }}); + MAP_CASADI_FNC(phi_constraint[i], {{ model.name }}_phi_constraint); } - {%- endif %} +{%- endif %} - {%- if constraints.constr_type_e == "BGP" %} +{%- if constraints.constr_type_e == "BGP" %} + // constraints.constr_type_e == "BGP" // nonlinear part of convex-composite constraint - capsule->phi_e_constraint.casadi_fun = &{{ model.name }}_phi_e_constraint; - capsule->phi_e_constraint.casadi_n_in = &{{ model.name }}_phi_e_constraint_n_in; - capsule->phi_e_constraint.casadi_n_out = &{{ model.name }}_phi_e_constraint_n_out; - capsule->phi_e_constraint.casadi_sparsity_in = &{{ model.name }}_phi_e_constraint_sparsity_in; - capsule->phi_e_constraint.casadi_sparsity_out = &{{ model.name }}_phi_e_constraint_sparsity_out; - capsule->phi_e_constraint.casadi_work = &{{ model.name }}_phi_e_constraint_work; - - external_function_param_casadi_create(&capsule->phi_e_constraint, {{ dims.np }}); - {% endif %} + MAP_CASADI_FNC(phi_e_constraint, {{ model.name }}_phi_e_constraint); +{%- endif %} - {%- if constraints.constr_type == "BGH" and dims.nh > 0 %} +{%- if constraints.constr_type == "BGH" and dims.nh > 0 %} + // constraints.constr_type == "BGH" and dims.nh > 0 capsule->nl_constr_h_fun_jac = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { - capsule->nl_constr_h_fun_jac[i].casadi_fun = &{{ model.name }}_constr_h_fun_jac_uxt_zt; - capsule->nl_constr_h_fun_jac[i].casadi_n_in = &{{ model.name }}_constr_h_fun_jac_uxt_zt_n_in; - capsule->nl_constr_h_fun_jac[i].casadi_n_out = &{{ model.name }}_constr_h_fun_jac_uxt_zt_n_out; - capsule->nl_constr_h_fun_jac[i].casadi_sparsity_in = &{{ model.name }}_constr_h_fun_jac_uxt_zt_sparsity_in; - capsule->nl_constr_h_fun_jac[i].casadi_sparsity_out = &{{ model.name }}_constr_h_fun_jac_uxt_zt_sparsity_out; - capsule->nl_constr_h_fun_jac[i].casadi_work = &{{ model.name }}_constr_h_fun_jac_uxt_zt_work; - external_function_param_casadi_create(&capsule->nl_constr_h_fun_jac[i], {{ dims.np }}); + MAP_CASADI_FNC(nl_constr_h_fun_jac[i], {{ model.name }}_constr_h_fun_jac_uxt_zt); } capsule->nl_constr_h_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { - capsule->nl_constr_h_fun[i].casadi_fun = &{{ model.name }}_constr_h_fun; - capsule->nl_constr_h_fun[i].casadi_n_in = &{{ model.name }}_constr_h_fun_n_in; - capsule->nl_constr_h_fun[i].casadi_n_out = &{{ model.name }}_constr_h_fun_n_out; - capsule->nl_constr_h_fun[i].casadi_sparsity_in = &{{ model.name }}_constr_h_fun_sparsity_in; - capsule->nl_constr_h_fun[i].casadi_sparsity_out = &{{ model.name }}_constr_h_fun_sparsity_out; - capsule->nl_constr_h_fun[i].casadi_work = &{{ model.name }}_constr_h_fun_work; - external_function_param_casadi_create(&capsule->nl_constr_h_fun[i], {{ dims.np }}); + MAP_CASADI_FNC(nl_constr_h_fun[i], {{ model.name }}_constr_h_fun); } {% if solver_options.hessian_approx == "EXACT" %} capsule->nl_constr_h_fun_jac_hess = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { - capsule->nl_constr_h_fun_jac_hess[i].casadi_fun = &{{ model.name }}_constr_h_fun_jac_uxt_zt_hess; - capsule->nl_constr_h_fun_jac_hess[i].casadi_n_in = &{{ model.name }}_constr_h_fun_jac_uxt_zt_hess_n_in; - capsule->nl_constr_h_fun_jac_hess[i].casadi_n_out = &{{ model.name }}_constr_h_fun_jac_uxt_zt_hess_n_out; - capsule->nl_constr_h_fun_jac_hess[i].casadi_sparsity_in = &{{ model.name }}_constr_h_fun_jac_uxt_zt_hess_sparsity_in; - capsule->nl_constr_h_fun_jac_hess[i].casadi_sparsity_out = &{{ model.name }}_constr_h_fun_jac_uxt_zt_hess_sparsity_out; - capsule->nl_constr_h_fun_jac_hess[i].casadi_work = &{{ model.name }}_constr_h_fun_jac_uxt_zt_hess_work; - - external_function_param_casadi_create(&capsule->nl_constr_h_fun_jac_hess[i], {{ dims.np }}); + MAP_CASADI_FNC(nl_constr_h_fun_jac_hess[i], {{ model.name }}_constr_h_fun_jac_uxt_zt_hess); } {% endif %} - {% endif %} +{% endif %} - {%- if constraints.constr_type_e == "BGH" and dims.nh_e > 0 %} - capsule->nl_constr_h_e_fun_jac.casadi_fun = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt; - capsule->nl_constr_h_e_fun_jac.casadi_n_in = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_n_in; - capsule->nl_constr_h_e_fun_jac.casadi_n_out = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_n_out; - capsule->nl_constr_h_e_fun_jac.casadi_sparsity_in = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_sparsity_in; - capsule->nl_constr_h_e_fun_jac.casadi_sparsity_out = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_sparsity_out; - capsule->nl_constr_h_e_fun_jac.casadi_work = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_work; - external_function_param_casadi_create(&capsule->nl_constr_h_e_fun_jac, {{ dims.np }}); - - capsule->nl_constr_h_e_fun.casadi_fun = &{{ model.name }}_constr_h_e_fun; - capsule->nl_constr_h_e_fun.casadi_n_in = &{{ model.name }}_constr_h_e_fun_n_in; - capsule->nl_constr_h_e_fun.casadi_n_out = &{{ model.name }}_constr_h_e_fun_n_out; - capsule->nl_constr_h_e_fun.casadi_sparsity_in = &{{ model.name }}_constr_h_e_fun_sparsity_in; - capsule->nl_constr_h_e_fun.casadi_sparsity_out = &{{ model.name }}_constr_h_e_fun_sparsity_out; - capsule->nl_constr_h_e_fun.casadi_work = &{{ model.name }}_constr_h_e_fun_work; - external_function_param_casadi_create(&capsule->nl_constr_h_e_fun, {{ dims.np }}); +{%- if constraints.constr_type_e == "BGH" and dims.nh_e > 0 %} + MAP_CASADI_FNC(nl_constr_h_e_fun_jac, {{ model.name }}_constr_h_e_fun_jac_uxt_zt); + MAP_CASADI_FNC(nl_constr_h_e_fun, {{ model.name }}_constr_h_e_fun); - {% if solver_options.hessian_approx == "EXACT" %} - capsule->nl_constr_h_e_fun_jac_hess.casadi_fun = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess; - capsule->nl_constr_h_e_fun_jac_hess.casadi_n_in = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess_n_in; - capsule->nl_constr_h_e_fun_jac_hess.casadi_n_out = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess_n_out; - capsule->nl_constr_h_e_fun_jac_hess.casadi_sparsity_in = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess_sparsity_in; - capsule->nl_constr_h_e_fun_jac_hess.casadi_sparsity_out = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess_sparsity_out; - capsule->nl_constr_h_e_fun_jac_hess.casadi_work = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess_work; - external_function_param_casadi_create(&capsule->nl_constr_h_e_fun_jac_hess, {{ dims.np }}); + {%- if solver_options.hessian_approx == "EXACT" %} + MAP_CASADI_FNC(nl_constr_h_e_fun_jac_hess, {{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess); {% endif %} - {%- endif %} +{%- endif %} {% if solver_options.integrator_type == "ERK" %} // explicit ode capsule->forw_vde_casadi = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { - capsule->forw_vde_casadi[i].casadi_fun = &{{ model.name }}_expl_vde_forw; - capsule->forw_vde_casadi[i].casadi_n_in = &{{ model.name }}_expl_vde_forw_n_in; - capsule->forw_vde_casadi[i].casadi_n_out = &{{ model.name }}_expl_vde_forw_n_out; - capsule->forw_vde_casadi[i].casadi_sparsity_in = &{{ model.name }}_expl_vde_forw_sparsity_in; - capsule->forw_vde_casadi[i].casadi_sparsity_out = &{{ model.name }}_expl_vde_forw_sparsity_out; - capsule->forw_vde_casadi[i].casadi_work = &{{ model.name }}_expl_vde_forw_work; - external_function_param_casadi_create(&capsule->forw_vde_casadi[i], {{ dims.np }}); + MAP_CASADI_FNC(forw_vde_casadi[i], {{ model.name }}_expl_vde_forw); } capsule->expl_ode_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { - capsule->expl_ode_fun[i].casadi_fun = &{{ model.name }}_expl_ode_fun; - capsule->expl_ode_fun[i].casadi_n_in = &{{ model.name }}_expl_ode_fun_n_in; - capsule->expl_ode_fun[i].casadi_n_out = &{{ model.name }}_expl_ode_fun_n_out; - capsule->expl_ode_fun[i].casadi_sparsity_in = &{{ model.name }}_expl_ode_fun_sparsity_in; - capsule->expl_ode_fun[i].casadi_sparsity_out = &{{ model.name }}_expl_ode_fun_sparsity_out; - capsule->expl_ode_fun[i].casadi_work = &{{ model.name }}_expl_ode_fun_work; - external_function_param_casadi_create(&capsule->expl_ode_fun[i], {{ dims.np }}); + MAP_CASADI_FNC(expl_ode_fun[i], {{ model.name }}_expl_ode_fun); } {%- if solver_options.hessian_approx == "EXACT" %} capsule->hess_vde_casadi = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { - capsule->hess_vde_casadi[i].casadi_fun = &{{ model.name }}_expl_ode_hess; - capsule->hess_vde_casadi[i].casadi_n_in = &{{ model.name }}_expl_ode_hess_n_in; - capsule->hess_vde_casadi[i].casadi_n_out = &{{ model.name }}_expl_ode_hess_n_out; - capsule->hess_vde_casadi[i].casadi_sparsity_in = &{{ model.name }}_expl_ode_hess_sparsity_in; - capsule->hess_vde_casadi[i].casadi_sparsity_out = &{{ model.name }}_expl_ode_hess_sparsity_out; - capsule->hess_vde_casadi[i].casadi_work = &{{ model.name }}_expl_ode_hess_work; - external_function_param_casadi_create(&capsule->hess_vde_casadi[i], {{ dims.np }}); + MAP_CASADI_FNC(hess_vde_casadi[i], {{ model.name }}_expl_ode_hess); } {%- endif %} @@ -517,126 +470,64 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c // implicit dae capsule->impl_dae_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { - capsule->impl_dae_fun[i].casadi_fun = &{{ model.name }}_impl_dae_fun; - capsule->impl_dae_fun[i].casadi_work = &{{ model.name }}_impl_dae_fun_work; - capsule->impl_dae_fun[i].casadi_sparsity_in = &{{ model.name }}_impl_dae_fun_sparsity_in; - capsule->impl_dae_fun[i].casadi_sparsity_out = &{{ model.name }}_impl_dae_fun_sparsity_out; - capsule->impl_dae_fun[i].casadi_n_in = &{{ model.name }}_impl_dae_fun_n_in; - capsule->impl_dae_fun[i].casadi_n_out = &{{ model.name }}_impl_dae_fun_n_out; - external_function_param_casadi_create(&capsule->impl_dae_fun[i], {{ dims.np }}); + MAP_CASADI_FNC(impl_dae_fun[i], {{ model.name }}_impl_dae_fun); } capsule->impl_dae_fun_jac_x_xdot_z = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { - capsule->impl_dae_fun_jac_x_xdot_z[i].casadi_fun = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z; - capsule->impl_dae_fun_jac_x_xdot_z[i].casadi_work = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z_work; - capsule->impl_dae_fun_jac_x_xdot_z[i].casadi_sparsity_in = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z_sparsity_in; - capsule->impl_dae_fun_jac_x_xdot_z[i].casadi_sparsity_out = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z_sparsity_out; - capsule->impl_dae_fun_jac_x_xdot_z[i].casadi_n_in = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z_n_in; - capsule->impl_dae_fun_jac_x_xdot_z[i].casadi_n_out = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z_n_out; - external_function_param_casadi_create(&capsule->impl_dae_fun_jac_x_xdot_z[i], {{ dims.np }}); + MAP_CASADI_FNC(impl_dae_fun_jac_x_xdot_z[i], {{ model.name }}_impl_dae_fun_jac_x_xdot_z); } capsule->impl_dae_jac_x_xdot_u_z = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { - capsule->impl_dae_jac_x_xdot_u_z[i].casadi_fun = &{{ model.name }}_impl_dae_jac_x_xdot_u_z; - capsule->impl_dae_jac_x_xdot_u_z[i].casadi_work = &{{ model.name }}_impl_dae_jac_x_xdot_u_z_work; - capsule->impl_dae_jac_x_xdot_u_z[i].casadi_sparsity_in = &{{ model.name }}_impl_dae_jac_x_xdot_u_z_sparsity_in; - capsule->impl_dae_jac_x_xdot_u_z[i].casadi_sparsity_out = &{{ model.name }}_impl_dae_jac_x_xdot_u_z_sparsity_out; - capsule->impl_dae_jac_x_xdot_u_z[i].casadi_n_in = &{{ model.name }}_impl_dae_jac_x_xdot_u_z_n_in; - capsule->impl_dae_jac_x_xdot_u_z[i].casadi_n_out = &{{ model.name }}_impl_dae_jac_x_xdot_u_z_n_out; - external_function_param_casadi_create(&capsule->impl_dae_jac_x_xdot_u_z[i], {{ dims.np }}); + MAP_CASADI_FNC(impl_dae_jac_x_xdot_u_z[i], {{ model.name }}_impl_dae_jac_x_xdot_u_z); } {%- if solver_options.hessian_approx == "EXACT" %} capsule->impl_dae_hess = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { - capsule->impl_dae_hess[i].casadi_fun = &{{ model.name }}_impl_dae_hess; - capsule->impl_dae_hess[i].casadi_work = &{{ model.name }}_impl_dae_hess_work; - capsule->impl_dae_hess[i].casadi_sparsity_in = &{{ model.name }}_impl_dae_hess_sparsity_in; - capsule->impl_dae_hess[i].casadi_sparsity_out = &{{ model.name }}_impl_dae_hess_sparsity_out; - capsule->impl_dae_hess[i].casadi_n_in = &{{ model.name }}_impl_dae_hess_n_in; - capsule->impl_dae_hess[i].casadi_n_out = &{{ model.name }}_impl_dae_hess_n_out; - external_function_param_casadi_create(&capsule->impl_dae_hess[i], {{ dims.np }}); + MAP_CASADI_FNC(impl_dae_hess[i], {{ model.name }}_impl_dae_hess); } {%- endif %} {% elif solver_options.integrator_type == "LIFTED_IRK" %} // external functions (implicit model) capsule->impl_dae_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { - capsule->impl_dae_fun[i].casadi_fun = &{{ model.name }}_impl_dae_fun; - capsule->impl_dae_fun[i].casadi_work = &{{ model.name }}_impl_dae_fun_work; - capsule->impl_dae_fun[i].casadi_sparsity_in = &{{ model.name }}_impl_dae_fun_sparsity_in; - capsule->impl_dae_fun[i].casadi_sparsity_out = &{{ model.name }}_impl_dae_fun_sparsity_out; - capsule->impl_dae_fun[i].casadi_n_in = &{{ model.name }}_impl_dae_fun_n_in; - capsule->impl_dae_fun[i].casadi_n_out = &{{ model.name }}_impl_dae_fun_n_out; - external_function_param_casadi_create(&capsule->impl_dae_fun[i], {{ dims.np }}); + MAP_CASADI_FNC(impl_dae_fun[i], {{ model.name }}_impl_dae_fun); } - capsule->impl_dae_fun_jac_x_xdot_u = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { - capsule->impl_dae_fun_jac_x_xdot_u[i].casadi_fun = &{{ model.name }}_impl_dae_fun_jac_x_xdot_u; - capsule->impl_dae_fun_jac_x_xdot_u[i].casadi_work = &{{ model.name }}_impl_dae_fun_jac_x_xdot_u_work; - capsule->impl_dae_fun_jac_x_xdot_u[i].casadi_sparsity_in = &{{ model.name }}_impl_dae_fun_jac_x_xdot_u_sparsity_in; - capsule->impl_dae_fun_jac_x_xdot_u[i].casadi_sparsity_out = &{{ model.name }}_impl_dae_fun_jac_x_xdot_u_sparsity_out; - capsule->impl_dae_fun_jac_x_xdot_u[i].casadi_n_in = &{{ model.name }}_impl_dae_fun_jac_x_xdot_u_n_in; - capsule->impl_dae_fun_jac_x_xdot_u[i].casadi_n_out = &{{ model.name }}_impl_dae_fun_jac_x_xdot_u_n_out; - external_function_param_casadi_create(&capsule->impl_dae_fun_jac_x_xdot_u[i], {{ dims.np }}); + capsule->impl_dae_fun_jac_x_xdot_u = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); + for (int i = 0; i < N; i++) { + MAP_CASADI_FNC(impl_dae_fun_jac_x_xdot_u[i], {{ model.name }}_impl_dae_fun_jac_x_xdot_u); } {% elif solver_options.integrator_type == "GNSF" %} + {% if model.gnsf.purely_linear != 1 %} capsule->gnsf_phi_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { - capsule->gnsf_phi_fun[i].casadi_fun = &{{ model.name }}_gnsf_phi_fun; - capsule->gnsf_phi_fun[i].casadi_work = &{{ model.name }}_gnsf_phi_fun_work; - capsule->gnsf_phi_fun[i].casadi_sparsity_in = &{{ model.name }}_gnsf_phi_fun_sparsity_in; - capsule->gnsf_phi_fun[i].casadi_sparsity_out = &{{ model.name }}_gnsf_phi_fun_sparsity_out; - capsule->gnsf_phi_fun[i].casadi_n_in = &{{ model.name }}_gnsf_phi_fun_n_in; - capsule->gnsf_phi_fun[i].casadi_n_out = &{{ model.name }}_gnsf_phi_fun_n_out; - external_function_param_casadi_create(&capsule->gnsf_phi_fun[i], {{ dims.np }}); + MAP_CASADI_FNC(gnsf_phi_fun[i], {{ model.name }}_gnsf_phi_fun); } capsule->gnsf_phi_fun_jac_y = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { - capsule->gnsf_phi_fun_jac_y[i].casadi_fun = &{{ model.name }}_gnsf_phi_fun_jac_y; - capsule->gnsf_phi_fun_jac_y[i].casadi_work = &{{ model.name }}_gnsf_phi_fun_jac_y_work; - capsule->gnsf_phi_fun_jac_y[i].casadi_sparsity_in = &{{ model.name }}_gnsf_phi_fun_jac_y_sparsity_in; - capsule->gnsf_phi_fun_jac_y[i].casadi_sparsity_out = &{{ model.name }}_gnsf_phi_fun_jac_y_sparsity_out; - capsule->gnsf_phi_fun_jac_y[i].casadi_n_in = &{{ model.name }}_gnsf_phi_fun_jac_y_n_in; - capsule->gnsf_phi_fun_jac_y[i].casadi_n_out = &{{ model.name }}_gnsf_phi_fun_jac_y_n_out; - external_function_param_casadi_create(&capsule->gnsf_phi_fun_jac_y[i], {{ dims.np }}); + MAP_CASADI_FNC(gnsf_phi_fun_jac_y[i], {{ model.name }}_gnsf_phi_fun_jac_y); } capsule->gnsf_phi_jac_y_uhat = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { - capsule->gnsf_phi_jac_y_uhat[i].casadi_fun = &{{ model.name }}_gnsf_phi_jac_y_uhat; - capsule->gnsf_phi_jac_y_uhat[i].casadi_work = &{{ model.name }}_gnsf_phi_jac_y_uhat_work; - capsule->gnsf_phi_jac_y_uhat[i].casadi_sparsity_in = &{{ model.name }}_gnsf_phi_jac_y_uhat_sparsity_in; - capsule->gnsf_phi_jac_y_uhat[i].casadi_sparsity_out = &{{ model.name }}_gnsf_phi_jac_y_uhat_sparsity_out; - capsule->gnsf_phi_jac_y_uhat[i].casadi_n_in = &{{ model.name }}_gnsf_phi_jac_y_uhat_n_in; - capsule->gnsf_phi_jac_y_uhat[i].casadi_n_out = &{{ model.name }}_gnsf_phi_jac_y_uhat_n_out; - external_function_param_casadi_create(&capsule->gnsf_phi_jac_y_uhat[i], {{ dims.np }}); + MAP_CASADI_FNC(gnsf_phi_jac_y_uhat[i], {{ model.name }}_gnsf_phi_jac_y_uhat); } + {% if model.gnsf.nontrivial_f_LO == 1 %} capsule->gnsf_f_lo_jac_x1_x1dot_u_z = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { - capsule->gnsf_f_lo_jac_x1_x1dot_u_z[i].casadi_fun = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz; - capsule->gnsf_f_lo_jac_x1_x1dot_u_z[i].casadi_work = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_work; - capsule->gnsf_f_lo_jac_x1_x1dot_u_z[i].casadi_sparsity_in = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_sparsity_in; - capsule->gnsf_f_lo_jac_x1_x1dot_u_z[i].casadi_sparsity_out = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_sparsity_out; - capsule->gnsf_f_lo_jac_x1_x1dot_u_z[i].casadi_n_in = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_n_in; - capsule->gnsf_f_lo_jac_x1_x1dot_u_z[i].casadi_n_out = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_n_out; - external_function_param_casadi_create(&capsule->gnsf_f_lo_jac_x1_x1dot_u_z[i], {{ dims.np }}); + MAP_CASADI_FNC(gnsf_f_lo_jac_x1_x1dot_u_z[i], {{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz); } - + {%- endif %} + {%- endif %} capsule->gnsf_get_matrices_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { - capsule->gnsf_get_matrices_fun[i].casadi_fun = &{{ model.name }}_gnsf_get_matrices_fun; - capsule->gnsf_get_matrices_fun[i].casadi_work = &{{ model.name }}_gnsf_get_matrices_fun_work; - capsule->gnsf_get_matrices_fun[i].casadi_sparsity_in = &{{ model.name }}_gnsf_get_matrices_fun_sparsity_in; - capsule->gnsf_get_matrices_fun[i].casadi_sparsity_out = &{{ model.name }}_gnsf_get_matrices_fun_sparsity_out; - capsule->gnsf_get_matrices_fun[i].casadi_n_in = &{{ model.name }}_gnsf_get_matrices_fun_n_in; - capsule->gnsf_get_matrices_fun[i].casadi_n_out = &{{ model.name }}_gnsf_get_matrices_fun_n_out; - external_function_param_casadi_create(&capsule->gnsf_get_matrices_fun[i], {{ dims.np }}); + MAP_CASADI_FNC(gnsf_get_matrices_fun[i], {{ model.name }}_gnsf_get_matrices_fun); } {% elif solver_options.integrator_type == "DISCRETE" %} // discrete dynamics @@ -644,32 +535,22 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c for (int i = 0; i < N; i++) { {%- if model.dyn_ext_fun_type == "casadi" %} - capsule->discr_dyn_phi_fun[i].casadi_fun = &{{ model.name }}_dyn_disc_phi_fun; - capsule->discr_dyn_phi_fun[i].casadi_n_in = &{{ model.name }}_dyn_disc_phi_fun_n_in; - capsule->discr_dyn_phi_fun[i].casadi_n_out = &{{ model.name }}_dyn_disc_phi_fun_n_out; - capsule->discr_dyn_phi_fun[i].casadi_sparsity_in = &{{ model.name }}_dyn_disc_phi_fun_sparsity_in; - capsule->discr_dyn_phi_fun[i].casadi_sparsity_out = &{{ model.name }}_dyn_disc_phi_fun_sparsity_out; - capsule->discr_dyn_phi_fun[i].casadi_work = &{{ model.name }}_dyn_disc_phi_fun_work; + MAP_CASADI_FNC(discr_dyn_phi_fun[i], {{ model.name }}_dyn_disc_phi_fun); {%- else %} capsule->discr_dyn_phi_fun[i].fun = &{{ model.dyn_disc_fun }}; - {%- endif %} external_function_param_{{ model.dyn_ext_fun_type }}_create(&capsule->discr_dyn_phi_fun[i], {{ dims.np }}); + {%- endif %} } capsule->discr_dyn_phi_fun_jac_ut_xt = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})*N); for (int i = 0; i < N; i++) { {%- if model.dyn_ext_fun_type == "casadi" %} - capsule->discr_dyn_phi_fun_jac_ut_xt[i].casadi_fun = &{{ model.name }}_dyn_disc_phi_fun_jac; - capsule->discr_dyn_phi_fun_jac_ut_xt[i].casadi_n_in = &{{ model.name }}_dyn_disc_phi_fun_jac_n_in; - capsule->discr_dyn_phi_fun_jac_ut_xt[i].casadi_n_out = &{{ model.name }}_dyn_disc_phi_fun_jac_n_out; - capsule->discr_dyn_phi_fun_jac_ut_xt[i].casadi_sparsity_in = &{{ model.name }}_dyn_disc_phi_fun_jac_sparsity_in; - capsule->discr_dyn_phi_fun_jac_ut_xt[i].casadi_sparsity_out = &{{ model.name }}_dyn_disc_phi_fun_jac_sparsity_out; - capsule->discr_dyn_phi_fun_jac_ut_xt[i].casadi_work = &{{ model.name }}_dyn_disc_phi_fun_jac_work; + MAP_CASADI_FNC(discr_dyn_phi_fun_jac_ut_xt[i], {{ model.name }}_dyn_disc_phi_fun_jac); {%- else %} capsule->discr_dyn_phi_fun_jac_ut_xt[i].fun = &{{ model.dyn_disc_fun_jac }}; - {%- endif %} external_function_param_{{ model.dyn_ext_fun_type }}_create(&capsule->discr_dyn_phi_fun_jac_ut_xt[i], {{ dims.np }}); + {%- endif %} } {%- if solver_options.hessian_approx == "EXACT" %} @@ -677,86 +558,46 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c for (int i = 0; i < N; i++) { {%- if model.dyn_ext_fun_type == "casadi" %} - capsule->discr_dyn_phi_fun_jac_ut_xt_hess[i].casadi_fun = &{{ model.name }}_dyn_disc_phi_fun_jac_hess; - capsule->discr_dyn_phi_fun_jac_ut_xt_hess[i].casadi_n_in = &{{ model.name }}_dyn_disc_phi_fun_jac_hess_n_in; - capsule->discr_dyn_phi_fun_jac_ut_xt_hess[i].casadi_n_out = &{{ model.name }}_dyn_disc_phi_fun_jac_hess_n_out; - capsule->discr_dyn_phi_fun_jac_ut_xt_hess[i].casadi_sparsity_in = &{{ model.name }}_dyn_disc_phi_fun_jac_hess_sparsity_in; - capsule->discr_dyn_phi_fun_jac_ut_xt_hess[i].casadi_sparsity_out = &{{ model.name }}_dyn_disc_phi_fun_jac_hess_sparsity_out; - capsule->discr_dyn_phi_fun_jac_ut_xt_hess[i].casadi_work = &{{ model.name }}_dyn_disc_phi_fun_jac_hess_work; + MAP_CASADI_FNC(discr_dyn_phi_fun_jac_ut_xt_hess[i], {{ model.name }}_dyn_disc_phi_fun_jac_hess); {%- else %} capsule->discr_dyn_phi_fun_jac_ut_xt_hess[i].fun = &{{ model.dyn_disc_fun_jac_hess }}; - {%- endif %} external_function_param_{{ model.dyn_ext_fun_type }}_create(&capsule->discr_dyn_phi_fun_jac_ut_xt_hess[i], {{ dims.np }}); + {%- endif %} } {%- endif %} {%- endif %} {%- if cost.cost_type_0 == "NONLINEAR_LS" %} - // nonlinear least square function - capsule->cost_y_0_fun.casadi_fun = &{{ model.name }}_cost_y_0_fun; - capsule->cost_y_0_fun.casadi_n_in = &{{ model.name }}_cost_y_0_fun_n_in; - capsule->cost_y_0_fun.casadi_n_out = &{{ model.name }}_cost_y_0_fun_n_out; - capsule->cost_y_0_fun.casadi_sparsity_in = &{{ model.name }}_cost_y_0_fun_sparsity_in; - capsule->cost_y_0_fun.casadi_sparsity_out = &{{ model.name }}_cost_y_0_fun_sparsity_out; - capsule->cost_y_0_fun.casadi_work = &{{ model.name }}_cost_y_0_fun_work; - external_function_param_casadi_create(&capsule->cost_y_0_fun, {{ dims.np }}); - - capsule->cost_y_0_fun_jac_ut_xt.casadi_fun = &{{ model.name }}_cost_y_0_fun_jac_ut_xt; - capsule->cost_y_0_fun_jac_ut_xt.casadi_n_in = &{{ model.name }}_cost_y_0_fun_jac_ut_xt_n_in; - capsule->cost_y_0_fun_jac_ut_xt.casadi_n_out = &{{ model.name }}_cost_y_0_fun_jac_ut_xt_n_out; - capsule->cost_y_0_fun_jac_ut_xt.casadi_sparsity_in = &{{ model.name }}_cost_y_0_fun_jac_ut_xt_sparsity_in; - capsule->cost_y_0_fun_jac_ut_xt.casadi_sparsity_out = &{{ model.name }}_cost_y_0_fun_jac_ut_xt_sparsity_out; - capsule->cost_y_0_fun_jac_ut_xt.casadi_work = &{{ model.name }}_cost_y_0_fun_jac_ut_xt_work; - external_function_param_casadi_create(&capsule->cost_y_0_fun_jac_ut_xt, {{ dims.np }}); - - capsule->cost_y_0_hess.casadi_fun = &{{ model.name }}_cost_y_0_hess; - capsule->cost_y_0_hess.casadi_n_in = &{{ model.name }}_cost_y_0_hess_n_in; - capsule->cost_y_0_hess.casadi_n_out = &{{ model.name }}_cost_y_0_hess_n_out; - capsule->cost_y_0_hess.casadi_sparsity_in = &{{ model.name }}_cost_y_0_hess_sparsity_in; - capsule->cost_y_0_hess.casadi_sparsity_out = &{{ model.name }}_cost_y_0_hess_sparsity_out; - capsule->cost_y_0_hess.casadi_work = &{{ model.name }}_cost_y_0_hess_work; - external_function_param_casadi_create(&capsule->cost_y_0_hess, {{ dims.np }}); + // nonlinear least squares function + MAP_CASADI_FNC(cost_y_0_fun, {{ model.name }}_cost_y_0_fun); + MAP_CASADI_FNC(cost_y_0_fun_jac_ut_xt, {{ model.name }}_cost_y_0_fun_jac_ut_xt); + MAP_CASADI_FNC(cost_y_0_hess, {{ model.name }}_cost_y_0_hess); {%- elif cost.cost_type_0 == "EXTERNAL" %} // external cost - {% if cost.cost_ext_fun_type_0 == "casadi" %} - capsule->ext_cost_0_fun.casadi_fun = &{{ model.name }}_cost_ext_cost_0_fun; - capsule->ext_cost_0_fun.casadi_n_in = &{{ model.name }}_cost_ext_cost_0_fun_n_in; - capsule->ext_cost_0_fun.casadi_n_out = &{{ model.name }}_cost_ext_cost_0_fun_n_out; - capsule->ext_cost_0_fun.casadi_sparsity_in = &{{ model.name }}_cost_ext_cost_0_fun_sparsity_in; - capsule->ext_cost_0_fun.casadi_sparsity_out = &{{ model.name }}_cost_ext_cost_0_fun_sparsity_out; - capsule->ext_cost_0_fun.casadi_work = &{{ model.name }}_cost_ext_cost_0_fun_work; - {% else %} + {%- if cost.cost_ext_fun_type_0 == "casadi" %} + MAP_CASADI_FNC(ext_cost_0_fun, {{ model.name }}_cost_ext_cost_0_fun); + {%- else %} capsule->ext_cost_0_fun.fun = &{{ cost.cost_function_ext_cost_0 }}; - {% endif %} external_function_param_{{ cost.cost_ext_fun_type_0 }}_create(&capsule->ext_cost_0_fun, {{ dims.np }}); + {%- endif %} // external cost - {% if cost.cost_ext_fun_type_0 == "casadi" %} - capsule->ext_cost_0_fun_jac.casadi_fun = &{{ model.name }}_cost_ext_cost_0_fun_jac; - capsule->ext_cost_0_fun_jac.casadi_n_in = &{{ model.name }}_cost_ext_cost_0_fun_jac_n_in; - capsule->ext_cost_0_fun_jac.casadi_n_out = &{{ model.name }}_cost_ext_cost_0_fun_jac_n_out; - capsule->ext_cost_0_fun_jac.casadi_sparsity_in = &{{ model.name }}_cost_ext_cost_0_fun_jac_sparsity_in; - capsule->ext_cost_0_fun_jac.casadi_sparsity_out = &{{ model.name }}_cost_ext_cost_0_fun_jac_sparsity_out; - capsule->ext_cost_0_fun_jac.casadi_work = &{{ model.name }}_cost_ext_cost_0_fun_jac_work; - {% else %} + {%- if cost.cost_ext_fun_type_0 == "casadi" %} + MAP_CASADI_FNC(ext_cost_0_fun_jac, {{ model.name }}_cost_ext_cost_0_fun_jac); + {%- else %} capsule->ext_cost_0_fun_jac.fun = &{{ cost.cost_function_ext_cost_0 }}; - {% endif %} external_function_param_{{ cost.cost_ext_fun_type_0 }}_create(&capsule->ext_cost_0_fun_jac, {{ dims.np }}); + {%- endif %} // external cost - {% if cost.cost_ext_fun_type_0 == "casadi" %} - capsule->ext_cost_0_fun_jac_hess.casadi_fun = &{{ model.name }}_cost_ext_cost_0_fun_jac_hess; - capsule->ext_cost_0_fun_jac_hess.casadi_n_in = &{{ model.name }}_cost_ext_cost_0_fun_jac_hess_n_in; - capsule->ext_cost_0_fun_jac_hess.casadi_n_out = &{{ model.name }}_cost_ext_cost_0_fun_jac_hess_n_out; - capsule->ext_cost_0_fun_jac_hess.casadi_sparsity_in = &{{ model.name }}_cost_ext_cost_0_fun_jac_hess_sparsity_in; - capsule->ext_cost_0_fun_jac_hess.casadi_sparsity_out = &{{ model.name }}_cost_ext_cost_0_fun_jac_hess_sparsity_out; - capsule->ext_cost_0_fun_jac_hess.casadi_work = &{{ model.name }}_cost_ext_cost_0_fun_jac_hess_work; - {% else %} + {%- if cost.cost_ext_fun_type_0 == "casadi" %} + MAP_CASADI_FNC(ext_cost_0_fun_jac_hess, {{ model.name }}_cost_ext_cost_0_fun_jac_hess); + {%- else %} capsule->ext_cost_0_fun_jac_hess.fun = &{{ cost.cost_function_ext_cost_0 }}; - {% endif %} external_function_param_{{ cost.cost_ext_fun_type_0 }}_create(&capsule->ext_cost_0_fun_jac_hess, {{ dims.np }}); + {%- endif %} {%- endif %} {%- if cost.cost_type == "NONLINEAR_LS" %} @@ -764,164 +605,130 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c capsule->cost_y_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N-1; i++) { - capsule->cost_y_fun[i].casadi_fun = &{{ model.name }}_cost_y_fun; - capsule->cost_y_fun[i].casadi_n_in = &{{ model.name }}_cost_y_fun_n_in; - capsule->cost_y_fun[i].casadi_n_out = &{{ model.name }}_cost_y_fun_n_out; - capsule->cost_y_fun[i].casadi_sparsity_in = &{{ model.name }}_cost_y_fun_sparsity_in; - capsule->cost_y_fun[i].casadi_sparsity_out = &{{ model.name }}_cost_y_fun_sparsity_out; - capsule->cost_y_fun[i].casadi_work = &{{ model.name }}_cost_y_fun_work; - - external_function_param_casadi_create(&capsule->cost_y_fun[i], {{ dims.np }}); + MAP_CASADI_FNC(cost_y_fun[i], {{ model.name }}_cost_y_fun); } capsule->cost_y_fun_jac_ut_xt = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N-1; i++) { - capsule->cost_y_fun_jac_ut_xt[i].casadi_fun = &{{ model.name }}_cost_y_fun_jac_ut_xt; - capsule->cost_y_fun_jac_ut_xt[i].casadi_n_in = &{{ model.name }}_cost_y_fun_jac_ut_xt_n_in; - capsule->cost_y_fun_jac_ut_xt[i].casadi_n_out = &{{ model.name }}_cost_y_fun_jac_ut_xt_n_out; - capsule->cost_y_fun_jac_ut_xt[i].casadi_sparsity_in = &{{ model.name }}_cost_y_fun_jac_ut_xt_sparsity_in; - capsule->cost_y_fun_jac_ut_xt[i].casadi_sparsity_out = &{{ model.name }}_cost_y_fun_jac_ut_xt_sparsity_out; - capsule->cost_y_fun_jac_ut_xt[i].casadi_work = &{{ model.name }}_cost_y_fun_jac_ut_xt_work; - - external_function_param_casadi_create(&capsule->cost_y_fun_jac_ut_xt[i], {{ dims.np }}); + MAP_CASADI_FNC(cost_y_fun_jac_ut_xt[i], {{ model.name }}_cost_y_fun_jac_ut_xt); } capsule->cost_y_hess = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N-1; i++) { - capsule->cost_y_hess[i].casadi_fun = &{{ model.name }}_cost_y_hess; - capsule->cost_y_hess[i].casadi_n_in = &{{ model.name }}_cost_y_hess_n_in; - capsule->cost_y_hess[i].casadi_n_out = &{{ model.name }}_cost_y_hess_n_out; - capsule->cost_y_hess[i].casadi_sparsity_in = &{{ model.name }}_cost_y_hess_sparsity_in; - capsule->cost_y_hess[i].casadi_sparsity_out = &{{ model.name }}_cost_y_hess_sparsity_out; - capsule->cost_y_hess[i].casadi_work = &{{ model.name }}_cost_y_hess_work; - - external_function_param_casadi_create(&capsule->cost_y_hess[i], {{ dims.np }}); + MAP_CASADI_FNC(cost_y_hess[i], {{ model.name }}_cost_y_hess); } {%- elif cost.cost_type == "EXTERNAL" %} // external cost capsule->ext_cost_fun = (external_function_param_{{ cost.cost_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ cost.cost_ext_fun_type }})*N); for (int i = 0; i < N-1; i++) { - {% if cost.cost_ext_fun_type == "casadi" %} - capsule->ext_cost_fun[i].casadi_fun = &{{ model.name }}_cost_ext_cost_fun; - capsule->ext_cost_fun[i].casadi_n_in = &{{ model.name }}_cost_ext_cost_fun_n_in; - capsule->ext_cost_fun[i].casadi_n_out = &{{ model.name }}_cost_ext_cost_fun_n_out; - capsule->ext_cost_fun[i].casadi_sparsity_in = &{{ model.name }}_cost_ext_cost_fun_sparsity_in; - capsule->ext_cost_fun[i].casadi_sparsity_out = &{{ model.name }}_cost_ext_cost_fun_sparsity_out; - capsule->ext_cost_fun[i].casadi_work = &{{ model.name }}_cost_ext_cost_fun_work; - {% else %} + {%- if cost.cost_ext_fun_type == "casadi" %} + MAP_CASADI_FNC(ext_cost_fun[i], {{ model.name }}_cost_ext_cost_fun); + {%- else %} capsule->ext_cost_fun[i].fun = &{{ cost.cost_function_ext_cost }}; - {% endif %} external_function_param_{{ cost.cost_ext_fun_type }}_create(&capsule->ext_cost_fun[i], {{ dims.np }}); + {%- endif %} } capsule->ext_cost_fun_jac = (external_function_param_{{ cost.cost_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ cost.cost_ext_fun_type }})*N); for (int i = 0; i < N-1; i++) { - {% if cost.cost_ext_fun_type == "casadi" %} - capsule->ext_cost_fun_jac[i].casadi_fun = &{{ model.name }}_cost_ext_cost_fun_jac; - capsule->ext_cost_fun_jac[i].casadi_n_in = &{{ model.name }}_cost_ext_cost_fun_jac_n_in; - capsule->ext_cost_fun_jac[i].casadi_n_out = &{{ model.name }}_cost_ext_cost_fun_jac_n_out; - capsule->ext_cost_fun_jac[i].casadi_sparsity_in = &{{ model.name }}_cost_ext_cost_fun_jac_sparsity_in; - capsule->ext_cost_fun_jac[i].casadi_sparsity_out = &{{ model.name }}_cost_ext_cost_fun_jac_sparsity_out; - capsule->ext_cost_fun_jac[i].casadi_work = &{{ model.name }}_cost_ext_cost_fun_jac_work; - {% else %} + {%- if cost.cost_ext_fun_type == "casadi" %} + MAP_CASADI_FNC(ext_cost_fun_jac[i], {{ model.name }}_cost_ext_cost_fun_jac); + {%- else %} capsule->ext_cost_fun_jac[i].fun = &{{ cost.cost_function_ext_cost }}; - {% endif %} external_function_param_{{ cost.cost_ext_fun_type }}_create(&capsule->ext_cost_fun_jac[i], {{ dims.np }}); + {%- endif %} } capsule->ext_cost_fun_jac_hess = (external_function_param_{{ cost.cost_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ cost.cost_ext_fun_type }})*N); for (int i = 0; i < N-1; i++) { - {% if cost.cost_ext_fun_type == "casadi" %} - capsule->ext_cost_fun_jac_hess[i].casadi_fun = &{{ model.name }}_cost_ext_cost_fun_jac_hess; - capsule->ext_cost_fun_jac_hess[i].casadi_n_in = &{{ model.name }}_cost_ext_cost_fun_jac_hess_n_in; - capsule->ext_cost_fun_jac_hess[i].casadi_n_out = &{{ model.name }}_cost_ext_cost_fun_jac_hess_n_out; - capsule->ext_cost_fun_jac_hess[i].casadi_sparsity_in = &{{ model.name }}_cost_ext_cost_fun_jac_hess_sparsity_in; - capsule->ext_cost_fun_jac_hess[i].casadi_sparsity_out = &{{ model.name }}_cost_ext_cost_fun_jac_hess_sparsity_out; - capsule->ext_cost_fun_jac_hess[i].casadi_work = &{{ model.name }}_cost_ext_cost_fun_jac_hess_work; - {% else %} + {%- if cost.cost_ext_fun_type == "casadi" %} + MAP_CASADI_FNC(ext_cost_fun_jac_hess[i], {{ model.name }}_cost_ext_cost_fun_jac_hess); + {%- else %} capsule->ext_cost_fun_jac_hess[i].fun = &{{ cost.cost_function_ext_cost }}; - {% endif %} external_function_param_{{ cost.cost_ext_fun_type }}_create(&capsule->ext_cost_fun_jac_hess[i], {{ dims.np }}); + {%- endif %} } {%- endif %} {%- if cost.cost_type_e == "NONLINEAR_LS" %} // nonlinear least square function - capsule->cost_y_e_fun.casadi_fun = &{{ model.name }}_cost_y_e_fun; - capsule->cost_y_e_fun.casadi_n_in = &{{ model.name }}_cost_y_e_fun_n_in; - capsule->cost_y_e_fun.casadi_n_out = &{{ model.name }}_cost_y_e_fun_n_out; - capsule->cost_y_e_fun.casadi_sparsity_in = &{{ model.name }}_cost_y_e_fun_sparsity_in; - capsule->cost_y_e_fun.casadi_sparsity_out = &{{ model.name }}_cost_y_e_fun_sparsity_out; - capsule->cost_y_e_fun.casadi_work = &{{ model.name }}_cost_y_e_fun_work; - external_function_param_casadi_create(&capsule->cost_y_e_fun, {{ dims.np }}); - - capsule->cost_y_e_fun_jac_ut_xt.casadi_fun = &{{ model.name }}_cost_y_e_fun_jac_ut_xt; - capsule->cost_y_e_fun_jac_ut_xt.casadi_n_in = &{{ model.name }}_cost_y_e_fun_jac_ut_xt_n_in; - capsule->cost_y_e_fun_jac_ut_xt.casadi_n_out = &{{ model.name }}_cost_y_e_fun_jac_ut_xt_n_out; - capsule->cost_y_e_fun_jac_ut_xt.casadi_sparsity_in = &{{ model.name }}_cost_y_e_fun_jac_ut_xt_sparsity_in; - capsule->cost_y_e_fun_jac_ut_xt.casadi_sparsity_out = &{{ model.name }}_cost_y_e_fun_jac_ut_xt_sparsity_out; - capsule->cost_y_e_fun_jac_ut_xt.casadi_work = &{{ model.name }}_cost_y_e_fun_jac_ut_xt_work; - external_function_param_casadi_create(&capsule->cost_y_e_fun_jac_ut_xt, {{ dims.np }}); - - capsule->cost_y_e_hess.casadi_fun = &{{ model.name }}_cost_y_e_hess; - capsule->cost_y_e_hess.casadi_n_in = &{{ model.name }}_cost_y_e_hess_n_in; - capsule->cost_y_e_hess.casadi_n_out = &{{ model.name }}_cost_y_e_hess_n_out; - capsule->cost_y_e_hess.casadi_sparsity_in = &{{ model.name }}_cost_y_e_hess_sparsity_in; - capsule->cost_y_e_hess.casadi_sparsity_out = &{{ model.name }}_cost_y_e_hess_sparsity_out; - capsule->cost_y_e_hess.casadi_work = &{{ model.name }}_cost_y_e_hess_work; - external_function_param_casadi_create(&capsule->cost_y_e_hess, {{ dims.np }}); - + MAP_CASADI_FNC(cost_y_e_fun, {{ model.name }}_cost_y_e_fun); + MAP_CASADI_FNC(cost_y_e_fun_jac_ut_xt, {{ model.name }}_cost_y_e_fun_jac_ut_xt); + MAP_CASADI_FNC(cost_y_e_hess, {{ model.name }}_cost_y_e_hess); {%- elif cost.cost_type_e == "EXTERNAL" %} - // external cost - {% if cost.cost_ext_fun_type_e == "casadi" %} - capsule->ext_cost_e_fun.casadi_fun = &{{ model.name }}_cost_ext_cost_e_fun; - capsule->ext_cost_e_fun.casadi_n_in = &{{ model.name }}_cost_ext_cost_e_fun_n_in; - capsule->ext_cost_e_fun.casadi_n_out = &{{ model.name }}_cost_ext_cost_e_fun_n_out; - capsule->ext_cost_e_fun.casadi_sparsity_in = &{{ model.name }}_cost_ext_cost_e_fun_sparsity_in; - capsule->ext_cost_e_fun.casadi_sparsity_out = &{{ model.name }}_cost_ext_cost_e_fun_sparsity_out; - capsule->ext_cost_e_fun.casadi_work = &{{ model.name }}_cost_ext_cost_e_fun_work; + // external cost - function + {%- if cost.cost_ext_fun_type_e == "casadi" %} + MAP_CASADI_FNC(ext_cost_e_fun, {{ model.name }}_cost_ext_cost_e_fun); {% else %} capsule->ext_cost_e_fun.fun = &{{ cost.cost_function_ext_cost_e }}; - {% endif %} external_function_param_{{ cost.cost_ext_fun_type_e }}_create(&capsule->ext_cost_e_fun, {{ dims.np }}); + {%- endif %} - // external cost - {% if cost.cost_ext_fun_type_e == "casadi" %} - capsule->ext_cost_e_fun_jac.casadi_fun = &{{ model.name }}_cost_ext_cost_e_fun_jac; - capsule->ext_cost_e_fun_jac.casadi_n_in = &{{ model.name }}_cost_ext_cost_e_fun_jac_n_in; - capsule->ext_cost_e_fun_jac.casadi_n_out = &{{ model.name }}_cost_ext_cost_e_fun_jac_n_out; - capsule->ext_cost_e_fun_jac.casadi_sparsity_in = &{{ model.name }}_cost_ext_cost_e_fun_jac_sparsity_in; - capsule->ext_cost_e_fun_jac.casadi_sparsity_out = &{{ model.name }}_cost_ext_cost_e_fun_jac_sparsity_out; - capsule->ext_cost_e_fun_jac.casadi_work = &{{ model.name }}_cost_ext_cost_e_fun_jac_work; - {% else %} + // external cost - jacobian + {%- if cost.cost_ext_fun_type_e == "casadi" %} + MAP_CASADI_FNC(ext_cost_e_fun_jac, {{ model.name }}_cost_ext_cost_e_fun_jac); + {%- else %} capsule->ext_cost_e_fun_jac.fun = &{{ cost.cost_function_ext_cost_e }}; - {% endif %} external_function_param_{{ cost.cost_ext_fun_type_e }}_create(&capsule->ext_cost_e_fun_jac, {{ dims.np }}); + {%- endif %} - // external cost - {% if cost.cost_ext_fun_type_e == "casadi" %} - capsule->ext_cost_e_fun_jac_hess.casadi_fun = &{{ model.name }}_cost_ext_cost_e_fun_jac_hess; - capsule->ext_cost_e_fun_jac_hess.casadi_n_in = &{{ model.name }}_cost_ext_cost_e_fun_jac_hess_n_in; - capsule->ext_cost_e_fun_jac_hess.casadi_n_out = &{{ model.name }}_cost_ext_cost_e_fun_jac_hess_n_out; - capsule->ext_cost_e_fun_jac_hess.casadi_sparsity_in = &{{ model.name }}_cost_ext_cost_e_fun_jac_hess_sparsity_in; - capsule->ext_cost_e_fun_jac_hess.casadi_sparsity_out = &{{ model.name }}_cost_ext_cost_e_fun_jac_hess_sparsity_out; - capsule->ext_cost_e_fun_jac_hess.casadi_work = &{{ model.name }}_cost_ext_cost_e_fun_jac_hess_work; - {% else %} + // external cost - hessian + {%- if cost.cost_ext_fun_type_e == "casadi" %} + MAP_CASADI_FNC(ext_cost_e_fun_jac_hess, {{ model.name }}_cost_ext_cost_e_fun_jac_hess); + {%- else %} capsule->ext_cost_e_fun_jac_hess.fun = &{{ cost.cost_function_ext_cost_e }}; - {% endif %} external_function_param_{{ cost.cost_ext_fun_type_e }}_create(&capsule->ext_cost_e_fun_jac_hess, {{ dims.np }}); + {%- endif %} {%- endif %} +#undef MAP_CASADI_FNC +} + + +/** + * Internal function for {{ model.name }}_acados_create: step 4 + */ +void {{ model.name }}_acados_create_4_set_default_parameters({{ model.name }}_solver_capsule* capsule) { +{%- if dims.np > 0 %} + const int N = capsule->nlp_solver_plan->N; + // initialize parameters to nominal value + double* p = calloc(NP, sizeof(double)); + {%- for item in parameter_values %} + {%- if item != 0 %} + p[{{ loop.index0 }}] = {{ item }}; + {%- endif %} + {%- endfor %} + + for (int i = 0; i <= N; i++) { + {{ model.name }}_acados_update_params(capsule, i, p, NP); + } + free(p); +{%- else %} + // no parameters defined +{%- endif %}{# if dims.np #} +} + + +/** + * Internal function for {{ model.name }}_acados_create: step 5 + */ +void {{ model.name }}_acados_create_5_set_nlp_in({{ model.name }}_solver_capsule* capsule, const int N, double* new_time_steps) +{ + assert(N == capsule->nlp_solver_plan->N); + ocp_nlp_config* nlp_config = capsule->nlp_config; + ocp_nlp_dims* nlp_dims = capsule->nlp_dims; + /************************************************ * nlp_in ************************************************/ - ocp_nlp_in * nlp_in = ocp_nlp_in_create(nlp_config, nlp_dims); - capsule->nlp_in = nlp_in; +// ocp_nlp_in * nlp_in = ocp_nlp_in_create(nlp_config, nlp_dims); +// capsule->nlp_in = nlp_in; + ocp_nlp_in * nlp_in = capsule->nlp_in; // set up time_steps {% set all_equal = true -%} @@ -978,11 +785,15 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "impl_dae_fun_jac_x_xdot_u", &capsule->impl_dae_fun_jac_x_xdot_u[i]); {% elif solver_options.integrator_type == "GNSF" %} + {% if model.gnsf.purely_linear != 1 %} ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "phi_fun", &capsule->gnsf_phi_fun[i]); ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "phi_fun_jac_y", &capsule->gnsf_phi_fun_jac_y[i]); ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "phi_jac_y_uhat", &capsule->gnsf_phi_jac_y_uhat[i]); + {% if model.gnsf.nontrivial_f_LO == 1 %} ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "f_lo_jac_x1_x1dot_u_z", &capsule->gnsf_f_lo_jac_x1_x1dot_u_z[i]); + {%- endif %} + {%- endif %} ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "gnsf_get_matrices_fun", &capsule->gnsf_get_matrices_fun[i]); {% elif solver_options.integrator_type == "DISCRETE" %} @@ -996,10 +807,9 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c {%- endif %} } - /**** Cost ****/ {%- if cost.cost_type_0 == "NONLINEAR_LS" or cost.cost_type_0 == "LINEAR_LS" %} -{% if dims.ny_0 > 0 %} + {%- if dims.ny_0 > 0 %} double* W_0 = calloc(NY0*NY0, sizeof(double)); // change only the non-zero elements: {%- for j in range(end=dims.ny_0) %} @@ -1021,14 +831,14 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c {%- endfor %} ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "yref", yref_0); free(yref_0); -{% endif %} -{% endif %} + {%- endif %} +{%- endif %} {%- if cost.cost_type == "NONLINEAR_LS" or cost.cost_type == "LINEAR_LS" %} -{% if dims.ny > 0 %} + {%- if dims.ny > 0 %} double* W = calloc(NY*NY, sizeof(double)); // change only the non-zero elements: - {% for j in range(end=dims.ny) %} + {%- for j in range(end=dims.ny) %} {%- for k in range(end=dims.ny) %} {%- if cost.W[j][k] != 0 %} W[{{ j }}+(NY) * {{ k }}] = {{ cost.W[j][k] }}; @@ -1051,13 +861,13 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c } free(W); free(yref); -{% endif %} -{% endif %} + {%- endif %} +{%- endif %} {%- if cost.cost_type_0 == "LINEAR_LS" %} double* Vx_0 = calloc(NY0*NX, sizeof(double)); // change only the non-zero elements: - {% for j in range(end=dims.ny_0) %} + {%- for j in range(end=dims.ny_0) %} {%- for k in range(end=dims.nx) %} {%- if cost.Vx_0[j][k] != 0 %} Vx_0[{{ j }}+(NY0) * {{ k }}] = {{ cost.Vx_0[j][k] }}; @@ -1067,10 +877,10 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "Vx", Vx_0); free(Vx_0); -{% if dims.ny_0 > 0 and dims.nu > 0 %} + {%- if dims.ny_0 > 0 and dims.nu > 0 %} double* Vu_0 = calloc(NY0*NU, sizeof(double)); // change only the non-zero elements: - {% for j in range(end=dims.ny_0) %} + {%- for j in range(end=dims.ny_0) %} {%- for k in range(end=dims.nu) %} {%- if cost.Vu_0[j][k] != 0 %} Vu_0[{{ j }}+(NY0) * {{ k }}] = {{ cost.Vu_0[j][k] }}; @@ -1079,8 +889,9 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c {%- endfor %} ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "Vu", Vu_0); free(Vu_0); -{% endif %} -{% if dims.ny_0 > 0 and dims.nz > 0 %} + {%- endif %} + + {%- if dims.ny_0 > 0 and dims.nz > 0 %} double* Vz_0 = calloc(NY0*NZ, sizeof(double)); // change only the non-zero elements: {% for j in range(end=dims.ny_0) %} @@ -1092,14 +903,14 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c {%- endfor %} ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "Vz", Vz_0); free(Vz_0); -{%- endif %} + {%- endif %} {%- endif %}{# LINEAR LS #} {%- if cost.cost_type == "LINEAR_LS" %} double* Vx = calloc(NY*NX, sizeof(double)); // change only the non-zero elements: - {% for j in range(end=dims.ny) %} + {%- for j in range(end=dims.ny) %} {%- for k in range(end=dims.nx) %} {%- if cost.Vx[j][k] != 0 %} Vx[{{ j }}+(NY) * {{ k }}] = {{ cost.Vx[j][k] }}; @@ -1112,7 +923,7 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c } free(Vx); -{% if dims.ny > 0 and dims.nu > 0 %} + {% if dims.ny > 0 and dims.nu > 0 %} double* Vu = calloc(NY*NU, sizeof(double)); // change only the non-zero elements: {% for j in range(end=dims.ny) %} @@ -1128,9 +939,9 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "Vu", Vu); } free(Vu); -{% endif %} + {%- endif %} -{% if dims.ny > 0 and dims.nz > 0 %} + {%- if dims.ny > 0 and dims.nz > 0 %} double* Vz = calloc(NY*NZ, sizeof(double)); // change only the non-zero elements: {% for j in range(end=dims.ny) %} @@ -1146,7 +957,7 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "Vz", Vz); } free(Vz); -{%- endif %} + {%- endif %} {%- endif %}{# LINEAR LS #} @@ -1176,8 +987,7 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c } {%- endif %} - -{% if dims.ns > 0 %} +{%- if dims.ns > 0 %} double* zlumem = calloc(4*NS, sizeof(double)); double* Zl = zlumem+NS*0; double* Zu = zlumem+NS*1; @@ -1216,14 +1026,14 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "zu", zu); } free(zlumem); -{% endif %} +{%- endif %} // terminal cost -{% if cost.cost_type_e == "LINEAR_LS" or cost.cost_type_e == "NONLINEAR_LS" %} -{% if dims.ny_e > 0 %} +{%- if cost.cost_type_e == "LINEAR_LS" or cost.cost_type_e == "NONLINEAR_LS" %} + {%- if dims.ny_e > 0 %} double* yref_e = calloc(NYN, sizeof(double)); // change only the non-zero elements: - {% for j in range(end=dims.ny_e) %} + {%- for j in range(end=dims.ny_e) %} {%- if cost.yref_e[j] != 0 %} yref_e[{{ j }}] = {{ cost.yref_e[j] }}; {%- endif %} @@ -1233,7 +1043,7 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c double* W_e = calloc(NYN*NYN, sizeof(double)); // change only the non-zero elements: - {% for j in range(end=dims.ny_e) %} + {%- for j in range(end=dims.ny_e) %} {%- for k in range(end=dims.ny_e) %} {%- if cost.W_e[j][k] != 0 %} W_e[{{ j }}+(NYN) * {{ k }}] = {{ cost.W_e[j][k] }}; @@ -1243,7 +1053,7 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "W", W_e); free(W_e); - {%- if cost.cost_type_e == "LINEAR_LS" %} + {%- if cost.cost_type_e == "LINEAR_LS" %} double* Vx_e = calloc(NYN*NX, sizeof(double)); // change only the non-zero elements: {% for j in range(end=dims.ny_e) %} @@ -1255,14 +1065,14 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c {%- endfor %} ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "Vx", Vx_e); free(Vx_e); - {%- endif %} + {%- endif %} - {%- if cost.cost_type_e == "NONLINEAR_LS" %} + {%- if cost.cost_type_e == "NONLINEAR_LS" %} ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "nls_y_fun", &capsule->cost_y_e_fun); ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "nls_y_fun_jac", &capsule->cost_y_e_fun_jac_ut_xt); ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "nls_y_hess", &capsule->cost_y_e_hess); - {%- endif %} -{%- endif %}{# ny_e > 0 #} + {%- endif %} + {%- endif %}{# ny_e > 0 #} {%- elif cost.cost_type_e == "EXTERNAL" %} ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "ext_cost_fun", &capsule->ext_cost_e_fun); @@ -1312,7 +1122,7 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c /**** Constraints ****/ // bounds for initial stage -{% if dims.nbx_0 > 0 %} +{%- if dims.nbx_0 > 0 %} // x0 int* idxbx0 = malloc(NBX0 * sizeof(int)); {%- for i in range(end=dims.nbx_0) %} @@ -1337,8 +1147,9 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "ubx", ubx0); free(idxbx0); free(lubx0); -{% endif %} -{% if dims.nbxe_0 > 0 %} +{%- endif %} + +{%- if dims.nbxe_0 > 0 %} // idxbxe_0 int* idxbxe_0 = malloc({{ dims.nbxe_0 }} * sizeof(int)); {% for i in range(end=dims.nbxe_0) %} @@ -1346,7 +1157,7 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c {%- endfor %} ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "idxbxe", idxbxe_0); free(idxbxe_0); -{% endif %} +{%- endif %} /* constraints that are the same for initial and intermediate */ {%- if dims.nsbx > 0 %} @@ -1357,14 +1168,14 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c // soft bounds on x int* idxsbx = malloc(NSBX * sizeof(int)); - {% for i in range(end=dims.nsbx) %} + {%- for i in range(end=dims.nsbx) %} idxsbx[{{ i }}] = {{ constraints.idxsbx[i] }}; {%- endfor %} double* lusbx = calloc(2*NSBX, sizeof(double)); double* lsbx = lusbx; double* usbx = lusbx + NSBX; - {% for i in range(end=dims.nsbx) %} + {%- for i in range(end=dims.nsbx) %} {%- if constraints.lsbx[i] != 0 %} lsbx[{{ i }}] = {{ constraints.lsbx[i] }}; {%- endif %} @@ -1384,7 +1195,7 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c {%- endif %} -{% if dims.nbu > 0 %} +{%- if dims.nbu > 0 %} // u int* idxbu = malloc(NBU * sizeof(int)); {% for i in range(end=dims.nbu) %} @@ -1410,9 +1221,9 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c } free(idxbu); free(lubu); -{% endif %} +{%- endif %} -{% if dims.nsbu > 0 %} +{%- if dims.nsbu > 0 %} // set up soft bounds for u int* idxsbu = malloc(NSBU * sizeof(int)); {% for i in range(end=dims.nsbu) %} @@ -1437,7 +1248,7 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c } free(idxsbu); free(lusbu); -{% endif %} +{%- endif %} {% if dims.nsg > 0 %} // set up soft bounds for general linear constraints @@ -1465,7 +1276,7 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c } free(idxsg); free(lusg); -{% endif %} +{%- endif %} {% if dims.nsh > 0 %} // set up soft bounds for nonlinear constraints @@ -1493,7 +1304,7 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c } free(idxsh); free(lush); -{% endif %} +{%- endif %} {% if dims.nsphi > 0 %} // set up soft bounds for convex-over-nonlinear constraints @@ -1521,7 +1332,7 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c } free(idxsphi); free(lusphi); -{% endif %} +{%- endif %} {% if dims.nbx > 0 %} // x @@ -1549,7 +1360,7 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c } free(idxbx); free(lubx); -{% endif %} +{%- endif %} {% if dims.ng > 0 %} // set up general constraints for stage 0 to N-1 @@ -1597,7 +1408,7 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c free(D); free(C); free(lug); -{% endif %} +{%- endif %} {% if dims.nh > 0 %} // set up nonlinear constraints for stage 0 to N-1 @@ -1632,7 +1443,7 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "uh", uh); } free(luh); -{% endif %} +{%- endif %} {% if dims.nphi > 0 and constraints.constr_type == "BGP" %} // set up convex-over-nonlinear constraints for stage 0 to N-1 @@ -1659,7 +1470,7 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "uphi", uphi); } free(luphi); -{% endif %} +{%- endif %} /* terminal constraints */ {% if dims.nbx_e > 0 %} @@ -1866,42 +1677,62 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c "nl_constr_phi_o_r_fun_phi_jac_ux_z_phi_hess_r_jac_ux", &capsule->phi_e_constraint); free(luphi_e); {% endif %} +} +/** + * Internal function for {{ model.name }}_acados_create: step 6 + */ +void {{ model.name }}_acados_create_6_set_opts({{ model.name }}_solver_capsule* capsule) +{ + const int N = capsule->nlp_solver_plan->N; + ocp_nlp_config* nlp_config = capsule->nlp_config; + ocp_nlp_dims* nlp_dims = capsule->nlp_dims; + void *nlp_opts = capsule->nlp_opts; + /************************************************ * opts ************************************************/ - capsule->nlp_opts = ocp_nlp_solver_opts_create(nlp_config, nlp_dims); - {% if solver_options.hessian_approx == "EXACT" %} bool nlp_solver_exact_hessian = true; // TODO: this if should not be needed! however, calling the setter with false leads to weird behavior. Investigate! if (nlp_solver_exact_hessian) { - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "exact_hess", &nlp_solver_exact_hessian); + ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "exact_hess", &nlp_solver_exact_hessian); } int exact_hess_dyn = {{ solver_options.exact_hess_dyn }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "exact_hess_dyn", &exact_hess_dyn); + ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "exact_hess_dyn", &exact_hess_dyn); int exact_hess_cost = {{ solver_options.exact_hess_cost }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "exact_hess_cost", &exact_hess_cost); + ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "exact_hess_cost", &exact_hess_cost); int exact_hess_constr = {{ solver_options.exact_hess_constr }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "exact_hess_constr", &exact_hess_constr); + ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "exact_hess_constr", &exact_hess_constr); {%- endif -%} {%- if solver_options.globalization == "FIXED_STEP" %} - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "globalization", "fixed_step"); + ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "globalization", "fixed_step"); {%- elif solver_options.globalization == "MERIT_BACKTRACKING" %} - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "globalization", "merit_backtracking"); + ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "globalization", "merit_backtracking"); double alpha_min = {{ solver_options.alpha_min }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "alpha_min", &alpha_min); + ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "alpha_min", &alpha_min); double alpha_reduction = {{ solver_options.alpha_reduction }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "alpha_reduction", &alpha_reduction); + ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "alpha_reduction", &alpha_reduction); + + int line_search_use_sufficient_descent = {{ solver_options.line_search_use_sufficient_descent }}; + ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "line_search_use_sufficient_descent", &line_search_use_sufficient_descent); + + int globalization_use_SOC = {{ solver_options.globalization_use_SOC }}; + ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "globalization_use_SOC", &globalization_use_SOC); + + double eps_sufficient_descent = {{ solver_options.eps_sufficient_descent }}; + ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "eps_sufficient_descent", &eps_sufficient_descent); {%- endif -%} + int full_step_dual = {{ solver_options.full_step_dual }}; + ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "full_step_dual", &full_step_dual); {%- if dims.nz > 0 %} // TODO: these options are lower level -> should be encapsulated! maybe through hessian approx option. @@ -1909,9 +1740,9 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c bool sens_algebraic_val = true; for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, capsule->nlp_opts, i, "dynamics_output_z", &output_z_val); + ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_output_z", &output_z_val); for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, capsule->nlp_opts, i, "dynamics_sens_algebraic", &sens_algebraic_val); + ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_sens_algebraic", &sens_algebraic_val); {%- endif %} {%- if solver_options.integrator_type != "DISCRETE" %} @@ -1919,7 +1750,7 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c // set collocation type (relevant for implicit integrators) sim_collocation_type collocation_type = {{ solver_options.collocation_type }}; for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, capsule->nlp_opts, i, "dynamics_collocation_type", &collocation_type); + ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_collocation_type", &collocation_type); // set up sim_method_num_steps {%- set all_equal = true %} @@ -1935,7 +1766,7 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c // all sim_method_num_steps are identical int sim_method_num_steps = {{ solver_options.sim_method_num_steps[0] }}; for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, capsule->nlp_opts, i, "dynamics_num_steps", &sim_method_num_steps); + ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_num_steps", &sim_method_num_steps); {%- else %} // sim_method_num_steps are different int* sim_method_num_steps = malloc(N*sizeof(int)); @@ -1944,7 +1775,7 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c {%- endfor %} for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, capsule->nlp_opts, i, "dynamics_num_steps", &sim_method_num_steps[i]); + ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_num_steps", &sim_method_num_steps[i]); free(sim_method_num_steps); {%- endif %} @@ -1962,7 +1793,7 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c // all sim_method_num_stages are identical int sim_method_num_stages = {{ solver_options.sim_method_num_stages[0] }}; for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, capsule->nlp_opts, i, "dynamics_num_stages", &sim_method_num_stages); + ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_num_stages", &sim_method_num_stages); {%- else %} int* sim_method_num_stages = malloc(N*sizeof(int)); {%- for j in range(end=dims.N) %} @@ -1970,13 +1801,13 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c {%- endfor %} for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, capsule->nlp_opts, i, "dynamics_num_stages", &sim_method_num_stages[i]); + ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_num_stages", &sim_method_num_stages[i]); free(sim_method_num_stages); {%- endif %} int newton_iter_val = {{ solver_options.sim_method_newton_iter }}; for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, capsule->nlp_opts, i, "dynamics_newton_iter", &newton_iter_val); + ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_newton_iter", &newton_iter_val); // set up sim_method_jac_reuse @@ -1991,7 +1822,7 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c {%- if all_equal == true %} bool tmp_bool = (bool) {{ solver_options.sim_method_jac_reuse[0] }}; for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, capsule->nlp_opts, i, "dynamics_jac_reuse", &tmp_bool); + ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_jac_reuse", &tmp_bool); {%- else %} bool* sim_method_jac_reuse = malloc(N*sizeof(bool)); {%- for j in range(end=dims.N) %} @@ -1999,104 +1830,119 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c {%- endfor %} for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, capsule->nlp_opts, i, "dynamics_jac_reuse", &sim_method_jac_reuse[i]); + ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_jac_reuse", &sim_method_jac_reuse[i]); free(sim_method_jac_reuse); {%- endif %} {%- endif %} double nlp_solver_step_length = {{ solver_options.nlp_solver_step_length }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "step_length", &nlp_solver_step_length); + ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "step_length", &nlp_solver_step_length); {%- if solver_options.nlp_solver_warm_start_first_qp %} int nlp_solver_warm_start_first_qp = {{ solver_options.nlp_solver_warm_start_first_qp }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "warm_start_first_qp", &nlp_solver_warm_start_first_qp); + ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "warm_start_first_qp", &nlp_solver_warm_start_first_qp); {%- endif %} double levenberg_marquardt = {{ solver_options.levenberg_marquardt }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "levenberg_marquardt", &levenberg_marquardt); + ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "levenberg_marquardt", &levenberg_marquardt); /* options QP solver */ {%- if solver_options.qp_solver is starting_with("PARTIAL_CONDENSING") %} int qp_solver_cond_N; - {%- if solver_options.qp_solver_cond_N %} - qp_solver_cond_N = {{ solver_options.qp_solver_cond_N }}; - {% else %} + {% if solver_options.qp_solver_cond_N -%} + const int qp_solver_cond_N_ori = {{ solver_options.qp_solver_cond_N }}; + qp_solver_cond_N = N < qp_solver_cond_N_ori ? N : qp_solver_cond_N_ori; // use the minimum value here + {%- else %} // NOTE: there is no condensing happening here! qp_solver_cond_N = N; {%- endif %} - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "qp_cond_N", &qp_solver_cond_N); -{% endif %} + ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_cond_N", &qp_solver_cond_N); +{%- endif %} + + +{%- if solver_options.qp_solver is containing("HPIPM") %} + // set HPIPM mode: should be done before setting other QP solver options + ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_hpipm_mode", "{{ solver_options.hpipm_mode }}"); +{%- endif %} + +{% if solver_options.nlp_solver_type == "SQP" %} + // set SQP specific options + double nlp_solver_tol_stat = {{ solver_options.nlp_solver_tol_stat }}; + ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "tol_stat", &nlp_solver_tol_stat); + + double nlp_solver_tol_eq = {{ solver_options.nlp_solver_tol_eq }}; + ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "tol_eq", &nlp_solver_tol_eq); + + double nlp_solver_tol_ineq = {{ solver_options.nlp_solver_tol_ineq }}; + ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "tol_ineq", &nlp_solver_tol_ineq); + + double nlp_solver_tol_comp = {{ solver_options.nlp_solver_tol_comp }}; + ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "tol_comp", &nlp_solver_tol_comp); + + int nlp_solver_max_iter = {{ solver_options.nlp_solver_max_iter }}; + ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "max_iter", &nlp_solver_max_iter); + + int initialize_t_slacks = {{ solver_options.initialize_t_slacks }}; + ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "initialize_t_slacks", &initialize_t_slacks); +{%- endif %} int qp_solver_iter_max = {{ solver_options.qp_solver_iter_max }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "qp_iter_max", &qp_solver_iter_max); + ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_iter_max", &qp_solver_iter_max); +{# NOTE: qp_solver tolerances must be set after NLP ones, since the setter for NLP tolerances sets the QP tolerances to the sam values. #} {%- if solver_options.qp_solver_tol_stat %} double qp_solver_tol_stat = {{ solver_options.qp_solver_tol_stat }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "qp_tol_stat", &qp_solver_tol_stat); + ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_tol_stat", &qp_solver_tol_stat); {%- endif -%} {%- if solver_options.qp_solver_tol_eq %} double qp_solver_tol_eq = {{ solver_options.qp_solver_tol_eq }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "qp_tol_eq", &qp_solver_tol_eq); + ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_tol_eq", &qp_solver_tol_eq); {%- endif -%} {%- if solver_options.qp_solver_tol_ineq %} double qp_solver_tol_ineq = {{ solver_options.qp_solver_tol_ineq }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "qp_tol_ineq", &qp_solver_tol_ineq); + ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_tol_ineq", &qp_solver_tol_ineq); {%- endif -%} {%- if solver_options.qp_solver_tol_comp %} double qp_solver_tol_comp = {{ solver_options.qp_solver_tol_comp }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "qp_tol_comp", &qp_solver_tol_comp); + ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_tol_comp", &qp_solver_tol_comp); {%- endif -%} {%- if solver_options.qp_solver_warm_start %} int qp_solver_warm_start = {{ solver_options.qp_solver_warm_start }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "qp_warm_start", &qp_solver_warm_start); + ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_warm_start", &qp_solver_warm_start); {%- endif -%} - -{% if solver_options.nlp_solver_type == "SQP" %} - // set SQP specific options - double nlp_solver_tol_stat = {{ solver_options.nlp_solver_tol_stat }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "tol_stat", &nlp_solver_tol_stat); - - double nlp_solver_tol_eq = {{ solver_options.nlp_solver_tol_eq }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "tol_eq", &nlp_solver_tol_eq); - - double nlp_solver_tol_ineq = {{ solver_options.nlp_solver_tol_ineq }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "tol_ineq", &nlp_solver_tol_ineq); - - double nlp_solver_tol_comp = {{ solver_options.nlp_solver_tol_comp }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "tol_comp", &nlp_solver_tol_comp); - - int nlp_solver_max_iter = {{ solver_options.nlp_solver_max_iter }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "max_iter", &nlp_solver_max_iter); - - int initialize_t_slacks = {{ solver_options.initialize_t_slacks }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "initialize_t_slacks", &initialize_t_slacks); -{%- endif %} int print_level = {{ solver_options.print_level }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "print_level", &print_level); + ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "print_level", &print_level); int ext_cost_num_hess = {{ solver_options.ext_cost_num_hess }}; {%- if cost.cost_type == "EXTERNAL" %} for (int i = 0; i < N; i++) { - ocp_nlp_solver_opts_set_at_stage(nlp_config, capsule->nlp_opts, i, "cost_numerical_hessian", &ext_cost_num_hess); + ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "cost_numerical_hessian", &ext_cost_num_hess); } {%- endif %} {%- if cost.cost_type_e == "EXTERNAL" %} - ocp_nlp_solver_opts_set_at_stage(nlp_config, capsule->nlp_opts, N, "cost_numerical_hessian", &ext_cost_num_hess); + ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, N, "cost_numerical_hessian", &ext_cost_num_hess); {%- endif %} +} - /* out */ - ocp_nlp_out * nlp_out = ocp_nlp_out_create(nlp_config, nlp_dims); - capsule->nlp_out = nlp_out; +/** + * Internal function for {{ model.name }}_acados_create: step 7 + */ +void {{ model.name }}_acados_create_7_set_nlp_out({{ model.name }}_solver_capsule* capsule) +{ + const int N = capsule->nlp_solver_plan->N; + ocp_nlp_config* nlp_config = capsule->nlp_config; + ocp_nlp_dims* nlp_dims = capsule->nlp_dims; + ocp_nlp_out* nlp_out = capsule->nlp_out; // initialize primal solution double* xu0 = calloc(NX+NU, sizeof(double)); @@ -2123,39 +1969,171 @@ int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_c } ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, N, "x", x0); free(xu0); - - capsule->nlp_solver = ocp_nlp_solver_create(nlp_config, nlp_dims, capsule->nlp_opts); +} -{% if dims.np > 0 %} - // initialize parameters to nominal value - double* p = calloc(NP, sizeof(double)); - {% for item in parameter_values %} - {%- if item != 0 %} - p[{{ loop.index0 }}] = {{ item }}; - {%- endif %} - {%- endfor %} +/** + * Internal function for {{ model.name }}_acados_create: step 8 + */ +//void {{ model.name }}_acados_create_8_create_solver({{ model.name }}_solver_capsule* capsule) +//{ +// capsule->nlp_solver = ocp_nlp_solver_create(capsule->nlp_config, capsule->nlp_dims, capsule->nlp_opts); +//} - for (int i = 0; i <= N; i++) - { - {{ model.name }}_acados_update_params(capsule, i, p, NP); +/** + * Internal function for {{ model.name }}_acados_create: step 9 + */ +int {{ model.name }}_acados_create_9_precompute({{ model.name }}_solver_capsule* capsule) { + int status = ocp_nlp_precompute(capsule->nlp_solver, capsule->nlp_in, capsule->nlp_out); + + if (status != ACADOS_SUCCESS) { + printf("\nocp_nlp_precompute failed!\n\n"); + exit(1); } - free(p); -{%- endif %}{# if dims.np #} - status = ocp_nlp_precompute(capsule->nlp_solver, nlp_in, nlp_out); + return status; +} - if (status != ACADOS_SUCCESS) - { - printf("\nocp_precompute failed!\n\n"); - exit(1); + +int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_capsule* capsule, int N, double* new_time_steps) +{ + // If N does not match the number of shooting intervals used for code generation, new_time_steps must be given. + if (N != {{ model.name | upper }}_N && !new_time_steps) { + fprintf(stderr, "{{ model.name }}_acados_create_with_discretization: new_time_steps is NULL " \ + "but the number of shooting intervals (= %d) differs from the number of " \ + "shooting intervals (= %d) during code generation! Please provide a new vector of time_stamps!\n", \ + N, {{ model.name | upper }}_N); + return 1; } + // number of expected runtime parameters + capsule->nlp_np = NP; + + // 1) create and set nlp_solver_plan; create nlp_config + capsule->nlp_solver_plan = ocp_nlp_plan_create(N); + {{ model.name }}_acados_create_1_set_plan(capsule->nlp_solver_plan, N); + capsule->nlp_config = ocp_nlp_config_create(*capsule->nlp_solver_plan); + + // 3) create and set dimensions + capsule->nlp_dims = {{ model.name }}_acados_create_2_create_and_set_dimensions(capsule); + {{ model.name }}_acados_create_3_create_and_set_functions(capsule); + + // 4) set default parameters in functions + {{ model.name }}_acados_create_4_set_default_parameters(capsule); + + // 5) create and set nlp_in + capsule->nlp_in = ocp_nlp_in_create(capsule->nlp_config, capsule->nlp_dims); + {{ model.name }}_acados_create_5_set_nlp_in(capsule, N, new_time_steps); + + // 6) create and set nlp_opts + capsule->nlp_opts = ocp_nlp_solver_opts_create(capsule->nlp_config, capsule->nlp_dims); + {{ model.name }}_acados_create_6_set_opts(capsule); + + // 7) create and set nlp_out + // 7.1) nlp_out + capsule->nlp_out = ocp_nlp_out_create(capsule->nlp_config, capsule->nlp_dims); + // 7.2) sens_out + capsule->sens_out = ocp_nlp_out_create(capsule->nlp_config, capsule->nlp_dims); + {{ model.name }}_acados_create_7_set_nlp_out(capsule); + + // 8) create solver + capsule->nlp_solver = ocp_nlp_solver_create(capsule->nlp_config, capsule->nlp_dims, capsule->nlp_opts); + //{{ model.name }}_acados_create_8_create_solver(capsule); + + // 9) do precomputations + int status = {{ model.name }}_acados_create_9_precompute(capsule); + return status; +} + +/** + * This function is for updating an already initialized solver with a different number of qp_cond_N. It is useful for code reuse after code export. + */ +int {{ model.name }}_acados_update_qp_solver_cond_N({{ model.name }}_solver_capsule* capsule, int qp_solver_cond_N) +{ +{%- if solver_options.qp_solver is starting_with("PARTIAL_CONDENSING") %} + // 1) destroy solver + ocp_nlp_solver_destroy(capsule->nlp_solver); + + // 2) set new value for "qp_cond_N" + const int N = capsule->nlp_solver_plan->N; + if(qp_solver_cond_N > N) + printf("Warning: qp_solver_cond_N = %d > N = %d\n", qp_solver_cond_N, N); + ocp_nlp_solver_opts_set(capsule->nlp_config, capsule->nlp_opts, "qp_cond_N", &qp_solver_cond_N); + + // 3) continue with the remaining steps from {{ model.name }}_acados_create_with_discretization(...): + // -> 8) create solver + capsule->nlp_solver = ocp_nlp_solver_create(capsule->nlp_config, capsule->nlp_dims, capsule->nlp_opts); + + // -> 9) do precomputations + int status = {{ model.name }}_acados_create_9_precompute(capsule); return status; +{%- else %} + printf("\nacados_update_qp_solver_cond_N() failed, since no partial condensing solver is used!\n\n"); + // Todo: what is an adequate behavior here? + exit(1); + return -1; +{%- endif %} } -int {{ model.name }}_acados_update_params({{ model.name }}_solver_capsule * capsule, int stage, double *p, int np) +int {{ model.name }}_acados_reset({{ model.name }}_solver_capsule* capsule) +{ + + // set initialization to all zeros +{# TODO: use guess values / initial state value from json instead?! #} + const int N = capsule->nlp_solver_plan->N; + ocp_nlp_config* nlp_config = capsule->nlp_config; + ocp_nlp_dims* nlp_dims = capsule->nlp_dims; + ocp_nlp_out* nlp_out = capsule->nlp_out; + ocp_nlp_in* nlp_in = capsule->nlp_in; + ocp_nlp_solver* nlp_solver = capsule->nlp_solver; + + int nx, nu, nv, ns, nz, ni, dim; + + double* buffer = calloc(NX+NU+NZ+2*NS+2*NSN+NBX+NBU+NG+NH+NPHI+NBX0+NBXN+NHN+NPHIN+NGN, sizeof(double)); + + for(int i=0; i reset memory + int qp_status; + ocp_nlp_get(capsule->nlp_config, capsule->nlp_solver, "qp_status", &qp_status); + if (qp_status == 3) + { + // printf("\nin reset qp_status %d -> resetting QP memory\n", qp_status); + ocp_nlp_solver_reset_qp_memory(nlp_solver, nlp_in, nlp_out); + } +{%- endif %} + + free(buffer); + return 0; +} + + + + +int {{ model.name }}_acados_update_params({{ model.name }}_solver_capsule* capsule, int stage, double *p, int np) { int solver_status = 0; @@ -2180,7 +2158,7 @@ int {{ model.name }}_acados_update_params({{ model.name }}_solver_capsule * caps {%- endif %} {% elif solver_options.integrator_type == "LIFTED_IRK" %} capsule->impl_dae_fun[stage].set_param(capsule->impl_dae_fun+stage, p); - capsule->impl_dae_fun_jac_x_xdot_z[stage].set_param(capsule->impl_dae_fun_jac_x_xdot_z+stage, p); + capsule->impl_dae_fun_jac_x_xdot_u[stage].set_param(capsule->impl_dae_fun_jac_x_xdot_u+stage, p); {% elif solver_options.integrator_type == "ERK" %} capsule->forw_vde_casadi[stage].set_param(capsule->forw_vde_casadi+stage, p); capsule->expl_ode_fun[stage].set_param(capsule->expl_ode_fun+stage, p); @@ -2189,11 +2167,14 @@ int {{ model.name }}_acados_update_params({{ model.name }}_solver_capsule * caps capsule->hess_vde_casadi[stage].set_param(capsule->hess_vde_casadi+stage, p); {%- endif %} {% elif solver_options.integrator_type == "GNSF" %} + {% if model.gnsf.purely_linear != 1 %} capsule->gnsf_phi_fun[stage].set_param(capsule->gnsf_phi_fun+stage, p); capsule->gnsf_phi_fun_jac_y[stage].set_param(capsule->gnsf_phi_fun_jac_y+stage, p); capsule->gnsf_phi_jac_y_uhat[stage].set_param(capsule->gnsf_phi_jac_y_uhat+stage, p); - - capsule->gnsf_f_lo_jac_x1_x1dot_u_z[stage].set_param(capsule->gnsf_f_lo_jac_x1_x1dot_u_z+stage, p); + {% if model.gnsf.nontrivial_f_LO == 1 %} + capsule->gnsf_f_lo_jac_x1_x1dot_u_z[stage].set_param(capsule->gnsf_f_lo_jac_x1_x1dot_u_z+stage, p); + {%- endif %} + {%- endif %} {% elif solver_options.integrator_type == "DISCRETE" %} capsule->discr_dyn_phi_fun[stage].set_param(capsule->discr_dyn_phi_fun+stage, p); capsule->discr_dyn_phi_fun_jac_ut_xt[stage].set_param(capsule->discr_dyn_phi_fun_jac_ut_xt+stage, p); @@ -2271,7 +2252,7 @@ int {{ model.name }}_acados_update_params({{ model.name }}_solver_capsule * caps -int {{ model.name }}_acados_solve({{ model.name }}_solver_capsule * capsule) +int {{ model.name }}_acados_solve({{ model.name }}_solver_capsule* capsule) { // solve NLP int solver_status = ocp_nlp_solve(capsule->nlp_solver, capsule->nlp_in, capsule->nlp_out); @@ -2280,7 +2261,7 @@ int {{ model.name }}_acados_solve({{ model.name }}_solver_capsule * capsule) } -int {{ model.name }}_acados_free({{ model.name }}_solver_capsule * capsule) +int {{ model.name }}_acados_free({{ model.name }}_solver_capsule* capsule) { // before destroying, keep some info const int N = capsule->nlp_solver_plan->N; @@ -2288,6 +2269,7 @@ int {{ model.name }}_acados_free({{ model.name }}_solver_capsule * capsule) ocp_nlp_solver_opts_destroy(capsule->nlp_opts); ocp_nlp_in_destroy(capsule->nlp_in); ocp_nlp_out_destroy(capsule->nlp_out); + ocp_nlp_out_destroy(capsule->sens_out); ocp_nlp_solver_destroy(capsule->nlp_solver); ocp_nlp_dims_destroy(capsule->nlp_dims); ocp_nlp_config_destroy(capsule->nlp_config); @@ -2339,16 +2321,24 @@ int {{ model.name }}_acados_free({{ model.name }}_solver_capsule * capsule) {%- elif solver_options.integrator_type == "GNSF" %} for (int i = 0; i < N; i++) { + {% if model.gnsf.purely_linear != 1 %} external_function_param_casadi_free(&capsule->gnsf_phi_fun[i]); external_function_param_casadi_free(&capsule->gnsf_phi_fun_jac_y[i]); external_function_param_casadi_free(&capsule->gnsf_phi_jac_y_uhat[i]); + {% if model.gnsf.nontrivial_f_LO == 1 %} external_function_param_casadi_free(&capsule->gnsf_f_lo_jac_x1_x1dot_u_z[i]); + {%- endif %} + {%- endif %} external_function_param_casadi_free(&capsule->gnsf_get_matrices_fun[i]); } + {% if model.gnsf.purely_linear != 1 %} free(capsule->gnsf_phi_fun); free(capsule->gnsf_phi_fun_jac_y); free(capsule->gnsf_phi_jac_y_uhat); + {% if model.gnsf.nontrivial_f_LO == 1 %} free(capsule->gnsf_f_lo_jac_x1_x1dot_u_z); + {%- endif %} + {%- endif %} free(capsule->gnsf_get_matrices_fun); {%- elif solver_options.integrator_type == "DISCRETE" %} for (int i = 0; i < N; i++) @@ -2448,34 +2438,36 @@ int {{ model.name }}_acados_free({{ model.name }}_solver_capsule * capsule) return 0; } -ocp_nlp_in *{{ model.name }}_acados_get_nlp_in({{ model.name }}_solver_capsule * capsule) { return capsule->nlp_in; } -ocp_nlp_out *{{ model.name }}_acados_get_nlp_out({{ model.name }}_solver_capsule * capsule) { return capsule->nlp_out; } -ocp_nlp_solver *{{ model.name }}_acados_get_nlp_solver({{ model.name }}_solver_capsule * capsule) { return capsule->nlp_solver; } -ocp_nlp_config *{{ model.name }}_acados_get_nlp_config({{ model.name }}_solver_capsule * capsule) { return capsule->nlp_config; } -void *{{ model.name }}_acados_get_nlp_opts({{ model.name }}_solver_capsule * capsule) { return capsule->nlp_opts; } -ocp_nlp_dims *{{ model.name }}_acados_get_nlp_dims({{ model.name }}_solver_capsule * capsule) { return capsule->nlp_dims; } -ocp_nlp_plan *{{ model.name }}_acados_get_nlp_plan({{ model.name }}_solver_capsule * capsule) { return capsule->nlp_solver_plan; } +ocp_nlp_in *{{ model.name }}_acados_get_nlp_in({{ model.name }}_solver_capsule* capsule) { return capsule->nlp_in; } +ocp_nlp_out *{{ model.name }}_acados_get_nlp_out({{ model.name }}_solver_capsule* capsule) { return capsule->nlp_out; } +ocp_nlp_out *{{ model.name }}_acados_get_sens_out({{ model.name }}_solver_capsule* capsule) { return capsule->sens_out; } +ocp_nlp_solver *{{ model.name }}_acados_get_nlp_solver({{ model.name }}_solver_capsule* capsule) { return capsule->nlp_solver; } +ocp_nlp_config *{{ model.name }}_acados_get_nlp_config({{ model.name }}_solver_capsule* capsule) { return capsule->nlp_config; } +void *{{ model.name }}_acados_get_nlp_opts({{ model.name }}_solver_capsule* capsule) { return capsule->nlp_opts; } +ocp_nlp_dims *{{ model.name }}_acados_get_nlp_dims({{ model.name }}_solver_capsule* capsule) { return capsule->nlp_dims; } +ocp_nlp_plan_t *{{ model.name }}_acados_get_nlp_plan({{ model.name }}_solver_capsule* capsule) { return capsule->nlp_solver_plan; } -void {{ model.name }}_acados_print_stats({{ model.name }}_solver_capsule * capsule) +void {{ model.name }}_acados_print_stats({{ model.name }}_solver_capsule* capsule) { int sqp_iter, stat_m, stat_n, tmp_int; ocp_nlp_get(capsule->nlp_config, capsule->nlp_solver, "sqp_iter", &sqp_iter); ocp_nlp_get(capsule->nlp_config, capsule->nlp_solver, "stat_n", &stat_n); ocp_nlp_get(capsule->nlp_config, capsule->nlp_solver, "stat_m", &stat_m); - {% set stat_n_max = 10 %} + {% set stat_n_max = 12 %} double stat[{{ solver_options.nlp_solver_max_iter * stat_n_max }}]; ocp_nlp_get(capsule->nlp_config, capsule->nlp_solver, "statistics", stat); int nrow = sqp_iter+1 < stat_m ? sqp_iter+1 : stat_m; - printf("iter\tres_stat\tres_eq\t\tres_ineq\tres_comp\tqp_stat\tqp_iter\n"); +{%- if solver_options.nlp_solver_type == "SQP" %} + printf("iter\tres_stat\tres_eq\t\tres_ineq\tres_comp\tqp_stat\tqp_iter\talpha\n"); for (int i = 0; i < nrow; i++) { for (int j = 0; j < stat_n + 1; j++) { - if (j == 0 || j > 4) + if (j == 0 || j == 5 || j == 6) { tmp_int = (int) stat[i + j * nrow]; printf("%d\t", tmp_int); @@ -2487,5 +2479,17 @@ void {{ model.name }}_acados_print_stats({{ model.name }}_solver_capsule * capsu } printf("\n"); } +{% else %} + printf("iter\tqp_stat\tqp_iter\n"); + for (int i = 0; i < nrow; i++) + { + for (int j = 0; j < stat_n + 1; j++) + { + tmp_int = (int) stat[i + j * nrow]; + printf("%d\t", tmp_int); + } + printf("\n"); + } +{%- endif %} } diff --git a/pyextra/acados_template/c_templates_tera/acados_solver.in.h b/pyextra/acados_template/c_templates_tera/acados_solver.in.h index e8c0a38ca3..1c82ef3ba0 100644 --- a/pyextra/acados_template/c_templates_tera/acados_solver.in.h +++ b/pyextra/acados_template/c_templates_tera/acados_solver.in.h @@ -34,6 +34,8 @@ #ifndef ACADOS_SOLVER_{{ model.name }}_H_ #define ACADOS_SOLVER_{{ model.name }}_H_ +#include "acados/utils/types.h" + #include "acados_c/ocp_nlp_interface.h" #include "acados_c/external_function_interface.h" @@ -78,9 +80,10 @@ typedef struct {{ model.name }}_solver_capsule // acados objects ocp_nlp_in *nlp_in; ocp_nlp_out *nlp_out; + ocp_nlp_out *sens_out; ocp_nlp_solver *nlp_solver; void *nlp_opts; - ocp_nlp_plan *nlp_solver_plan; + ocp_nlp_plan_t *nlp_solver_plan; ocp_nlp_config *nlp_config; ocp_nlp_dims *nlp_dims; @@ -171,33 +174,41 @@ typedef struct {{ model.name }}_solver_capsule } {{ model.name }}_solver_capsule; -{{ model.name }}_solver_capsule * {{ model.name }}_acados_create_capsule(void); -int {{ model.name }}_acados_free_capsule({{ model.name }}_solver_capsule *capsule); +ACADOS_SYMBOL_EXPORT {{ model.name }}_solver_capsule * {{ model.name }}_acados_create_capsule(void); +ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_free_capsule({{ model.name }}_solver_capsule *capsule); + +ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_create({{ model.name }}_solver_capsule * capsule); + +ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_reset({{ model.name }}_solver_capsule* capsule); -int {{ model.name }}_acados_create({{ model.name }}_solver_capsule * capsule); /** * Generic version of {{ model.name }}_acados_create which allows to use a different number of shooting intervals than * the number used for code generation. If new_time_steps=NULL and n_time_steps matches the number used for code * generation, the time-steps from code generation is used. */ -int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_capsule * capsule, int n_time_steps, double* new_time_steps); +ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_capsule * capsule, int n_time_steps, double* new_time_steps); /** * Update the time step vector. Number N must be identical to the currently set number of shooting nodes in the * nlp_solver_plan. Returns 0 if no error occurred and a otherwise a value other than 0. */ -int {{ model.name }}_acados_update_time_steps({{ model.name }}_solver_capsule * capsule, int N, double* new_time_steps); -int {{ model.name }}_acados_update_params({{ model.name }}_solver_capsule * capsule, int stage, double *value, int np); -int {{ model.name }}_acados_solve({{ model.name }}_solver_capsule * capsule); -int {{ model.name }}_acados_free({{ model.name }}_solver_capsule * capsule); -void {{ model.name }}_acados_print_stats({{ model.name }}_solver_capsule * capsule); - -ocp_nlp_in *{{ model.name }}_acados_get_nlp_in({{ model.name }}_solver_capsule * capsule); -ocp_nlp_out *{{ model.name }}_acados_get_nlp_out({{ model.name }}_solver_capsule * capsule); -ocp_nlp_solver *{{ model.name }}_acados_get_nlp_solver({{ model.name }}_solver_capsule * capsule); -ocp_nlp_config *{{ model.name }}_acados_get_nlp_config({{ model.name }}_solver_capsule * capsule); -void *{{ model.name }}_acados_get_nlp_opts({{ model.name }}_solver_capsule * capsule); -ocp_nlp_dims *{{ model.name }}_acados_get_nlp_dims({{ model.name }}_solver_capsule * capsule); -ocp_nlp_plan *{{ model.name }}_acados_get_nlp_plan({{ model.name }}_solver_capsule * capsule); +ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_update_time_steps({{ model.name }}_solver_capsule * capsule, int N, double* new_time_steps); +/** + * This function is used for updating an already initialized solver with a different number of qp_cond_N. + */ +ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_update_qp_solver_cond_N({{ model.name }}_solver_capsule * capsule, int qp_solver_cond_N); +ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_update_params({{ model.name }}_solver_capsule * capsule, int stage, double *value, int np); +ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_solve({{ model.name }}_solver_capsule * capsule); +ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_free({{ model.name }}_solver_capsule * capsule); +ACADOS_SYMBOL_EXPORT void {{ model.name }}_acados_print_stats({{ model.name }}_solver_capsule * capsule); + +ACADOS_SYMBOL_EXPORT ocp_nlp_in *{{ model.name }}_acados_get_nlp_in({{ model.name }}_solver_capsule * capsule); +ACADOS_SYMBOL_EXPORT ocp_nlp_out *{{ model.name }}_acados_get_nlp_out({{ model.name }}_solver_capsule * capsule); +ACADOS_SYMBOL_EXPORT ocp_nlp_out *{{ model.name }}_acados_get_sens_out({{ model.name }}_solver_capsule * capsule); +ACADOS_SYMBOL_EXPORT ocp_nlp_solver *{{ model.name }}_acados_get_nlp_solver({{ model.name }}_solver_capsule * capsule); +ACADOS_SYMBOL_EXPORT ocp_nlp_config *{{ model.name }}_acados_get_nlp_config({{ model.name }}_solver_capsule * capsule); +ACADOS_SYMBOL_EXPORT void *{{ model.name }}_acados_get_nlp_opts({{ model.name }}_solver_capsule * capsule); +ACADOS_SYMBOL_EXPORT ocp_nlp_dims *{{ model.name }}_acados_get_nlp_dims({{ model.name }}_solver_capsule * capsule); +ACADOS_SYMBOL_EXPORT ocp_nlp_plan_t *{{ model.name }}_acados_get_nlp_plan({{ model.name }}_solver_capsule * capsule); #ifdef __cplusplus } /* extern "C" */ diff --git a/pyextra/acados_template/c_templates_tera/acados_solver.in.pxd b/pyextra/acados_template/c_templates_tera/acados_solver.in.pxd index 8387980c24..09f8755cbe 100644 --- a/pyextra/acados_template/c_templates_tera/acados_solver.in.pxd +++ b/pyextra/acados_template/c_templates_tera/acados_solver.in.pxd @@ -1,3 +1,36 @@ +# +# Copyright 2019 Gianluca Frison, Dimitris Kouzoupis, Robin Verschueren, +# Andrea Zanelli, Niels van Duijkeren, Jonathan Frey, Tommaso Sartor, +# Branimir Novoselnik, Rien Quirynen, Rezart Qelibari, Dang Doan, +# Jonas Koenemann, Yutao Chen, Tobias Schöls, Jonas Schlagenhauf, Moritz Diehl +# +# This file is part of acados. +# +# The 2-Clause BSD License +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# +# 2. 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. +# +# 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 AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.; +# + cimport acados_solver_common cdef extern from "acados_solver_{{ model.name }}.h": @@ -8,13 +41,20 @@ cdef extern from "acados_solver_{{ model.name }}.h": int acados_free_capsule "{{ model.name }}_acados_free_capsule"(nlp_solver_capsule *capsule) int acados_create "{{ model.name }}_acados_create"(nlp_solver_capsule * capsule) + + int acados_create_with_discretization "{{ model.name }}_acados_create_with_discretization"(nlp_solver_capsule * capsule, int n_time_steps, double* new_time_steps) + int acados_update_time_steps "{{ model.name }}_acados_update_time_steps"(nlp_solver_capsule * capsule, int N, double* new_time_steps) + int acados_update_qp_solver_cond_N "{{ model.name }}_acados_update_qp_solver_cond_N"(nlp_solver_capsule * capsule, int qp_solver_cond_N) + int acados_update_params "{{ model.name }}_acados_update_params"(nlp_solver_capsule * capsule, int stage, double *value, int np_) int acados_solve "{{ model.name }}_acados_solve"(nlp_solver_capsule * capsule) + int acados_reset "{{ model.name }}_acados_reset"(nlp_solver_capsule * capsule) int acados_free "{{ model.name }}_acados_free"(nlp_solver_capsule * capsule) void acados_print_stats "{{ model.name }}_acados_print_stats"(nlp_solver_capsule * capsule) acados_solver_common.ocp_nlp_in *acados_get_nlp_in "{{ model.name }}_acados_get_nlp_in"(nlp_solver_capsule * capsule) acados_solver_common.ocp_nlp_out *acados_get_nlp_out "{{ model.name }}_acados_get_nlp_out"(nlp_solver_capsule * capsule) + acados_solver_common.ocp_nlp_out *acados_get_sens_out "{{ model.name }}_acados_get_sens_out"(nlp_solver_capsule * capsule) acados_solver_common.ocp_nlp_solver *acados_get_nlp_solver "{{ model.name }}_acados_get_nlp_solver"(nlp_solver_capsule * capsule) acados_solver_common.ocp_nlp_config *acados_get_nlp_config "{{ model.name }}_acados_get_nlp_config"(nlp_solver_capsule * capsule) void *acados_get_nlp_opts "{{ model.name }}_acados_get_nlp_opts"(nlp_solver_capsule * capsule) diff --git a/pyextra/acados_template/c_templates_tera/acados_solver_sfun.in.c b/pyextra/acados_template/c_templates_tera/acados_solver_sfun.in.c index a6cd1faa8c..96e0983de6 100644 --- a/pyextra/acados_template/c_templates_tera/acados_solver_sfun.in.c +++ b/pyextra/acados_template/c_templates_tera/acados_solver_sfun.in.c @@ -37,7 +37,7 @@ #define MDL_START // acados -#include "acados/utils/print.h" +// #include "acados/utils/print.h" #include "acados_c/sim_interface.h" #include "acados_c/external_function_interface.h" @@ -126,10 +126,14 @@ static void mdlInitializeSizes (SimStruct *S) {%- if dims.ny_0 > 0 and simulink_opts.inputs.cost_W_0 %} {#- cost_W_0 #} {%- set n_inputs = n_inputs + 1 %} {%- endif -%} - {%- if dims.ny > 0 and simulink_opts.inputs.cost_W -%} {#- cost_W #} + {%- if dims.ny > 0 and simulink_opts.inputs.cost_W %} {#- cost_W #} {%- set n_inputs = n_inputs + 1 %} {%- endif -%} - {%- if dims.ny_e > 0 and simulink_opts.inputs.cost_W_e -%} {#- cost_W_e #} + {%- if dims.ny_e > 0 and simulink_opts.inputs.cost_W_e %} {#- cost_W_e #} + {%- set n_inputs = n_inputs + 1 -%} + {%- endif -%} + + {%- if simulink_opts.inputs.reset_solver -%} {#- reset_solver #} {%- set n_inputs = n_inputs + 1 -%} {%- endif -%} @@ -256,7 +260,7 @@ static void mdlInitializeSizes (SimStruct *S) ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.ny_0 * dims.ny_0 }}); {%- endif %} - {%- if dims.ny_0 > 0 and simulink_opts.inputs.cost_W %} {#- cost_W #} + {%- if dims.ny > 0 and simulink_opts.inputs.cost_W %} {#- cost_W #} {%- set i_input = i_input + 1 %} // cost_W ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.ny * dims.ny }}); @@ -268,6 +272,12 @@ static void mdlInitializeSizes (SimStruct *S) ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.ny_e * dims.ny_e }}); {%- endif %} + {%- if simulink_opts.inputs.reset_solver -%} {#- reset_solver #} + {%- set i_input = i_input + 1 %} + // reset_solver + ssSetInputPortVectorDimension(S, {{ i_input }}, 1); + {%- endif -%} + {%- if simulink_opts.inputs.x_init -%} {#- x_init #} {%- set i_input = i_input + 1 %} // x_init @@ -406,13 +416,13 @@ static void mdlOutputs(SimStruct *S, int_T tid) {%- set buffer_sizes = buffer_sizes | concat(with=(dims.ny_e)) %} {%- endif %} - {%- if dims.ny_0 > 0 and simulink_opts.inputs.cost_W_0 %} {# cost_W_0 #} + {%- if dims.ny_0 > 0 and simulink_opts.inputs.cost_W_0 %} {#- cost_W_0 #} {%- set buffer_sizes = buffer_sizes | concat(with=(dims.ny_0 * dims.ny_0)) %} {%- endif %} - {%- if dims.ny > 0 and simulink_opts.inputs.cost_W %} {# cost_W #} + {%- if dims.ny > 0 and simulink_opts.inputs.cost_W %} {#- cost_W #} {%- set buffer_sizes = buffer_sizes | concat(with=(dims.ny * dims.ny)) %} {%- endif %} - {%- if dims.ny_e > 0 and simulink_opts.inputs.cost_W_e %} {# cost_W_e #} + {%- if dims.ny_e > 0 and simulink_opts.inputs.cost_W_e %} {#- cost_W_e #} {%- set buffer_sizes = buffer_sizes | concat(with=(dims.ny_e * dims.ny_e)) %} {%- endif %} @@ -602,7 +612,7 @@ static void mdlOutputs(SimStruct *S, int_T tid) ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii, "uh", buffer); {%- endif -%} - {%- if dims.ny_0 > 0 and simulink_opts.inputs.cost_W_0 %} {# cost_W_0 #} + {%- if dims.ny_0 > 0 and simulink_opts.inputs.cost_W_0 %} {#- cost_W_0 #} // cost_W_0 {%- set i_input = i_input + 1 %} in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); @@ -612,7 +622,7 @@ static void mdlOutputs(SimStruct *S, int_T tid) ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "W", buffer); {%- endif %} - {%- if dims.ny > 0 and simulink_opts.inputs.cost_W %} {# cost_W #} + {%- if dims.ny > 0 and simulink_opts.inputs.cost_W %} {#- cost_W #} // cost_W {%- set i_input = i_input + 1 %} in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); @@ -633,6 +643,17 @@ static void mdlOutputs(SimStruct *S, int_T tid) ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, {{ dims.N }}, "W", buffer); {%- endif %} + {%- if simulink_opts.inputs.reset_solver %} {#- reset_solver #} + // reset_solver + {%- set i_input = i_input + 1 %} + in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); + double reset = (double)(*in_sign[0]); + if (reset) + { + {{ model.name }}_acados_reset(capsule); + } + {%- endif %} + {%- if simulink_opts.inputs.x_init %} {#- x_init #} // x_init {%- set i_input = i_input + 1 %} diff --git a/pyextra/acados_template/c_templates_tera/main.in.c b/pyextra/acados_template/c_templates_tera/main.in.c index 3348eea5cb..99c4f13be1 100644 --- a/pyextra/acados_template/c_templates_tera/main.in.c +++ b/pyextra/acados_template/c_templates_tera/main.in.c @@ -156,11 +156,12 @@ int main() for (int ii = 0; ii < NTIMINGS; ii++) { // initialize solution - for (int i = 0; i <= nlp_dims->N; i++) + for (int i = 0; i < N; i++) { ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, i, "x", x_init); ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, i, "u", u0); } + ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, N, "x", x_init); ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "rti_phase", &rti_phase); status = {{ model.name }}_acados_solve(acados_ocp_capsule); ocp_nlp_get(nlp_config, nlp_solver, "time_tot", &elapsed_time); diff --git a/pyextra/acados_template/c_templates_tera/make_sfun.in.m b/pyextra/acados_template/c_templates_tera/make_sfun.in.m index 172da654ee..77603a78fa 100644 --- a/pyextra/acados_template/c_templates_tera/make_sfun.in.m +++ b/pyextra/acados_template/c_templates_tera/make_sfun.in.m @@ -46,10 +46,14 @@ SOURCES = { ... '{{ model.name }}_model/{{ model.name }}_impl_dae_hess.c',... {%- endif %} {%- elif solver_options.integrator_type == "GNSF" %} + {% if model.gnsf.purely_linear != 1 %} '{{ model.name }}_model/{{ model.name }}_gnsf_phi_fun.c',... '{{ model.name }}_model/{{ model.name }}_gnsf_phi_fun_jac_y.c',... '{{ model.name }}_model/{{ model.name }}_gnsf_phi_jac_y_uhat.c',... + {% if model.gnsf.nontrivial_f_LO == 1 %} '{{ model.name }}_model/{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz.c',... + {%- endif %} + {%- endif %} '{{ model.name }}_model/{{ model.name }}_gnsf_get_matrices_fun.c',... {%- elif solver_options.integrator_type == "DISCRETE" %} '{{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun.c',... @@ -260,6 +264,11 @@ input_note = strcat(input_note, num2str(i_in), ') cost_W_e in column-major forma i_in = i_in + 1; {%- endif %} +{%- if simulink_opts.inputs.reset_solver %} {#- reset_solver #} +input_note = strcat(input_note, num2str(i_in), ') reset_solver determines if iterate is set to all zeros before other initializations (x_init, u_init) are set and before solver is called, size [1]\n '); +i_in = i_in + 1; +{%- endif %} + {%- if simulink_opts.inputs.x_init %} {#- x_init #} input_note = strcat(input_note, num2str(i_in), ') initialization of x for all shooting nodes, size [{{ dims.nx * (dims.N+1) }}]\n '); i_in = i_in + 1; diff --git a/pyextra/acados_template/c_templates_tera/make_sfun_sim.in.m b/pyextra/acados_template/c_templates_tera/make_sfun_sim.in.m index 1c5cf0b123..a0c503e41a 100644 --- a/pyextra/acados_template/c_templates_tera/make_sfun_sim.in.m +++ b/pyextra/acados_template/c_templates_tera/make_sfun_sim.in.m @@ -47,10 +47,14 @@ SOURCES = [ 'acados_sim_solver_sfunction_{{ model.name }}.c ', ... '{{ model.name }}_model/{{ model.name }}_impl_dae_hess.c ',... {%- endif %} {%- elif solver_options.integrator_type == "GNSF" %} + {% if model.gnsf.purely_linear != 1 %} '{{ model.name }}_model/{{ model.name }}_gnsf_phi_fun.c ' '{{ model.name }}_model/{{ model.name }}_gnsf_phi_fun_jac_y.c ' '{{ model.name }}_model/{{ model.name }}_gnsf_phi_jac_y_uhat.c ' + {% if model.gnsf.nontrivial_f_LO == 1 %} '{{ model.name }}_model/{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz.c ' + {%- endif %} + {%- endif %} '{{ model.name }}_model/{{ model.name }}_gnsf_get_matrices_fun.c ' {%- endif %} ]; diff --git a/pyextra/acados_template/c_templates_tera/mex_solver.in.m b/pyextra/acados_template/c_templates_tera/mex_solver.in.m index 728741a46e..278e0a605c 100644 --- a/pyextra/acados_template/c_templates_tera/mex_solver.in.m +++ b/pyextra/acados_template/c_templates_tera/mex_solver.in.m @@ -125,15 +125,15 @@ classdef {{ model.name }}_mex_solver < handle if strcmp(field, 'stat') stat = obj.get('stat'); {%- if solver_options.nlp_solver_type == "SQP" %} - fprintf('\niter\tres_stat\tres_eq\t\tres_ineq\tres_comp\tqp_stat\tqp_iter'); - if size(stat,2)>7 + fprintf('\niter\tres_stat\tres_eq\t\tres_ineq\tres_comp\tqp_stat\tqp_iter\talpha'); + if size(stat,2)>8 fprintf('\tqp_res_stat\tqp_res_eq\tqp_res_ineq\tqp_res_comp'); end fprintf('\n'); for jj=1:size(stat,1) - fprintf('%d\t%e\t%e\t%e\t%e\t%d\t%d', stat(jj,1), stat(jj,2), stat(jj,3), stat(jj,4), stat(jj,5), stat(jj,6), stat(jj,7)); - if size(stat,2)>7 - fprintf('\t%e\t%e\t%e\t%e', stat(jj,8), stat(jj,9), stat(jj,10), stat(jj,11)); + fprintf('%d\t%e\t%e\t%e\t%e\t%d\t%d\t%e', stat(jj,1), stat(jj,2), stat(jj,3), stat(jj,4), stat(jj,5), stat(jj,6), stat(jj,7), stat(jj, 8)); + if size(stat,2)>8 + fprintf('\t%e\t%e\t%e\t%e', stat(jj,9), stat(jj,10), stat(jj,11), stat(jj,12)); end fprintf('\n'); end diff --git a/pyextra/acados_template/c_templates_tera/model.in.h b/pyextra/acados_template/c_templates_tera/model.in.h index 661811232c..918e2bc29e 100644 --- a/pyextra/acados_template/c_templates_tera/model.in.h +++ b/pyextra/acados_template/c_templates_tera/model.in.h @@ -90,14 +90,7 @@ int {{ model.name }}_impl_dae_hess_n_out(void); {% elif solver_options.integrator_type == "GNSF" %} /* GNSF Functions */ -// used to import model matrices -int {{ model.name }}_gnsf_get_matrices_fun(const double** arg, double** res, int* iw, double* w, void *mem); -int {{ model.name }}_gnsf_get_matrices_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_gnsf_get_matrices_fun_sparsity_in(int); -const int *{{ model.name }}_gnsf_get_matrices_fun_sparsity_out(int); -int {{ model.name }}_gnsf_get_matrices_fun_n_in(void); -int {{ model.name }}_gnsf_get_matrices_fun_n_out(void); - + {% if model.gnsf.purely_linear != 1 %} // phi_fun int {{ model.name }}_gnsf_phi_fun(const double** arg, double** res, int* iw, double* w, void *mem); int {{ model.name }}_gnsf_phi_fun_work(int *, int *, int *, int *); @@ -121,7 +114,7 @@ const int *{{ model.name }}_gnsf_phi_jac_y_uhat_sparsity_in(int); const int *{{ model.name }}_gnsf_phi_jac_y_uhat_sparsity_out(int); int {{ model.name }}_gnsf_phi_jac_y_uhat_n_in(void); int {{ model.name }}_gnsf_phi_jac_y_uhat_n_out(void); - + {% if model.gnsf.nontrivial_f_LO == 1 %} // f_lo_fun_jac_x1k1uz int {{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz(const double** arg, double** res, int* iw, double* w, void *mem); int {{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_work(int *, int *, int *, int *); @@ -129,6 +122,15 @@ const int *{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_sparsity_in(int); const int *{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_sparsity_out(int); int {{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_n_in(void); int {{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_n_out(void); + {%- endif %} + {%- endif %} +// used to import model matrices +int {{ model.name }}_gnsf_get_matrices_fun(const double** arg, double** res, int* iw, double* w, void *mem); +int {{ model.name }}_gnsf_get_matrices_fun_work(int *, int *, int *, int *); +const int *{{ model.name }}_gnsf_get_matrices_fun_sparsity_in(int); +const int *{{ model.name }}_gnsf_get_matrices_fun_sparsity_out(int); +int {{ model.name }}_gnsf_get_matrices_fun_n_in(void); +int {{ model.name }}_gnsf_get_matrices_fun_n_out(void); {% elif solver_options.integrator_type == "ERK" %} /* explicit ODE */ diff --git a/pyextra/acados_template/generate_c_code_discrete_dynamics.py b/pyextra/acados_template/generate_c_code_discrete_dynamics.py index 334e18dab7..c6a245ff81 100644 --- a/pyextra/acados_template/generate_c_code_discrete_dynamics.py +++ b/pyextra/acados_template/generate_c_code_discrete_dynamics.py @@ -32,12 +32,12 @@ # import os -from casadi import * +import casadi as ca from .utils import ALLOWED_CASADI_VERSIONS, casadi_length, casadi_version_warning def generate_c_code_discrete_dynamics( model, opts ): - casadi_version = CasadiMeta.version() + casadi_version = ca.CasadiMeta.version() casadi_opts = dict(mex=False, casadi_int='int', casadi_real='double') if casadi_version not in (ALLOWED_CASADI_VERSIONS): @@ -49,13 +49,12 @@ def generate_c_code_discrete_dynamics( model, opts ): p = model.p phi = model.disc_dyn_expr model_name = model.name - nx = x.size()[0] + nx = casadi_length(x) - - if isinstance(phi, casadi.MX): - symbol = MX.sym - elif isinstance(phi, casadi.SX): - symbol = SX.sym + if isinstance(phi, ca.MX): + symbol = ca.MX.sym + elif isinstance(phi, ca.SX): + symbol = ca.SX.sym else: Exception("generate_c_code_disc_dyn: disc_dyn_expr must be a CasADi expression, you have type: {}".format(type(phi))) @@ -63,12 +62,12 @@ def generate_c_code_discrete_dynamics( model, opts ): lam = symbol('lam', nx, 1) # generate jacobians - ux = vertcat(u,x) - jac_ux = jacobian(phi, ux) + ux = ca.vertcat(u,x) + jac_ux = ca.jacobian(phi, ux) # generate adjoint - adj_ux = jtimes(phi, ux, lam, True) + adj_ux = ca.jtimes(phi, ux, lam, True) # generate hessian - hess_ux = jacobian(adj_ux, ux) + hess_ux = ca.jacobian(adj_ux, ux) ## change directory code_export_dir = opts["code_export_directory"] @@ -85,15 +84,15 @@ def generate_c_code_discrete_dynamics( model, opts ): # set up & generate Functions fun_name = model_name + '_dyn_disc_phi_fun' - phi_fun = Function(fun_name, [x, u, p], [phi]) + phi_fun = ca.Function(fun_name, [x, u, p], [phi]) phi_fun.generate(fun_name, casadi_opts) fun_name = model_name + '_dyn_disc_phi_fun_jac' - phi_fun_jac_ut_xt = Function(fun_name, [x, u, p], [phi, jac_ux.T]) + phi_fun_jac_ut_xt = ca.Function(fun_name, [x, u, p], [phi, jac_ux.T]) phi_fun_jac_ut_xt.generate(fun_name, casadi_opts) fun_name = model_name + '_dyn_disc_phi_fun_jac_hess' - phi_fun_jac_ut_xt_hess = Function(fun_name, [x, u, lam, p], [phi, jac_ux.T, hess_ux]) + phi_fun_jac_ut_xt_hess = ca.Function(fun_name, [x, u, lam, p], [phi, jac_ux.T, hess_ux]) phi_fun_jac_ut_xt_hess.generate(fun_name, casadi_opts) os.chdir(cwd) diff --git a/pyextra/acados_template/simulink_default_opts.json b/pyextra/acados_template/simulink_default_opts.json index 258a224cb2..70c939cb88 100644 --- a/pyextra/acados_template/simulink_default_opts.json +++ b/pyextra/acados_template/simulink_default_opts.json @@ -32,6 +32,7 @@ "cost_W_0": 0, "cost_W": 0, "cost_W_e": 0, + "reset_solver": 0, "x_init": 0, "u_init": 0 }, diff --git a/pyextra/acados_template/utils.py b/pyextra/acados_template/utils.py index bf8ae4d5db..8f44f61e7e 100644 --- a/pyextra/acados_template/utils.py +++ b/pyextra/acados_template/utils.py @@ -1,3 +1,4 @@ +# -*- coding: future_fstrings -*- # # Copyright 2019 Gianluca Frison, Dimitris Kouzoupis, Robin Verschueren, # Andrea Zanelli, Niels van Duijkeren, Jonathan Frey, Tommaso Sartor, @@ -49,7 +50,7 @@ def get_acados_path(): ACADOS_PATH = os.path.realpath(acados_path) msg = 'Warning: Did not find environment variable ACADOS_SOURCE_DIR, ' msg += 'guessed ACADOS_PATH to be {}.\n'.format(ACADOS_PATH) - msg += 'Please export ACADOS_SOURCE_DIR to not avoid this warning.' + msg += 'Please export ACADOS_SOURCE_DIR to avoid this warning.' print(msg) return ACADOS_PATH @@ -74,7 +75,7 @@ def get_tera_exec_path(): platform2tera = { "linux": "linux", "darwin": "osx", - "win32": "window.exe" + "win32": "windows" } @@ -212,16 +213,14 @@ def render_template(in_file, out_file, template_dir, json_path): template_glob = os.path.join(acados_path, 'c_templates_tera', '*') # call tera as system cmd - os_cmd = "{tera_path} '{template_glob}' '{in_file}' '{json_path}' '{out_file}'".format( - tera_path=tera_path, - template_glob=template_glob, - json_path=json_path, - in_file=in_file, - out_file=out_file - ) + os_cmd = f"{tera_path} '{template_glob}' '{in_file}' '{json_path}' '{out_file}'" + # Windows cmd.exe can not cope with '...', so use "..." instead: + if os.name == 'nt': + os_cmd = os_cmd.replace('\'', '\"') + status = os.system(os_cmd) if (status != 0): - raise Exception('Rendering of {} failed!\n\nAttempted to execute OS command:\n{}\n\nExiting.\n'.format(in_file, os_cmd)) + raise Exception(f'Rendering of {in_file} failed!\n\nAttempted to execute OS command:\n{os_cmd}\n\nExiting.\n') os.chdir(cwd) @@ -235,9 +234,7 @@ def np_array_to_list(np_array): elif isinstance(np_array, (DM)): return np_array.full() else: - raise(Exception( - "Cannot convert to list type {}".format(type(np_array)) - )) + raise(Exception(f"Cannot convert to list type {type(np_array)}")) def format_class_dict(d): @@ -254,22 +251,6 @@ def format_class_dict(d): return out -def acados_class2dict(class_instance): - """ - removes the __ artifact from class to dict conversion - """ - - d = dict(class_instance.__dict__) - out = {} - for k, v in d.items(): - if isinstance(v, dict): - v = format_class_dict(v) - - out_key = k.split('__', 1)[-1] - out[k.replace(k, out_key)] = v - return out - - def get_ocp_nlp_layout(): python_interface_path = get_python_interface_path() abs_path = os.path.join(python_interface_path, 'acados_layout.json') @@ -433,6 +414,13 @@ def set_up_imported_gnsf_model(acados_formulation): acados_formulation.model.phi_jac_y_uhat = phi_jac_y_uhat acados_formulation.model.get_matrices_fun = get_matrices_fun + # get_matrices_fun = Function([model_name,'_gnsf_get_matrices_fun'], {dummy},... + # {A, B, C, E, L_x, L_xdot, L_z, L_u, A_LO, c, E_LO, B_LO,... + # nontrivial_f_LO, purely_linear, ipiv_x, ipiv_z, c_LO}); + get_matrices_out = get_matrices_fun(0) + acados_formulation.model.gnsf['nontrivial_f_LO'] = int(get_matrices_out[12]) + acados_formulation.model.gnsf['purely_linear'] = int(get_matrices_out[13]) + if "f_lo_fun_jac_x1k1uz" in gnsf: f_lo_fun_jac_x1k1uz = Function.deserialize(gnsf['f_lo_fun_jac_x1k1uz']) acados_formulation.model.f_lo_fun_jac_x1k1uz = f_lo_fun_jac_x1k1uz diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000000..d26fc7ff1d --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,180 @@ +[tool.poetry] +name = "openpilot" +version = "0.1.0" +description = "an open source driver assistance system" +authors = ["Vehicle Researcher "] +license = "MIT" +readme = "README.md" +repository = "https://github.com/commaai/openpilot" +documentation = "https://docs.comma.ai" + + +[tool.poetry.dependencies] +python = "~3.8" +atomicwrites = "^1.4.0" +casadi = { version = "==3.5.5", markers = "platform_system != 'Darwin'" } +cffi = "^1.15.1" +crcmod = "^1.7" +cryptography = "^37.0.4" +Cython = "^0.29.30" +flake8 = "^4.0.1" +Flask = "^2.1.2" +future-fstrings = "^1.2.0" # for acados +gunicorn = "^20.1.0" +hatanaka = "==2.4" +hexdump = "^3.3" +Jinja2 = "^3.1.2" +json-rpc = "^1.13.0" +libusb1 = "^3.0.0" +nose = "^1.3.7" +numpy = "^1.23.0" +onnx = "^1.12.0" +onnxruntime-gpu = { version = "^1.11.1", markers = "platform_system != 'Darwin'" } +pillow = "^9.2.0" +poetry = "==1.2.2" +protobuf = "==3.20.1" +psutil = "^5.9.1" +pycapnp = "==1.1.0" +pycryptodome = "^3.15.0" +PyJWT = "^2.5.0" +pylint = "^2.15.4" +pyopencl = "^2022.2.4" +pyserial = "^3.5" +python-dateutil = "^2.8.2" +PyYAML = "^6.0" +pyzmq = "^23.2.0" +requests = "^2.28.1" +scons = "^4.3.0" +sentry-sdk = "^1.6.0" +setproctitle = "^1.2.3" +six = "^1.16.0" +smbus2 = "^0.4.2" +sounddevice = "^0.4.5" +sympy = "^1.10.1" +timezonefinder = "^6.0.1" +tqdm = "^4.64.0" +urllib3 = "^1.26.10" +utm = "^0.7.0" +websocket_client = "^1.3.3" +spidev = "^3.6" + + +[tool.poetry.group.dev.dependencies] +av = "^9.2.0" +azure-storage-blob = "~2.1" +breathe = "^4.34.0" +carla = "==0.9.13" +control = "^0.9.2" +coverage = "^6.4.1" +dictdiffer = "^0.9.0" +fastcluster = "^1.2.6" +ft4222 = "^1.4.1" +hexdump = "^3.3" +hypothesis = "==6.46.7" +inputs = "^0.5" +lru-dict = "^1.1.7" +lxml = "^4.9.1" +markdown-it-py = "^2.1.0" +matplotlib = "^3.5.2" +mpld3 = "^0.5.8" +mypy = "^0.961" +myst-parser = "^0.18.0" +natsort = "^8.1.0" +numpy = "^1.23.0" +opencv-python-headless = { url = "https://github.com/commaai/opencv-python-builder/releases/download/4.5.5.64%2Bcu113/opencv_python_headless-4.5.5.64-cp38-cp38-manylinux_2_31_x86_64.whl" } +pandas = "^1.4.3" +parameterized = "^0.8.1" +paramiko = "^2.11.0" +pprofile = "^2.1.0" +pre-commit = "^2.19.0" +pycurl = "^7.45.1" +pygame = "^2.1.2" +pyprof2calltree = "^1.4.5" +pytest = "^7.1.2" +pytest-xdist = "^2.5.0" +reverse_geocoder = "^1.5.1" +scipy = "^1.8.1" +sphinx = "^5.0.2" +sphinx-rtd-theme = "^1.0.0" +sphinx-sitemap = "^2.2.0" +subprocess32 = "^3.5.4" +tabulate = "^0.8.10" +tenacity = "^8.0.1" +types-atomicwrites = "^1.4.5" +types-certifi = "^2021.10.8" +types-pycurl = "^7.45.1" +types-PyYAML = "^6.0" +types-requests = "^2.28.11" + + +[tool.poetry.group.xx] +optional = true + +[tool.poetry.group.xx.dependencies] +aenum = "^3.1.11" +aiohttp = "^3.8.1" +albumentations = "^1.2.1" +apex = { url = "https://github.com/commaai/apex/releases/download/pytorch1.10.0%2Bcu11.1/apex-0.1-cp38-cp38-linux_x86_64.whl" } +azure-cli-core = "^2.38.0" +azure-common = "^1.1.28" +azure-core = "^1.24.2" +azure-nspkg = "~3.0" +azure-storage-blob = "~2.1" +azure-storage-common = "~2.1" +azure-storage-nspkg = "~3.1" +blosc = "==1.9.2" +cloudpickle = "^2.1.0" +configargparse = "^1.5.3" +cupy-cuda113 = "^10.6.0" +datadog = "^0.44.0" +dotmap = "^1.3.30" +einops = "^0.5.0" +elasticsearch = "^8.3.1" +Flask-Cors = "^3.0.10" +Flask-SocketIO = "^5.2.0" +GeoAlchemy2 = "^0.12.1" +imageio = "^2.19.5" +influxdb-client = "^1.30.0" +ipykernel = "^6.15.1" +ipython = "^8.4.0" +joblib = "^1.1.0" +json-logging-py = "^0.2" +jupyter = "^1.0.0" +jupyterlab = "^3.4.4" +jupyterlab-vim = "^0.15.1" +Markdown = "^3.4.1" +mpld3 = "^0.5.8" +msgpack-python = "^0.5.6" +networkx = "~2.3" +nvidia-ml-py3 = "^7.352.0" +onnx2torch = "^1.5.4" +onnxoptimizer = "^0.3.1" +opencv-python-headless = { url = "https://github.com/commaai/opencv-python-builder/releases/download/4.5.5.64%2Bcu113/opencv_python_headless-4.5.5.64-cp38-cp38-manylinux_2_31_x86_64.whl" } +osmium = "^3.3.0" +pandas = "^1.4.3" +pillow-avif-plugin = "^1.2.2" +pipenv = "==2022.10.12" +plotly = "^5.9.0" +pycuda = "^2022.1" +Pygments = "^2.12.0" +PyMySQL = "~0.9" +pyproj = "^3.3.1" +python-logstash = "^0.4.8" +redis = "^4.3.4" +s2sphere = "^0.2.5" +scikit-image = "^0.19.3" +scikit-learn = "^1.1.1" +segmentation-models-pytorch = "==0.2.1" +simplejson = "^3.17.6" +SQLAlchemy = "^1.4.39" +torch = { url = "https://download.pytorch.org/whl/cu113/torch-1.11.0%2Bcu113-cp38-cp38-linux_x86_64.whl" } +torchsummary = "^1.5.1" +torchvision = { url = "https://download.pytorch.org/whl/cu113/torchvision-0.12.0%2Bcu113-cp38-cp38-linux_x86_64.whl" } +triton = "^1.1.1" +Werkzeug = "^2.1.2" +zerorpc = { git = "https://github.com/commaai/zerorpc-python.git", branch = "master" } + + +[build-system] +requires = ["poetry-core"] +build-backend = "poetry.core.masonry.api" diff --git a/rednose_repo b/rednose_repo index 5b526a8e00..3b6bd703b7 160000 --- a/rednose_repo +++ b/rednose_repo @@ -1 +1 @@ -Subproject commit 5b526a8e00bdc1c3922be470af1602cf9dc72dde +Subproject commit 3b6bd703b7a7667e4f82d0b81ef9a454819b94bd diff --git a/release/build_devel.sh b/release/build_devel.sh index db8c69bd7a..668ac0de19 100755 --- a/release/build_devel.sh +++ b/release/build_devel.sh @@ -1,33 +1,36 @@ -#!/usr/bin/bash -e +#!/usr/bin/bash + +set -ex DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" -TARGET_DIR=/data/openpilot -SOURCE_DIR="$(git rev-parse --show-toplevel)" +SOURCE_DIR="$(git -C $DIR rev-parse --show-toplevel)" +if [ -z "$TARGET_DIR" ]; then + TARGET_DIR="$(mktemp -d)" +fi # set git identity source $DIR/identity.sh -echo "[-] Setting up repo T=$SECONDS" -if [ ! -d "$TARGET_DIR" ]; then - mkdir -p $TARGET_DIR - cd $TARGET_DIR - git init - git remote add origin git@github.com:commaai/openpilot.git -fi +echo "[-] Setting up target repo T=$SECONDS" + +rm -rf $TARGET_DIR +mkdir -p $TARGET_DIR +cd $TARGET_DIR +cp -r $SOURCE_DIR/.git $TARGET_DIR +pre-commit uninstall || true echo "[-] bringing master-ci and devel in sync T=$SECONDS" cd $TARGET_DIR -git prune || true -git remote prune origin || true -git fetch origin master-ci -git fetch origin devel +git fetch --depth 1 origin master-ci +git fetch --depth 1 origin devel git checkout -f --track origin/master-ci git reset --hard master-ci git checkout master-ci git reset --hard origin/devel -git clean -xdf +git clean -xdff +git lfs uninstall # remove everything except .git echo "[-] erasing old openpilot T=$SECONDS" @@ -35,36 +38,46 @@ find . -maxdepth 1 -not -path './.git' -not -name '.' -not -name '..' -exec rm - # reset source tree cd $SOURCE_DIR -git clean -xdf +git clean -xdff # do the files copy echo "[-] copying files T=$SECONDS" cd $SOURCE_DIR -cp -pR --parents $(cat release/files_common) $TARGET_DIR/ -cp -pR --parents $(cat release/files_tici) $TARGET_DIR/ +cp -pR --parents $(cat release/files_*) $TARGET_DIR/ if [ ! -z "$EXTRA_FILES" ]; then cp -pR --parents $EXTRA_FILES $TARGET_DIR/ fi -# append source commit hash and build date to version -GIT_HASH=$(git --git-dir=$SOURCE_DIR/.git rev-parse --short HEAD) -DATETIME=$(date '+%Y-%m-%dT%H:%M:%S') -VERSION=$(cat selfdrive/common/version.h | awk -F\" '{print $2}') -echo "#define COMMA_VERSION \"$VERSION-$GIT_HASH-$DATETIME\"" > selfdrive/common/version.h - # in the directory cd $TARGET_DIR rm -f panda/board/obj/panda.bin.signed +# include source commit hash and build date in commit +GIT_HASH=$(git --git-dir=$SOURCE_DIR/.git rev-parse HEAD) +DATETIME=$(date '+%Y-%m-%dT%H:%M:%S') +VERSION=$(cat $SOURCE_DIR/common/version.h | awk -F\" '{print $2}') + echo "[-] committing version $VERSION T=$SECONDS" git add -f . git status -git commit -a -m "openpilot v$VERSION release" +git commit -a -m "openpilot v$VERSION release + +date: $DATETIME +master commit: $GIT_HASH +" + +# ensure files are within GitHub's limit +BIG_FILES="$(find . -type f -not -path './.git/*' -size +95M)" +if [ ! -z "$BIG_FILES" ]; then + printf '\n\n\n' + echo "Found files exceeding GitHub's 100MB limit:" + echo "$BIG_FILES" + exit 1 +fi -if [ ! -z "$PUSH" ]; then - echo "[-] Pushing to $PUSH T=$SECONDS" - git remote set-url origin git@github.com:commaai/openpilot.git - git push -f origin master-ci:$PUSH +if [ ! -z "$BRANCH" ]; then + echo "[-] Pushing to $BRANCH T=$SECONDS" + git push -f origin master-ci:$BRANCH fi -echo "[-] done T=$SECONDS" +echo "[-] done T=$SECONDS, ready at $TARGET_DIR" diff --git a/release/build_release.sh b/release/build_release.sh index 95fcfea1a1..80106eefb2 100755 --- a/release/build_release.sh +++ b/release/build_release.sh @@ -13,16 +13,13 @@ if [ -f /TICI ]; then FILES_SRC="release/files_tici" RELEASE_BRANCH=release3-staging DASHCAM_BRANCH=dashcam3-staging -elif [ -f /EON ]; then - FILES_SRC="release/files_eon" - RELEASE_BRANCH=release2-staging - DASHCAM_BRANCH=dashcam-staging else exit 0 fi # set git identity source $DIR/identity.sh +export GIT_SSH_COMMAND="ssh -i /data/gitkey" echo "[-] Setting up repo T=$SECONDS" rm -rf $BUILD_DIR @@ -43,9 +40,10 @@ cp -pR --parents $(cat $FILES_SRC) $BUILD_DIR/ cd $BUILD_DIR rm -f panda/board/obj/panda.bin.signed +rm -f panda/board/obj/panda_h7.bin.signed -VERSION=$(cat selfdrive/common/version.h | awk -F[\"-] '{print $2}') -echo "#define COMMA_VERSION \"$VERSION-release\"" > selfdrive/common/version.h +VERSION=$(cat common/version.h | awk -F[\"-] '{print $2}') +echo "#define COMMA_VERSION \"$VERSION-release\"" > common/version.h echo "[-] committing version $VERSION T=$SECONDS" git add -f . @@ -56,6 +54,7 @@ git branch --set-upstream-to=origin/$RELEASE_BRANCH pushd panda/ CERT=/data/pandaextra/certs/release RELEASE=1 scons -u . mv board/obj/panda.bin.signed /tmp/panda.bin.signed +mv board/obj/panda_h7.bin.signed /tmp/panda_h7.bin.signed popd # Build @@ -79,11 +78,12 @@ find . -name 'moc_*' -delete find . -name '__pycache__' -delete rm -rf panda/board panda/certs panda/crypto rm -rf .sconsign.dblite Jenkinsfile release/ -rm models/supercombo.dlc +rm selfdrive/modeld/models/supercombo.onnx # Move back signed panda fw mkdir -p panda/board/obj mv /tmp/panda.bin.signed panda/board/obj/panda.bin.signed +mv /tmp/panda_h7.bin.signed panda/board/obj/panda_h7.bin.signed # Restore third_party git checkout third_party/ diff --git a/release/check-dirty.sh b/release/check-dirty.sh new file mode 100755 index 0000000000..9c6389f380 --- /dev/null +++ b/release/check-dirty.sh @@ -0,0 +1,11 @@ +#!/usr/bin/bash +set -e + +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" +cd $DIR + +if [ ! -z "$(git status --porcelain)" ]; then + echo "Dirty working tree after build:" + git status --porcelain + exit 1 +fi diff --git a/release/files_common b/release/files_common index cfc8150e3b..297a7a808e 100644 --- a/release/files_common +++ b/release/files_common @@ -17,6 +17,7 @@ site_scons/site_tools/cython.py common/.gitignore common/__init__.py +common/conversions.py common/gpio.py common/realtime.py common/clock.pyx @@ -25,10 +26,8 @@ common/ffi_wrapper.py common/file_helpers.py common/logging_extra.py common/numpy_fast.py -common/markdown.py common/params.py common/params_pyx.pyx -common/xattr.py common/profiler.py common/basedir.py common/dict_helpers.py @@ -36,7 +35,6 @@ common/filter_simple.py common/stat_live.py common/spinner.py common/text_window.py -common/SConscript common/kalman/.gitignore common/kalman/* @@ -57,29 +55,26 @@ common/transformations/transformations.pyx common/api/__init__.py -models/supercombo.dlc -models/big_supercombo.dlc -models/dmonitoring_model_q.dlc - release/* +tools/__init__.py tools/lib/* - -installer/updater/updater - -selfdrive/version.py +tools/joystick/* +tools/replay/*.cc +tools/replay/*.h selfdrive/__init__.py -selfdrive/config.py selfdrive/sentry.py -selfdrive/swaglog.py -selfdrive/logmessaged.py selfdrive/tombstoned.py -selfdrive/pandad.py selfdrive/updated.py selfdrive/rtshield.py selfdrive/statsd.py +system/logmessaged.py +system/micd.py +system/swaglog.py +system/version.py + selfdrive/athena/__init__.py selfdrive/athena/athenad.py selfdrive/athena/manage_athenad.py @@ -96,135 +91,83 @@ selfdrive/boardd/boardd_api_impl.pyx selfdrive/boardd/can_list_to_can_capnp.cc selfdrive/boardd/panda.cc selfdrive/boardd/panda.h -selfdrive/boardd/pigeon.cc -selfdrive/boardd/pigeon.h +selfdrive/boardd/spi.cc +selfdrive/boardd/panda_comms.h +selfdrive/boardd/panda_comms.cc selfdrive/boardd/set_time.py +selfdrive/boardd/pandad.py +selfdrive/boardd/tests/test_boardd_loopback.py selfdrive/car/__init__.py +selfdrive/car/docs_definitions.py selfdrive/car/car_helpers.py selfdrive/car/fingerprints.py selfdrive/car/interfaces.py selfdrive/car/vin.py selfdrive/car/disable_ecu.py selfdrive/car/fw_versions.py +selfdrive/car/fw_query_definitions.py +selfdrive/car/ecu_addrs.py selfdrive/car/isotp_parallel_query.py selfdrive/car/tests/__init__.py selfdrive/car/tests/test_car_interfaces.py -selfdrive/car/chrysler/__init__.py -selfdrive/car/chrysler/carstate.py -selfdrive/car/chrysler/interface.py -selfdrive/car/chrysler/radar_interface.py -selfdrive/car/chrysler/values.py -selfdrive/car/chrysler/carcontroller.py -selfdrive/car/chrysler/chryslercan.py -selfdrive/car/honda/__init__.py -selfdrive/car/honda/carstate.py -selfdrive/car/honda/interface.py -selfdrive/car/honda/radar_interface.py -selfdrive/car/honda/values.py -selfdrive/car/honda/carcontroller.py -selfdrive/car/honda/hondacan.py -selfdrive/car/hyundai/__init__.py -selfdrive/car/hyundai/carstate.py -selfdrive/car/hyundai/interface.py -selfdrive/car/hyundai/radar_interface.py -selfdrive/car/hyundai/values.py -selfdrive/car/hyundai/carcontroller.py -selfdrive/car/hyundai/hyundaican.py -selfdrive/car/toyota/__init__.py -selfdrive/car/toyota/carstate.py -selfdrive/car/toyota/tunes.py -selfdrive/car/toyota/interface.py -selfdrive/car/toyota/radar_interface.py -selfdrive/car/toyota/values.py -selfdrive/car/toyota/carcontroller.py -selfdrive/car/toyota/toyotacan.py -selfdrive/car/nissan/__init__.py -selfdrive/car/nissan/carcontroller.py -selfdrive/car/nissan/carstate.py -selfdrive/car/nissan/interface.py -selfdrive/car/nissan/nissancan.py -selfdrive/car/nissan/radar_interface.py -selfdrive/car/nissan/values.py -selfdrive/car/volkswagen/__init__.py -selfdrive/car/volkswagen/carstate.py -selfdrive/car/volkswagen/interface.py -selfdrive/car/volkswagen/radar_interface.py -selfdrive/car/volkswagen/values.py -selfdrive/car/volkswagen/carcontroller.py -selfdrive/car/volkswagen/volkswagencan.py -selfdrive/car/gm/__init__.py -selfdrive/car/gm/carstate.py -selfdrive/car/gm/interface.py -selfdrive/car/gm/radar_interface.py -selfdrive/car/gm/values.py -selfdrive/car/gm/carcontroller.py -selfdrive/car/gm/gmcan.py -selfdrive/car/ford/__init__.py -selfdrive/car/ford/carstate.py -selfdrive/car/ford/interface.py -selfdrive/car/ford/radar_interface.py -selfdrive/car/ford/values.py -selfdrive/car/ford/carcontroller.py -selfdrive/car/ford/fordcan.py -selfdrive/car/subaru/__init__.py -selfdrive/car/subaru/carstate.py -selfdrive/car/subaru/interface.py -selfdrive/car/subaru/radar_interface.py -selfdrive/car/subaru/values.py -selfdrive/car/subaru/carcontroller.py -selfdrive/car/subaru/subarucan.py -selfdrive/car/mazda/__init__.py -selfdrive/car/mazda/carstate.py -selfdrive/car/mazda/interface.py -selfdrive/car/mazda/radar_interface.py -selfdrive/car/mazda/values.py -selfdrive/car/mazda/carcontroller.py -selfdrive/car/mazda/mazdacan.py -selfdrive/car/tesla/__init__.py -selfdrive/car/tesla/teslacan.py -selfdrive/car/tesla/carcontroller.py -selfdrive/car/tesla/radar_interface.py -selfdrive/car/tesla/values.py -selfdrive/car/tesla/carstate.py -selfdrive/car/tesla/interface.py +selfdrive/car/torque_data/params.yaml +selfdrive/car/torque_data/substitute.yaml +selfdrive/car/torque_data/override.yaml + +selfdrive/car/body/*.py +selfdrive/car/chrysler/*.py +selfdrive/car/ford/*.py +selfdrive/car/gm/*.py +selfdrive/car/honda/*.py +selfdrive/car/hyundai/*.py +selfdrive/car/mazda/*.py selfdrive/car/mock/*.py +selfdrive/car/nissan/*.py +selfdrive/car/subaru/*.py +selfdrive/car/tesla/*.py +selfdrive/car/toyota/*.py +selfdrive/car/volkswagen/*.py + +system/clocksd/.gitignore +system/clocksd/SConscript +system/clocksd/clocksd.cc + +selfdrive/debug/can_printer.py +selfdrive/debug/check_freq.py +selfdrive/debug/dump.py +selfdrive/debug/filter_log_message.py +selfdrive/debug/get_fingerprint.py +selfdrive/debug/uiview.py + +selfdrive/debug/hyundai_enable_radar_points.py +selfdrive/debug/vw_mqb_config.py -selfdrive/clocksd/.gitignore -selfdrive/clocksd/SConscript -selfdrive/clocksd/clocksd.cc - -selfdrive/debug/*.py - -selfdrive/common/SConscript -selfdrive/common/version.h - -selfdrive/common/swaglog.h -selfdrive/common/swaglog.cc -selfdrive/common/statlog.h -selfdrive/common/statlog.cc -selfdrive/common/util.cc -selfdrive/common/util.h -selfdrive/common/queue.h -selfdrive/common/clutil.cc -selfdrive/common/clutil.h -selfdrive/common/params.h -selfdrive/common/params.cc -selfdrive/common/watchdog.cc -selfdrive/common/watchdog.h - -selfdrive/common/modeldata.h -selfdrive/common/mat.h -selfdrive/common/timing.h - -selfdrive/common/visionimg.cc -selfdrive/common/visionimg.h - -selfdrive/common/gpio.cc -selfdrive/common/gpio.h -selfdrive/common/i2c.cc -selfdrive/common/i2c.h - +common/SConscript +common/version.h + +common/swaglog.h +common/swaglog.cc +common/statlog.h +common/statlog.cc +common/util.cc +common/util.h +common/queue.h +common/clutil.cc +common/clutil.h +common/params.h +common/params.cc +common/watchdog.cc +common/watchdog.h + +common/modeldata.h +common/mat.h +common/timing.h + +common/gpio.cc +common/gpio.h +common/i2c.cc +common/i2c.h selfdrive/controls/__init__.py selfdrive/controls/controlsd.py @@ -236,10 +179,9 @@ selfdrive/controls/lib/alerts_offroad.json selfdrive/controls/lib/desire_helper.py selfdrive/controls/lib/drive_helpers.py selfdrive/controls/lib/events.py -selfdrive/controls/lib/lane_planner.py selfdrive/controls/lib/latcontrol_angle.py selfdrive/controls/lib/latcontrol_indi.py -selfdrive/controls/lib/latcontrol_lqr.py +selfdrive/controls/lib/latcontrol_torque.py selfdrive/controls/lib/latcontrol_pid.py selfdrive/controls/lib/latcontrol.py selfdrive/controls/lib/lateral_planner.py @@ -256,24 +198,27 @@ selfdrive/controls/lib/longitudinal_mpc_lib/.gitignore selfdrive/controls/lib/lateral_mpc_lib/* selfdrive/controls/lib/longitudinal_mpc_lib/* -selfdrive/hardware/__init__.py -selfdrive/hardware/base.h -selfdrive/hardware/base.py -selfdrive/hardware/hw.h -selfdrive/hardware/eon/__init__.py -selfdrive/hardware/eon/androidd.py -selfdrive/hardware/eon/shutdownd.py -selfdrive/hardware/eon/hardware.h -selfdrive/hardware/eon/hardware.py -selfdrive/hardware/eon/neos.py -selfdrive/hardware/eon/neos.json -selfdrive/hardware/eon/updater -selfdrive/hardware/tici/__init__.py -selfdrive/hardware/tici/hardware.py -selfdrive/hardware/tici/amplifier.py -selfdrive/hardware/tici/iwlist.py -selfdrive/hardware/pc/__init__.py -selfdrive/hardware/pc/hardware.py +selfdrive/hardware + +system/__init__.py + +system/hardware/__init__.py +system/hardware/base.h +system/hardware/base.py +system/hardware/hw.h +system/hardware/tici/__init__.py +system/hardware/tici/hardware.h +system/hardware/tici/hardware.py +system/hardware/tici/pins.py +system/hardware/tici/agnos.py +system/hardware/tici/casync.py +system/hardware/tici/agnos.json +system/hardware/tici/amplifier.py +system/hardware/tici/updater +system/hardware/tici/iwlist.py +system/hardware/pc/__init__.py +system/hardware/pc/hardware.h +system/hardware/pc/hardware.py selfdrive/locationd/__init__.py selfdrive/locationd/.gitignore @@ -286,40 +231,49 @@ selfdrive/locationd/generated/ubx.h selfdrive/locationd/generated/gps.cpp selfdrive/locationd/generated/gps.h +selfdrive/locationd/laikad.py +selfdrive/locationd/laikad_helpers.py selfdrive/locationd/locationd.h selfdrive/locationd/locationd.cc selfdrive/locationd/paramsd.py +selfdrive/locationd/models/__init__.py selfdrive/locationd/models/.gitignore -selfdrive/locationd/models/live_kf.py selfdrive/locationd/models/car_kf.py -selfdrive/locationd/models/constants.py +selfdrive/locationd/models/gnss_kf.py +selfdrive/locationd/models/live_kf.py selfdrive/locationd/models/live_kf.h selfdrive/locationd/models/live_kf.cc +selfdrive/locationd/models/constants.py +selfdrive/locationd/models/gnss_helpers.py +selfdrive/locationd/torqued.py selfdrive/locationd/calibrationd.py -selfdrive/logcatd/SConscript -selfdrive/logcatd/logcatd_android.cc -selfdrive/logcatd/logcatd_systemd.cc +system/logcatd/.gitignore +system/logcatd/SConscript +system/logcatd/logcatd_systemd.cc -selfdrive/proclogd/SConscript -selfdrive/proclogd/main.cc -selfdrive/proclogd/proclog.cc -selfdrive/proclogd/proclog.h +system/proclogd/SConscript +system/proclogd/main.cc +system/proclogd/proclog.cc +system/proclogd/proclog.h +selfdrive/loggerd/.gitignore selfdrive/loggerd/SConscript -selfdrive/loggerd/encoder.h -selfdrive/loggerd/omx_encoder.cc -selfdrive/loggerd/omx_encoder.h +selfdrive/loggerd/encoder/encoder.cc +selfdrive/loggerd/encoder/encoder.h +selfdrive/loggerd/encoder/v4l_encoder.cc +selfdrive/loggerd/encoder/v4l_encoder.h +selfdrive/loggerd/video_writer.cc +selfdrive/loggerd/video_writer.h selfdrive/loggerd/logger.cc selfdrive/loggerd/logger.h selfdrive/loggerd/loggerd.cc selfdrive/loggerd/loggerd.h -selfdrive/loggerd/main.cc +selfdrive/loggerd/encoderd.cc selfdrive/loggerd/bootlog.cc -selfdrive/loggerd/raw_logger.cc -selfdrive/loggerd/raw_logger.h -selfdrive/loggerd/include/msm_media_info.h +selfdrive/loggerd/encoder/ffmpeg_encoder.cc +selfdrive/loggerd/encoder/ffmpeg_encoder.h selfdrive/loggerd/__init__.py selfdrive/loggerd/config.py @@ -329,19 +283,19 @@ selfdrive/loggerd/xattr_cache.py selfdrive/sensord/SConscript selfdrive/sensord/libdiag.h -selfdrive/sensord/sensors_qcom.cc selfdrive/sensord/sensors_qcom2.cc selfdrive/sensord/sensors/*.cc selfdrive/sensord/sensors/*.h selfdrive/sensord/sensord +selfdrive/sensord/pigeond.py selfdrive/thermald/thermald.py selfdrive/thermald/power_monitoring.py +selfdrive/thermald/fan_controller.py selfdrive/test/__init__.py selfdrive/test/helpers.py selfdrive/test/setup_device_ci.sh -selfdrive/test/test_fingerprints.py selfdrive/test/test_onroad.py selfdrive/ui/.gitignore @@ -355,6 +309,10 @@ selfdrive/ui/soundd/*.cc selfdrive/ui/soundd/*.h selfdrive/ui/soundd/soundd selfdrive/ui/soundd/.gitignore +selfdrive/ui/translations/*.ts +selfdrive/ui/translations/languages.json +selfdrive/ui/update_translations.py +selfdrive/ui/tests/test_translations.py selfdrive/ui/qt/*.cc selfdrive/ui/qt/*.h @@ -363,36 +321,22 @@ selfdrive/ui/qt/offroad/*.h selfdrive/ui/qt/offroad/*.qml selfdrive/ui/qt/widgets/*.cc selfdrive/ui/qt/widgets/*.h -selfdrive/ui/qt/spinner_aarch64 -selfdrive/ui/qt/text_aarch64 - -selfdrive/ui/replay/*.cc -selfdrive/ui/replay/*.h - -selfdrive/camerad/SConscript -selfdrive/camerad/main.cc - -selfdrive/camerad/snapshot/* -selfdrive/camerad/include/* -selfdrive/camerad/cameras/camera_common.h -selfdrive/camerad/cameras/camera_common.cc -selfdrive/camerad/cameras/camera_qcom.cc -selfdrive/camerad/cameras/camera_qcom.h -selfdrive/camerad/cameras/camera_replay.cc -selfdrive/camerad/cameras/camera_replay.h -selfdrive/camerad/cameras/debayer.cl -selfdrive/camerad/cameras/sensor_i2c.h -selfdrive/camerad/cameras/sensor2_i2c.h - -selfdrive/camerad/transforms/rgb_to_yuv.cc -selfdrive/camerad/transforms/rgb_to_yuv.h -selfdrive/camerad/transforms/rgb_to_yuv.cl -selfdrive/camerad/transforms/rgb_to_yuv_test.cc - -selfdrive/camerad/imgproc/conv.cl -selfdrive/camerad/imgproc/pool.cl -selfdrive/camerad/imgproc/utils.cc -selfdrive/camerad/imgproc/utils.h +selfdrive/ui/qt/maps/*.cc +selfdrive/ui/qt/maps/*.h + +system/camerad/SConscript +system/camerad/main.cc + +system/camerad/snapshot/* +system/camerad/include/* +system/camerad/cameras/camera_common.h +system/camerad/cameras/camera_common.cc +system/camerad/cameras/sensor2_i2c.h + +system/camerad/imgproc/conv.cl +system/camerad/imgproc/pool.cl +system/camerad/imgproc/utils.cc +system/camerad/imgproc/utils.h selfdrive/manager/__init__.py selfdrive/manager/build.py @@ -403,19 +347,30 @@ selfdrive/manager/process.py selfdrive/manager/test/__init__.py selfdrive/manager/test/test_manager.py +selfdrive/modeld/__init__.py selfdrive/modeld/SConscript selfdrive/modeld/modeld.cc +selfdrive/modeld/navmodeld.cc selfdrive/modeld/dmonitoringmodeld.cc selfdrive/modeld/constants.py selfdrive/modeld/modeld +selfdrive/modeld/navmodeld selfdrive/modeld/dmonitoringmodeld selfdrive/modeld/models/commonmodel.cc selfdrive/modeld/models/commonmodel.h + selfdrive/modeld/models/driving.cc selfdrive/modeld/models/driving.h +selfdrive/modeld/models/supercombo.onnx + selfdrive/modeld/models/dmonitoring.cc selfdrive/modeld/models/dmonitoring.h +selfdrive/modeld/models/dmonitoring_model_q.dlc + +selfdrive/modeld/models/nav.cc +selfdrive/modeld/models/nav.h +selfdrive/modeld/models/navmodel_q.dlc selfdrive/modeld/transforms/loadyuv.cc selfdrive/modeld/transforms/loadyuv.h @@ -424,12 +379,12 @@ selfdrive/modeld/transforms/transform.cc selfdrive/modeld/transforms/transform.h selfdrive/modeld/transforms/transform.cl -selfdrive/modeld/thneed/thneed.* +selfdrive/modeld/thneed/*.py +selfdrive/modeld/thneed/thneed.h +selfdrive/modeld/thneed/thneed_common.cc +selfdrive/modeld/thneed/thneed_qcom2.cc selfdrive/modeld/thneed/serialize.cc -selfdrive/modeld/thneed/compile.cc -selfdrive/modeld/thneed/optimizer.cc selfdrive/modeld/thneed/include/* -selfdrive/modeld/thneed/kernels/*.cl selfdrive/modeld/runners/snpemodel.cc selfdrive/modeld/runners/snpemodel.h @@ -441,10 +396,15 @@ selfdrive/modeld/runners/run.h selfdrive/monitoring/dmonitoringd.py selfdrive/monitoring/driver_monitor.py +selfdrive/navd/__init__.py +selfdrive/navd/navd.py +selfdrive/navd/helpers.py + selfdrive/assets/.gitignore selfdrive/assets/assets.qrc selfdrive/assets/*.png selfdrive/assets/*.svg +selfdrive/assets/body/* selfdrive/assets/fonts/*.ttf selfdrive/assets/icons/* selfdrive/assets/images/* @@ -454,12 +414,8 @@ selfdrive/assets/training/* third_party/SConscript -third_party/libgralloc/** third_party/linux/** third_party/opencl/** -third_party/zlib/* -third_party/bzip2/* -third_party/openmax/** third_party/json11/json11.cpp third_party/json11/json11.hpp @@ -475,18 +431,13 @@ third_party/libyuv/lib/** third_party/libyuv/larch64/** third_party/snpe/include/** -third_party/snpe/aarch64** -third_party/snpe/larch64** third_party/snpe/dsp** third_party/acados/x86_64/** -third_party/acados/aarch64/** third_party/acados/larch64/** third_party/acados/include/** -third_party/android_frameworks_native/** -third_party/android_hardware_libhardware/** -third_party/android_system_core/** +third_party/qt5/larch64/bin/** scripts/update_now.sh scripts/stop_updater.sh @@ -494,7 +445,22 @@ scripts/stop_updater.sh pyextra/.gitignore pyextra/acados_template/** +rednose/.gitignore rednose/** +laika/** + +body/.gitignore +body/board/SConscript +body/board/*.h +body/board/*.c +body/board/*.s +body/board/*.ld +body/board/inc/** +body/board/obj/ +body/board/bldc/** +body/board/drivers/** +body/certs/** +body/crypto/** cereal/.gitignore cereal/__init__.py @@ -528,6 +494,7 @@ cereal/visionipc/*.pxd panda/.gitignore panda/__init__.py +panda/SConscript panda/board/** panda/certs/** panda/crypto/** @@ -544,27 +511,27 @@ opendbc/can/common.h opendbc/can/common.pxd opendbc/can/common_dbc.h opendbc/can/dbc.cc -opendbc/can/dbc.py -opendbc/can/dbc_template.cc opendbc/can/packer.cc opendbc/can/packer.py opendbc/can/packer_pyx.pyx opendbc/can/parser.cc opendbc/can/parser.py opendbc/can/parser_pyx.pyx -opendbc/can/process_dbc.py -opendbc/can/dbc_out/.gitkeep -opendbc/can/dbc_out/.gitignore -opendbc/chrysler_pacifica_2017_hybrid.dbc +opendbc/comma_body.dbc + +opendbc/chrysler_ram_hd_generated.dbc +opendbc/chrysler_ram_dt_generated.dbc +opendbc/chrysler_pacifica_2017_hybrid_generated.dbc opendbc/chrysler_pacifica_2017_hybrid_private_fusion.dbc opendbc/gm_global_a_powertrain_generated.dbc opendbc/gm_global_a_object.dbc opendbc/gm_global_a_chassis.dbc -opendbc/ford_fusion_2018_pt.dbc +opendbc/FORD_CADS.dbc opendbc/ford_fusion_2018_adas.dbc +opendbc/ford_lincoln_base_pt.dbc opendbc/honda_accord_2018_can_generated.dbc opendbc/acura_ilx_2016_can_generated.dbc @@ -581,9 +548,11 @@ opendbc/honda_odyssey_exl_2018_generated.dbc opendbc/honda_odyssey_extreme_edition_2018_china_can_generated.dbc opendbc/honda_insight_ex_2019_can_generated.dbc opendbc/acura_ilx_2016_nidec.dbc +opendbc/honda_civic_ex_2022_can_generated.dbc +opendbc/hyundai_canfd.dbc opendbc/hyundai_kia_generic.dbc -opendbc/hyundai_kia_mando_front_radar.dbc +opendbc/hyundai_kia_mando_front_radar_generated.dbc opendbc/mazda_2017.dbc @@ -601,8 +570,24 @@ opendbc/toyota_nodsu_pt_generated.dbc opendbc/toyota_adas.dbc opendbc/toyota_tss2_adas.dbc +opendbc/vw_golf_mk4.dbc opendbc/vw_mqb_2010.dbc opendbc/tesla_can.dbc opendbc/tesla_radar.dbc opendbc/tesla_powertrain.dbc + +tinygrad_repo/openpilot/compile.py +tinygrad_repo/accel/opencl/* +tinygrad_repo/extra/onnx.py +tinygrad_repo/extra/thneed.py +tinygrad_repo/extra/utils.py +tinygrad_repo/tinygrad/llops/ops_gpu.py +tinygrad_repo/tinygrad/llops/ops_opencl.py +tinygrad_repo/tinygrad/helpers.py +tinygrad_repo/tinygrad/mlops.py +tinygrad_repo/tinygrad/ops.py +tinygrad_repo/tinygrad/shapetracker.py +tinygrad_repo/tinygrad/tensor.py +tinygrad_repo/tinygrad/nn/__init__.py +tinygrad_repo/tinygrad/nn/optim.py diff --git a/release/files_eon b/release/files_eon deleted file mode 100644 index b43bf86b50..0000000000 --- a/release/files_eon +++ /dev/null @@ -1 +0,0 @@ -README.md diff --git a/release/files_pc b/release/files_pc index d00de7e475..01ecae4327 100644 --- a/release/files_pc +++ b/release/files_pc @@ -1,5 +1,7 @@ -selfdrive/ui/replay/* +selfdrive/modeld/runners/onnx* -third_party/mapbox-gl-native-qt/x86_64/** +third_party/mapbox-gl-native-qt/x86_64/*.so -third_party/qt-plugins/x86_64/** +third_party/libyuv/x64/** +third_party/snpe/x86_64/** +third_party/snpe/x86_64-linux-clang/** diff --git a/release/files_tici b/release/files_tici index 59cc41918f..c8abd720d5 100644 --- a/release/files_tici +++ b/release/files_tici @@ -1,30 +1,19 @@ +third_party/snpe/larch64** +third_party/snpe/aarch64-ubuntu-gcc7.5/* third_party/mapbox-gl-native-qt/include/* -selfdrive/timezoned.py +system/timezoned.py selfdrive/assets/navigation/* selfdrive/assets/training_wide/* -selfdrive/camerad/cameras/camera_qcom2.cc -selfdrive/camerad/cameras/camera_qcom2.h -selfdrive/camerad/cameras/real_debayer.cl +system/camerad/cameras/camera_qcom2.cc +system/camerad/cameras/camera_qcom2.h +system/camerad/cameras/camera_util.cc +system/camerad/cameras/camera_util.h +system/camerad/cameras/real_debayer.cl -selfdrive/hardware/tici/__init__.py -selfdrive/hardware/tici/hardware.h -selfdrive/hardware/tici/hardware.py -selfdrive/hardware/tici/pins.py -selfdrive/hardware/tici/agnos.py -selfdrive/hardware/tici/agnos.json -selfdrive/hardware/tici/amplifier.py -selfdrive/hardware/tici/updater +selfdrive/sensord/rawgps/* selfdrive/ui/qt/spinner_larch64 selfdrive/ui/qt/text_larch64 -selfdrive/ui/qt/maps/*.cc -selfdrive/ui/qt/maps/*.h - -selfdrive/ui/navd/*.cc -selfdrive/ui/navd/*.h -selfdrive/ui/navd/navd -selfdrive/ui/navd/.gitignore - diff --git a/release/identity.sh b/release/identity.sh index b90372d825..c699c94650 100644 --- a/release/identity.sh +++ b/release/identity.sh @@ -2,4 +2,3 @@ export GIT_COMMITTER_NAME="Vehicle Researcher" export GIT_COMMITTER_EMAIL="user@comma.ai" export GIT_AUTHOR_NAME="Vehicle Researcher" export GIT_AUTHOR_EMAIL="user@comma.ai" -export GIT_SSH_COMMAND="ssh -i /data/gitkey" diff --git a/release/verify.sh b/release/verify.sh index 2ebd50a29d..56f21183f1 100755 --- a/release/verify.sh +++ b/release/verify.sh @@ -6,7 +6,7 @@ RED="\033[0;31m" GREEN="\033[0;32m" CLEAR="\033[0m" -BRANCHES="devel dashcam dashcam3 release2 release3" +BRANCHES="devel dashcam3 release3" for b in $BRANCHES; do if git diff --quiet origin/$b origin/$b-staging && [ "$(git rev-parse origin/$b)" = "$(git rev-parse origin/$b-staging)" ]; then printf "%-10s $GREEN ok $CLEAR\n" "$b" diff --git a/scripts/cell.sh b/scripts/cell.sh new file mode 100755 index 0000000000..cae701eccc --- /dev/null +++ b/scripts/cell.sh @@ -0,0 +1,5 @@ +#!/usr/bin/bash + +nmcli connection modify --temporary lte ipv4.route-metric 1 +nmcli connection modify --temporary lte ipv6.route-metric 1 +nmcli con up lte diff --git a/scripts/clwaste b/scripts/clwaste deleted file mode 100755 index 51770f0e37..0000000000 Binary files a/scripts/clwaste and /dev/null differ diff --git a/scripts/count_cars.py b/scripts/count_cars.py index b01f97570e..25bad2c9b4 100755 --- a/scripts/count_cars.py +++ b/scripts/count_cars.py @@ -1,15 +1,11 @@ #!/usr/bin/env python3 -import os from collections import Counter from pprint import pprint -from common.basedir import BASEDIR +from selfdrive.car.docs import get_all_car_info -with open(os.path.join(BASEDIR, "docs/CARS.md")) as f: - lines = f.readlines() - cars = [l for l in lines if l.strip().startswith("|") and l.strip().endswith("|") and - "Make" not in l and any(c.isalpha() for c in l)] - - make_count = Counter(l.split('|')[1].split('|')[0].strip() for l in cars) - print("\n", "*"*20, len(cars), "total", "*"*20, "\n") +if __name__ == "__main__": + cars = get_all_car_info() + make_count = Counter(l.make for l in cars) + print("\n", "*" * 20, len(cars), "total", "*" * 20, "\n") pprint(make_count) diff --git a/scripts/disable-powersave.py b/scripts/disable-powersave.py index f651bc87f1..93688504f3 100755 --- a/scripts/disable-powersave.py +++ b/scripts/disable-powersave.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -from selfdrive.hardware import HARDWARE +from system.hardware import HARDWARE if __name__ == "__main__": HARDWARE.set_power_save(False) diff --git a/scripts/launch_corolla.sh b/scripts/launch_corolla.sh new file mode 100755 index 0000000000..146fbacf0a --- /dev/null +++ b/scripts/launch_corolla.sh @@ -0,0 +1,7 @@ +#!/usr/bin/bash + +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" + +export FINGERPRINT="TOYOTA COROLLA TSS2 2019" +export SKIP_FW_QUERY="1" +$DIR/../launch_openpilot.sh diff --git a/scripts/restart_modem.sh b/scripts/restart_modem.sh deleted file mode 100755 index fac54b32ff..0000000000 --- a/scripts/restart_modem.sh +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/bash -echo "restart" > /sys/kernel/debug/msm_subsys/modem diff --git a/scripts/switch_to_master.sh b/scripts/switch_to_master.sh deleted file mode 100755 index cad51eb549..0000000000 --- a/scripts/switch_to_master.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/bash - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" -cd $DIR/.. - -git clean -xdf . -git rm -r --cached . - -git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*" -git fetch origin master -git checkout master -git reset --hard -git submodule update --init - -printf '\n\n' -echo "master checked out. reboot to start building openpilot master" diff --git a/scripts/throttling.sh b/scripts/throttling.sh deleted file mode 100755 index d100c5f5ab..0000000000 --- a/scripts/throttling.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/data/data/com.termux/files/usr/bin/bash -watch -n1 ' - cat /sys/kernel/debug/clk/pwrcl_clk/measure - cat /sys/kernel/debug/clk/perfcl_clk/measure - cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_cur_freq - cat /sys/class/kgsl/kgsl-3d0/gpuclk - echo - echo -n "CPU0 " ; cat /sys/devices/virtual/thermal/thermal_zone5/temp - echo -n "CPU1 " ; cat /sys/devices/virtual/thermal/thermal_zone7/temp - echo -n "CPU2 " ; cat /sys/devices/virtual/thermal/thermal_zone10/temp - echo -n "CPU3 " ; cat /sys/devices/virtual/thermal/thermal_zone12/temp - echo -n "MEM " ; cat /sys/devices/virtual/thermal/thermal_zone2/temp - echo -n "GPU " ; cat /sys/devices/virtual/thermal/thermal_zone16/temp - echo -n "BAT " ; cat /sys/devices/virtual/thermal/thermal_zone29/temp -' - diff --git a/scripts/waste b/scripts/waste deleted file mode 100755 index e3154ab01f..0000000000 Binary files a/scripts/waste and /dev/null differ diff --git a/scripts/waste.c b/scripts/waste.c index 62233b7fc4..2e492916a7 100644 --- a/scripts/waste.c +++ b/scripts/waste.c @@ -11,7 +11,7 @@ #include #include #include -#include "../selfdrive/common/timing.h" +#include "../common/timing.h" int get_nprocs(void); double *ttime, *oout; diff --git a/scripts/waste.py b/scripts/waste.py index f2820ea670..d3c96bf198 100755 --- a/scripts/waste.py +++ b/scripts/waste.py @@ -6,7 +6,7 @@ from multiprocessing import Process from setproctitle import setproctitle # pylint: disable=no-name-in-module def waste(core): - os.sched_setaffinity(0, [core,]) + os.sched_setaffinity(0, [core,]) # pylint: disable=no-member m1 = np.zeros((200, 200)) + 0.8 m2 = np.zeros((200, 200)) + 1.2 diff --git a/selfdrive/assets/body/awake.gif b/selfdrive/assets/body/awake.gif new file mode 100644 index 0000000000..7ec67055dd Binary files /dev/null and b/selfdrive/assets/body/awake.gif differ diff --git a/selfdrive/assets/body/sleep.gif b/selfdrive/assets/body/sleep.gif new file mode 100644 index 0000000000..469cc80338 Binary files /dev/null and b/selfdrive/assets/body/sleep.gif differ diff --git a/selfdrive/assets/compress-images.sh b/selfdrive/assets/compress-images.sh index 607b27c2a8..8601b2d61b 100755 --- a/selfdrive/assets/compress-images.sh +++ b/selfdrive/assets/compress-images.sh @@ -2,3 +2,6 @@ echo "compressing training guide images" optipng -o7 -strip all training/* training_wide/* + +# This can sometimes provide smaller images +# mogrify -quality 100 -format jpg training_wide/* training/* diff --git a/selfdrive/assets/fonts/JetBrainsMono-Medium.ttf b/selfdrive/assets/fonts/JetBrainsMono-Medium.ttf new file mode 100644 index 0000000000..a6ba5529af Binary files /dev/null and b/selfdrive/assets/fonts/JetBrainsMono-Medium.ttf differ diff --git a/selfdrive/assets/fonts/opensans_bold.ttf b/selfdrive/assets/fonts/opensans_bold.ttf deleted file mode 100644 index 7b52945603..0000000000 Binary files a/selfdrive/assets/fonts/opensans_bold.ttf and /dev/null differ diff --git a/selfdrive/assets/fonts/opensans_regular.ttf b/selfdrive/assets/fonts/opensans_regular.ttf deleted file mode 100644 index 2e31d02424..0000000000 Binary files a/selfdrive/assets/fonts/opensans_regular.ttf and /dev/null differ diff --git a/selfdrive/assets/fonts/opensans_semibold.ttf b/selfdrive/assets/fonts/opensans_semibold.ttf deleted file mode 100644 index 99db86aa02..0000000000 Binary files a/selfdrive/assets/fonts/opensans_semibold.ttf and /dev/null differ diff --git a/selfdrive/assets/images/button_flag.png b/selfdrive/assets/images/button_flag.png new file mode 100644 index 0000000000..cac4db6d4c Binary files /dev/null and b/selfdrive/assets/images/button_flag.png differ diff --git a/selfdrive/assets/img_couch.svg b/selfdrive/assets/img_couch.svg new file mode 100644 index 0000000000..2e86012809 --- /dev/null +++ b/selfdrive/assets/img_couch.svg @@ -0,0 +1,4 @@ + + + + diff --git a/selfdrive/assets/img_experimental.svg b/selfdrive/assets/img_experimental.svg new file mode 100644 index 0000000000..0eaec3b3cd --- /dev/null +++ b/selfdrive/assets/img_experimental.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/selfdrive/assets/img_experimental_grey.svg b/selfdrive/assets/img_experimental_grey.svg new file mode 100644 index 0000000000..dc87105ac5 --- /dev/null +++ b/selfdrive/assets/img_experimental_grey.svg @@ -0,0 +1,4 @@ + + + + diff --git a/selfdrive/assets/img_experimental_white.svg b/selfdrive/assets/img_experimental_white.svg new file mode 100644 index 0000000000..ae4f18fde2 --- /dev/null +++ b/selfdrive/assets/img_experimental_white.svg @@ -0,0 +1,4 @@ + + + + diff --git a/selfdrive/assets/navigation/direction_turn_left_inactive.png b/selfdrive/assets/navigation/direction_turn_left_inactive.png new file mode 100644 index 0000000000..2946984acd Binary files /dev/null and b/selfdrive/assets/navigation/direction_turn_left_inactive.png differ diff --git a/selfdrive/assets/navigation/direction_turn_right_inactive.png b/selfdrive/assets/navigation/direction_turn_right_inactive.png new file mode 100644 index 0000000000..7d327766af Binary files /dev/null and b/selfdrive/assets/navigation/direction_turn_right_inactive.png differ diff --git a/selfdrive/assets/navigation/direction_turn_straight_inactive.png b/selfdrive/assets/navigation/direction_turn_straight_inactive.png new file mode 100644 index 0000000000..4c567966ee Binary files /dev/null and b/selfdrive/assets/navigation/direction_turn_straight_inactive.png differ diff --git a/selfdrive/assets/offroad/icon_disengage_on_accelerator.svg b/selfdrive/assets/offroad/icon_disengage_on_accelerator.svg new file mode 100644 index 0000000000..0175e672c6 --- /dev/null +++ b/selfdrive/assets/offroad/icon_disengage_on_accelerator.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/selfdrive/assets/offroad/icon_openpilot_mirrored.png b/selfdrive/assets/offroad/icon_openpilot_mirrored.png deleted file mode 100644 index 23a7d5a552..0000000000 Binary files a/selfdrive/assets/offroad/icon_openpilot_mirrored.png and /dev/null differ diff --git a/selfdrive/assets/sounds/prompt.wav b/selfdrive/assets/sounds/prompt.wav index 420e9fabee..1ae77051eb 100644 Binary files a/selfdrive/assets/sounds/prompt.wav and b/selfdrive/assets/sounds/prompt.wav differ diff --git a/selfdrive/assets/training/step0.png b/selfdrive/assets/training/step0.png index 8ea90610d1..b942703b5d 100644 Binary files a/selfdrive/assets/training/step0.png and b/selfdrive/assets/training/step0.png differ diff --git a/selfdrive/assets/training/step1.png b/selfdrive/assets/training/step1.png index 22a629beaa..e2c9f9f60e 100644 Binary files a/selfdrive/assets/training/step1.png and b/selfdrive/assets/training/step1.png differ diff --git a/selfdrive/assets/training/step10.png b/selfdrive/assets/training/step10.png index 96390aa324..c5ed8fd624 100644 Binary files a/selfdrive/assets/training/step10.png and b/selfdrive/assets/training/step10.png differ diff --git a/selfdrive/assets/training/step11.png b/selfdrive/assets/training/step11.png index 94342a4b5b..4776593922 100644 Binary files a/selfdrive/assets/training/step11.png and b/selfdrive/assets/training/step11.png differ diff --git a/selfdrive/assets/training/step12.png b/selfdrive/assets/training/step12.png index 8b2b01af21..497170c978 100644 Binary files a/selfdrive/assets/training/step12.png and b/selfdrive/assets/training/step12.png differ diff --git a/selfdrive/assets/training/step13.png b/selfdrive/assets/training/step13.png index 6593b93d79..228d7549d4 100644 Binary files a/selfdrive/assets/training/step13.png and b/selfdrive/assets/training/step13.png differ diff --git a/selfdrive/assets/training/step14.png b/selfdrive/assets/training/step14.png index 1cb8fb9921..7f8da0552b 100644 Binary files a/selfdrive/assets/training/step14.png and b/selfdrive/assets/training/step14.png differ diff --git a/selfdrive/assets/training/step15.png b/selfdrive/assets/training/step15.png index b4c0841b71..9aa861c9fa 100644 Binary files a/selfdrive/assets/training/step15.png and b/selfdrive/assets/training/step15.png differ diff --git a/selfdrive/assets/training/step16.png b/selfdrive/assets/training/step16.png index d8518b10b5..e0b36b0337 100644 Binary files a/selfdrive/assets/training/step16.png and b/selfdrive/assets/training/step16.png differ diff --git a/selfdrive/assets/training/step17.png b/selfdrive/assets/training/step17.png index a9ab912697..c6b33c237e 100644 Binary files a/selfdrive/assets/training/step17.png and b/selfdrive/assets/training/step17.png differ diff --git a/selfdrive/assets/training/step18.png b/selfdrive/assets/training/step18.png index a5d8833a32..bd062d4cc0 100644 Binary files a/selfdrive/assets/training/step18.png and b/selfdrive/assets/training/step18.png differ diff --git a/selfdrive/assets/training/step2.png b/selfdrive/assets/training/step2.png index 03a45f8de9..97c2eb0f4b 100644 Binary files a/selfdrive/assets/training/step2.png and b/selfdrive/assets/training/step2.png differ diff --git a/selfdrive/assets/training/step3.png b/selfdrive/assets/training/step3.png index 0712678ac9..7489722316 100644 Binary files a/selfdrive/assets/training/step3.png and b/selfdrive/assets/training/step3.png differ diff --git a/selfdrive/assets/training/step4.png b/selfdrive/assets/training/step4.png index 60a99310fd..8139349ff7 100644 Binary files a/selfdrive/assets/training/step4.png and b/selfdrive/assets/training/step4.png differ diff --git a/selfdrive/assets/training/step5.png b/selfdrive/assets/training/step5.png index 54aa049dd1..714162ae1f 100644 Binary files a/selfdrive/assets/training/step5.png and b/selfdrive/assets/training/step5.png differ diff --git a/selfdrive/assets/training/step6.png b/selfdrive/assets/training/step6.png index 80cbb0a558..356d76a3e8 100644 Binary files a/selfdrive/assets/training/step6.png and b/selfdrive/assets/training/step6.png differ diff --git a/selfdrive/assets/training/step7.png b/selfdrive/assets/training/step7.png index e5e403df22..ac09faffe8 100644 Binary files a/selfdrive/assets/training/step7.png and b/selfdrive/assets/training/step7.png differ diff --git a/selfdrive/assets/training/step8.png b/selfdrive/assets/training/step8.png index d5193ae333..f081ac6e45 100644 Binary files a/selfdrive/assets/training/step8.png and b/selfdrive/assets/training/step8.png differ diff --git a/selfdrive/assets/training/step9.png b/selfdrive/assets/training/step9.png index 10dadc2ae0..540dafe787 100644 Binary files a/selfdrive/assets/training/step9.png and b/selfdrive/assets/training/step9.png differ diff --git a/selfdrive/assets/training_wide/step0.png b/selfdrive/assets/training_wide/step0.png index cff6d4f88b..3c2c5c72a0 100644 Binary files a/selfdrive/assets/training_wide/step0.png and b/selfdrive/assets/training_wide/step0.png differ diff --git a/selfdrive/assets/training_wide/step1.png b/selfdrive/assets/training_wide/step1.png index e81e2ce801..0857893118 100644 Binary files a/selfdrive/assets/training_wide/step1.png and b/selfdrive/assets/training_wide/step1.png differ diff --git a/selfdrive/assets/training_wide/step10.png b/selfdrive/assets/training_wide/step10.png index c595f602a1..2941316d17 100644 Binary files a/selfdrive/assets/training_wide/step10.png and b/selfdrive/assets/training_wide/step10.png differ diff --git a/selfdrive/assets/training_wide/step11.png b/selfdrive/assets/training_wide/step11.png index 26680b9021..7a7c72e3df 100644 Binary files a/selfdrive/assets/training_wide/step11.png and b/selfdrive/assets/training_wide/step11.png differ diff --git a/selfdrive/assets/training_wide/step12.png b/selfdrive/assets/training_wide/step12.png index c93ea6b251..0d6f64eb84 100644 Binary files a/selfdrive/assets/training_wide/step12.png and b/selfdrive/assets/training_wide/step12.png differ diff --git a/selfdrive/assets/training_wide/step13.png b/selfdrive/assets/training_wide/step13.png index 103b6db974..565e02fa3f 100644 Binary files a/selfdrive/assets/training_wide/step13.png and b/selfdrive/assets/training_wide/step13.png differ diff --git a/selfdrive/assets/training_wide/step14.png b/selfdrive/assets/training_wide/step14.png index cf4f35b724..225231cbaa 100644 Binary files a/selfdrive/assets/training_wide/step14.png and b/selfdrive/assets/training_wide/step14.png differ diff --git a/selfdrive/assets/training_wide/step15.png b/selfdrive/assets/training_wide/step15.png index 29999f0ada..929c759b26 100644 Binary files a/selfdrive/assets/training_wide/step15.png and b/selfdrive/assets/training_wide/step15.png differ diff --git a/selfdrive/assets/training_wide/step16.png b/selfdrive/assets/training_wide/step16.png index 601ff4eb03..161af863aa 100644 Binary files a/selfdrive/assets/training_wide/step16.png and b/selfdrive/assets/training_wide/step16.png differ diff --git a/selfdrive/assets/training_wide/step17.png b/selfdrive/assets/training_wide/step17.png index d110451af2..1b0cdb6fbc 100644 Binary files a/selfdrive/assets/training_wide/step17.png and b/selfdrive/assets/training_wide/step17.png differ diff --git a/selfdrive/assets/training_wide/step18.png b/selfdrive/assets/training_wide/step18.png index c1ce4ec1e3..0e3b64bab5 100644 Binary files a/selfdrive/assets/training_wide/step18.png and b/selfdrive/assets/training_wide/step18.png differ diff --git a/selfdrive/assets/training_wide/step2.png b/selfdrive/assets/training_wide/step2.png index ac03677ef5..55814b8ef9 100644 Binary files a/selfdrive/assets/training_wide/step2.png and b/selfdrive/assets/training_wide/step2.png differ diff --git a/selfdrive/assets/training_wide/step3.png b/selfdrive/assets/training_wide/step3.png index 70649b82b9..831095b0ae 100644 Binary files a/selfdrive/assets/training_wide/step3.png and b/selfdrive/assets/training_wide/step3.png differ diff --git a/selfdrive/assets/training_wide/step4.png b/selfdrive/assets/training_wide/step4.png index 3f393ca797..5433034939 100644 Binary files a/selfdrive/assets/training_wide/step4.png and b/selfdrive/assets/training_wide/step4.png differ diff --git a/selfdrive/assets/training_wide/step5.png b/selfdrive/assets/training_wide/step5.png index a26ecbf1eb..7191b63a0c 100644 Binary files a/selfdrive/assets/training_wide/step5.png and b/selfdrive/assets/training_wide/step5.png differ diff --git a/selfdrive/assets/training_wide/step6.png b/selfdrive/assets/training_wide/step6.png index bb1b116022..8eafd4a198 100644 Binary files a/selfdrive/assets/training_wide/step6.png and b/selfdrive/assets/training_wide/step6.png differ diff --git a/selfdrive/assets/training_wide/step7.png b/selfdrive/assets/training_wide/step7.png index 8a3d930811..502f5f1b2e 100644 Binary files a/selfdrive/assets/training_wide/step7.png and b/selfdrive/assets/training_wide/step7.png differ diff --git a/selfdrive/assets/training_wide/step8.png b/selfdrive/assets/training_wide/step8.png index c559d6a6c1..c4e8668332 100644 Binary files a/selfdrive/assets/training_wide/step8.png and b/selfdrive/assets/training_wide/step8.png differ diff --git a/selfdrive/assets/training_wide/step9.png b/selfdrive/assets/training_wide/step9.png index 19b2d483d7..84eae3a066 100644 Binary files a/selfdrive/assets/training_wide/step9.png and b/selfdrive/assets/training_wide/step9.png differ diff --git a/selfdrive/athena/athenad.py b/selfdrive/athena/athenad.py index 7250754d54..5b351ca0f5 100755 --- a/selfdrive/athena/athenad.py +++ b/selfdrive/athena/athenad.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 import base64 +import bz2 import hashlib import io import json @@ -30,13 +31,13 @@ from common.api import Api from common.basedir import PERSIST from common.file_helpers import CallbackReader from common.params import Params -from common.realtime import sec_since_boot -from selfdrive.hardware import HARDWARE, PC, TICI +from common.realtime import sec_since_boot, set_core_affinity +from system.hardware import HARDWARE, PC, AGNOS from selfdrive.loggerd.config import ROOT from selfdrive.loggerd.xattr_cache import getxattr, setxattr from selfdrive.statsd import STATS_DIR -from selfdrive.swaglog import SWAGLOG_DIR, cloudlog -from selfdrive.version import get_commit, get_origin, get_short_branch, get_version +from system.swaglog import SWAGLOG_DIR, cloudlog +from system.version import get_commit, get_origin, get_short_branch, get_version ATHENA_HOST = os.getenv('ATHENA_HOST', 'wss://athena.comma.ai') HANDLER_THREADS = int(os.getenv('HANDLER_THREADS', "4")) @@ -64,6 +65,13 @@ UploadItem = namedtuple('UploadItem', ['path', 'url', 'headers', 'created_at', ' cur_upload_items: Dict[int, Any] = {} + +def strip_bz2_extension(fn): + if fn.endswith('.bz2'): + return fn[:-4] + return fn + + class AbortTransferException(Exception): pass @@ -163,8 +171,6 @@ def upload_handler(end_event: threading.Event) -> None: sm = messaging.SubMaster(['deviceState']) tid = threading.get_ident() - cellular_unmetered = Params().get_bool("CellularUnmetered") - while not end_event.is_set(): cur_upload_items[tid] = None @@ -181,46 +187,45 @@ def upload_handler(end_event: threading.Event) -> None: cloudlog.event("athena.upload_handler.expired", item=cur_upload_items[tid], error=True) continue - # Check if uploading over cell is allowed + # Check if uploading over metered connection is allowed sm.update(0) - cell = sm['deviceState'].networkType not in [NetworkType.wifi, NetworkType.ethernet] - if cell and (not cur_upload_items[tid].allow_cellular) and (not cellular_unmetered): + metered = sm['deviceState'].networkMetered + network_type = sm['deviceState'].networkType.raw + if metered and (not cur_upload_items[tid].allow_cellular): retry_upload(tid, end_event, False) continue try: def cb(sz, cur): - # Abort transfer if connection changed to cell after starting upload + # Abort transfer if connection changed to metered after starting upload sm.update(0) - cell = sm['deviceState'].networkType not in [NetworkType.wifi, NetworkType.ethernet] - if cell and (not cur_upload_items[tid].allow_cellular) and (not cellular_unmetered): + metered = sm['deviceState'].networkMetered + if metered and (not cur_upload_items[tid].allow_cellular): raise AbortTransferException cur_upload_items[tid] = cur_upload_items[tid]._replace(progress=cur / sz if sz else 1) - - network_type = sm['deviceState'].networkType.raw fn = cur_upload_items[tid].path try: sz = os.path.getsize(fn) except OSError: sz = -1 - cloudlog.event("athena.upload_handler.upload_start", fn=fn, sz=sz, network_type=network_type) + cloudlog.event("athena.upload_handler.upload_start", fn=fn, sz=sz, network_type=network_type, metered=metered, retry_count=cur_upload_items[tid].retry_count) response = _do_upload(cur_upload_items[tid], cb) - if response.status_code not in (200, 201, 403, 412): - cloudlog.event("athena.upload_handler.retry", status_code=response.status_code, fn=fn, sz=sz, network_type=network_type) + if response.status_code not in (200, 201, 401, 403, 412): + cloudlog.event("athena.upload_handler.retry", status_code=response.status_code, fn=fn, sz=sz, network_type=network_type, metered=metered) retry_upload(tid, end_event) else: - cloudlog.event("athena.upload_handler.success", fn=fn, sz=sz, network_type=network_type) + cloudlog.event("athena.upload_handler.success", fn=fn, sz=sz, network_type=network_type, metered=metered) UploadQueueCache.cache(upload_queue) except (requests.exceptions.Timeout, requests.exceptions.ConnectionError, requests.exceptions.SSLError): - cloudlog.event("athena.upload_handler.timeout", fn=fn, sz=sz, network_type=network_type) + cloudlog.event("athena.upload_handler.timeout", fn=fn, sz=sz, network_type=network_type, metered=metered) retry_upload(tid, end_event) except AbortTransferException: - cloudlog.event("athena.upload_handler.abort", fn=fn, sz=sz, network_type=network_type) + cloudlog.event("athena.upload_handler.abort", fn=fn, sz=sz, network_type=network_type, metered=metered) retry_upload(tid, end_event, False) except queue.Empty: @@ -230,14 +235,29 @@ def upload_handler(end_event: threading.Event) -> None: def _do_upload(upload_item, callback=None): - with open(upload_item.path, "rb") as f: - size = os.fstat(f.fileno()).st_size + path = upload_item.path + compress = False + + # If file does not exist, but does exist without the .bz2 extension we will compress on the fly + if not os.path.exists(path) and os.path.exists(strip_bz2_extension(path)): + path = strip_bz2_extension(path) + compress = True + + with open(path, "rb") as f: + if compress: + cloudlog.event("athena.upload_handler.compress", fn=path, fn_orig=upload_item.path) + data = bz2.compress(f.read()) + size = len(data) + data = io.BytesIO(data) + else: + size = os.fstat(f.fileno()).st_size + data = f if callback: - f = CallbackReader(f, callback, size) + data = CallbackReader(data, callback, size) return requests.put(upload_item.url, - data=f, + data=data, headers={**upload_item.headers, 'Content-Length': str(size)}, timeout=30) @@ -258,12 +278,12 @@ def getMessage(service=None, timeout=1000): @dispatcher.add_method -def getVersion(): +def getVersion() -> Dict[str, str]: return { "version": get_version(), - "remote": get_origin(), - "branch": get_short_branch(), - "commit": get_commit(), + "remote": get_origin(''), + "branch": get_short_branch(''), + "commit": get_commit(default=''), } @@ -338,11 +358,17 @@ def uploadFilesToUrls(files_data): if len(fn) == 0 or fn[0] == '/' or '..' in fn or 'url' not in file: failed.append(fn) continue + path = os.path.join(ROOT, fn) - if not os.path.exists(path): + if not os.path.exists(path) and not os.path.exists(strip_bz2_extension(path)): failed.append(fn) continue + # Skip item if already in queue + url = file['url'].split('?')[0] + if any(url == item['url'].split('?')[0] for item in listUploadQueue()): + continue + item = UploadItem( path=path, url=file['url'], @@ -392,8 +418,8 @@ def primeActivated(activated): @dispatcher.add_method def setBandwithLimit(upload_speed_kbps, download_speed_kbps): - if not TICI: - return {"success": 0, "error": "only supported on comma three"} + if not AGNOS: + return {"success": 0, "error": "only supported on AGNOS"} try: HARDWARE.set_bandwidth_limit(upload_speed_kbps, download_speed_kbps) @@ -418,7 +444,7 @@ def startLocalProxy(global_end_event, remote_ws_uri, local_port): ssock, csock = socket.socketpair() local_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) local_sock.connect(('127.0.0.1', local_port)) - local_sock.setblocking(0) + local_sock.setblocking(False) proxy_end_event = threading.Event() threads = [ @@ -459,6 +485,12 @@ def getNetworkType(): return HARDWARE.get_network_type() +@dispatcher.add_method +def getNetworkMetered(): + network_type = HARDWARE.get_network_type() + return HARDWARE.get_network_metered(network_type) + + @dispatcher.add_method def getNetworks(): return HARDWARE.get_networks() @@ -466,7 +498,7 @@ def getNetworks(): @dispatcher.add_method def takeSnapshot(): - from selfdrive.camerad.snapshot.snapshot import jpeg_write, snapshot + from system.camerad.snapshot.snapshot import jpeg_write, snapshot ret = snapshot() if ret is not None: def b64jpeg(x): @@ -677,6 +709,11 @@ def backoff(retries): def main(): + try: + set_core_affinity([0, 1, 2, 3]) + except Exception: + cloudlog.exception("failed to set core affinity") + params = Params() dongle_id = params.get("DongleId", encoding='utf-8') UploadQueueCache.initialize(upload_queue) @@ -693,7 +730,6 @@ def main(): enable_multithread=True, timeout=30.0) cloudlog.event("athenad.main.connected_ws", ws_uri=ws_uri) - params.delete("PrimeRedirected") conn_retries = 0 cur_upload_items.clear() @@ -703,23 +739,14 @@ def main(): break except (ConnectionError, TimeoutError, WebSocketException): conn_retries += 1 - params.delete("PrimeRedirected") - params.delete("LastAthenaPingTime") + params.remove("LastAthenaPingTime") except socket.timeout: - try: - r = requests.get("http://api.commadotai.com/v1/me", allow_redirects=False, - headers={"User-Agent": f"openpilot-{get_version()}"}, timeout=15.0) - if r.status_code == 302 and r.headers['Location'].startswith("http://u.web2go.com"): - params.put_bool("PrimeRedirected", True) - except Exception: - cloudlog.exception("athenad.socket_timeout.exception") - params.delete("LastAthenaPingTime") + params.remove("LastAthenaPingTime") except Exception: cloudlog.exception("athenad.main.exception") conn_retries += 1 - params.delete("PrimeRedirected") - params.delete("LastAthenaPingTime") + params.remove("LastAthenaPingTime") time.sleep(backoff(conn_retries)) diff --git a/selfdrive/athena/manage_athenad.py b/selfdrive/athena/manage_athenad.py index 58ad58310f..59ca2430ce 100755 --- a/selfdrive/athena/manage_athenad.py +++ b/selfdrive/athena/manage_athenad.py @@ -5,8 +5,8 @@ from multiprocessing import Process from common.params import Params from selfdrive.manager.process import launcher -from selfdrive.swaglog import cloudlog -from selfdrive.version import get_version, is_dirty +from system.swaglog import cloudlog +from system.version import get_version, is_dirty ATHENA_MGR_PID_PARAM = "AthenadPid" @@ -27,7 +27,7 @@ def main(): except Exception: cloudlog.exception("manage_athenad.exception") finally: - params.delete(ATHENA_MGR_PID_PARAM) + params.remove(ATHENA_MGR_PID_PARAM) if __name__ == '__main__': diff --git a/selfdrive/athena/registration.py b/selfdrive/athena/registration.py index 10f5d46f77..32bc92059c 100755 --- a/selfdrive/athena/registration.py +++ b/selfdrive/athena/registration.py @@ -3,6 +3,7 @@ import time import json import jwt from pathlib import Path +from typing import Optional from datetime import datetime, timedelta from common.api import api_get @@ -10,8 +11,8 @@ from common.params import Params from common.spinner import Spinner from common.basedir import PERSIST from selfdrive.controls.lib.alertmanager import set_offroad_alert -from selfdrive.hardware import HARDWARE, PC -from selfdrive.swaglog import cloudlog +from system.hardware import HARDWARE, PC +from system.swaglog import cloudlog UNREGISTERED_DONGLE_ID = "UnregisteredDevice" @@ -22,13 +23,13 @@ def is_registered_device() -> bool: return dongle not in (None, UNREGISTERED_DONGLE_ID) -def register(show_spinner=False) -> str: +def register(show_spinner=False) -> Optional[str]: params = Params() params.put("SubscriberInfo", HARDWARE.get_subscriber_info()) IMEI = params.get("IMEI", encoding='utf8') HardwareSerial = params.get("HardwareSerial", encoding='utf8') - dongle_id = params.get("DongleId", encoding='utf8') + dongle_id: Optional[str] = params.get("DongleId", encoding='utf8') needs_registration = None in (IMEI, HardwareSerial, dongle_id) pubkey = Path(PERSIST+"/comma/id_rsa.pub") @@ -48,7 +49,8 @@ def register(show_spinner=False) -> str: # Block until we get the imei serial = HARDWARE.get_serial() start_time = time.monotonic() - imei1, imei2 = None, None + imei1: Optional[str] = None + imei2: Optional[str] = None while imei1 is None and imei2 is None: try: imei1, imei2 = HARDWARE.get_imei(0), HARDWARE.get_imei(1) diff --git a/selfdrive/athena/tests/helpers.py b/selfdrive/athena/tests/helpers.py index bb5fcd1063..a43527c260 100644 --- a/selfdrive/athena/tests/helpers.py +++ b/selfdrive/athena/tests/helpers.py @@ -53,8 +53,8 @@ class MockParams(): default_params = { "DongleId": b"0000000000000000", "GithubSshKeys": b"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC307aE+nuHzTAgaJhzSf5v7ZZQW9gaperjhCmyPyl4PzY7T1mDGenTlVTN7yoVFZ9UfO9oMQqo0n1OwDIiqbIFxqnhrHU0cYfj88rI85m5BEKlNu5RdaVTj1tcbaPpQc5kZEolaI1nDDjzV0lwS7jo5VYDHseiJHlik3HH1SgtdtsuamGR2T80q1SyW+5rHoMOJG73IH2553NnWuikKiuikGHUYBd00K1ilVAK2xSiMWJp55tQfZ0ecr9QjEsJ+J/efL4HqGNXhffxvypCXvbUYAFSddOwXUPo5BTKevpxMtH+2YrkpSjocWA04VnTYFiPG6U4ItKmbLOTFZtPzoez private", # noqa: E501 + "GsmMetered": True, "AthenadUploadQueue": '[]', - "CellularUnmetered": False, } params = default_params.copy() @@ -116,7 +116,7 @@ def with_http_server(func): with Timeout(2, 'HTTP Server seeding failed'): while True: try: - requests.put(f'http://{host}:{port}/qlog.bz2', data='') + requests.put(f'http://{host}:{port}/qlog.bz2', data='', timeout=10) break except requests.exceptions.ConnectionError: time.sleep(0.1) diff --git a/selfdrive/athena/tests/test_athenad.py b/selfdrive/athena/tests/test_athenad.py index 1742ed4347..5e86a2e821 100755 --- a/selfdrive/athena/tests/test_athenad.py +++ b/selfdrive/athena/tests/test_athenad.py @@ -9,6 +9,7 @@ import threading import queue import unittest from datetime import datetime, timedelta +from typing import Optional from multiprocessing import Process from pathlib import Path @@ -16,7 +17,7 @@ from unittest import mock from websocket import ABNF from websocket._exceptions import WebSocketConnectionClosedException -from selfdrive import swaglog +from system import swaglog from selfdrive.athena import athenad from selfdrive.athena.athenad import MAX_RETRY_COUNT, dispatcher from selfdrive.athena.tests.helpers import MockWebsocket, MockParams, MockApi, EchoSocket, with_http_server @@ -46,12 +47,26 @@ class TestAthenadMethods(unittest.TestCase): else: os.unlink(p) - def wait_for_upload(self): + + # *** test helpers *** + + @staticmethod + def _wait_for_upload(): now = time.time() while time.time() - now < 5: if athenad.upload_queue.qsize() == 0: break + @staticmethod + def _create_file(file: str, parent: Optional[str] = None) -> str: + fn = os.path.join(athenad.ROOT if parent is None else parent, file) + os.makedirs(os.path.dirname(fn), exist_ok=True) + Path(fn).touch() + return fn + + + # *** test cases *** + def test_echo(self): assert dispatcher["echo"]("bob") == "bob" @@ -81,12 +96,11 @@ class TestAthenadMethods(unittest.TestCase): def test_listDataDirectory(self): route = '2021-03-29--13-32-47' segments = [0, 1, 2, 3, 11] - filenames = ['qlog.bz2', 'qcamera.ts', 'rlog.bz2', 'fcamera.hevc', 'ecamera.hevc', 'dcamera.hevc'] + + filenames = ['qlog', 'qcamera.ts', 'rlog', 'fcamera.hevc', 'ecamera.hevc', 'dcamera.hevc'] files = [f'{route}--{s}/{f}' for s in segments for f in filenames] for file in files: - fn = os.path.join(athenad.ROOT, file) - os.makedirs(os.path.dirname(fn), exist_ok=True) - Path(fn).touch() + self._create_file(file) resp = dispatcher["listDataDirectory"]() self.assertTrue(resp, 'list empty!') @@ -119,10 +133,15 @@ class TestAthenadMethods(unittest.TestCase): self.assertTrue(resp, 'list empty!') self.assertCountEqual(resp, expected) + def test_strip_bz2_extension(self): + fn = self._create_file('qlog.bz2') + if fn.endswith('.bz2'): + self.assertEqual(athenad.strip_bz2_extension(fn), fn[:-4]) + + @with_http_server def test_do_upload(self, host): - fn = os.path.join(athenad.ROOT, 'qlog.bz2') - Path(fn).touch() + fn = self._create_file('qlog.bz2') item = athenad.UploadItem(path=fn, url="http://localhost:1238", headers={}, created_at=int(time.time()*1000), id='') with self.assertRaises(requests.exceptions.ConnectionError): @@ -134,11 +153,7 @@ class TestAthenadMethods(unittest.TestCase): @with_http_server def test_uploadFileToUrl(self, host): - not_exists_resp = dispatcher["uploadFileToUrl"]("does_not_exist.bz2", "http://localhost:1238", {}) - self.assertEqual(not_exists_resp, {'enqueued': 0, 'items': [], 'failed': ['does_not_exist.bz2']}) - - fn = os.path.join(athenad.ROOT, 'qlog.bz2') - Path(fn).touch() + fn = self._create_file('qlog.bz2') resp = dispatcher["uploadFileToUrl"]("qlog.bz2", f"{host}/qlog.bz2", {}) self.assertEqual(resp['enqueued'], 1) @@ -147,10 +162,26 @@ class TestAthenadMethods(unittest.TestCase): self.assertIsNotNone(resp['items'][0].get('id')) self.assertEqual(athenad.upload_queue.qsize(), 1) + @with_http_server + def test_uploadFileToUrl_duplicate(self, host): + self._create_file('qlog.bz2') + + url1 = f"{host}/qlog.bz2?sig=sig1" + dispatcher["uploadFileToUrl"]("qlog.bz2", url1, {}) + + # Upload same file again, but with different signature + url2 = f"{host}/qlog.bz2?sig=sig2" + resp = dispatcher["uploadFileToUrl"]("qlog.bz2", url2, {}) + self.assertEqual(resp, {'enqueued': 0, 'items': []}) + + @with_http_server + def test_uploadFileToUrl_does_not_exist(self, host): + not_exists_resp = dispatcher["uploadFileToUrl"]("does_not_exist.bz2", "http://localhost:1238", {}) + self.assertEqual(not_exists_resp, {'enqueued': 0, 'items': [], 'failed': ['does_not_exist.bz2']}) + @with_http_server def test_upload_handler(self, host): - fn = os.path.join(athenad.ROOT, 'qlog.bz2') - Path(fn).touch() + fn = self._create_file('qlog.bz2') item = athenad.UploadItem(path=fn, url=f"{host}/qlog.bz2", headers={}, created_at=int(time.time()*1000), id='', allow_cellular=True) end_event = threading.Event() @@ -159,7 +190,7 @@ class TestAthenadMethods(unittest.TestCase): athenad.upload_queue.put_nowait(item) try: - self.wait_for_upload() + self._wait_for_upload() time.sleep(0.1) # TODO: verify that upload actually succeeded @@ -172,8 +203,7 @@ class TestAthenadMethods(unittest.TestCase): def test_upload_handler_retry(self, host, mock_put): for status, retry in ((500, True), (412, False)): mock_put.return_value.status_code = status - fn = os.path.join(athenad.ROOT, 'qlog.bz2') - Path(fn).touch() + fn = self._create_file('qlog.bz2') item = athenad.UploadItem(path=fn, url=f"{host}/qlog.bz2", headers={}, created_at=int(time.time()*1000), id='', allow_cellular=True) end_event = threading.Event() @@ -182,7 +212,7 @@ class TestAthenadMethods(unittest.TestCase): athenad.upload_queue.put_nowait(item) try: - self.wait_for_upload() + self._wait_for_upload() time.sleep(0.1) self.assertEqual(athenad.upload_queue.qsize(), 1 if retry else 0) @@ -194,8 +224,7 @@ class TestAthenadMethods(unittest.TestCase): def test_upload_handler_timeout(self): """When an upload times out or fails to connect it should be placed back in the queue""" - fn = os.path.join(athenad.ROOT, 'qlog.bz2') - Path(fn).touch() + fn = self._create_file('qlog.bz2') item = athenad.UploadItem(path=fn, url="http://localhost:44444/qlog.bz2", headers={}, created_at=int(time.time()*1000), id='', allow_cellular=True) item_no_retry = item._replace(retry_count=MAX_RETRY_COUNT) @@ -205,14 +234,14 @@ class TestAthenadMethods(unittest.TestCase): try: athenad.upload_queue.put_nowait(item_no_retry) - self.wait_for_upload() + self._wait_for_upload() time.sleep(0.1) # Check that upload with retry count exceeded is not put back self.assertEqual(athenad.upload_queue.qsize(), 0) athenad.upload_queue.put_nowait(item) - self.wait_for_upload() + self._wait_for_upload() time.sleep(0.1) # Check that upload item was put back in the queue with incremented retry count @@ -233,7 +262,7 @@ class TestAthenadMethods(unittest.TestCase): thread = threading.Thread(target=athenad.upload_handler, args=(end_event,)) thread.start() try: - self.wait_for_upload() + self._wait_for_upload() time.sleep(0.1) self.assertEqual(athenad.upload_queue.qsize(), 0) @@ -246,8 +275,7 @@ class TestAthenadMethods(unittest.TestCase): ts = int(t_future.strftime("%s")) * 1000 # Item that would time out if actually uploaded - fn = os.path.join(athenad.ROOT, 'qlog.bz2') - Path(fn).touch() + fn = self._create_file('qlog.bz2') item = athenad.UploadItem(path=fn, url="http://localhost:44444/qlog.bz2", headers={}, created_at=ts, id='', allow_cellular=True) @@ -256,7 +284,7 @@ class TestAthenadMethods(unittest.TestCase): thread.start() try: athenad.upload_queue.put_nowait(item) - self.wait_for_upload() + self._wait_for_upload() time.sleep(0.1) self.assertEqual(athenad.upload_queue.qsize(), 0) @@ -269,8 +297,7 @@ class TestAthenadMethods(unittest.TestCase): @with_http_server def test_listUploadQueueCurrent(self, host): - fn = os.path.join(athenad.ROOT, 'qlog.bz2') - Path(fn).touch() + fn = self._create_file('qlog.bz2') item = athenad.UploadItem(path=fn, url=f"{host}/qlog.bz2", headers={}, created_at=int(time.time()*1000), id='', allow_cellular=True) end_event = threading.Event() @@ -279,7 +306,7 @@ class TestAthenadMethods(unittest.TestCase): try: athenad.upload_queue.put_nowait(item) - self.wait_for_upload() + self._wait_for_upload() items = dispatcher["listUploadQueue"]() self.assertEqual(len(items), 1) @@ -382,9 +409,9 @@ class TestAthenadMethods(unittest.TestCase): def test_get_logs_to_send_sorted(self): fl = list() for i in range(10): - fn = os.path.join(swaglog.SWAGLOG_DIR, f'swaglog.{i:010}') - Path(fn).touch() - fl.append(os.path.basename(fn)) + file = f'swaglog.{i:010}' + self._create_file(file, athenad.SWAGLOG_DIR) + fl.append(file) # ensure the list is all logs except most recent sl = athenad.get_logs_to_send_sorted() diff --git a/selfdrive/boardd/SConscript b/selfdrive/boardd/SConscript index 922107509a..d99e67a9f0 100644 --- a/selfdrive/boardd/SConscript +++ b/selfdrive/boardd/SConscript @@ -1,9 +1,9 @@ Import('env', 'envCython', 'common', 'cereal', 'messaging') libs = ['usb-1.0', common, cereal, messaging, 'pthread', 'zmq', 'capnp', 'kj'] -env.Program('boardd', ['main.cc', 'boardd.cc', 'panda.cc', 'pigeon.cc'], LIBS=libs) +env.Program('boardd', ['main.cc', 'boardd.cc', 'panda.cc', 'panda_comms.cc', 'spi.cc'], LIBS=libs) env.Library('libcan_list_to_can_capnp', ['can_list_to_can_capnp.cc']) envCython.Program('boardd_api_impl.so', 'boardd_api_impl.pyx', LIBS=["can_list_to_can_capnp", 'capnp', 'kj'] + envCython["LIBS"]) if GetOption('test'): - env.Program('tests/test_boardd_usbprotocol', ['tests/test_boardd_usbprotocol.cc', 'panda.cc'], LIBS=libs) + env.Program('tests/test_boardd_usbprotocol', ['tests/test_boardd_usbprotocol.cc', 'panda.cc', 'panda_comms.cc', 'spi.cc'], LIBS=libs) diff --git a/selfdrive/boardd/boardd.cc b/selfdrive/boardd/boardd.cc index e8ace77a1d..1f1249194d 100644 --- a/selfdrive/boardd/boardd.cc +++ b/selfdrive/boardd/boardd.cc @@ -19,24 +19,20 @@ #include #include -#include - #include "cereal/gen/cpp/car.capnp.h" #include "cereal/messaging/messaging.h" -#include "selfdrive/common/params.h" -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/timing.h" -#include "selfdrive/common/util.h" -#include "selfdrive/hardware/hw.h" - -#include "selfdrive/boardd/pigeon.h" +#include "common/params.h" +#include "common/swaglog.h" +#include "common/timing.h" +#include "common/util.h" +#include "system/hardware/hw.h" // -- Multi-panda conventions -- // Ordering: // - The internal panda will always be the first panda // - Consecutive pandas will be sorted based on panda type, and then serial number // Connecting: -// - If a panda connection is dropped, boardd wil reconnect to all pandas +// - If a panda connection is dropped, boardd will reconnect to all pandas // - If a panda is added, we will only reconnect when we are offroad // CAN buses: // - Each panda will have it's block of 4 buses. E.g.: the second panda will use @@ -46,7 +42,7 @@ // Safety: // - SafetyConfig is a list, which is mapped to the connected pandas // - If there are more pandas connected than there are SafetyConfigs, -// the excess pandas will remain in "silent" ot "noOutput" mode +// the excess pandas will remain in "silent" or "noOutput" mode // Ignition: // - If any of the ignition sources in any panda is high, ignition is high @@ -58,7 +54,6 @@ using namespace std::chrono_literals; std::atomic ignition(false); -std::atomic pigeon_active(false); ExitHandler do_exit; @@ -70,7 +65,7 @@ static std::string get_time_str(const struct tm &time) { bool check_all_connected(const std::vector &pandas) { for (const auto& panda : pandas) { - if (!panda->connected) { + if (!panda->connected()) { do_exit = true; return false; } @@ -115,11 +110,15 @@ bool safety_setter_thread(std::vector pandas) { return false; } - pandas[0]->set_safety_model(cereal::CarParams::SafetyModel::ELM327); + // set to ELM327 for fingerprinting + for (int i = 0; i < pandas.size(); i++) { + const uint16_t safety_param = (i > 0) ? 1U : 0U; + pandas[i]->set_safety_model(cereal::CarParams::SafetyModel::ELM327, safety_param); + } Params p = Params(); - // switch to SILENT when CarVin param is read + // wait for VIN to be read while (true) { if (do_exit || !check_all_connected(pandas) || !ignition) { return false; @@ -135,15 +134,16 @@ bool safety_setter_thread(std::vector pandas) { util::sleep_for(20); } - pandas[0]->set_safety_model(cereal::CarParams::SafetyModel::ELM327, 1); + // set to ELM327 for ECU knockouts + for (Panda *panda : pandas) { + panda->set_safety_model(cereal::CarParams::SafetyModel::ELM327, 1U); + } std::string params; LOGW("waiting for params to set safety model"); while (true) { - for (const auto& panda : pandas) { - if (do_exit || !panda->connected || !ignition) { - return false; - } + if (do_exit || !check_all_connected(pandas) || !ignition) { + return false; } if (p.getBool("ControlsReady")) { @@ -158,10 +158,10 @@ bool safety_setter_thread(std::vector pandas) { capnp::FlatArrayMessageReader cmsg(aligned_buf.align(params.data(), params.size())); cereal::CarParams::Reader car_params = cmsg.getRoot(); cereal::CarParams::SafetyModel safety_model; - int safety_param; + uint16_t safety_param; auto safety_configs = car_params.getSafetyConfigs(); - uint16_t unsafe_mode = car_params.getUnsafeMode(); + uint16_t alternative_experience = car_params.getAlternativeExperience(); for (uint32_t i = 0; i < pandas.size(); i++) { auto panda = pandas[i]; @@ -171,18 +171,18 @@ bool safety_setter_thread(std::vector pandas) { } else { // If no safety mode is specified, default to silent safety_model = cereal::CarParams::SafetyModel::SILENT; - safety_param = 0; + safety_param = 0U; } - LOGW("panda %d: setting safety model: %d, param: %d, unsafe mode: %d", i, (int)safety_model, safety_param, unsafe_mode); - panda->set_unsafe_mode(unsafe_mode); + LOGW("panda %d: setting safety model: %d, param: %d, alternative experience: %d", i, (int)safety_model, safety_param, alternative_experience); + panda->set_alternative_experience(alternative_experience); panda->set_safety_model(safety_model, safety_param); } return true; } -Panda *usb_connect(std::string serial="", uint32_t index=0) { +Panda *connect(std::string serial="", uint32_t index=0) { std::unique_ptr panda; try { panda = std::make_unique(serial, (index * PANDA_BUS_CNT)); @@ -190,15 +190,11 @@ Panda *usb_connect(std::string serial="", uint32_t index=0) { return nullptr; } + // common panda config if (getenv("BOARDD_LOOPBACK")) { panda->set_loopback(true); } - - // power on charging, only the first time. Panda can also change mode and it causes a brief disconneciton -#ifndef __x86_64__ - static std::once_flag connected_once; - std::call_once(connected_once, &Panda::set_usb_power_mode, panda, cereal::PeripheralState::UsbPowerMode::CDP); -#endif + //panda->enable_deepsleep(); sync_time(panda.get(), SyncTimeDir::FROM_PANDA); return panda.release(); @@ -229,7 +225,9 @@ void can_send_thread(std::vector pandas, bool fake_send) { //Dont send if older than 1 second if ((nanos_since_boot() - event.getLogMonoTime() < 1e9) && !fake_send) { for (const auto& panda : pandas) { + LOGT("sending sendcan to panda: %s", (panda->hw_serial).c_str()); panda->can_send(event.getSendcan()); + LOGT("sendcan sent to panda: %s", (panda->hw_serial).c_str()); } } } @@ -296,13 +294,19 @@ void send_empty_panda_state(PubMaster *pm) { std::optional send_panda_states(PubMaster *pm, const std::vector &pandas, bool spoofing_started) { bool ignition_local = false; + const uint32_t pandas_cnt = pandas.size(); // build msg MessageBuilder msg; auto evt = msg.initEvent(); - auto pss = evt.initPandaStates(pandas.size()); + auto pss = evt.initPandaStates(pandas_cnt); std::vector pandaStates; + pandaStates.reserve(pandas_cnt); + + std::vector> pandaCanStates; + pandaCanStates.reserve(pandas_cnt); + for (const auto& panda : pandas){ auto health_opt = panda->get_state(); if (!health_opt) { @@ -311,6 +315,16 @@ std::optional send_panda_states(PubMaster *pm, const std::vector health_t health = *health_opt; + std::array can_health{}; + for (uint32_t i = 0; i < PANDA_CAN_CNT; i++) { + auto can_health_opt = panda->get_can_state(i); + if (!can_health_opt) { + return std::nullopt; + } + can_health[i] = *can_health_opt; + } + pandaCanStates.push_back(can_health); + if (spoofing_started) { health.ignition_line_pkt = 1; } @@ -320,7 +334,7 @@ std::optional send_panda_states(PubMaster *pm, const std::vector pandaStates.push_back(health); } - for (uint32_t i = 0; i < pandas.size(); i++) { + for (uint32_t i = 0; i < pandas_cnt; i++) { auto panda = pandas[i]; const auto &health = pandaStates[i]; @@ -330,7 +344,7 @@ std::optional send_panda_states(PubMaster *pm, const std::vector } #ifndef __x86_64__ - bool power_save_desired = !ignition_local && !pigeon_active; + bool power_save_desired = !ignition_local; if (health.power_save_enabled_pkt != power_save_desired) { panda->set_power_saving(power_save_desired); } @@ -341,20 +355,20 @@ std::optional send_panda_states(PubMaster *pm, const std::vector } #endif - if (!panda->comms_healthy) { + if (!panda->comms_healthy()) { evt.setValid(false); } auto ps = pss[i]; ps.setUptime(health.uptime_pkt); - ps.setBlockedCnt(health.blocked_msg_cnt_pkt); + ps.setSafetyTxBlocked(health.safety_tx_blocked_pkt); + ps.setSafetyRxInvalid(health.safety_rx_invalid_pkt); ps.setIgnitionLine(health.ignition_line_pkt); ps.setIgnitionCan(health.ignition_can_pkt); ps.setControlsAllowed(health.controls_allowed_pkt); ps.setGasInterceptorDetected(health.gas_interceptor_detected_pkt); - ps.setCanRxErrs(health.can_rx_errs_pkt); - ps.setCanSendErrs(health.can_send_errs_pkt); - ps.setCanFwdErrs(health.can_fwd_errs_pkt); + ps.setTxBufferOverflow(health.tx_buffer_overflow_pkt); + ps.setRxBufferOverflow(health.rx_buffer_overflow_pkt); ps.setGmlanSendErrs(health.gmlan_send_errs_pkt); ps.setPandaType(panda->hw_type); ps.setSafetyModel(cereal::CarParams::SafetyModel(health.safety_mode_pkt)); @@ -362,8 +376,38 @@ std::optional send_panda_states(PubMaster *pm, const std::vector ps.setFaultStatus(cereal::PandaState::FaultStatus(health.fault_status_pkt)); ps.setPowerSaveEnabled((bool)(health.power_save_enabled_pkt)); ps.setHeartbeatLost((bool)(health.heartbeat_lost_pkt)); - ps.setUnsafeMode(health.unsafe_mode_pkt); + ps.setAlternativeExperience(health.alternative_experience_pkt); ps.setHarnessStatus(cereal::PandaState::HarnessStatus(health.car_harness_status_pkt)); + ps.setInterruptLoad(health.interrupt_load); + ps.setFanPower(health.fan_power); + ps.setSafetyRxChecksInvalid((bool)(health.safety_rx_checks_invalid)); + + std::array cs = {ps.initCanState0(), ps.initCanState1(), ps.initCanState2()}; + + for (uint32_t j = 0; j < PANDA_CAN_CNT; j++) { + const auto &can_health = pandaCanStates[i][j]; + cs[j].setBusOff((bool)can_health.bus_off); + cs[j].setBusOffCnt(can_health.bus_off_cnt); + cs[j].setErrorWarning((bool)can_health.error_warning); + cs[j].setErrorPassive((bool)can_health.error_passive); + cs[j].setLastError(cereal::PandaState::PandaCanState::LecErrorCode(can_health.last_error)); + cs[j].setLastStoredError(cereal::PandaState::PandaCanState::LecErrorCode(can_health.last_stored_error)); + cs[j].setLastDataError(cereal::PandaState::PandaCanState::LecErrorCode(can_health.last_data_error)); + cs[j].setLastDataStoredError(cereal::PandaState::PandaCanState::LecErrorCode(can_health.last_data_stored_error)); + cs[j].setReceiveErrorCnt(can_health.receive_error_cnt); + cs[j].setTransmitErrorCnt(can_health.transmit_error_cnt); + cs[j].setTotalErrorCnt(can_health.total_error_cnt); + cs[j].setTotalTxLostCnt(can_health.total_tx_lost_cnt); + cs[j].setTotalRxLostCnt(can_health.total_rx_lost_cnt); + cs[j].setTotalTxCnt(can_health.total_tx_cnt); + cs[j].setTotalRxCnt(can_health.total_rx_cnt); + cs[j].setTotalFwdCnt(can_health.total_fwd_cnt); + cs[j].setCanSpeed(can_health.can_speed); + cs[j].setCanDataSpeed(can_health.can_data_speed); + cs[j].setCanfdEnabled(can_health.canfd_enabled); + cs[j].setBrsEnabled(can_health.brs_enabled); + cs[j].setCanfdNonIso(can_health.canfd_non_iso); + } // Convert faults bitset to capnp list std::bitset fault_bits(health.faults_pkt); @@ -371,7 +415,7 @@ std::optional send_panda_states(PubMaster *pm, const std::vector size_t j = 0; for (size_t f = size_t(cereal::PandaState::FaultType::RELAY_MALFUNCTION); - f <= size_t(cereal::PandaState::FaultType::INTERRUPT_RATE_TICK); f++) { + f <= size_t(cereal::PandaState::FaultType::INTERRUPT_RATE_EXTI); f++) { if (fault_bits.test(f)) { faults.set(j, cereal::PandaState::FaultType(f)); j++; @@ -384,36 +428,23 @@ std::optional send_panda_states(PubMaster *pm, const std::vector } void send_peripheral_state(PubMaster *pm, Panda *panda) { - auto pandaState_opt = panda->get_state(); - if (!pandaState_opt) { - return; - } - - health_t pandaState = *pandaState_opt; - // build msg MessageBuilder msg; auto evt = msg.initEvent(); - evt.setValid(panda->comms_healthy); + evt.setValid(panda->comms_healthy()); auto ps = evt.initPeripheralState(); ps.setPandaType(panda->hw_type); - if (Hardware::TICI()) { - double read_time = millis_since_boot(); - ps.setVoltage(std::atoi(util::read_file("/sys/class/hwmon/hwmon1/in1_input").c_str())); - ps.setCurrent(std::atoi(util::read_file("/sys/class/hwmon/hwmon1/curr1_input").c_str())); - read_time = millis_since_boot() - read_time; - if (read_time > 50) { - LOGW("reading hwmon took %lfms", read_time); - } - } else { - ps.setVoltage(pandaState.voltage_pkt); - ps.setCurrent(pandaState.current_pkt); + double read_time = millis_since_boot(); + ps.setVoltage(Hardware::get_voltage()); + ps.setCurrent(Hardware::get_current()); + read_time = millis_since_boot() - read_time; + if (read_time > 50) { + LOGW("reading hwmon took %lfms", read_time); } uint16_t fan_speed_rpm = panda->get_fan_speed(); - ps.setUsbPowerMode(cereal::PeripheralState::UsbPowerMode(pandaState.usb_power_mode_pkt)); ps.setFanSpeedRpm(fan_speed_rpm); pm->send("peripheralState", msg); @@ -480,7 +511,7 @@ void panda_state_thread(PubMaster *pm, std::vector pandas, bool spoofin } -void peripheral_control_thread(Panda *panda) { +void peripheral_control_thread(Panda *panda, bool no_fan_control) { util::set_thread_name("boardd_peripheral_control"); SubMaster sm({"deviceState", "driverCameraState"}); @@ -489,33 +520,15 @@ void peripheral_control_thread(Panda *panda) { uint16_t prev_fan_speed = 999; uint16_t ir_pwr = 0; uint16_t prev_ir_pwr = 999; - bool prev_charging_disabled = false; unsigned int cnt = 0; FirstOrderFilter integ_lines_filter(0, 30.0, 0.05); - while (!do_exit && panda->connected) { + while (!do_exit && panda->connected()) { cnt++; sm.update(1000); // TODO: what happens if EINTR is sent while in sm.update? - if (!Hardware::PC() && sm.updated("deviceState")) { - // Charging mode - bool charging_disabled = sm["deviceState"].getDeviceState().getChargingDisabled(); - if (charging_disabled != prev_charging_disabled) { - if (charging_disabled) { - panda->set_usb_power_mode(cereal::PeripheralState::UsbPowerMode::CLIENT); - LOGW("TURN OFF CHARGING!\n"); - } else { - panda->set_usb_power_mode(cereal::PeripheralState::UsbPowerMode::CDP); - LOGW("TURN ON CHARGING!\n"); - } - prev_charging_disabled = charging_disabled; - } - } - - // Other pandas don't have fan/IR to control - if (panda->hw_type != cereal::PandaState::PandaType::UNO && panda->hw_type != cereal::PandaState::PandaType::DOS) continue; - if (sm.updated("deviceState")) { + if (sm.updated("deviceState") && !no_fan_control) { // Fan speed uint16_t fan_speed = sm["deviceState"].getDeviceState().getFanSpeedPercentDesired(); if (fan_speed != prev_fan_speed || cnt % 100 == 0) { @@ -523,14 +536,13 @@ void peripheral_control_thread(Panda *panda) { prev_fan_speed = fan_speed; } } + if (sm.updated("driverCameraState")) { auto event = sm["driverCameraState"]; int cur_integ_lines = event.getDriverCameraState().getIntegLines(); float cur_gain = event.getDriverCameraState().getGain(); - if (Hardware::TICI()) { - cur_integ_lines = integ_lines_filter.update(cur_integ_lines * cur_gain); - } + cur_integ_lines = integ_lines_filter.update(cur_integ_lines * cur_gain); last_front_frame_t = event.getLogMonoTime(); if (cur_integ_lines <= CUTOFF_IL) { @@ -541,6 +553,7 @@ void peripheral_control_thread(Panda *panda) { ir_pwr = 100.0 * (MIN_IR_POWER + ((cur_integ_lines - CUTOFF_IL) * (MAX_IR_POWER - MIN_IR_POWER) / (SATURATE_IL - CUTOFF_IL))); } } + // Disable ir_pwr on front frame timeout uint64_t cur_t = nanos_since_boot(); if (cur_t - last_front_frame_t > 1e9) { @@ -559,66 +572,25 @@ void peripheral_control_thread(Panda *panda) { } } -static void pigeon_publish_raw(PubMaster &pm, const std::string &dat) { - // create message - MessageBuilder msg; - msg.initEvent().setUbloxRaw(capnp::Data::Reader((uint8_t*)dat.data(), dat.length())); - pm.send("ubloxRaw", msg); -} - -void pigeon_thread(Panda *panda) { - util::set_thread_name("boardd_pigeon"); - - PubMaster pm({"ubloxRaw"}); - bool ignition_last = false; - - std::unique_ptr pigeon(Hardware::TICI() ? Pigeon::connect("/dev/ttyHS0") : Pigeon::connect(panda)); - - while (!do_exit && panda->connected) { - bool need_reset = false; - bool ignition_local = ignition; - std::string recv = pigeon->receive(); - - // Check based on null bytes - if (ignition_local && recv.length() > 0 && recv[0] == (char)0x00) { - need_reset = true; - LOGW("received invalid ublox message while onroad, resetting panda GPS"); - } +void boardd_main_thread(std::vector serials) { + PubMaster pm({"pandaStates", "peripheralState"}); + LOGW("attempting to connect"); - if (recv.length() > 0) { - pigeon_publish_raw(pm, recv); - } + if (serials.size() == 0) { + // connect to all + serials = Panda::list(); - // init pigeon on rising ignition edge - // since it was turned off in low power mode - if((ignition_local && !ignition_last) || need_reset) { - pigeon_active = true; - pigeon->init(); - } else if (!ignition_local && ignition_last) { - // power off on falling edge of ignition - LOGD("powering off pigeon\n"); - pigeon->stop(); - pigeon->set_power(false); - pigeon_active = false; + // exit if no pandas are connected + if (serials.size() == 0) { + LOGW("no pandas found, exiting"); + return; } - - ignition_last = ignition_local; - - // 10ms - 100 Hz - util::sleep_for(10); } -} -void boardd_main_thread(std::vector serials) { - PubMaster pm({"pandaStates", "peripheralState"}); - LOGW("attempting to connect"); - - if (serials.size() == 0) serials = Panda::list(); - // connect to all provided serials std::vector pandas; for (int i = 0; i < serials.size() && !do_exit; /**/) { - Panda *p = usb_connect(serials[i], i); + Panda *p = connect(serials[i], i); if (!p) { // send empty pandaState & peripheralState and try again send_empty_panda_state(&pm); @@ -636,11 +608,8 @@ void boardd_main_thread(std::vector serials) { Panda *peripheral_panda = pandas[0]; std::vector threads; - Params().put("LastPeripheralPandaType", std::to_string((int) peripheral_panda->get_hw_type())); - threads.emplace_back(panda_state_thread, &pm, pandas, getenv("STARTED") != nullptr); - threads.emplace_back(peripheral_control_thread, peripheral_panda); - threads.emplace_back(pigeon_thread, peripheral_panda); + threads.emplace_back(peripheral_control_thread, peripheral_panda, getenv("NO_FAN_CONTROL") != nullptr); threads.emplace_back(can_send_thread, pandas, getenv("FAKESEND") != nullptr); threads.emplace_back(can_recv_thread, pandas); diff --git a/selfdrive/boardd/main.cc b/selfdrive/boardd/main.cc index d802e42f86..cb17a584bd 100644 --- a/selfdrive/boardd/main.cc +++ b/selfdrive/boardd/main.cc @@ -1,9 +1,9 @@ #include #include "selfdrive/boardd/boardd.h" -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/util.h" -#include "selfdrive/hardware/hw.h" +#include "common/swaglog.h" +#include "common/util.h" +#include "system/hardware/hw.h" int main(int argc, char *argv[]) { LOGW("starting boardd"); @@ -12,7 +12,7 @@ int main(int argc, char *argv[]) { int err; err = util::set_realtime_priority(54); assert(err == 0); - err = util::set_core_affinity({Hardware::TICI() ? 4 : 3}); + err = util::set_core_affinity({4}); assert(err == 0); } diff --git a/selfdrive/boardd/panda.cc b/selfdrive/boardd/panda.cc index 5e621b12cd..3e447c830e 100644 --- a/selfdrive/boardd/panda.cc +++ b/selfdrive/boardd/panda.cc @@ -4,273 +4,67 @@ #include #include -#include #include "cereal/messaging/messaging.h" -#include "panda/board/dlc_to_len.h" -#include "selfdrive/common/gpio.h" -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/util.h" - -static int init_usb_ctx(libusb_context **context) { - assert(context != nullptr); - - int err = libusb_init(context); - if (err != 0) { - LOGE("libusb initialization error"); - return err; - } - -#if LIBUSB_API_VERSION >= 0x01000106 - libusb_set_option(*context, LIBUSB_OPTION_LOG_LEVEL, LIBUSB_LOG_LEVEL_INFO); -#else - libusb_set_debug(*context, 3); -#endif - - return err; -} - +#include "common/swaglog.h" +#include "common/util.h" Panda::Panda(std::string serial, uint32_t bus_offset) : bus_offset(bus_offset) { - // init libusb - ssize_t num_devices; - libusb_device **dev_list = NULL; - int err = init_usb_ctx(&ctx); - if (err != 0) { goto fail; } - - // connect by serial - num_devices = libusb_get_device_list(ctx, &dev_list); - if (num_devices < 0) { goto fail; } - for (size_t i = 0; i < num_devices; ++i) { - libusb_device_descriptor desc; - libusb_get_device_descriptor(dev_list[i], &desc); - if (desc.idVendor == 0xbbaa && desc.idProduct == 0xddcc) { - int ret = libusb_open(dev_list[i], &dev_handle); - if (dev_handle == NULL || ret < 0) { goto fail; } - - unsigned char desc_serial[26] = { 0 }; - ret = libusb_get_string_descriptor_ascii(dev_handle, desc.iSerialNumber, desc_serial, std::size(desc_serial)); - if (ret < 0) { goto fail; } - - usb_serial = std::string((char *)desc_serial, ret).c_str(); - if (serial.empty() || serial == usb_serial) { - break; - } - libusb_close(dev_handle); - dev_handle = NULL; - } - } - if (dev_handle == NULL) goto fail; - libusb_free_device_list(dev_list, 1); - dev_list = nullptr; - - if (libusb_kernel_driver_active(dev_handle, 0) == 1) { - libusb_detach_kernel_driver(dev_handle, 0); + // TODO: support SPI here one day... + if (serial.find("spi") != std::string::npos) { + handle = std::make_unique(serial); + } else { + handle = std::make_unique(serial); } - err = libusb_set_configuration(dev_handle, 1); - if (err != 0) { goto fail; } - - err = libusb_claim_interface(dev_handle, 0); - if (err != 0) { goto fail; } - hw_type = get_hw_type(); assert((hw_type != cereal::PandaState::PandaType::WHITE_PANDA) && (hw_type != cereal::PandaState::PandaType::GREY_PANDA)); has_rtc = (hw_type == cereal::PandaState::PandaType::UNO) || - (hw_type == cereal::PandaState::PandaType::DOS); + (hw_type == cereal::PandaState::PandaType::DOS) || + (hw_type == cereal::PandaState::PandaType::TRES); return; - -fail: - if (dev_list != NULL) { - libusb_free_device_list(dev_list, 1); - } - cleanup(); - throw std::runtime_error("Error connecting to panda"); } -Panda::~Panda() { - std::lock_guard lk(usb_lock); - cleanup(); - connected = false; +bool Panda::connected() { + return handle->connected; } -void Panda::cleanup() { - if (dev_handle) { - libusb_release_interface(dev_handle, 0); - libusb_close(dev_handle); - } - - if (ctx) { - libusb_exit(ctx); - } +bool Panda::comms_healthy() { + return handle->comms_healthy; } std::vector Panda::list() { - // init libusb - ssize_t num_devices; - libusb_context *context = NULL; - libusb_device **dev_list = NULL; - std::vector serials; - - int err = init_usb_ctx(&context); - if (err != 0) { return serials; } - - num_devices = libusb_get_device_list(context, &dev_list); - if (num_devices < 0) { - LOGE("libusb can't get device list"); - goto finish; - } - for (size_t i = 0; i < num_devices; ++i) { - libusb_device *device = dev_list[i]; - libusb_device_descriptor desc; - libusb_get_device_descriptor(device, &desc); - if (desc.idVendor == 0xbbaa && desc.idProduct == 0xddcc) { - libusb_device_handle *handle = NULL; - int ret = libusb_open(device, &handle); - if (ret < 0) { goto finish; } - - unsigned char desc_serial[26] = { 0 }; - ret = libusb_get_string_descriptor_ascii(handle, desc.iSerialNumber, desc_serial, std::size(desc_serial)); - libusb_close(handle); - if (ret < 0) { goto finish; } - - serials.push_back(std::string((char *)desc_serial, ret).c_str()); - } - } - -finish: - if (dev_list != NULL) { - libusb_free_device_list(dev_list, 1); - } - if (context) { - libusb_exit(context); - } - return serials; -} - -void Panda::handle_usb_issue(int err, const char func[]) { - LOGE_100("usb error %d \"%s\" in %s", err, libusb_strerror((enum libusb_error)err), func); - if (err == LIBUSB_ERROR_NO_DEVICE) { - LOGE("lost connection"); - connected = false; - } - // TODO: check other errors, is simply retrying okay? -} - -int Panda::usb_write(uint8_t bRequest, uint16_t wValue, uint16_t wIndex, unsigned int timeout) { - int err; - const uint8_t bmRequestType = LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE; - - if (!connected) { - return LIBUSB_ERROR_NO_DEVICE; - } - - std::lock_guard lk(usb_lock); - do { - err = libusb_control_transfer(dev_handle, bmRequestType, bRequest, wValue, wIndex, NULL, 0, timeout); - if (err < 0) handle_usb_issue(err, __func__); - } while (err < 0 && connected); - - return err; -} - -int Panda::usb_read(uint8_t bRequest, uint16_t wValue, uint16_t wIndex, unsigned char *data, uint16_t wLength, unsigned int timeout) { - int err; - const uint8_t bmRequestType = LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE; - - if (!connected) { - return LIBUSB_ERROR_NO_DEVICE; - } - - std::lock_guard lk(usb_lock); - do { - err = libusb_control_transfer(dev_handle, bmRequestType, bRequest, wValue, wIndex, data, wLength, timeout); - if (err < 0) handle_usb_issue(err, __func__); - } while (err < 0 && connected); - - return err; -} - -int Panda::usb_bulk_write(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout) { - int err; - int transferred = 0; - - if (!connected) { - return 0; - } - - std::lock_guard lk(usb_lock); - do { - // Try sending can messages. If the receive buffer on the panda is full it will NAK - // and libusb will try again. After 5ms, it will time out. We will drop the messages. - err = libusb_bulk_transfer(dev_handle, endpoint, data, length, &transferred, timeout); - - if (err == LIBUSB_ERROR_TIMEOUT) { - LOGW("Transmit buffer full"); - break; - } else if (err != 0 || length != transferred) { - handle_usb_issue(err, __func__); - } - } while(err != 0 && connected); - - return transferred; + return PandaUsbHandle::list(); } -int Panda::usb_bulk_read(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout) { - int err; - int transferred = 0; - - if (!connected) { - return 0; - } - - std::lock_guard lk(usb_lock); - - do { - err = libusb_bulk_transfer(dev_handle, endpoint, data, length, &transferred, timeout); - - if (err == LIBUSB_ERROR_TIMEOUT) { - break; // timeout is okay to exit, recv still happened - } else if (err == LIBUSB_ERROR_OVERFLOW) { - comms_healthy = false; - LOGE_100("overflow got 0x%x", transferred); - } else if (err != 0) { - handle_usb_issue(err, __func__); - } - - } while(err != 0 && connected); - - return transferred; +void Panda::set_safety_model(cereal::CarParams::SafetyModel safety_model, uint16_t safety_param) { + handle->control_write(0xdc, (uint16_t)safety_model, safety_param); } -void Panda::set_safety_model(cereal::CarParams::SafetyModel safety_model, int safety_param) { - usb_write(0xdc, (uint16_t)safety_model, safety_param); -} - -void Panda::set_unsafe_mode(uint16_t unsafe_mode) { - usb_write(0xdf, unsafe_mode, 0); +void Panda::set_alternative_experience(uint16_t alternative_experience) { + handle->control_write(0xdf, alternative_experience, 0); } cereal::PandaState::PandaType Panda::get_hw_type() { unsigned char hw_query[1] = {0}; - usb_read(0xc1, 0, 0, hw_query, 1); + handle->control_read(0xc1, 0, 0, hw_query, 1); return (cereal::PandaState::PandaType)(hw_query[0]); } void Panda::set_rtc(struct tm sys_time) { // tm struct has year defined as years since 1900 - usb_write(0xa1, (uint16_t)(1900 + sys_time.tm_year), 0); - usb_write(0xa2, (uint16_t)(1 + sys_time.tm_mon), 0); - usb_write(0xa3, (uint16_t)sys_time.tm_mday, 0); - // usb_write(0xa4, (uint16_t)(1 + sys_time.tm_wday), 0); - usb_write(0xa5, (uint16_t)sys_time.tm_hour, 0); - usb_write(0xa6, (uint16_t)sys_time.tm_min, 0); - usb_write(0xa7, (uint16_t)sys_time.tm_sec, 0); + handle->control_write(0xa1, (uint16_t)(1900 + sys_time.tm_year), 0); + handle->control_write(0xa2, (uint16_t)(1 + sys_time.tm_mon), 0); + handle->control_write(0xa3, (uint16_t)sys_time.tm_mday, 0); + // handle->control_write(0xa4, (uint16_t)(1 + sys_time.tm_wday), 0); + handle->control_write(0xa5, (uint16_t)sys_time.tm_hour, 0); + handle->control_write(0xa6, (uint16_t)sys_time.tm_min, 0); + handle->control_write(0xa7, (uint16_t)sys_time.tm_sec, 0); } struct tm Panda::get_rtc() { @@ -284,7 +78,7 @@ struct tm Panda::get_rtc() { uint8_t second; } rtc_time = {0}; - usb_read(0xa0, 0, 0, (unsigned char*)&rtc_time, sizeof(rtc_time)); + handle->control_read(0xa0, 0, 0, (unsigned char*)&rtc_time, sizeof(rtc_time)); struct tm new_time = { 0 }; new_time.tm_year = rtc_time.year - 1900; // tm struct has year defined as years since 1900 @@ -298,60 +92,70 @@ struct tm Panda::get_rtc() { } void Panda::set_fan_speed(uint16_t fan_speed) { - usb_write(0xb1, fan_speed, 0); + handle->control_write(0xb1, fan_speed, 0); } uint16_t Panda::get_fan_speed() { uint16_t fan_speed_rpm = 0; - usb_read(0xb2, 0, 0, (unsigned char*)&fan_speed_rpm, sizeof(fan_speed_rpm)); + handle->control_read(0xb2, 0, 0, (unsigned char*)&fan_speed_rpm, sizeof(fan_speed_rpm)); return fan_speed_rpm; } void Panda::set_ir_pwr(uint16_t ir_pwr) { - usb_write(0xb0, ir_pwr, 0); + handle->control_write(0xb0, ir_pwr, 0); } std::optional Panda::get_state() { health_t health {0}; - int err = usb_read(0xd2, 0, 0, (unsigned char*)&health, sizeof(health)); + int err = handle->control_read(0xd2, 0, 0, (unsigned char*)&health, sizeof(health)); return err >= 0 ? std::make_optional(health) : std::nullopt; } +std::optional Panda::get_can_state(uint16_t can_number) { + can_health_t can_health {0}; + int err = handle->control_read(0xc2, can_number, 0, (unsigned char*)&can_health, sizeof(can_health)); + return err >= 0 ? std::make_optional(can_health) : std::nullopt; +} + void Panda::set_loopback(bool loopback) { - usb_write(0xe5, loopback, 0); + handle->control_write(0xe5, loopback, 0); } std::optional> Panda::get_firmware_version() { std::vector fw_sig_buf(128); - int read_1 = usb_read(0xd3, 0, 0, &fw_sig_buf[0], 64); - int read_2 = usb_read(0xd4, 0, 0, &fw_sig_buf[64], 64); + int read_1 = handle->control_read(0xd3, 0, 0, &fw_sig_buf[0], 64); + int read_2 = handle->control_read(0xd4, 0, 0, &fw_sig_buf[64], 64); return ((read_1 == 64) && (read_2 == 64)) ? std::make_optional(fw_sig_buf) : std::nullopt; } std::optional Panda::get_serial() { char serial_buf[17] = {'\0'}; - int err = usb_read(0xd0, 0, 0, (uint8_t*)serial_buf, 16); + int err = handle->control_read(0xd0, 0, 0, (uint8_t*)serial_buf, 16); return err >= 0 ? std::make_optional(serial_buf) : std::nullopt; } void Panda::set_power_saving(bool power_saving) { - usb_write(0xe7, power_saving, 0); + handle->control_write(0xe7, power_saving, 0); } -void Panda::set_usb_power_mode(cereal::PeripheralState::UsbPowerMode power_mode) { - usb_write(0xe6, (uint16_t)power_mode, 0); +void Panda::enable_deepsleep() { + handle->control_write(0xfb, 0, 0); } void Panda::send_heartbeat(bool engaged) { - usb_write(0xf3, engaged, 0); + handle->control_write(0xf3, engaged, 0); } void Panda::set_can_speed_kbps(uint16_t bus, uint16_t speed) { - usb_write(0xde, bus, (speed * 10)); + handle->control_write(0xde, bus, (speed * 10)); } void Panda::set_data_speed_kbps(uint16_t bus, uint16_t speed) { - usb_write(0xf9, bus, (speed * 10)); + handle->control_write(0xf9, bus, (speed * 10)); +} + +void Panda::set_canfd_non_iso(uint16_t bus, bool non_iso) { + handle->control_write(0xfc, bus, non_iso); } static uint8_t len_to_dlc(uint8_t len) { @@ -365,22 +169,15 @@ static uint8_t len_to_dlc(uint8_t len) { } } -static void write_packet(uint8_t *dest, int *write_pos, const uint8_t *src, size_t size) { - for (int i = 0, &pos = *write_pos; i < size; ++i, ++pos) { - // Insert counter every 64 bytes (first byte of 64 bytes USB packet) - if (pos % USBPACKET_MAX_SIZE == 0) { - dest[pos] = pos / USBPACKET_MAX_SIZE; - pos++; - } - dest[pos] = src[i]; - } -} - void Panda::pack_can_buffer(const capnp::List::Reader &can_data_list, std::function write_func) { int32_t pos = 0; uint8_t send_buf[2 * USB_TX_SOFT_LIMIT]; + uint32_t magic = CAN_TRANSACTION_MAGIC; + memcpy(&send_buf[0], &magic, sizeof(uint32_t)); + pos += sizeof(uint32_t); + for (auto cmsg : can_data_list) { // check if the message is intended for this panda uint8_t bus = cmsg.getSrc(); @@ -389,7 +186,7 @@ void Panda::pack_can_buffer(const capnp::List::Reader &can_data } auto can_data = cmsg.getDat(); uint8_t data_len_code = len_to_dlc(can_data.size()); - assert(can_data.size() <= ((hw_type == cereal::PandaState::PandaType::RED_PANDA) ? 64 : 8)); + assert(can_data.size() <= 64); assert(can_data.size() == dlc_to_len[data_len_code]); can_header header; @@ -398,28 +195,31 @@ void Panda::pack_can_buffer(const capnp::List::Reader &can_data header.data_len_code = data_len_code; header.bus = bus - bus_offset; - write_packet(send_buf, &pos, (uint8_t *)&header, sizeof(can_header)); - write_packet(send_buf, &pos, (uint8_t *)can_data.begin(), can_data.size()); + memcpy(&send_buf[pos], (uint8_t *)&header, sizeof(can_header)); + pos += sizeof(can_header); + memcpy(&send_buf[pos], (uint8_t *)can_data.begin(), can_data.size()); + pos += can_data.size(); + if (pos >= USB_TX_SOFT_LIMIT) { write_func(send_buf, pos); - pos = 0; + pos = sizeof(uint32_t); } } // send remaining packets - if (pos > 0) write_func(send_buf, pos); + if (pos > sizeof(uint32_t)) write_func(send_buf, pos); } void Panda::can_send(capnp::List::Reader can_data_list) { pack_can_buffer(can_data_list, [=](uint8_t* data, size_t size) { - usb_bulk_write(3, data, size, 5); + handle->bulk_write(3, data, size, 5); }); } bool Panda::can_receive(std::vector& out_vec) { uint8_t data[RECV_SIZE]; - int recv = usb_bulk_read(0x81, (uint8_t*)data, RECV_SIZE); - if (!comms_healthy) { + int recv = handle->bulk_read(0x81, (uint8_t*)data, RECV_SIZE); + if (!comms_healthy()) { return false; } if (recv == RECV_SIZE) { @@ -430,33 +230,38 @@ bool Panda::can_receive(std::vector& out_vec) { } bool Panda::unpack_can_buffer(uint8_t *data, int size, std::vector &out_vec) { - recv_buf.clear(); - for (int i = 0; i < size; i += USBPACKET_MAX_SIZE) { - if (data[i] != i / USBPACKET_MAX_SIZE) { - LOGE("CAN: MALFORMED USB RECV PACKET"); - comms_healthy = false; - return false; - } - int chunk_len = std::min(USBPACKET_MAX_SIZE, (size - i)); - recv_buf.insert(recv_buf.end(), &data[i + 1], &data[i + chunk_len]); + if (size < sizeof(uint32_t)) { + return true; + } + + uint32_t magic; + memcpy(&magic, &data[0], sizeof(uint32_t)); + if (magic != CAN_TRANSACTION_MAGIC) { + LOGE("CAN recv: buffer didn't start with magic"); + handle->comms_healthy = false; + return false; } - int pos = 0; - while (pos < recv_buf.size()) { + int pos = sizeof(uint32_t); + while (pos < size) { can_header header; - memcpy(&header, &recv_buf[pos], CANPACKET_HEAD_SIZE); + memcpy(&header, &data[pos], sizeof(can_header)); can_frame &canData = out_vec.emplace_back(); canData.busTime = 0; canData.address = header.addr; canData.src = header.bus + bus_offset; - if (header.rejected) { canData.src += CANPACKET_REJECTED; } - if (header.returned) { canData.src += CANPACKET_RETURNED; } + if (header.rejected) { + canData.src += CAN_REJECTED_BUS_OFFSET; + } + if (header.returned) { + canData.src += CAN_RETURNED_BUS_OFFSET; + } const uint8_t data_len = dlc_to_len[header.data_len_code]; - canData.dat.assign((char *)&recv_buf[pos + CANPACKET_HEAD_SIZE], data_len); + canData.dat.assign((char *)&data[pos + sizeof(can_header)], data_len); - pos += CANPACKET_HEAD_SIZE + data_len; + pos += sizeof(can_header) + data_len; } return true; } diff --git a/selfdrive/boardd/panda.h b/selfdrive/boardd/panda.h index dbd866adf4..75fec57a3e 100644 --- a/selfdrive/boardd/panda.h +++ b/selfdrive/boardd/panda.h @@ -1,29 +1,26 @@ #pragma once -#include #include #include #include #include -#include +#include #include #include -#include - #include "cereal/gen/cpp/car.capnp.h" #include "cereal/gen/cpp/log.capnp.h" #include "panda/board/health.h" +#include "panda/board/can_definitions.h" +#include "selfdrive/boardd/panda_comms.h" -#define TIMEOUT 0 -#define PANDA_BUS_CNT 4 -#define RECV_SIZE (0x4000U) #define USB_TX_SOFT_LIMIT (0x100U) #define USBPACKET_MAX_SIZE (0x40) -#define CANPACKET_HEAD_SIZE 5U -#define CANPACKET_MAX_SIZE 72U -#define CANPACKET_REJECTED (0xC0U) -#define CANPACKET_RETURNED (0x80U) + +#define RECV_SIZE (0x4000U) + +#define CAN_REJECTED_BUS_OFFSET 0xC0U +#define CAN_RETURNED_BUS_OFFSET 0x80U struct __attribute__((packed)) can_header { uint8_t reserved : 1; @@ -36,59 +33,51 @@ struct __attribute__((packed)) can_header { }; struct can_frame { - long address; - std::string dat; - long busTime; - long src; + long address; + std::string dat; + long busTime; + long src; }; + class Panda { - private: - libusb_context *ctx = NULL; - libusb_device_handle *dev_handle = NULL; - std::mutex usb_lock; - std::vector recv_buf; - void handle_usb_issue(int err, const char func[]); - void cleanup(); +private: + std::unique_ptr handle; - public: +public: Panda(std::string serial="", uint32_t bus_offset=0); - ~Panda(); - std::string usb_serial; - std::atomic connected = true; - std::atomic comms_healthy = true; + std::string hw_serial; cereal::PandaState::PandaType hw_type = cereal::PandaState::PandaType::UNKNOWN; bool has_rtc = false; const uint32_t bus_offset; + bool connected(); + bool comms_healthy(); + // Static functions static std::vector list(); - // HW communication - int usb_write(uint8_t bRequest, uint16_t wValue, uint16_t wIndex, unsigned int timeout=TIMEOUT); - int usb_read(uint8_t bRequest, uint16_t wValue, uint16_t wIndex, unsigned char *data, uint16_t wLength, unsigned int timeout=TIMEOUT); - int usb_bulk_write(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout=TIMEOUT); - int usb_bulk_read(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout=TIMEOUT); - // Panda functionality cereal::PandaState::PandaType get_hw_type(); - void set_safety_model(cereal::CarParams::SafetyModel safety_model, int safety_param=0); - void set_unsafe_mode(uint16_t unsafe_mode); + void set_safety_model(cereal::CarParams::SafetyModel safety_model, uint16_t safety_param=0U); + void set_alternative_experience(uint16_t alternative_experience); void set_rtc(struct tm sys_time); struct tm get_rtc(); void set_fan_speed(uint16_t fan_speed); uint16_t get_fan_speed(); void set_ir_pwr(uint16_t ir_pwr); std::optional get_state(); + std::optional get_can_state(uint16_t can_number); void set_loopback(bool loopback); std::optional> get_firmware_version(); std::optional get_serial(); void set_power_saving(bool power_saving); - void set_usb_power_mode(cereal::PeripheralState::UsbPowerMode power_mode); + void enable_deepsleep(); void send_heartbeat(bool engaged); void set_can_speed_kbps(uint16_t bus, uint16_t speed); void set_data_speed_kbps(uint16_t bus, uint16_t speed); + void set_canfd_non_iso(uint16_t bus, bool non_iso); void can_send(capnp::List::Reader can_data_list); bool can_receive(std::vector& out_vec); diff --git a/selfdrive/boardd/panda_comms.cc b/selfdrive/boardd/panda_comms.cc new file mode 100644 index 0000000000..e73cb69318 --- /dev/null +++ b/selfdrive/boardd/panda_comms.cc @@ -0,0 +1,232 @@ +#include "selfdrive/boardd/panda.h" + +#include +#include + +#include "common/swaglog.h" + +static int init_usb_ctx(libusb_context **context) { + assert(context != nullptr); + + int err = libusb_init(context); + if (err != 0) { + LOGE("libusb initialization error"); + return err; + } + +#if LIBUSB_API_VERSION >= 0x01000106 + libusb_set_option(*context, LIBUSB_OPTION_LOG_LEVEL, LIBUSB_LOG_LEVEL_INFO); +#else + libusb_set_debug(*context, 3); +#endif + + return err; +} + +PandaUsbHandle::PandaUsbHandle(std::string serial) : PandaCommsHandle(serial) { + // init libusb + ssize_t num_devices; + libusb_device **dev_list = NULL; + int err = init_usb_ctx(&ctx); + if (err != 0) { goto fail; } + + // connect by serial + num_devices = libusb_get_device_list(ctx, &dev_list); + if (num_devices < 0) { goto fail; } + for (size_t i = 0; i < num_devices; ++i) { + libusb_device_descriptor desc; + libusb_get_device_descriptor(dev_list[i], &desc); + if (desc.idVendor == 0xbbaa && desc.idProduct == 0xddcc) { + int ret = libusb_open(dev_list[i], &dev_handle); + if (dev_handle == NULL || ret < 0) { goto fail; } + + unsigned char desc_serial[26] = { 0 }; + ret = libusb_get_string_descriptor_ascii(dev_handle, desc.iSerialNumber, desc_serial, std::size(desc_serial)); + if (ret < 0) { goto fail; } + + auto hw_serial = std::string((char *)desc_serial, ret); + if (serial.empty() || serial == hw_serial) { + break; + } + libusb_close(dev_handle); + dev_handle = NULL; + } + } + if (dev_handle == NULL) goto fail; + libusb_free_device_list(dev_list, 1); + dev_list = nullptr; + + if (libusb_kernel_driver_active(dev_handle, 0) == 1) { + libusb_detach_kernel_driver(dev_handle, 0); + } + + err = libusb_set_configuration(dev_handle, 1); + if (err != 0) { goto fail; } + + err = libusb_claim_interface(dev_handle, 0); + if (err != 0) { goto fail; } + + return; + +fail: + if (dev_list != NULL) { + libusb_free_device_list(dev_list, 1); + } + cleanup(); + throw std::runtime_error("Error connecting to panda"); +} + +PandaUsbHandle::~PandaUsbHandle() { + std::lock_guard lk(hw_lock); + cleanup(); + connected = false; +} + +void PandaUsbHandle::cleanup() { + if (dev_handle) { + libusb_release_interface(dev_handle, 0); + libusb_close(dev_handle); + } + + if (ctx) { + libusb_exit(ctx); + } +} + +std::vector PandaUsbHandle::list() { + // init libusb + ssize_t num_devices; + libusb_context *context = NULL; + libusb_device **dev_list = NULL; + std::vector serials; + + int err = init_usb_ctx(&context); + if (err != 0) { return serials; } + + num_devices = libusb_get_device_list(context, &dev_list); + if (num_devices < 0) { + LOGE("libusb can't get device list"); + goto finish; + } + for (size_t i = 0; i < num_devices; ++i) { + libusb_device *device = dev_list[i]; + libusb_device_descriptor desc; + libusb_get_device_descriptor(device, &desc); + if (desc.idVendor == 0xbbaa && desc.idProduct == 0xddcc) { + libusb_device_handle *handle = NULL; + int ret = libusb_open(device, &handle); + if (ret < 0) { goto finish; } + + unsigned char desc_serial[26] = { 0 }; + ret = libusb_get_string_descriptor_ascii(handle, desc.iSerialNumber, desc_serial, std::size(desc_serial)); + libusb_close(handle); + if (ret < 0) { goto finish; } + + serials.push_back(std::string((char *)desc_serial, ret).c_str()); + } + } + +finish: + if (dev_list != NULL) { + libusb_free_device_list(dev_list, 1); + } + if (context) { + libusb_exit(context); + } + return serials; +} + +void PandaUsbHandle::handle_usb_issue(int err, const char func[]) { + LOGE_100("usb error %d \"%s\" in %s", err, libusb_strerror((enum libusb_error)err), func); + if (err == LIBUSB_ERROR_NO_DEVICE) { + LOGE("lost connection"); + connected = false; + } + // TODO: check other errors, is simply retrying okay? +} + +int PandaUsbHandle::control_write(uint8_t bRequest, uint16_t wValue, uint16_t wIndex, unsigned int timeout) { + int err; + const uint8_t bmRequestType = LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE; + + if (!connected) { + return LIBUSB_ERROR_NO_DEVICE; + } + + std::lock_guard lk(hw_lock); + do { + err = libusb_control_transfer(dev_handle, bmRequestType, bRequest, wValue, wIndex, NULL, 0, timeout); + if (err < 0) handle_usb_issue(err, __func__); + } while (err < 0 && connected); + + return err; +} + +int PandaUsbHandle::control_read(uint8_t bRequest, uint16_t wValue, uint16_t wIndex, unsigned char *data, uint16_t wLength, unsigned int timeout) { + int err; + const uint8_t bmRequestType = LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE; + + if (!connected) { + return LIBUSB_ERROR_NO_DEVICE; + } + + std::lock_guard lk(hw_lock); + do { + err = libusb_control_transfer(dev_handle, bmRequestType, bRequest, wValue, wIndex, data, wLength, timeout); + if (err < 0) handle_usb_issue(err, __func__); + } while (err < 0 && connected); + + return err; +} + +int PandaUsbHandle::bulk_write(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout) { + int err; + int transferred = 0; + + if (!connected) { + return 0; + } + + std::lock_guard lk(hw_lock); + do { + // Try sending can messages. If the receive buffer on the panda is full it will NAK + // and libusb will try again. After 5ms, it will time out. We will drop the messages. + err = libusb_bulk_transfer(dev_handle, endpoint, data, length, &transferred, timeout); + + if (err == LIBUSB_ERROR_TIMEOUT) { + LOGW("Transmit buffer full"); + break; + } else if (err != 0 || length != transferred) { + handle_usb_issue(err, __func__); + } + } while(err != 0 && connected); + + return transferred; +} + +int PandaUsbHandle::bulk_read(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout) { + int err; + int transferred = 0; + + if (!connected) { + return 0; + } + + std::lock_guard lk(hw_lock); + + do { + err = libusb_bulk_transfer(dev_handle, endpoint, data, length, &transferred, timeout); + + if (err == LIBUSB_ERROR_TIMEOUT) { + break; // timeout is okay to exit, recv still happened + } else if (err == LIBUSB_ERROR_OVERFLOW) { + comms_healthy = false; + LOGE_100("overflow got 0x%x", transferred); + } else if (err != 0) { + handle_usb_issue(err, __func__); + } + + } while(err != 0 && connected); + + return transferred; +} diff --git a/selfdrive/boardd/panda_comms.h b/selfdrive/boardd/panda_comms.h new file mode 100644 index 0000000000..bd262dfa0e --- /dev/null +++ b/selfdrive/boardd/panda_comms.h @@ -0,0 +1,77 @@ +#pragma once + +#include +#include +#include +#include + +#include + +#include + + +#define TIMEOUT 0 +#define SPI_BUF_SIZE 1024 + + +// comms base class +class PandaCommsHandle { +public: + PandaCommsHandle(std::string serial) {}; + virtual ~PandaCommsHandle() {}; + virtual void cleanup() = 0; + + std::atomic connected = true; + std::atomic comms_healthy = true; + static std::vector list(); + + // HW communication + virtual int control_write(uint8_t request, uint16_t param1, uint16_t param2, unsigned int timeout=TIMEOUT) = 0; + virtual int control_read(uint8_t request, uint16_t param1, uint16_t param2, unsigned char *data, uint16_t length, unsigned int timeout=TIMEOUT) = 0; + virtual int bulk_write(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout=TIMEOUT) = 0; + virtual int bulk_read(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout=TIMEOUT) = 0; + +protected: + std::recursive_mutex hw_lock; +}; + +class PandaUsbHandle : public PandaCommsHandle { +public: + PandaUsbHandle(std::string serial); + ~PandaUsbHandle(); + int control_write(uint8_t request, uint16_t param1, uint16_t param2, unsigned int timeout=TIMEOUT); + int control_read(uint8_t request, uint16_t param1, uint16_t param2, unsigned char *data, uint16_t length, unsigned int timeout=TIMEOUT); + int bulk_write(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout=TIMEOUT); + int bulk_read(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout=TIMEOUT); + void cleanup(); + + static std::vector list(); + +private: + libusb_context *ctx = NULL; + libusb_device_handle *dev_handle = NULL; + void handle_usb_issue(int err, const char func[]); +}; + +class PandaSpiHandle : public PandaCommsHandle { +public: + PandaSpiHandle(std::string serial); + ~PandaSpiHandle(); + int control_write(uint8_t request, uint16_t param1, uint16_t param2, unsigned int timeout=TIMEOUT); + int control_read(uint8_t request, uint16_t param1, uint16_t param2, unsigned char *data, uint16_t length, unsigned int timeout=TIMEOUT); + int bulk_write(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout=TIMEOUT); + int bulk_read(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout=TIMEOUT); + void cleanup(); + + static std::vector list(); + +private: + int spi_fd = -1; + uint8_t tx_buf[SPI_BUF_SIZE]; + uint8_t rx_buf[SPI_BUF_SIZE]; + + int wait_for_ack(spi_ioc_transfer &transfer, uint8_t ack); + int bulk_transfer(uint8_t endpoint, uint8_t *tx_data, uint16_t tx_len, uint8_t *rx_data, uint16_t rx_len); + int spi_transfer(uint8_t endpoint, uint8_t *tx_data, uint16_t tx_len, uint8_t *rx_data, uint16_t max_rx_len); + int spi_transfer_retry(uint8_t endpoint, uint8_t *tx_data, uint16_t tx_len, uint8_t *rx_data, uint16_t max_rx_len); +}; diff --git a/selfdrive/pandad.py b/selfdrive/boardd/pandad.py similarity index 87% rename from selfdrive/pandad.py rename to selfdrive/boardd/pandad.py index 1f9fddab7a..971756002b 100755 --- a/selfdrive/pandad.py +++ b/selfdrive/boardd/pandad.py @@ -4,13 +4,14 @@ import os import usb1 import time import subprocess -from typing import NoReturn +from typing import List, NoReturn from functools import cmp_to_key from panda import DEFAULT_FW_FN, DEFAULT_H7_FW_FN, MCU_TYPE_H7, Panda, PandaDFU from common.basedir import BASEDIR from common.params import Params -from selfdrive.swaglog import cloudlog +from system.hardware import HARDWARE +from system.swaglog import cloudlog def get_expected_signature(panda: Panda) -> bytes: @@ -27,6 +28,7 @@ def flash_panda(panda_serial: str) -> Panda: panda = Panda(panda_serial) fw_signature = get_expected_signature(panda) + internal_panda = panda.is_internal() and not panda.bootstub panda_version = "bootstub" if panda.bootstub else panda.get_version() panda_signature = b"" if panda.bootstub else panda.get_signature() @@ -40,7 +42,9 @@ def flash_panda(panda_serial: str) -> Panda: if panda.bootstub: bootstub_version = panda.get_version() cloudlog.info(f"Flashed firmware not booting, flashing development bootloader. Bootstub version: {bootstub_version}") - panda.recover() + if internal_panda: + HARDWARE.recover_internal_panda() + panda.recover(reset=(not internal_panda)) cloudlog.info("Done flashing bootloader") if panda.bootstub: @@ -79,7 +83,7 @@ def main() -> NoReturn: while True: try: - params.delete("PandaSignatures") + params.remove("PandaSignatures") # Flash all Pandas in DFU mode for p in PandaDFU.list(): @@ -89,12 +93,16 @@ def main() -> NoReturn: panda_serials = Panda.list() if len(panda_serials) == 0: + if first_run: + cloudlog.info("Resetting internal panda") + HARDWARE.reset_internal_panda() + time.sleep(2) # wait to come back up continue cloudlog.info(f"{len(panda_serials)} panda(s) found, connecting - {panda_serials}") # Flash pandas - pandas = [] + pandas: List[Panda] = [] for serial in panda_serials: pandas.append(flash_panda(serial)) @@ -111,7 +119,7 @@ def main() -> NoReturn: # sort pandas to have deterministic order pandas.sort(key=cmp_to_key(panda_sort_cmp)) - panda_serials = list(map(lambda p: p.get_usb_serial(), pandas)) + panda_serials = list(map(lambda p: p.get_usb_serial(), pandas)) # type: ignore # log panda fw versions params.put("PandaSignatures", b','.join(p.get_signature() for p in pandas)) @@ -127,6 +135,7 @@ def main() -> NoReturn: first_run = False # run boardd with all connected serials as arguments + os.environ['MANAGER_DAEMON'] = 'boardd' os.chdir(os.path.join(BASEDIR, "selfdrive/boardd")) subprocess.run(["./boardd", *panda_serials], check=True) diff --git a/selfdrive/boardd/pigeon.cc b/selfdrive/boardd/pigeon.cc deleted file mode 100644 index 912f4b03e7..0000000000 --- a/selfdrive/boardd/pigeon.cc +++ /dev/null @@ -1,333 +0,0 @@ -#include "selfdrive/boardd/pigeon.h" - -#include -#include -#include - -#include -#include -#include - -#include "selfdrive/common/gpio.h" -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/util.h" -#include "selfdrive/locationd/ublox_msg.h" - -// Termios on macos doesn't define all baud rate constants -#ifndef B460800 -#define B460800 0010004 -#endif - -using namespace std::string_literals; - -extern ExitHandler do_exit; - -const std::string ack = "\xb5\x62\x05\x01\x02\x00"; -const std::string nack = "\xb5\x62\x05\x00\x02\x00"; -const std::string sos_save_ack = "\xb5\x62\x09\x14\x08\x00\x02\x00\x00\x00\x01\x00\x00\x00"; -const std::string sos_save_nack = "\xb5\x62\x09\x14\x08\x00\x02\x00\x00\x00\x00\x00\x00\x00"; - -Pigeon * Pigeon::connect(Panda * p) { - PandaPigeon * pigeon = new PandaPigeon(); - pigeon->connect(p); - - return pigeon; -} - -Pigeon * Pigeon::connect(const char * tty) { - TTYPigeon * pigeon = new TTYPigeon(); - pigeon->connect(tty); - - return pigeon; -} - -bool Pigeon::wait_for_ack(const std::string &ack_, const std::string &nack_, int timeout_ms) { - std::string s; - const double start_t = millis_since_boot(); - while (!do_exit) { - s += receive(); - - if (s.find(ack_) != std::string::npos) { - LOGD("Received ACK from ublox"); - return true; - } else if (s.find(nack_) != std::string::npos) { - LOGE("Received NACK from ublox"); - return false; - } else if (s.size() > 0x1000 || ((millis_since_boot() - start_t) > timeout_ms)) { - LOGE("No response from ublox"); - return false; - } - - util::sleep_for(1); // Allow other threads to be scheduled - } - return false; -} - -bool Pigeon::wait_for_ack() { - return wait_for_ack(ack, nack); -} - -bool Pigeon::send_with_ack(const std::string &cmd) { - send(cmd); - return wait_for_ack(); -} - -sos_restore_response Pigeon::wait_for_backup_restore_status(int timeout_ms) { - std::string s; - const double start_t = millis_since_boot(); - while (!do_exit) { - s += receive(); - - size_t position = s.find("\xb5\x62\x09\x14\x08\x00\x03"); - if (position != std::string::npos && s.size() >= (position + 11)) { - return static_cast(s[position + 10]); - } else if (s.size() > 0x1000 || ((millis_since_boot() - start_t) > timeout_ms)) { - LOGE("No backup restore response from ublox"); - return error; - } - - util::sleep_for(1); // Allow other threads to be scheduled - } - return error; -} - -void Pigeon::init() { - for (int i = 0; i < 10; i++) { - if (do_exit) return; - LOGW("panda GPS start"); - - // power off pigeon - set_power(false); - util::sleep_for(100); - - // 9600 baud at init - set_baud(9600); - - // power on pigeon - set_power(true); - util::sleep_for(500); - - // baud rate upping - send("\x24\x50\x55\x42\x58\x2C\x34\x31\x2C\x31\x2C\x30\x30\x30\x37\x2C\x30\x30\x30\x33\x2C\x34\x36\x30\x38\x30\x30\x2C\x30\x2A\x31\x35\x0D\x0A"s); - util::sleep_for(100); - - // set baud rate to 460800 - set_baud(460800); - - // init from ubloxd - // To generate this data, run selfdrive/locationd/test/ubloxd.py - if (!send_with_ack("\xB5\x62\x06\x00\x14\x00\x03\xFF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x01\x00\x00\x00\x00\x00\x1E\x7F"s)) continue; - if (!send_with_ack("\xB5\x62\x06\x00\x14\x00\x00\xFF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x19\x35"s)) continue; - if (!send_with_ack("\xB5\x62\x06\x00\x14\x00\x01\x00\x00\x00\xC0\x08\x00\x00\x00\x08\x07\x00\x01\x00\x01\x00\x00\x00\x00\x00\xF4\x80"s)) continue; - if (!send_with_ack("\xB5\x62\x06\x00\x14\x00\x04\xFF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x1D\x85"s)) continue; - if (!send_with_ack("\xB5\x62\x06\x00\x00\x00\x06\x18"s)) continue; - if (!send_with_ack("\xB5\x62\x06\x00\x01\x00\x01\x08\x22"s)) continue; - if (!send_with_ack("\xB5\x62\x06\x00\x01\x00\x03\x0A\x24"s)) continue; - if (!send_with_ack("\xB5\x62\x06\x08\x06\x00\x64\x00\x01\x00\x00\x00\x79\x10"s)) continue; - if (!send_with_ack("\xB5\x62\x06\x24\x24\x00\x05\x00\x04\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x5A\x63"s)) continue; - if (!send_with_ack("\xB5\x62\x06\x1E\x14\x00\x00\x00\x00\x00\x01\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x3C\x37"s)) continue; - if (!send_with_ack("\xB5\x62\x06\x39\x08\x00\xFF\xAD\x62\xAD\x1E\x63\x00\x00\x83\x0C"s)) continue; - if (!send_with_ack("\xB5\x62\x06\x24\x00\x00\x2A\x84"s)) continue; - if (!send_with_ack("\xB5\x62\x06\x23\x00\x00\x29\x81"s)) continue; - if (!send_with_ack("\xB5\x62\x06\x1E\x00\x00\x24\x72"s)) continue; - if (!send_with_ack("\xB5\x62\x06\x39\x00\x00\x3F\xC3"s)) continue; - if (!send_with_ack("\xB5\x62\x06\x01\x03\x00\x01\x07\x01\x13\x51"s)) continue; - if (!send_with_ack("\xB5\x62\x06\x01\x03\x00\x02\x15\x01\x22\x70"s)) continue; - if (!send_with_ack("\xB5\x62\x06\x01\x03\x00\x02\x13\x01\x20\x6C"s)) continue; - if (!send_with_ack("\xB5\x62\x06\x01\x03\x00\x0A\x09\x01\x1E\x70"s)) continue; - if (!send_with_ack("\xB5\x62\x06\x01\x03\x00\x0A\x0B\x01\x20\x74"s)) continue; - - // check the backup restore status - send("\xB5\x62\x09\x14\x00\x00\x1D\x60"s); - sos_restore_response restore_status = wait_for_backup_restore_status(); - switch(restore_status) { - case restored: - LOGW("almanac backup restored"); - // clear the backup - send_with_ack("\xB5\x62\x06\x01\x03\x00\x0A\x0B\x01\x20\x74"s); - break; - case no_backup: - LOGW("no almanac backup found"); - break; - default: - LOGE("failed to restore almanac backup, status: %d", restore_status); - } - - auto time = util::get_time(); - if (util::time_valid(time)) { - LOGW("Sending current time to ublox"); - send(ublox::build_ubx_mga_ini_time_utc(time)); - } - - LOGW("panda GPS on"); - return; - } - LOGE("failed to initialize panda GPS"); -} - -void Pigeon::stop() { - LOGW("Storing almanac in ublox flash"); - - // Controlled GNSS stop - send("\xB5\x62\x06\x04\x04\x00\x00\x00\x08\x00\x16\x74"s); - - // Store almanac in flash - send("\xB5\x62\x09\x14\x04\x00\x00\x00\x00\x00\x21\xEC"s); - - if (wait_for_ack(sos_save_ack, sos_save_nack)) { - LOGW("Done storing almanac"); - } else { - LOGE("Error storing almanac"); - } -} - -void PandaPigeon::connect(Panda * p) { - panda = p; -} - -void PandaPigeon::set_baud(int baud) { - panda->usb_write(0xe2, 1, 0); - panda->usb_write(0xe4, 1, baud/300); -} - -void PandaPigeon::send(const std::string &s) { - int len = s.length(); - const char * dat = s.data(); - - unsigned char a[0x20+1]; - a[0] = 1; - for (int i=0; iusb_bulk_write(2, a, ll+1); - } -} - -std::string PandaPigeon::receive() { - std::string r; - r.reserve(0x1000 + 0x40); - unsigned char dat[0x40]; - while (r.length() < 0x1000) { - int len = panda->usb_read(0xe0, 1, 0, dat, sizeof(dat)); - if (len <= 0) break; - r.append((char*)dat, len); - } - - return r; -} - -void PandaPigeon::set_power(bool power) { - panda->usb_write(0xd9, power, 0); -} - -PandaPigeon::~PandaPigeon() { -} - -void handle_tty_issue(int err, const char func[]) { - LOGE_100("tty error %d \"%s\" in %s", err, strerror(err), func); -} - -void TTYPigeon::connect(const char * tty) { - pigeon_tty_fd = HANDLE_EINTR(open(tty, O_RDWR)); - if (pigeon_tty_fd < 0) { - handle_tty_issue(errno, __func__); - assert(pigeon_tty_fd >= 0); - } - int err = tcgetattr(pigeon_tty_fd, &pigeon_tty); - assert(err == 0); - - // configure tty - pigeon_tty.c_cflag &= ~PARENB; // disable parity - pigeon_tty.c_cflag &= ~CSTOPB; // single stop bit - pigeon_tty.c_cflag |= CS8; // 8 bits per byte - pigeon_tty.c_cflag &= ~CRTSCTS; // no RTS/CTS flow control - pigeon_tty.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines - pigeon_tty.c_lflag &= ~ICANON; // disable canonical mode - pigeon_tty.c_lflag &= ~ISIG; // disable interpretation of INTR, QUIT and SUSP - pigeon_tty.c_iflag &= ~(IXON | IXOFF | IXANY); // turn off software flow ctrl - pigeon_tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL); // disable any special handling of received bytes - pigeon_tty.c_oflag &= ~OPOST; // prevent special interpretation of output bytes - pigeon_tty.c_oflag &= ~ONLCR; // prevent conversion of newline to carriage return/line feed - - // configure blocking behavior - pigeon_tty.c_cc[VMIN] = 0; // min amount of characters returned - pigeon_tty.c_cc[VTIME] = 0; // max blocking time in s/10 (0=inf) - - err = tcsetattr(pigeon_tty_fd, TCSANOW, &pigeon_tty); - assert(err == 0); -} - -void TTYPigeon::set_baud(int baud) { - speed_t baud_const = 0; - switch(baud) { - case 9600: - baud_const = B9600; - break; - case 460800: - baud_const = B460800; - break; - default: - assert(false); - } - - // make sure everything is tx'ed before changing baud - int err = tcdrain(pigeon_tty_fd); - assert(err == 0); - - // change baud - err = tcgetattr(pigeon_tty_fd, &pigeon_tty); - assert(err == 0); - err = cfsetspeed(&pigeon_tty, baud_const); - assert(err == 0); - err = tcsetattr(pigeon_tty_fd, TCSANOW, &pigeon_tty); - assert(err == 0); - - // flush - err = tcflush(pigeon_tty_fd, TCIOFLUSH); - assert(err == 0); -} - -void TTYPigeon::send(const std::string &s) { - int err = HANDLE_EINTR(write(pigeon_tty_fd, s.data(), s.length())); - - if(err < 0) { handle_tty_issue(err, __func__); } - err = tcdrain(pigeon_tty_fd); - if(err < 0) { handle_tty_issue(err, __func__); } -} - -std::string TTYPigeon::receive() { - std::string r; - r.reserve(0x1000 + 0x40); - char dat[0x40]; - while (r.length() < 0x1000) { - int len = read(pigeon_tty_fd, dat, sizeof(dat)); - if(len < 0) { - handle_tty_issue(len, __func__); - } else if (len == 0) { - break; - } else { - r.append(dat, len); - } - - } - return r; -} - -void TTYPigeon::set_power(bool power) { -#ifdef QCOM2 - int err = 0; - err += gpio_init(GPIO_UBLOX_RST_N, true); - err += gpio_init(GPIO_UBLOX_SAFEBOOT_N, true); - err += gpio_init(GPIO_UBLOX_PWR_EN, true); - - err += gpio_set(GPIO_UBLOX_RST_N, power); - err += gpio_set(GPIO_UBLOX_SAFEBOOT_N, power); - err += gpio_set(GPIO_UBLOX_PWR_EN, power); - assert(err == 0); -#endif -} - -TTYPigeon::~TTYPigeon() { - close(pigeon_tty_fd); -} diff --git a/selfdrive/boardd/pigeon.h b/selfdrive/boardd/pigeon.h deleted file mode 100644 index c9ea4739dc..0000000000 --- a/selfdrive/boardd/pigeon.h +++ /dev/null @@ -1,58 +0,0 @@ -#pragma once - -#include - -#include -#include - -#include "selfdrive/boardd/panda.h" - -enum sos_restore_response : int { - unknown = 0, - failed = 1, - restored = 2, - no_backup = 3, - error = -1 -}; - -class Pigeon { - public: - static Pigeon* connect(Panda * p); - static Pigeon* connect(const char * tty); - virtual ~Pigeon(){}; - - void init(); - void stop(); - bool wait_for_ack(); - bool wait_for_ack(const std::string &ack, const std::string &nack, int timeout_ms = 1000); - bool send_with_ack(const std::string &cmd); - sos_restore_response wait_for_backup_restore_status(int timeout_ms = 1000); - virtual void set_baud(int baud) = 0; - virtual void send(const std::string &s) = 0; - virtual std::string receive() = 0; - virtual void set_power(bool power) = 0; -}; - -class PandaPigeon : public Pigeon { - Panda * panda = NULL; -public: - ~PandaPigeon(); - void connect(Panda * p); - void set_baud(int baud); - void send(const std::string &s); - std::string receive(); - void set_power(bool power); -}; - - -class TTYPigeon : public Pigeon { - int pigeon_tty_fd = -1; - struct termios pigeon_tty; -public: - ~TTYPigeon(); - void connect(const char* tty); - void set_baud(int baud); - void send(const std::string &s); - std::string receive(); - void set_power(bool power); -}; diff --git a/selfdrive/boardd/spi.cc b/selfdrive/boardd/spi.cc new file mode 100644 index 0000000000..717b6ce820 --- /dev/null +++ b/selfdrive/boardd/spi.cc @@ -0,0 +1,296 @@ +#include +#include + +#include +#include +#include + +#include "common/util.h" +#include "common/timing.h" +#include "common/swaglog.h" +#include "panda/board/comms_definitions.h" +#include "selfdrive/boardd/panda_comms.h" + + +#define SPI_SYNC 0x5AU +#define SPI_HACK 0x79U +#define SPI_DACK 0x85U +#define SPI_NACK 0x1FU +#define SPI_CHECKSUM_START 0xABU + +struct __attribute__((packed)) spi_header { + uint8_t sync; + uint8_t endpoint; + uint16_t tx_len; + uint16_t max_rx_len; +}; + +const int SPI_MAX_RETRIES = 5; +const int SPI_ACK_TIMEOUT = 50; // milliseconds + + +PandaSpiHandle::PandaSpiHandle(std::string serial) : PandaCommsHandle(serial) { + LOGD("opening SPI panda: %s", serial.c_str()); + + int err; + uint32_t spi_mode = SPI_MODE_0; + uint32_t spi_speed = 30000000; + uint8_t spi_bits_per_word = 8; + + spi_fd = open(serial.c_str(), O_RDWR); + if (spi_fd < 0) { + LOGE("failed opening SPI device %d", err); + goto fail; + } + + // SPI settings + err = util::safe_ioctl(spi_fd, SPI_IOC_WR_MODE, &spi_mode); + if (err < 0) { + LOGE("failed setting SPI mode %d", err); + goto fail; + } + + err = util::safe_ioctl(spi_fd, SPI_IOC_WR_MAX_SPEED_HZ, &spi_speed); + if (err < 0) { + LOGE("failed setting SPI speed"); + goto fail; + } + + err = util::safe_ioctl(spi_fd, SPI_IOC_WR_BITS_PER_WORD, &spi_bits_per_word); + if (err < 0) { + LOGE("failed setting SPI bits per word"); + goto fail; + } + + return; + +fail: + cleanup(); + throw std::runtime_error("Error connecting to panda"); +} + +PandaSpiHandle::~PandaSpiHandle() { + std::lock_guard lk(hw_lock); + cleanup(); +} + +void PandaSpiHandle::cleanup() { + if (spi_fd != -1) { + close(spi_fd); + spi_fd = -1; + } +} + + + +int PandaSpiHandle::control_write(uint8_t request, uint16_t param1, uint16_t param2, unsigned int timeout) { + ControlPacket_t packet = { + .request = request, + .param1 = param1, + .param2 = param2, + .length = 0 + }; + return spi_transfer_retry(0, (uint8_t *) &packet, sizeof(packet), NULL, 0); +} + +int PandaSpiHandle::control_read(uint8_t request, uint16_t param1, uint16_t param2, unsigned char *data, uint16_t length, unsigned int timeout) { + ControlPacket_t packet = { + .request = request, + .param1 = param1, + .param2 = param2, + .length = length + }; + return spi_transfer_retry(0, (uint8_t *) &packet, sizeof(packet), data, length); +} + +int PandaSpiHandle::bulk_write(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout) { + return bulk_transfer(endpoint, data, length, NULL, 0); +} +int PandaSpiHandle::bulk_read(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout) { + return bulk_transfer(endpoint, NULL, 0, data, length); +} + +int PandaSpiHandle::bulk_transfer(uint8_t endpoint, uint8_t *tx_data, uint16_t tx_len, uint8_t *rx_data, uint16_t rx_len) { + std::lock_guard lk(hw_lock); + + const int xfer_size = 0x40 * 15; + + int ret = 0; + uint16_t length = (tx_data != NULL) ? tx_len : rx_len; + for (int i = 0; i < (int)std::ceil((float)length / xfer_size); i++) { + int d; + if (tx_data != NULL) { + int len = std::min(xfer_size, tx_len - (xfer_size * i)); + d = spi_transfer_retry(endpoint, tx_data + (xfer_size * i), len, NULL, 0); + } else { + uint16_t to_read = std::min(xfer_size, rx_len - ret); + d = spi_transfer_retry(endpoint, NULL, 0, rx_data + (xfer_size * i), to_read); + } + + if (d < 0) { + LOGE("SPI: bulk transfer failed with %d", d); + comms_healthy = false; + return -1; + } + + ret += d; + if ((rx_data != NULL) && d < xfer_size) { + break; + } + } + + return ret; +} + +std::vector PandaSpiHandle::list() { + // TODO: list all pandas available over SPI + return {}; +} + +void add_checksum(uint8_t *data, int data_len) { + data[data_len] = SPI_CHECKSUM_START; + for (int i=0; i < data_len; i++) { + data[data_len] ^= data[i]; + } +} + +bool check_checksum(uint8_t *data, int data_len) { + uint8_t checksum = SPI_CHECKSUM_START; + for (uint16_t i = 0U; i < data_len; i++) { + checksum ^= data[i]; + } + return checksum == 0U; +} + + +int PandaSpiHandle::spi_transfer_retry(uint8_t endpoint, uint8_t *tx_data, uint16_t tx_len, uint8_t *rx_data, uint16_t max_rx_len) { + int ret; + + int count = SPI_MAX_RETRIES; + std::lock_guard lk(hw_lock); + do { + // TODO: handle error + ret = spi_transfer(endpoint, tx_data, tx_len, rx_data, max_rx_len); + count--; + } while (ret < 0 && connected && count > 0); + + return ret; +} + +int PandaSpiHandle::wait_for_ack(spi_ioc_transfer &transfer, uint8_t ack) { + double start_millis = millis_since_boot(); + while (true) { + int ret = util::safe_ioctl(spi_fd, SPI_IOC_MESSAGE(1), &transfer); + if (ret < 0) { + LOGE("SPI: failed to send ACK request"); + return ret; + } + + if (rx_buf[0] == ack) { + break; + } else if (rx_buf[0] == SPI_NACK) { + LOGW("SPI: got NACK"); + return -1; + } + + // handle timeout + if (millis_since_boot() - start_millis > SPI_ACK_TIMEOUT) { + LOGE("SPI: timed out waiting for ACK"); + return -1; + } + } + + return 0; +} + +int PandaSpiHandle::spi_transfer(uint8_t endpoint, uint8_t *tx_data, uint16_t tx_len, uint8_t *rx_data, uint16_t max_rx_len) { + int ret; + uint16_t rx_data_len; + + // needs to be less, since we need to have space for the checksum + assert(tx_len < SPI_BUF_SIZE); + assert(max_rx_len < SPI_BUF_SIZE); + + spi_header header = { + .sync = SPI_SYNC, + .endpoint = endpoint, + .tx_len = tx_len, + .max_rx_len = max_rx_len + }; + + spi_ioc_transfer transfer = { + .tx_buf = (uint64_t)tx_buf, + .rx_buf = (uint64_t)rx_buf + }; + + // Send header + memcpy(tx_buf, &header, sizeof(header)); + add_checksum(tx_buf, sizeof(header)); + transfer.len = sizeof(header) + 1; + ret = util::safe_ioctl(spi_fd, SPI_IOC_MESSAGE(1), &transfer); + if (ret < 0) { + LOGE("SPI: failed to send header"); + goto transfer_fail; + } + + // Wait for (N)ACK + tx_buf[0] = 0x12; + transfer.len = 1; + ret = wait_for_ack(transfer, SPI_HACK); + if (ret < 0) { + goto transfer_fail; + } + + // Send data + if (tx_data != NULL) { + memcpy(tx_buf, tx_data, tx_len); + } + add_checksum(tx_buf, tx_len); + transfer.len = tx_len + 1; + ret = util::safe_ioctl(spi_fd, SPI_IOC_MESSAGE(1), &transfer); + if (ret < 0) { + LOGE("SPI: failed to send data"); + goto transfer_fail; + } + + // Wait for (N)ACK + tx_buf[0] = 0xab; + transfer.len = 1; + ret = wait_for_ack(transfer, SPI_DACK); + if (ret < 0) { + goto transfer_fail; + } + + // Read data len + transfer.len = 2; + transfer.rx_buf = (uint64_t)(rx_buf + 1); + ret = util::safe_ioctl(spi_fd, SPI_IOC_MESSAGE(1), &transfer); + if (ret < 0) { + LOGE("SPI: failed to read rx data len"); + goto transfer_fail; + } + rx_data_len = *(uint16_t *)(rx_buf+1); + assert(rx_data_len < SPI_BUF_SIZE); + + // Read data + transfer.len = rx_data_len + 1; + transfer.rx_buf = (uint64_t)(rx_buf + 2 + 1); + ret = util::safe_ioctl(spi_fd, SPI_IOC_MESSAGE(1), &transfer); + if (ret < 0) { + LOGE("SPI: failed to read rx data"); + goto transfer_fail; + } + if (!check_checksum(rx_buf, rx_data_len + 4)) { + LOGE("SPI: bad checksum"); + goto transfer_fail; + } + + if (rx_data != NULL) { + memcpy(rx_data, rx_buf + 3, rx_data_len); + } + + return rx_data_len; + +transfer_fail: + return ret; +} diff --git a/selfdrive/boardd/tests/boardd_old.py b/selfdrive/boardd/tests/boardd_old.py deleted file mode 100755 index 5e740fbcd8..0000000000 --- a/selfdrive/boardd/tests/boardd_old.py +++ /dev/null @@ -1,245 +0,0 @@ -#!/usr/bin/env python3 -# pylint: skip-file - -# This file is not used by openpilot. Only boardd.cc is used. -# The python version is slower, but has more options for development. - -# TODO: merge the extra functionalities of this file (like MOCK) in boardd.c and -# delete this python version of boardd - -import os -import struct -import time - -import cereal.messaging as messaging -from common.realtime import Ratekeeper -from selfdrive.swaglog import cloudlog -from selfdrive.boardd.boardd import can_capnp_to_can_list -from cereal import car - -SafetyModel = car.CarParams.SafetyModel - -# USB is optional -try: - import usb1 - from usb1 import USBErrorIO, USBErrorOverflow # pylint: disable=no-name-in-module -except Exception: - pass - -# *** serialization functions *** -def can_list_to_can_capnp(can_msgs, msgtype='can'): - dat = messaging.new_message(msgtype, len(can_msgs)) - for i, can_msg in enumerate(can_msgs): - if msgtype == 'sendcan': - cc = dat.sendcan[i] - else: - cc = dat.can[i] - cc.address = can_msg[0] - cc.busTime = can_msg[1] - cc.dat = bytes(can_msg[2]) - cc.src = can_msg[3] - return dat - - -# *** can driver *** -def can_health(): - while 1: - try: - dat = handle.controlRead(usb1.TYPE_VENDOR | usb1.RECIPIENT_DEVICE, 0xd2, 0, 0, 0x16) - break - except (USBErrorIO, USBErrorOverflow): - cloudlog.exception("CAN: BAD HEALTH, RETRYING") - v, i = struct.unpack("II", dat[0:8]) - ign_line, ign_can = struct.unpack("BB", dat[20:22]) - return {"voltage": v, "current": i, "ignition_line": bool(ign_line), "ignition_can": bool(ign_can)} - -def __parse_can_buffer(dat): - ret = [] - for j in range(0, len(dat), 0x10): - ddat = dat[j:j+0x10] - f1, f2 = struct.unpack("II", ddat[0:8]) - ret.append((f1 >> 21, f2 >> 16, ddat[8:8 + (f2 & 0xF)], (f2 >> 4) & 0xFF)) - return ret - -def can_send_many(arr): - snds = [] - for addr, _, dat, alt in arr: - if addr < 0x800: # only support 11 bit addr - snd = struct.pack("II", ((addr << 21) | 1), len(dat) | (alt << 4)) + dat - snd = snd.ljust(0x10, b'\x00') - snds.append(snd) - while 1: - try: - handle.bulkWrite(3, b''.join(snds)) - break - except (USBErrorIO, USBErrorOverflow): - cloudlog.exception("CAN: BAD SEND MANY, RETRYING") - -def can_recv(): - dat = b"" - while 1: - try: - dat = handle.bulkRead(1, 0x10*256) - break - except (USBErrorIO, USBErrorOverflow): - cloudlog.exception("CAN: BAD RECV, RETRYING") - return __parse_can_buffer(dat) - -def can_init(): - global handle, context - handle = None - cloudlog.info("attempting can init") - - context = usb1.USBContext() - #context.setDebug(9) - - for device in context.getDeviceList(skip_on_error=True): - if device.getVendorID() == 0xbbaa and device.getProductID() == 0xddcc: - handle = device.open() - handle.claimInterface(0) - handle.controlWrite(0x40, 0xdc, SafetyModel.allOutput, 0, b'') - - if handle is None: - cloudlog.warning("CAN NOT FOUND") - exit(-1) - - cloudlog.info("got handle") - cloudlog.info("can init done") - -def boardd_mock_loop(): - can_init() - handle.controlWrite(0x40, 0xdc, SafetyModel.allOutput, 0, b'') - - logcan = messaging.sub_sock('can') - sendcan = messaging.pub_sock('sendcan') - - while 1: - tsc = messaging.drain_sock(logcan, wait_for_one=True) - snds = map(lambda x: can_capnp_to_can_list(x.can), tsc) - snd = [] - for s in snds: - snd += s - snd = list(filter(lambda x: x[-1] <= 2, snd)) - snd_0 = len(list(filter(lambda x: x[-1] == 0, snd))) - snd_1 = len(list(filter(lambda x: x[-1] == 1, snd))) - snd_2 = len(list(filter(lambda x: x[-1] == 2, snd))) - can_send_many(snd) - - # recv @ 100hz - can_msgs = can_recv() - got_0 = len(list(filter(lambda x: x[-1] == 0+0x80, can_msgs))) - got_1 = len(list(filter(lambda x: x[-1] == 1+0x80, can_msgs))) - got_2 = len(list(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()) - -def boardd_test_loop(): - can_init() - cnt = 0 - while 1: - can_send_many([[0xbb, 0, "\xaa\xaa\xaa\xaa", 0], [0xaa, 0, "\xaa\xaa\xaa\xaa"+struct.pack("!I", cnt), 1]]) - #can_send_many([[0xaa,0,"\xaa\xaa\xaa\xaa",0]]) - #can_send_many([[0xaa,0,"\xaa\xaa\xaa\xaa",1]]) - # recv @ 100hz - can_msgs = can_recv() - print("got %d" % (len(can_msgs))) - time.sleep(0.01) - cnt += 1 - -# *** main loop *** -def boardd_loop(rate=100): - rk = Ratekeeper(rate) - - can_init() - - # *** publishes can and health - logcan = messaging.pub_sock('can') - health_sock = messaging.pub_sock('pandaStates') - - # *** subscribes to can send - sendcan = messaging.sub_sock('sendcan') - - # drain sendcan to delete any stale messages from previous runs - messaging.drain_sock(sendcan) - - while 1: - # health packet @ 2hz - if (rk.frame % (rate // 2)) == 0: - health = can_health() - msg = messaging.new_message('pandaStates', 1) - - # store the health to be logged - msg.pandaState[0].voltage = health['voltage'] - msg.pandaState[0].current = health['current'] - msg.pandaState[0].ignitionLine = health['ignition_line'] - msg.pandaState[0].ignitionCan = health['ignition_can'] - msg.pandaState[0].controlsAllowed = True - - health_sock.send(msg.to_bytes()) - - # recv @ 100hz - can_msgs = can_recv() - - # publish to logger - # TODO: refactor for speed - if len(can_msgs) > 0: - dat = can_list_to_can_capnp(can_msgs).to_bytes() - logcan.send(dat) - - # send can if we have a packet - tsc = messaging.recv_sock(sendcan) - if tsc is not None: - can_send_many(can_capnp_to_can_list(tsc.sendcan)) - - rk.keep_time() - -# *** main loop *** -def boardd_proxy_loop(rate=100, address="192.168.2.251"): - rk = Ratekeeper(rate) - - can_init() - - # *** subscribes can - logcan = messaging.sub_sock('can', addr=address) - # *** publishes to can send - sendcan = messaging.pub_sock('sendcan') - - # drain sendcan to delete any stale messages from previous runs - messaging.drain_sock(sendcan) - - while 1: - # recv @ 100hz - can_msgs = can_recv() - #for m in can_msgs: - # print("R: {0} {1}".format(hex(m[0]), str(m[2]).encode("hex"))) - - # publish to logger - # TODO: refactor for speed - if len(can_msgs) > 0: - dat = can_list_to_can_capnp(can_msgs, "sendcan") - sendcan.send(dat) - - # send can if we have a packet - tsc = messaging.recv_sock(logcan) - if tsc is not None: - cl = can_capnp_to_can_list(tsc.can) - #for m in cl: - # print("S: {0} {1}".format(hex(m[0]), str(m[2]).encode("hex"))) - can_send_many(cl) - - rk.keep_time() - -def main(): - if os.getenv("MOCK") is not None: - boardd_mock_loop() - elif os.getenv("PROXY") is not None: - boardd_proxy_loop() - elif os.getenv("BOARDTEST") is not None: - boardd_test_loop() - else: - boardd_loop() - -if __name__ == "__main__": - main() diff --git a/selfdrive/boardd/tests/replay_many.py b/selfdrive/boardd/tests/replay_many.py deleted file mode 100755 index 78aef07497..0000000000 --- a/selfdrive/boardd/tests/replay_many.py +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/env python3 -import os -import sys -import time -import signal -import traceback -import usb1 -from panda import Panda, PandaDFU -from multiprocessing import Pool - -jungle = "JUNGLE" in os.environ -if jungle: - from panda_jungle import PandaJungle # pylint: disable=import-error - -import cereal.messaging as messaging -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(sender_serial): - while True: - try: - if jungle: - sender = PandaJungle(sender_serial) - else: - sender = Panda(sender_serial) - sender.set_safety_mode(Panda.SAFETY_ALLOUTPUT) - - sender.set_can_loopback(False) - can_sock = messaging.sub_sock('can') - - while True: - tsc = messaging.recv_one(can_sock) - snd = can_capnp_to_can_list(tsc.can) - snd = list(filter(lambda x: x[-1] <= 2, snd)) - - try: - sender.can_send_many(snd) - except usb1.USBErrorTimeout: - pass - - # Drain panda message buffer - sender.can_recv() - except Exception: - traceback.print_exc() - time.sleep(1) - -if __name__ == "__main__": - if jungle: - serials = PandaJungle.list() - else: - serials = Panda.list() - num_senders = len(serials) - - if num_senders == 0: - print("No senders found. Exiting") - sys.exit(1) - else: - print("%d senders found. Starting broadcast" % num_senders) - - if "FLASH" in os.environ: - for s in PandaDFU.list(): - PandaDFU(s).recover() - - time.sleep(1) - for s in serials: - Panda(s).recover() - Panda(s).flash() - - pool = Pool(num_senders, 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 b/selfdrive/boardd/tests/test_boardd index f249724f6a..b4455ce67c 100755 Binary files a/selfdrive/boardd/tests/test_boardd and b/selfdrive/boardd/tests/test_boardd differ diff --git a/selfdrive/boardd/tests/test_boardd_api.py b/selfdrive/boardd/tests/test_boardd_api.py deleted file mode 100644 index 9386c7845e..0000000000 --- a/selfdrive/boardd/tests/test_boardd_api.py +++ /dev/null @@ -1,77 +0,0 @@ -import random -import numpy as np - -import selfdrive.boardd.tests.boardd_old as boardd_old -import selfdrive.boardd.boardd as boardd - -from common.realtime import sec_since_boot -from cereal import log -import unittest - - -def generate_random_can_data_list(): - can_list = [] - cnt = random.randint(1, 64) - for _ in range(cnt): - can_data = np.random.bytes(random.randint(1, 8)) - can_list.append([random.randint(0, 128), random.randint(0, 128), can_data, random.randint(0, 128)]) - return can_list, cnt - - -class TestBoarddApiMethods(unittest.TestCase): - def test_correctness(self): - for i in range(1000): - can_list, _ = generate_random_can_data_list() - - # Sendcan - # Old API - m_old = boardd_old.can_list_to_can_capnp(can_list, 'sendcan').to_bytes() - # new API - m = boardd.can_list_to_can_capnp(can_list, 'sendcan') - - ev_old = log.Event.from_bytes(m_old) - ev = log.Event.from_bytes(m) - - self.assertEqual(ev_old.which(), ev.which()) - self.assertEqual(len(ev.sendcan), len(ev_old.sendcan)) - for i in range(len(ev.sendcan)): - attrs = ['address', 'busTime', 'dat', 'src'] - for attr in attrs: - self.assertEqual(getattr(ev.sendcan[i], attr, 'new'), getattr(ev_old.sendcan[i], attr, 'old')) - - # Can - m_old = boardd_old.can_list_to_can_capnp(can_list, 'can').to_bytes() - # new API - m = boardd.can_list_to_can_capnp(can_list, 'can') - - ev_old = log.Event.from_bytes(m_old) - ev = log.Event.from_bytes(m) - self.assertEqual(ev_old.which(), ev.which()) - self.assertEqual(len(ev.can), len(ev_old.can)) - for i in range(len(ev.can)): - attrs = ['address', 'busTime', 'dat', 'src'] - for attr in attrs: - self.assertEqual(getattr(ev.can[i], attr, 'new'), getattr(ev_old.can[i], attr, 'old')) - - def test_performance(self): - can_list, _ = generate_random_can_data_list() - recursions = 1000 - - n1 = sec_since_boot() - for _ in range(recursions): - boardd_old.can_list_to_can_capnp(can_list, 'sendcan').to_bytes() - n2 = sec_since_boot() - elapsed_old = n2 - n1 - - # print('Old API, elapsed time: {} secs'.format(elapsed_old)) - n1 = sec_since_boot() - for _ in range(recursions): - boardd.can_list_to_can_capnp(can_list) - n2 = sec_since_boot() - elapsed_new = n2 - n1 - # print('New API, elapsed time: {} secs'.format(elapsed_new)) - self.assertTrue(elapsed_new < elapsed_old / 2) - - -if __name__ == '__main__': - unittest.main() diff --git a/selfdrive/boardd/tests/test_boardd_loopback.py b/selfdrive/boardd/tests/test_boardd_loopback.py index 631b4c987f..e9bbcb4586 100755 --- a/selfdrive/boardd/tests/test_boardd_loopback.py +++ b/selfdrive/boardd/tests/test_boardd_loopback.py @@ -12,7 +12,7 @@ from common.spinner import Spinner from common.timeout import Timeout from selfdrive.boardd.boardd import can_list_to_can_capnp from selfdrive.car import make_can_msg -from selfdrive.hardware import TICI +from system.hardware import TICI from selfdrive.test.helpers import phone_only, with_processes diff --git a/selfdrive/boardd/tests/test_boardd_usbprotocol.cc b/selfdrive/boardd/tests/test_boardd_usbprotocol.cc index 6a13cbd71f..cc3b4bce9a 100644 --- a/selfdrive/boardd/tests/test_boardd_usbprotocol.cc +++ b/selfdrive/boardd/tests/test_boardd_usbprotocol.cc @@ -6,8 +6,6 @@ #include "cereal/messaging/messaging.h" #include "selfdrive/boardd/panda.h" -const unsigned char dlc_to_len[] = {0U, 1U, 2U, 3U, 4U, 5U, 6U, 7U, 8U, 12U, 16U, 20U, 24U, 32U, 48U, 64U}; - int random_int(int min, int max) { std::random_device dev; std::mt19937 rng(dev()); @@ -50,7 +48,7 @@ PandaTest::PandaTest(uint32_t bus_offset_, int can_list_size, cereal::PandaState can.setAddress(i); can.setSrc(random_int(0, 3) + bus_offset); can.setDat(kj::ArrayPtr((uint8_t *)dat.data(), dat.size())); - total_pakets_size += CANPACKET_HEAD_SIZE + dat.size(); + total_pakets_size += sizeof(can_header) + dat.size(); } can_data_list = can_list.asReader(); @@ -60,14 +58,11 @@ PandaTest::PandaTest(uint32_t bus_offset_, int can_list_size, cereal::PandaState void PandaTest::test_can_send() { std::vector unpacked_data; this->pack_can_buffer(can_data_list, [&](uint8_t *chunk, size_t size) { - int size_left = size; - for (int i = 0, counter = 0; i < size; i += USBPACKET_MAX_SIZE, counter++) { - REQUIRE(chunk[i] == counter); - - const int len = std::min(USBPACKET_MAX_SIZE, size_left); - unpacked_data.insert(unpacked_data.end(), &chunk[i + 1], &chunk[i + len]); - size_left -= len; - } + uint32_t magic; + memcpy(&magic, &chunk[0], sizeof(uint32_t)); + + REQUIRE(magic == CAN_TRANSACTION_MAGIC); + unpacked_data.insert(unpacked_data.end(), &chunk[sizeof(uint32_t)], &chunk[size]); }); REQUIRE(unpacked_data.size() == total_pakets_size); @@ -75,9 +70,9 @@ void PandaTest::test_can_send() { INFO("test can message integrity"); for (int pos = 0, pckt_len = 0; pos < unpacked_data.size(); pos += pckt_len) { can_header header; - memcpy(&header, &unpacked_data[pos], CANPACKET_HEAD_SIZE); + memcpy(&header, &unpacked_data[pos], sizeof(can_header)); const uint8_t data_len = dlc_to_len[header.data_len_code]; - pckt_len = CANPACKET_HEAD_SIZE + data_len; + pckt_len = sizeof(can_header) + data_len; REQUIRE(header.addr == cnt); REQUIRE(test_data.find(data_len) != test_data.end()); diff --git a/selfdrive/camerad/SConscript b/selfdrive/camerad/SConscript deleted file mode 100644 index 85bc756bc1..0000000000 --- a/selfdrive/camerad/SConscript +++ /dev/null @@ -1,47 +0,0 @@ -Import('env', 'arch', 'cereal', 'messaging', 'common', 'gpucommon', 'visionipc', 'USE_WEBCAM') - -libs = ['m', 'pthread', common, 'jpeg', 'OpenCL', 'yuv', cereal, messaging, 'zmq', 'capnp', 'kj', visionipc, gpucommon] - -if arch == "aarch64": - libs += ['gsl', 'CB', 'adreno_utils', 'EGL', 'GLESv3', 'cutils', 'ui'] - cameras = ['cameras/camera_qcom.cc'] -elif arch == "larch64": - libs += ['atomic'] - cameras = ['cameras/camera_qcom2.cc'] -else: - env['CXXFLAGS'] += ["-Wno-deprecated-declarations"] - if USE_WEBCAM: - libs += ['opencv_core', 'opencv_highgui', 'opencv_imgproc', 'opencv_videoio'] - cameras = ['cameras/camera_webcam.cc'] - env = env.Clone() - env.Append(CXXFLAGS = '-DWEBCAM') - env.Append(CFLAGS = '-DWEBCAM') - env.Append(CPPPATH = ['/usr/include/opencv4', '/usr/local/include/opencv4']) - else: - libs += ['avutil', 'avcodec', 'avformat', 'bz2', 'ssl', 'curl', 'crypto'] - # TODO: import replay_lib from root SConstruct - cameras = ['cameras/camera_replay.cc', - env.Object('camera-util', '#/selfdrive/ui/replay/util.cc'), - env.Object('camera-framereader', '#/selfdrive/ui/replay/framereader.cc'), - env.Object('camera-filereader', '#/selfdrive/ui/replay/filereader.cc')] - - if arch == "Darwin": - del libs[libs.index('OpenCL')] - del libs[libs.index(gpucommon)][gpucommon.index('GL')] - env = env.Clone() - env['FRAMEWORKS'] = ['OpenCL', 'OpenGL'] - -env.Program('camerad', [ - 'main.cc', - 'cameras/camera_common.cc', - 'transforms/rgb_to_yuv.cc', - 'imgproc/utils.cc', - cameras, - ], LIBS=libs) - -if GetOption("test"): - env.Program('test/ae_gray_test', [ - 'test/ae_gray_test.cc', - 'cameras/camera_common.cc', - 'transforms/rgb_to_yuv.cc', - ], LIBS=libs) diff --git a/selfdrive/camerad/cameras/camera_qcom.cc b/selfdrive/camerad/cameras/camera_qcom.cc deleted file mode 100644 index da01b94177..0000000000 --- a/selfdrive/camerad/cameras/camera_qcom.cc +++ /dev/null @@ -1,1164 +0,0 @@ -#include "selfdrive/camerad/cameras/camera_qcom.h" - -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#include -#include - -#include "selfdrive/camerad/cameras/sensor_i2c.h" -#include "selfdrive/camerad/include/msm_cam_sensor.h" -#include "selfdrive/camerad/include/msmb_camera.h" -#include "selfdrive/camerad/include/msmb_isp.h" -#include "selfdrive/camerad/include/msmb_ispif.h" -#include "selfdrive/common/clutil.h" -#include "selfdrive/common/params.h" -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/timing.h" -#include "selfdrive/common/util.h" - -// leeco actuator (DW9800W H-Bridge Driver IC) -// from sniff -const uint16_t INFINITY_DAC = 364; - -extern ExitHandler do_exit; - -static int cam_ioctl(int fd, unsigned long int request, void *arg, const char *log_msg = nullptr) { - int err = HANDLE_EINTR(ioctl(fd, request, arg)); - if (err != 0 && log_msg) { - LOG(util::string_format("%s: %d", log_msg, err).c_str()); - } - return err; -} -// global var for AE/AF ops -std::atomic road_cam_exp{{0}}; -std::atomic driver_cam_exp{{0}}; - -CameraInfo cameras_supported[CAMERA_ID_MAX] = { - [CAMERA_ID_IMX298] = { - .frame_width = 2328, - .frame_height = 1748, - .frame_stride = 2912, - .bayer = true, - .bayer_flip = 3, - .hdr = true - }, - [CAMERA_ID_OV8865] = { - .frame_width = 1632, - .frame_height = 1224, - .frame_stride = 2040, // seems right - .bayer = true, - .bayer_flip = 3, - .hdr = false - }, - // this exists to get the kernel to build for the LeEco in release - [CAMERA_ID_IMX298_FLIPPED] = { - .frame_width = 2328, - .frame_height = 1748, - .frame_stride = 2912, - .bayer = true, - .bayer_flip = 3, - .hdr = true - }, - [CAMERA_ID_OV10640] = { - .frame_width = 1280, - .frame_height = 1080, - .frame_stride = 2040, - .bayer = true, - .bayer_flip = 0, - .hdr = true - }, -}; - -static void camera_release_buffer(void* cookie, int buf_idx) { - CameraState *s = (CameraState *)cookie; - // printf("camera_release_buffer %d\n", buf_idx); - s->ss[0].qbuf_info[buf_idx].dirty_buf = 1; - HANDLE_EINTR(ioctl(s->isp_fd, VIDIOC_MSM_ISP_ENQUEUE_BUF, &s->ss[0].qbuf_info[buf_idx])); -} - -int sensor_write_regs(CameraState *s, struct msm_camera_i2c_reg_array* arr, size_t size, msm_camera_i2c_data_type data_type) { - struct msm_camera_i2c_reg_setting out_settings = { - .reg_setting = arr, - .size = (uint16_t)size, - .addr_type = MSM_CAMERA_I2C_WORD_ADDR, - .data_type = data_type, - .delay = 0, - }; - sensorb_cfg_data cfg_data = {.cfgtype = CFG_WRITE_I2C_ARRAY, .cfg.setting = &out_settings}; - return HANDLE_EINTR(ioctl(s->sensor_fd, VIDIOC_MSM_SENSOR_CFG, &cfg_data)); -} - -static int imx298_apply_exposure(CameraState *s, int gain, int integ_lines, uint32_t frame_length) { - int analog_gain = std::min(gain, 448); - s->digital_gain = gain > 448 ? (512.0/(512-(gain))) / 8.0 : 1.0; - //printf("%5d/%5d %5d %f\n", s->cur_integ_lines, s->frame_length, analog_gain, s->digital_gain); - - struct msm_camera_i2c_reg_array reg_array[] = { - // REG_HOLD - {0x104,0x1,0}, - {0x3002,0x0,0}, // long autoexposure off - - // FRM_LENGTH - {0x340, (uint16_t)(frame_length >> 8), 0}, {0x341, (uint16_t)(frame_length & 0xff), 0}, - // INTEG_TIME aka coarse_int_time_addr aka shutter speed - {0x202, (uint16_t)(integ_lines >> 8), 0}, {0x203, (uint16_t)(integ_lines & 0xff),0}, - // global_gain_addr - // if you assume 1x gain is 32, 448 is 14x gain, aka 2^14=16384 - {0x204, (uint16_t)(analog_gain >> 8), 0}, {0x205, (uint16_t)(analog_gain & 0xff),0}, - - // digital gain for colors: gain_greenR, gain_red, gain_blue, gain_greenB - /*{0x20e, digital_gain_gr >> 8, 0}, {0x20f,digital_gain_gr & 0xFF,0}, - {0x210, digital_gain_r >> 8, 0}, {0x211,digital_gain_r & 0xFF,0}, - {0x212, digital_gain_b >> 8, 0}, {0x213,digital_gain_b & 0xFF,0}, - {0x214, digital_gain_gb >> 8, 0}, {0x215,digital_gain_gb & 0xFF,0},*/ - - // REG_HOLD - {0x104,0x0,0}, - }; - return sensor_write_regs(s, reg_array, std::size(reg_array), MSM_CAMERA_I2C_BYTE_DATA); -} - -static int ov8865_apply_exposure(CameraState *s, int gain, int integ_lines, uint32_t frame_length) { - //printf("driver camera: %d %d %d\n", gain, integ_lines, frame_length); - int coarse_gain_bitmap, fine_gain_bitmap; - - // get bitmaps from iso - static const int gains[] = {0, 100, 200, 400, 800}; - int i; - for (i = 1; i < std::size(gains); i++) { - if (gain >= gains[i - 1] && gain < gains[i]) - break; - } - int coarse_gain = i - 1; - float fine_gain = (gain - gains[coarse_gain])/(float)(gains[coarse_gain+1]-gains[coarse_gain]); - coarse_gain_bitmap = (1 << coarse_gain) - 1; - fine_gain_bitmap = ((int)(16*fine_gain) << 3) + 128; // 7th is always 1, 0-2nd are always 0 - - integ_lines *= 16; // The exposure value in reg is in 16ths of a line - - struct msm_camera_i2c_reg_array reg_array[] = { - //{0x104,0x1,0}, - - // FRM_LENGTH - {0x380e, (uint16_t)(frame_length >> 8), 0}, {0x380f, (uint16_t)(frame_length & 0xff), 0}, - // AEC EXPO - {0x3500, (uint16_t)(integ_lines >> 16), 0}, {0x3501, (uint16_t)(integ_lines >> 8), 0}, {0x3502, (uint16_t)(integ_lines & 0xff),0}, - // AEC MANUAL - {0x3503, 0x4, 0}, - // AEC GAIN - {0x3508, (uint16_t)(coarse_gain_bitmap), 0}, {0x3509, (uint16_t)(fine_gain_bitmap), 0}, - - //{0x104,0x0,0}, - }; - return sensor_write_regs(s, reg_array, std::size(reg_array), MSM_CAMERA_I2C_BYTE_DATA); -} - -static void camera_init(VisionIpcServer *v, CameraState *s, int camera_id, int camera_num, - uint32_t pixel_clock, uint32_t line_length_pclk, - uint32_t max_gain, uint32_t fps, cl_device_id device_id, cl_context ctx, - VisionStreamType rgb_type, VisionStreamType yuv_type) { - s->camera_num = camera_num; - s->camera_id = camera_id; - - assert(camera_id < std::size(cameras_supported)); - s->ci = cameras_supported[camera_id]; - assert(s->ci.frame_width != 0); - - s->pixel_clock = pixel_clock; - s->max_gain = max_gain; - s->fps = fps; - s->frame_length = s->pixel_clock / line_length_pclk / s->fps; - s->self_recover = 0; - - s->apply_exposure = (camera_id == CAMERA_ID_IMX298) ? imx298_apply_exposure : ov8865_apply_exposure; - s->buf.init(device_id, ctx, s, v, FRAME_BUF_COUNT, rgb_type, yuv_type, camera_release_buffer); -} - -void cameras_init(VisionIpcServer *v, MultiCameraState *s, cl_device_id device_id, cl_context ctx) { - char project_name[1024] = {0}; - property_get("ro.boot.project_name", project_name, ""); - assert(strlen(project_name) == 0); - - // sensor is flipped in LP3 - // IMAGE_ORIENT = 3 - init_array_imx298[0].reg_data = 3; - - // 0 = ISO 100 - // 256 = ISO 200 - // 384 = ISO 400 - // 448 = ISO 800 - // 480 = ISO 1600 - // 496 = ISO 3200 - // 504 = ISO 6400, 8x digital gain - // 508 = ISO 12800, 16x digital gain - // 510 = ISO 25600, 32x digital gain - - camera_init(v, &s->road_cam, CAMERA_ID_IMX298, 0, - /*pixel_clock=*/600000000, /*line_length_pclk=*/5536, - /*max_gain=*/510, //0 (ISO 100)- 448 (ISO 800, max analog gain) - 511 (super noisy) -#ifdef HIGH_FPS - /*fps*/ 60, -#else - /*fps*/ 20, -#endif - device_id, ctx, - VISION_STREAM_RGB_BACK, VISION_STREAM_ROAD); - - camera_init(v, &s->driver_cam, CAMERA_ID_OV8865, 1, - /*pixel_clock=*/72000000, /*line_length_pclk=*/1602, - /*max_gain=*/510, 10, device_id, ctx, - VISION_STREAM_RGB_FRONT, VISION_STREAM_DRIVER); - - s->sm = new SubMaster({"driverState"}); - s->pm = new PubMaster({"roadCameraState", "driverCameraState", "thumbnail"}); - - for (int i = 0; i < FRAME_BUF_COUNT; i++) { - // TODO: make lengths correct - s->focus_bufs[i].allocate(0xb80); - s->stats_bufs[i].allocate(0xb80); - } - std::fill_n(s->lapres, std::size(s->lapres), 16160); - s->lap_conv = new LapConv(device_id, ctx, s->road_cam.buf.rgb_width, s->road_cam.buf.rgb_height, s->road_cam.buf.rgb_stride, 3); -} - -static void set_exposure(CameraState *s, float exposure_frac, float gain_frac) { - int err = 0; - uint32_t gain = s->cur_gain; - uint32_t integ_lines = s->cur_integ_lines; - - if (exposure_frac >= 0) { - exposure_frac = std::clamp(exposure_frac, 2.0f / s->frame_length, 1.0f); - integ_lines = s->frame_length * exposure_frac; - - // See page 79 of the datasheet, this is the max allowed (-1 for phase adjust) - integ_lines = std::min(integ_lines, s->frame_length - 11); - } - - if (gain_frac >= 0) { - // ISO200 is minimum gain - gain_frac = std::clamp(gain_frac, 1.0f/64, 1.0f); - - // linearize gain response - // TODO: will be wrong for driver camera - // 0.125 -> 448 - // 0.25 -> 480 - // 0.5 -> 496 - // 1.0 -> 504 - // 512 - 512/(128*gain_frac) - gain = (s->max_gain/510) * (512 - 512/(256*gain_frac)); - } - - if (gain != s->cur_gain || integ_lines != s->cur_integ_lines) { - if (s->apply_exposure == ov8865_apply_exposure) { - gain = 800 * gain_frac; // ISO - } - err = s->apply_exposure(s, gain, integ_lines, s->frame_length); - if (err == 0) { - std::lock_guard lk(s->frame_info_lock); - s->cur_gain = gain; - s->cur_integ_lines = integ_lines; - } else { - LOGE("camera %d apply_exposure err: %d", s->camera_num, err); - } - } - - if (err == 0) { - s->cur_exposure_frac = exposure_frac; - std::lock_guard lk(s->frame_info_lock); - s->cur_gain_frac = gain_frac; - } - - //LOGD("set exposure: %f %f - %d", exposure_frac, gain_frac, err); -} - -static void do_autoexposure(CameraState *s, float grey_frac) { - const float target_grey = 0.3; - - s->frame_info_lock.lock(); - s->measured_grey_fraction = grey_frac; - s->target_grey_fraction = target_grey; - s->frame_info_lock.unlock(); - - if (s->apply_exposure == ov8865_apply_exposure) { - // gain limits downstream - const float gain_frac_min = 0.015625; - const float gain_frac_max = 1.0; - // exposure time limits - const uint32_t exposure_time_min = 16; - const uint32_t exposure_time_max = s->frame_length - 11; // copied from set_exposure() - - float cur_gain_frac = s->cur_gain_frac; - float exposure_factor = pow(1.05, (target_grey - grey_frac) / 0.05); - if (cur_gain_frac > 0.125 && exposure_factor < 1) { - cur_gain_frac *= exposure_factor; - } else if (s->cur_integ_lines * exposure_factor <= exposure_time_max && s->cur_integ_lines * exposure_factor >= exposure_time_min) { // adjust exposure time first - s->cur_exposure_frac *= exposure_factor; - } else if (cur_gain_frac * exposure_factor <= gain_frac_max && cur_gain_frac * exposure_factor >= gain_frac_min) { - cur_gain_frac *= exposure_factor; - } - s->frame_info_lock.lock(); - s->cur_gain_frac = cur_gain_frac; - s->frame_info_lock.unlock(); - - set_exposure(s, s->cur_exposure_frac, cur_gain_frac); - } else { // keep the old for others - float new_exposure = s->cur_exposure_frac; - new_exposure *= pow(1.05, (target_grey - grey_frac) / 0.05 ); - //LOGD("diff %f: %f to %f", target_grey - grey_frac, s->cur_exposure_frac, new_exposure); - - float new_gain = s->cur_gain_frac; - if (new_exposure < 0.10) { - new_gain *= 0.95; - } else if (new_exposure > 0.40) { - new_gain *= 1.05; - } - - set_exposure(s, new_exposure, new_gain); - } -} - -static void sensors_init(MultiCameraState *s) { - msm_camera_sensor_slave_info slave_infos[2] = { - (msm_camera_sensor_slave_info){ // road camera - .sensor_name = "imx298", - .eeprom_name = "sony_imx298", - .actuator_name = "dw9800w", - .ois_name = "", - .flash_name = "pmic", - .camera_id = CAMERA_0, - .slave_addr = 32, - .i2c_freq_mode = I2C_FAST_MODE, - .addr_type = MSM_CAMERA_I2C_WORD_ADDR, - .sensor_id_info = {.sensor_id_reg_addr = 22, .sensor_id = 664, .module_id = 9, .vcm_id = 6}, - .power_setting_array = { - .power_setting_a = { - {.seq_type = SENSOR_GPIO, .delay = 1}, - {.seq_type = SENSOR_VREG, .seq_val = 2}, - {.seq_type = SENSOR_GPIO, .seq_val = 5, .config_val = 2}, - {.seq_type = SENSOR_VREG, .seq_val = 1}, - {.seq_type = SENSOR_VREG, .seq_val = 3, .delay = 1}, - {.seq_type = SENSOR_CLK, .config_val = 24000000, .delay = 1}, - {.seq_type = SENSOR_GPIO, .config_val = 2, .delay = 10}, - }, - .size = 7, - .power_down_setting_a = { - {.seq_type = SENSOR_CLK, .delay = 1}, - {.seq_type = SENSOR_GPIO, .delay = 1}, - {.seq_type = SENSOR_VREG, .seq_val = 1}, - {.seq_type = SENSOR_GPIO, .seq_val = 5}, - {.seq_type = SENSOR_VREG, .seq_val = 2}, - {.seq_type = SENSOR_VREG, .seq_val = 3, .delay = 1}, - }, - .size_down = 6, - }, - .is_init_params_valid = 0, - .sensor_init_params = {.modes_supported = 1, .position = BACK_CAMERA_B, .sensor_mount_angle = 90}, - .output_format = MSM_SENSOR_BAYER, - }, - (msm_camera_sensor_slave_info){ // driver camera - .sensor_name = "ov8865_sunny", - .eeprom_name = "ov8865_plus", - .actuator_name = "", - .ois_name = "", - .flash_name = "", - .camera_id = CAMERA_2, - .slave_addr = 108, - .i2c_freq_mode = I2C_FAST_MODE, - .addr_type = MSM_CAMERA_I2C_WORD_ADDR, - .sensor_id_info = {.sensor_id_reg_addr = 12299, .sensor_id = 34917, .module_id = 2}, - .power_setting_array = { - .power_setting_a = { - {.seq_type = SENSOR_GPIO, .delay = 5}, - {.seq_type = SENSOR_VREG, .seq_val = 1}, - {.seq_type = SENSOR_VREG, .seq_val = 2}, - {.seq_type = SENSOR_VREG}, - {.seq_type = SENSOR_CLK, .config_val = 24000000, .delay = 1}, - {.seq_type = SENSOR_GPIO, .config_val = 2, .delay = 1}, - }, - .size = 6, - .power_down_setting_a = { - {.seq_type = SENSOR_GPIO, .delay = 5}, - {.seq_type = SENSOR_CLK, .delay = 1}, - {.seq_type = SENSOR_VREG}, - {.seq_type = SENSOR_VREG, .seq_val = 1}, - {.seq_type = SENSOR_VREG, .seq_val = 2, .delay = 1}, - }, - .size_down = 5, - }, - .is_init_params_valid = 0, - .sensor_init_params = {.modes_supported = 1, .position = FRONT_CAMERA_B, .sensor_mount_angle = 270}, - .output_format = MSM_SENSOR_BAYER, - }}; - - unique_fd sensorinit_fd = open_v4l_by_name_and_index("msm_sensor_init"); - assert(sensorinit_fd >= 0); - for (auto &info : slave_infos) { - info.power_setting_array.power_setting = &info.power_setting_array.power_setting_a[0]; - info.power_setting_array.power_down_setting = &info.power_setting_array.power_down_setting_a[0]; - sensor_init_cfg_data sensor_init_cfg = {.cfgtype = CFG_SINIT_PROBE, .cfg.setting = &info}; - int err = cam_ioctl(sensorinit_fd, VIDIOC_MSM_SENSOR_INIT_CFG, &sensor_init_cfg, "sensor init cfg"); - assert(err >= 0); - } -} - -static void camera_open(CameraState *s, bool is_road_cam) { - struct csid_cfg_data csid_cfg_data = {}; - struct v4l2_event_subscription sub = {}; - - struct msm_actuator_cfg_data actuator_cfg_data = {}; - - // open devices - s->csid_fd = open_v4l_by_name_and_index("msm_csid", is_road_cam ? 0 : 2); - assert(s->csid_fd >= 0); - s->csiphy_fd = open_v4l_by_name_and_index("msm_csiphy", is_road_cam ? 0 : 2); - assert(s->csiphy_fd >= 0); - s->isp_fd = open_v4l_by_name_and_index("vfe", is_road_cam ? 0 : 1); - assert(s->isp_fd >= 0); - - if (is_road_cam) { - s->actuator_fd = open_v4l_by_name_and_index("msm_actuator"); - assert(s->actuator_fd >= 0); - } - - // wait for sensor device - // on first startup, these devices aren't present yet - for (int i = 0; i < 10; i++) { - s->sensor_fd = open_v4l_by_name_and_index(is_road_cam ? "imx298" : "ov8865_sunny"); - if (s->sensor_fd >= 0) break; - LOGW("waiting for sensors..."); - util::sleep_for(1000); // sleep one second - } - assert(s->sensor_fd >= 0); - - // *** SHUTDOWN ALL *** - - // CSIPHY: release csiphy - struct msm_camera_csi_lane_params csi_lane_params = {0}; - csi_lane_params.csi_lane_mask = 0x1f; - csiphy_cfg_data csiphy_cfg_data = { .cfg.csi_lane_params = &csi_lane_params, .cfgtype = CSIPHY_RELEASE}; - int err = cam_ioctl(s->csiphy_fd, VIDIOC_MSM_CSIPHY_IO_CFG, &csiphy_cfg_data, "release csiphy"); - - // CSID: release csid - csid_cfg_data.cfgtype = CSID_RELEASE; - cam_ioctl(s->csid_fd, VIDIOC_MSM_CSID_IO_CFG, &csid_cfg_data, "release csid"); - - // SENSOR: send power down - struct sensorb_cfg_data sensorb_cfg_data = {.cfgtype = CFG_POWER_DOWN}; - cam_ioctl(s->sensor_fd, VIDIOC_MSM_SENSOR_CFG, &sensorb_cfg_data, "sensor power down"); - - // actuator powerdown - actuator_cfg_data.cfgtype = CFG_ACTUATOR_POWERDOWN; - cam_ioctl(s->actuator_fd, VIDIOC_MSM_ACTUATOR_CFG, &actuator_cfg_data, "actuator powerdown"); - - // reset isp - // struct msm_vfe_axi_halt_cmd halt_cmd = { - // .stop_camif = 1, - // .overflow_detected = 1, - // .blocking_halt = 1, - // }; - // err = ioctl(s->isp_fd, VIDIOC_MSM_ISP_AXI_HALT, &halt_cmd); - // printf("axi halt: %d\n", err); - - // struct msm_vfe_axi_reset_cmd reset_cmd = { - // .blocking = 1, - // .frame_id = 1, - // }; - // err = ioctl(s->isp_fd, VIDIOC_MSM_ISP_AXI_RESET, &reset_cmd); - // printf("axi reset: %d\n", err); - - // struct msm_vfe_axi_restart_cmd restart_cmd = { - // .enable_camif = 1, - // }; - // err = ioctl(s->isp_fd, VIDIOC_MSM_ISP_AXI_RESTART, &restart_cmd); - // printf("axi restart: %d\n", err); - - // **** GO GO GO **** - LOG("******************** GO GO GO ************************"); - - // CSID: init csid - csid_cfg_data.cfgtype = CSID_INIT; - cam_ioctl(s->csid_fd, VIDIOC_MSM_CSID_IO_CFG, &csid_cfg_data, "init csid"); - - // CSIPHY: init csiphy - csiphy_cfg_data = {.cfgtype = CSIPHY_INIT}; - cam_ioctl(s->csiphy_fd, VIDIOC_MSM_CSIPHY_IO_CFG, &csiphy_cfg_data, "init csiphy"); - - // SENSOR: stop stream - struct msm_camera_i2c_reg_setting stop_settings = { - .reg_setting = stop_reg_array, - .size = std::size(stop_reg_array), - .addr_type = MSM_CAMERA_I2C_WORD_ADDR, - .data_type = MSM_CAMERA_I2C_BYTE_DATA, - .delay = 0 - }; - sensorb_cfg_data.cfgtype = CFG_SET_STOP_STREAM_SETTING; - sensorb_cfg_data.cfg.setting = &stop_settings; - cam_ioctl(s->sensor_fd, VIDIOC_MSM_SENSOR_CFG, &sensorb_cfg_data, "stop stream"); - - // SENSOR: send power up - sensorb_cfg_data = {.cfgtype = CFG_POWER_UP}; - cam_ioctl(s->sensor_fd, VIDIOC_MSM_SENSOR_CFG, &sensorb_cfg_data, "sensor power up"); - - // **** configure the sensor **** - - // SENSOR: send i2c configuration - if (s->camera_id == CAMERA_ID_IMX298) { - err = sensor_write_regs(s, init_array_imx298, std::size(init_array_imx298), MSM_CAMERA_I2C_BYTE_DATA); - } else if (s->camera_id == CAMERA_ID_OV8865) { - err = sensor_write_regs(s, init_array_ov8865, std::size(init_array_ov8865), MSM_CAMERA_I2C_BYTE_DATA); - } else { - assert(false); - } - LOG("sensor init i2c: %d", err); - - if (is_road_cam) { - // init the actuator - actuator_cfg_data.cfgtype = CFG_ACTUATOR_POWERUP; - cam_ioctl(s->actuator_fd, VIDIOC_MSM_ACTUATOR_CFG, &actuator_cfg_data, "actuator powerup"); - - actuator_cfg_data.cfgtype = CFG_ACTUATOR_INIT; - cam_ioctl(s->actuator_fd, VIDIOC_MSM_ACTUATOR_CFG, &actuator_cfg_data, "actuator init"); - - struct msm_actuator_reg_params_t actuator_reg_params[] = { - { - .reg_write_type = MSM_ACTUATOR_WRITE_DAC, - // MSB here at address 3 - .reg_addr = 3, - .data_type = 9, - .addr_type = 4, - }, - }; - - struct reg_settings_t actuator_init_settings[] = { - { .reg_addr=2, .addr_type=MSM_ACTUATOR_BYTE_ADDR, .reg_data=1, .data_type = MSM_ACTUATOR_BYTE_DATA, .i2c_operation = MSM_ACT_WRITE, .delay = 0 }, // PD = power down - { .reg_addr=2, .addr_type=MSM_ACTUATOR_BYTE_ADDR, .reg_data=0, .data_type = MSM_ACTUATOR_BYTE_DATA, .i2c_operation = MSM_ACT_WRITE, .delay = 2 }, // 0 = power up - { .reg_addr=2, .addr_type=MSM_ACTUATOR_BYTE_ADDR, .reg_data=2, .data_type = MSM_ACTUATOR_BYTE_DATA, .i2c_operation = MSM_ACT_WRITE, .delay = 2 }, // RING = SAC mode - { .reg_addr=6, .addr_type=MSM_ACTUATOR_BYTE_ADDR, .reg_data=64, .data_type = MSM_ACTUATOR_BYTE_DATA, .i2c_operation = MSM_ACT_WRITE, .delay = 0 }, // 0x40 = SAC3 mode - { .reg_addr=7, .addr_type=MSM_ACTUATOR_BYTE_ADDR, .reg_data=113, .data_type = MSM_ACTUATOR_BYTE_DATA, .i2c_operation = MSM_ACT_WRITE, .delay = 0 }, - // 0x71 = DIV1 | DIV0 | SACT0 -- Tvib x 1/4 (quarter) - // SAC Tvib = 6.3 ms + 0.1 ms = 6.4 ms / 4 = 1.6 ms - // LSC 1-step = 252 + 1*4 = 256 ms / 4 = 64 ms - }; - - struct region_params_t region_params[] = { - {.step_bound = {238, 0,}, .code_per_step = 235, .qvalue = 128} - }; - - actuator_cfg_data.cfgtype = CFG_SET_ACTUATOR_INFO; - actuator_cfg_data.cfg.set_info = (struct msm_actuator_set_info_t){ - .actuator_params = { - .act_type = ACTUATOR_BIVCM, - .reg_tbl_size = 1, - .data_size = 10, - .init_setting_size = 5, - .i2c_freq_mode = I2C_STANDARD_MODE, - .i2c_addr = 24, - .i2c_addr_type = MSM_ACTUATOR_BYTE_ADDR, - .i2c_data_type = MSM_ACTUATOR_WORD_DATA, - .reg_tbl_params = &actuator_reg_params[0], - .init_settings = &actuator_init_settings[0], - .park_lens = {.damping_step = 1023, .damping_delay = 14000, .hw_params = 11, .max_step = 20}, - }, - .af_tuning_params = { - .initial_code = INFINITY_DAC, - .pwd_step = 0, - .region_size = 1, - .total_steps = 238, - .region_params = ®ion_params[0], - }, - }; - - cam_ioctl(s->actuator_fd, VIDIOC_MSM_ACTUATOR_CFG, &actuator_cfg_data, "actuator set info"); - } - - if (s->camera_id == CAMERA_ID_IMX298) { - err = sensor_write_regs(s, mode_setting_array_imx298, std::size(mode_setting_array_imx298), MSM_CAMERA_I2C_BYTE_DATA); - LOG("sensor setup: %d", err); - } - - // CSIPHY: configure csiphy - struct msm_camera_csiphy_params csiphy_params = {}; - if (s->camera_id == CAMERA_ID_IMX298) { - csiphy_params = {.lane_cnt = 4, .settle_cnt = 14, .lane_mask = 0x1f, .csid_core = 0}; - } else if (s->camera_id == CAMERA_ID_OV8865) { - // guess! - csiphy_params = {.lane_cnt = 4, .settle_cnt = 24, .lane_mask = 0x1f, .csid_core = 2}; - } - csiphy_cfg_data.cfgtype = CSIPHY_CFG; - csiphy_cfg_data.cfg.csiphy_params = &csiphy_params; - cam_ioctl(s->csiphy_fd, VIDIOC_MSM_CSIPHY_IO_CFG, &csiphy_cfg_data, "csiphy configure"); - - // CSID: configure csid -#define CSI_STATS 0x35 -#define CSI_PD 0x36 - struct msm_camera_csid_params csid_params = { - .lane_cnt = 4, - .lane_assign = 0x4320, - .phy_sel = (uint8_t)(is_road_cam ? 0 : 2), - .lut_params.num_cid = (uint8_t)(is_road_cam ? 3 : 1), - .lut_params.vc_cfg_a = { - {.cid = 0, .dt = CSI_RAW10, .decode_format = CSI_DECODE_10BIT}, - {.cid = 1, .dt = CSI_PD, .decode_format = CSI_DECODE_10BIT}, - {.cid = 2, .dt = CSI_STATS, .decode_format = CSI_DECODE_10BIT}, - }, - }; - - csid_params.lut_params.vc_cfg[0] = &csid_params.lut_params.vc_cfg_a[0]; - csid_params.lut_params.vc_cfg[1] = &csid_params.lut_params.vc_cfg_a[1]; - csid_params.lut_params.vc_cfg[2] = &csid_params.lut_params.vc_cfg_a[2]; - - csid_cfg_data.cfgtype = CSID_CFG; - csid_cfg_data.cfg.csid_params = &csid_params; - cam_ioctl(s->csid_fd, VIDIOC_MSM_CSID_IO_CFG, &csid_cfg_data, "csid configure"); - - // ISP: SMMU_ATTACH - msm_vfe_smmu_attach_cmd smmu_attach_cmd = {.security_mode = 0, .iommu_attach_mode = IOMMU_ATTACH}; - cam_ioctl(s->isp_fd, VIDIOC_MSM_ISP_SMMU_ATTACH, &smmu_attach_cmd, "isp smmu attach"); - - // ******************* STREAM RAW ***************************** - - // configure QMET input - struct msm_vfe_input_cfg input_cfg = {}; - for (int i = 0; i < (is_road_cam ? 3 : 1); i++) { - StreamState *ss = &s->ss[i]; - - memset(&input_cfg, 0, sizeof(struct msm_vfe_input_cfg)); - input_cfg.input_src = (msm_vfe_input_src)(VFE_RAW_0+i); - input_cfg.input_pix_clk = s->pixel_clock; - input_cfg.d.rdi_cfg.cid = i; - input_cfg.d.rdi_cfg.frame_based = 1; - err = ioctl(s->isp_fd, VIDIOC_MSM_ISP_INPUT_CFG, &input_cfg); - LOG("configure input(%d): %d", i, err); - - // ISP: REQUEST_STREAM - ss->stream_req.axi_stream_handle = 0; - if (is_road_cam) { - ss->stream_req.session_id = 2; - ss->stream_req.stream_id = /*ISP_META_CHANNEL_BIT | */ISP_NATIVE_BUF_BIT | (1+i); - } else { - ss->stream_req.session_id = 3; - ss->stream_req.stream_id = ISP_NATIVE_BUF_BIT | 1; - } - - if (i == 0) { - ss->stream_req.output_format = v4l2_fourcc('R', 'G', '1', '0'); - } else { - ss->stream_req.output_format = v4l2_fourcc('Q', 'M', 'E', 'T'); - } - ss->stream_req.stream_src = (msm_vfe_axi_stream_src)(RDI_INTF_0+i); - -#ifdef HIGH_FPS - if (is_road_cam) { - ss->stream_req.frame_skip_pattern = EVERY_3FRAME; - } -#endif - - ss->stream_req.frame_base = 1; - ss->stream_req.buf_divert = 1; //i == 0; - - // setup stream plane. doesn't even matter? - /*s->stream_req.plane_cfg[0].output_plane_format = Y_PLANE; - s->stream_req.plane_cfg[0].output_width = s->ci.frame_width; - s->stream_req.plane_cfg[0].output_height = s->ci.frame_height; - s->stream_req.plane_cfg[0].output_stride = s->ci.frame_width; - s->stream_req.plane_cfg[0].output_scan_lines = s->ci.frame_height; - s->stream_req.plane_cfg[0].rdi_cid = 0;*/ - - err = ioctl(s->isp_fd, VIDIOC_MSM_ISP_REQUEST_STREAM, &ss->stream_req); - LOG("isp request stream: %d -> 0x%x", err, ss->stream_req.axi_stream_handle); - - // ISP: REQUEST_BUF - ss->buf_request.session_id = ss->stream_req.session_id; - ss->buf_request.stream_id = ss->stream_req.stream_id; - ss->buf_request.num_buf = FRAME_BUF_COUNT; - ss->buf_request.buf_type = ISP_PRIVATE_BUF; - ss->buf_request.handle = 0; - cam_ioctl(s->isp_fd, VIDIOC_MSM_ISP_REQUEST_BUF, &ss->buf_request, "isp request buf"); - LOG("got buf handle: 0x%x", ss->buf_request.handle); - - // ENQUEUE all buffers - for (int j = 0; j < ss->buf_request.num_buf; j++) { - ss->qbuf_info[j].handle = ss->buf_request.handle; - ss->qbuf_info[j].buf_idx = j; - ss->qbuf_info[j].buffer.num_planes = 1; - ss->qbuf_info[j].buffer.planes[0].addr = ss->bufs[j].fd; - ss->qbuf_info[j].buffer.planes[0].length = ss->bufs[j].len; - err = ioctl(s->isp_fd, VIDIOC_MSM_ISP_ENQUEUE_BUF, &ss->qbuf_info[j]); - } - - // ISP: UPDATE_STREAM - struct msm_vfe_axi_stream_update_cmd update_cmd = {}; - update_cmd.num_streams = 1; - update_cmd.update_info[0].user_stream_id = ss->stream_req.stream_id; - update_cmd.update_info[0].stream_handle = ss->stream_req.axi_stream_handle; - update_cmd.update_type = UPDATE_STREAM_ADD_BUFQ; - cam_ioctl(s->isp_fd, VIDIOC_MSM_ISP_UPDATE_STREAM, &update_cmd, "isp update stream"); - } - - LOG("******** START STREAMS ********"); - - sub.id = 0; - sub.type = 0x1ff; - cam_ioctl(s->isp_fd, VIDIOC_SUBSCRIBE_EVENT, &sub, "isp subscribe"); - - // ISP: START_STREAM - s->stream_cfg.cmd = START_STREAM; - s->stream_cfg.num_streams = is_road_cam ? 3 : 1; - for (int i = 0; i < s->stream_cfg.num_streams; i++) { - s->stream_cfg.stream_handle[i] = s->ss[i].stream_req.axi_stream_handle; - } - cam_ioctl(s->isp_fd, VIDIOC_MSM_ISP_CFG_STREAM, &s->stream_cfg, "isp start stream"); -} - -static void road_camera_start(CameraState *s) { - set_exposure(s, 1.0, 1.0); - - int err = sensor_write_regs(s, start_reg_array, std::size(start_reg_array), MSM_CAMERA_I2C_BYTE_DATA); - LOG("sensor start regs: %d", err); - - int inf_step = 512 - INFINITY_DAC; - - // initial guess - s->lens_true_pos = 400; - - // reset lens position - struct msm_actuator_cfg_data actuator_cfg_data = {}; - actuator_cfg_data.cfgtype = CFG_SET_POSITION; - actuator_cfg_data.cfg.setpos = (struct msm_actuator_set_position_t){ - .number_of_steps = 1, - .hw_params = (uint32_t)7, - .pos = {INFINITY_DAC, 0}, - .delay = {0,} - }; - cam_ioctl(s->actuator_fd, VIDIOC_MSM_ACTUATOR_CFG, &actuator_cfg_data, "actuator set pos"); - - // TODO: confirm this isn't needed - /*memset(&actuator_cfg_data, 0, sizeof(actuator_cfg_data)); - actuator_cfg_data.cfgtype = CFG_MOVE_FOCUS; - actuator_cfg_data.cfg.move = (struct msm_actuator_move_params_t){ - .dir = 0, - .sign_dir = 1, - .dest_step_pos = inf_step, - .num_steps = inf_step, - .curr_lens_pos = 0, - .ringing_params = &actuator_ringing_params, - }; - err = ioctl(s->actuator_fd, VIDIOC_MSM_ACTUATOR_CFG, &actuator_cfg_data); // should be ~332 at startup ? - LOG("init actuator move focus: %d", err);*/ - //actuator_cfg_data.cfg.move.curr_lens_pos; - - s->cur_lens_pos = 0; - s->cur_step_pos = inf_step; - - actuator_move(s, s->cur_lens_pos); - LOG("init lens pos: %d", s->cur_lens_pos); -} - -void actuator_move(CameraState *s, uint16_t target) { - // LP3 moves only on even positions. TODO: use proper sensor params - - // focus on infinity assuming phone is perpendicular - static struct damping_params_t actuator_ringing_params = { - .damping_step = 1023, - .damping_delay = 20000, - .hw_params = 13, - }; - - int step = (target - s->cur_lens_pos) / 2; - - int dest_step_pos = s->cur_step_pos + step; - dest_step_pos = std::clamp(dest_step_pos, 0, 255); - - struct msm_actuator_cfg_data actuator_cfg_data = {0}; - actuator_cfg_data.cfgtype = CFG_MOVE_FOCUS; - actuator_cfg_data.cfg.move = (struct msm_actuator_move_params_t){ - .dir = (int8_t)((step > 0) ? MOVE_NEAR : MOVE_FAR), - .sign_dir = (int8_t)((step > 0) ? MSM_ACTUATOR_MOVE_SIGNED_NEAR : MSM_ACTUATOR_MOVE_SIGNED_FAR), - .dest_step_pos = (int16_t)dest_step_pos, - .num_steps = abs(step), - .curr_lens_pos = s->cur_lens_pos, - .ringing_params = &actuator_ringing_params, - }; - HANDLE_EINTR(ioctl(s->actuator_fd, VIDIOC_MSM_ACTUATOR_CFG, &actuator_cfg_data)); - - s->cur_step_pos = dest_step_pos; - s->cur_lens_pos = actuator_cfg_data.cfg.move.curr_lens_pos; - //LOGD("step %d target: %d lens pos: %d", dest_step_pos, target, s->cur_lens_pos); -} - -static void parse_autofocus(CameraState *s, uint8_t *d) { - int good_count = 0; - int16_t max_focus = -32767; - int avg_focus = 0; - - /*printf("FOCUS: "); - for (int i = 0; i < 0x10; i++) { - printf("%2.2X ", d[i]); - }*/ - - for (int i = 0; i < NUM_FOCUS; i++) { - int doff = i*5+5; - s->confidence[i] = d[doff]; - // this should just be a 10-bit signed int instead of 11 - // TODO: write it in a nicer way - int16_t focus_t = (d[doff+1] << 3) | (d[doff+2] >> 5); - if (focus_t >= 1024) focus_t = -(2048-focus_t); - s->focus[i] = focus_t; - //printf("%x->%d ", d[doff], focus_t); - if (s->confidence[i] > 0x20) { - good_count++; - max_focus = std::max(max_focus, s->focus[i]); - avg_focus += s->focus[i]; - } - } - // self recover override - if (s->self_recover > 1) { - s->focus_err = 200 * ((s->self_recover % 2 == 0) ? 1:-1); // far for even numbers, close for odd - s->self_recover -= 2; - return; - } - - if (good_count < 4) { - s->focus_err = nan(""); - return; - } - - avg_focus /= good_count; - - // outlier rejection - if (abs(avg_focus - max_focus) > 200) { - s->focus_err = nan(""); - return; - } - - s->focus_err = max_focus*1.0; -} - -static void do_autofocus(CameraState *s) { - float lens_true_pos = s->lens_true_pos.load(); - if (!isnan(s->focus_err)) { - // learn lens_true_pos - const float focus_kp = 0.005; - lens_true_pos -= s->focus_err*focus_kp; - } - - // stay off the walls - lens_true_pos = std::clamp(lens_true_pos, float(LP3_AF_DAC_DOWN), float(LP3_AF_DAC_UP)); - s->lens_true_pos.store(lens_true_pos); - actuator_move(s, lens_true_pos); -} - -void camera_autoexposure(CameraState *s, float grey_frac) { - if (s->camera_num == 0) { - CameraExpInfo tmp = road_cam_exp.load(); - tmp.op_id++; - tmp.grey_frac = grey_frac; - road_cam_exp.store(tmp); - } else { - CameraExpInfo tmp = driver_cam_exp.load(); - tmp.op_id++; - tmp.grey_frac = grey_frac; - driver_cam_exp.store(tmp); - } -} - -static void driver_camera_start(CameraState *s) { - set_exposure(s, 1.0, 1.0); - int err = sensor_write_regs(s, start_reg_array, std::size(start_reg_array), MSM_CAMERA_I2C_BYTE_DATA); - LOG("sensor start regs: %d", err); -} - -void cameras_open(MultiCameraState *s) { - struct msm_ispif_param_data ispif_params = { - .num = 4, - .entries = { - // road camera - {.vfe_intf = VFE0, .intftype = RDI0, .num_cids = 1, .cids[0] = CID0, .csid = CSID0}, - // driver camera - {.vfe_intf = VFE1, .intftype = RDI0, .num_cids = 1, .cids[0] = CID0, .csid = CSID2}, - // road camera (focus) - {.vfe_intf = VFE0, .intftype = RDI1, .num_cids = 1, .cids[0] = CID1, .csid = CSID0}, - // road camera (stats, for AE) - {.vfe_intf = VFE0, .intftype = RDI2, .num_cids = 1, .cids[0] = CID2, .csid = CSID0}, - }, - }; - s->msmcfg_fd = HANDLE_EINTR(open("/dev/media0", O_RDWR | O_NONBLOCK)); - assert(s->msmcfg_fd >= 0); - - sensors_init(s); - - s->v4l_fd = HANDLE_EINTR(open("/dev/video0", O_RDWR | O_NONBLOCK)); - assert(s->v4l_fd >= 0); - - s->ispif_fd = open_v4l_by_name_and_index("msm_ispif"); - assert(s->ispif_fd >= 0); - - // ISPIF: stop - // memset(&ispif_cfg_data, 0, sizeof(ispif_cfg_data)); - // ispif_cfg_data.cfg_type = ISPIF_STOP_FRAME_BOUNDARY; - // ispif_cfg_data.params = ispif_params; - // err = ioctl(s->ispif_fd, VIDIOC_MSM_ISPIF_CFG, &ispif_cfg_data); - // LOG("ispif stop: %d", err); - - LOG("*** open driver camera ***"); - s->driver_cam.ss[0].bufs = s->driver_cam.buf.camera_bufs.get(); - camera_open(&s->driver_cam, false); - - LOG("*** open road camera ***"); - s->road_cam.ss[0].bufs = s->road_cam.buf.camera_bufs.get(); - s->road_cam.ss[1].bufs = s->focus_bufs; - s->road_cam.ss[2].bufs = s->stats_bufs; - camera_open(&s->road_cam, true); - - if (getenv("CAMERA_TEST")) { - cameras_close(s); - exit(0); - } - - // ISPIF: set vfe info - struct ispif_cfg_data ispif_cfg_data = {.cfg_type = ISPIF_SET_VFE_INFO, .vfe_info.num_vfe = 2}; - int err = HANDLE_EINTR(ioctl(s->ispif_fd, VIDIOC_MSM_ISPIF_CFG, &ispif_cfg_data)); - LOG("ispif set vfe info: %d", err); - - // ISPIF: setup - ispif_cfg_data = {.cfg_type = ISPIF_INIT, .csid_version = 0x30050000 /* CSID_VERSION_V35*/}; - cam_ioctl(s->ispif_fd, VIDIOC_MSM_ISPIF_CFG, &ispif_cfg_data, "ispif setup"); - - ispif_cfg_data = {.cfg_type = ISPIF_CFG, .params = ispif_params}; - cam_ioctl(s->ispif_fd, VIDIOC_MSM_ISPIF_CFG, &ispif_cfg_data, "ispif cfg"); - - ispif_cfg_data.cfg_type = ISPIF_START_FRAME_BOUNDARY; - cam_ioctl(s->ispif_fd, VIDIOC_MSM_ISPIF_CFG, &ispif_cfg_data, "ispif start_frame_boundary"); - - driver_camera_start(&s->driver_cam); - road_camera_start(&s->road_cam); -} - - -static void camera_close(CameraState *s) { - // ISP: STOP_STREAM - s->stream_cfg.cmd = STOP_STREAM; - cam_ioctl(s->isp_fd, VIDIOC_MSM_ISP_CFG_STREAM, &s->stream_cfg, "isp stop stream"); - - for (int i = 0; i < 3; i++) { - StreamState *ss = &s->ss[i]; - if (ss->stream_req.axi_stream_handle != 0) { - cam_ioctl(s->isp_fd, VIDIOC_MSM_ISP_RELEASE_BUF, &ss->buf_request, "isp release buf"); - - struct msm_vfe_axi_stream_release_cmd stream_release = { - .stream_handle = ss->stream_req.axi_stream_handle, - }; - cam_ioctl(s->isp_fd, VIDIOC_MSM_ISP_RELEASE_STREAM, &stream_release, "isp release stream"); - } - } -} - -const char* get_isp_event_name(uint32_t type) { - switch (type) { - case ISP_EVENT_REG_UPDATE: return "ISP_EVENT_REG_UPDATE"; - case ISP_EVENT_EPOCH_0: return "ISP_EVENT_EPOCH_0"; - case ISP_EVENT_EPOCH_1: return "ISP_EVENT_EPOCH_1"; - case ISP_EVENT_START_ACK: return "ISP_EVENT_START_ACK"; - case ISP_EVENT_STOP_ACK: return "ISP_EVENT_STOP_ACK"; - case ISP_EVENT_IRQ_VIOLATION: return "ISP_EVENT_IRQ_VIOLATION"; - case ISP_EVENT_STATS_OVERFLOW: return "ISP_EVENT_STATS_OVERFLOW"; - case ISP_EVENT_ERROR: return "ISP_EVENT_ERROR"; - case ISP_EVENT_SOF: return "ISP_EVENT_SOF"; - case ISP_EVENT_EOF: return "ISP_EVENT_EOF"; - case ISP_EVENT_BUF_DONE: return "ISP_EVENT_BUF_DONE"; - case ISP_EVENT_BUF_DIVERT: return "ISP_EVENT_BUF_DIVERT"; - case ISP_EVENT_STATS_NOTIFY: return "ISP_EVENT_STATS_NOTIFY"; - case ISP_EVENT_COMP_STATS_NOTIFY: return "ISP_EVENT_COMP_STATS_NOTIFY"; - case ISP_EVENT_FE_READ_DONE: return "ISP_EVENT_FE_READ_DONE"; - case ISP_EVENT_IOMMU_P_FAULT: return "ISP_EVENT_IOMMU_P_FAULT"; - case ISP_EVENT_HW_FATAL_ERROR: return "ISP_EVENT_HW_FATAL_ERROR"; - case ISP_EVENT_PING_PONG_MISMATCH: return "ISP_EVENT_PING_PONG_MISMATCH"; - case ISP_EVENT_REG_UPDATE_MISSING: return "ISP_EVENT_REG_UPDATE_MISSING"; - case ISP_EVENT_BUF_FATAL_ERROR: return "ISP_EVENT_BUF_FATAL_ERROR"; - case ISP_EVENT_STREAM_UPDATE_DONE: return "ISP_EVENT_STREAM_UPDATE_DONE"; - default: return "unknown"; - } -} - -static FrameMetadata get_frame_metadata(CameraState *s, uint32_t frame_id) { - std::lock_guard lk(s->frame_info_lock); - for (auto &i : s->frame_metadata) { - if (i.frame_id == frame_id) { - return i; - } - } - // should never happen - return (FrameMetadata){ - .frame_id = (uint32_t)-1, - }; -} - -static void ops_thread(MultiCameraState *s) { - int last_road_cam_op_id = 0; - int last_driver_cam_op_id = 0; - - CameraExpInfo road_cam_op; - CameraExpInfo driver_cam_op; - - util::set_thread_name("camera_settings"); - while(!do_exit) { - road_cam_op = road_cam_exp.load(); - if (road_cam_op.op_id != last_road_cam_op_id) { - do_autoexposure(&s->road_cam, road_cam_op.grey_frac); - do_autofocus(&s->road_cam); - last_road_cam_op_id = road_cam_op.op_id; - } - - driver_cam_op = driver_cam_exp.load(); - if (driver_cam_op.op_id != last_driver_cam_op_id) { - do_autoexposure(&s->driver_cam, driver_cam_op.grey_frac); - last_driver_cam_op_id = driver_cam_op.op_id; - } - - util::sleep_for(50); - } -} - -static void setup_self_recover(CameraState *c, const uint16_t *lapres, size_t lapres_size) { - const float lens_true_pos = c->lens_true_pos.load(); - int self_recover = c->self_recover.load(); - if (self_recover < 2 && (lens_true_pos < (LP3_AF_DAC_DOWN + 1) || lens_true_pos > (LP3_AF_DAC_UP - 1)) && is_blur(lapres, lapres_size)) { - // truly stuck, needs help - if (--self_recover < -FOCUS_RECOVER_PATIENCE) { - LOGD("road camera bad state detected. attempting recovery from %.1f, recover state is %d", lens_true_pos, self_recover); - // parity determined by which end is stuck at - self_recover = FOCUS_RECOVER_STEPS + (lens_true_pos < LP3_AF_DAC_M ? 1 : 0); - } - } else if (self_recover < 2 && (lens_true_pos < (LP3_AF_DAC_M - LP3_AF_DAC_3SIG) || lens_true_pos > (LP3_AF_DAC_M + LP3_AF_DAC_3SIG))) { - // in suboptimal position with high prob, but may still recover by itself - if (--self_recover < -(FOCUS_RECOVER_PATIENCE * 3)) { - self_recover = FOCUS_RECOVER_STEPS / 2 + (lens_true_pos < LP3_AF_DAC_M ? 1 : 0); - } - } else if (self_recover < 0) { - self_recover += 1; // reset if fine - } - c->self_recover.store(self_recover); -} - -// called by processing_thread -void process_road_camera(MultiCameraState *s, CameraState *c, int cnt) { - const CameraBuf *b = &c->buf; - const int roi_id = cnt % std::size(s->lapres); // rolling roi - s->lapres[roi_id] = s->lap_conv->Update(b->q, (uint8_t *)b->cur_rgb_buf->addr, roi_id); - setup_self_recover(c, &s->lapres[0], std::size(s->lapres)); - - MessageBuilder msg; - auto framed = msg.initEvent().initRoadCameraState(); - fill_frame_data(framed, b->cur_frame_data); - if (env_send_road) { - framed.setImage(get_frame_image(b)); - } - framed.setFocusVal(s->road_cam.focus); - framed.setFocusConf(s->road_cam.confidence); - framed.setRecoverState(s->road_cam.self_recover); - framed.setSharpnessScore(s->lapres); - framed.setTransform(b->yuv_transform.v); - s->pm->send("roadCameraState", msg); - - if (cnt % 3 == 0) { - const int x = 290, y = 322, width = 560, height = 314; - const int skip = 1; - camera_autoexposure(c, set_exposure_target(b, x, x + width, skip, y, y + height, skip)); - } -} - -void cameras_run(MultiCameraState *s) { - std::vector threads; - threads.push_back(std::thread(ops_thread, s)); - threads.push_back(start_process_thread(s, &s->road_cam, process_road_camera)); - threads.push_back(start_process_thread(s, &s->driver_cam, common_process_driver_camera)); - - CameraState* cameras[2] = {&s->road_cam, &s->driver_cam}; - - while (!do_exit) { - struct pollfd fds[2] = {{.fd = cameras[0]->isp_fd, .events = POLLPRI}, - {.fd = cameras[1]->isp_fd, .events = POLLPRI}}; - int ret = poll(fds, std::size(fds), 1000); - if (ret < 0) { - if (errno == EINTR || errno == EAGAIN) continue; - LOGE("poll failed (%d - %d)", ret, errno); - break; - } - - // process cameras - for (int i=0; i<2; i++) { - if (!fds[i].revents) continue; - - CameraState *c = cameras[i]; - - struct v4l2_event ev = {}; - ret = HANDLE_EINTR(ioctl(c->isp_fd, VIDIOC_DQEVENT, &ev)); - const msm_isp_event_data *isp_event_data = (const msm_isp_event_data *)ev.u.data; - - if (ev.type == ISP_EVENT_BUF_DIVERT) { - const int buf_idx = isp_event_data->u.buf_done.buf_idx; - const int buffer = (isp_event_data->u.buf_done.stream_id & 0xFFFF) - 1; - if (buffer == 0) { - c->buf.camera_bufs_metadata[buf_idx] = get_frame_metadata(c, isp_event_data->frame_id); - c->buf.queue(buf_idx); - } else { - auto &ss = c->ss[buffer]; - if (buffer == 1) { - parse_autofocus(c, (uint8_t *)(ss.bufs[buf_idx].addr)); - } - ss.qbuf_info[buf_idx].dirty_buf = 1; - HANDLE_EINTR(ioctl(c->isp_fd, VIDIOC_MSM_ISP_ENQUEUE_BUF, &ss.qbuf_info[buf_idx])); - } - - } else if (ev.type == ISP_EVENT_EOF) { - const uint64_t timestamp = (isp_event_data->mono_timestamp.tv_sec * 1000000000ULL + isp_event_data->mono_timestamp.tv_usec * 1000); - std::lock_guard lk(c->frame_info_lock); - c->frame_metadata[c->frame_metadata_idx] = (FrameMetadata){ - .frame_id = isp_event_data->frame_id, - .timestamp_eof = timestamp, - .frame_length = (uint32_t)c->frame_length, - .integ_lines = (uint32_t)c->cur_integ_lines, - .lens_pos = c->cur_lens_pos, - .lens_err = c->focus_err, - .lens_true_pos = c->lens_true_pos, - .gain = c->cur_gain_frac, - .measured_grey_fraction = c->measured_grey_fraction, - .target_grey_fraction = c->target_grey_fraction, - .high_conversion_gain = false, - }; - c->frame_metadata_idx = (c->frame_metadata_idx + 1) % METADATA_BUF_COUNT; - - } else if (ev.type == ISP_EVENT_ERROR) { - LOGE("ISP_EVENT_ERROR! err type: 0x%08x", isp_event_data->u.error_info.err_type); - } - } - } - - LOG(" ************** STOPPING **************"); - - for (auto &t : threads) t.join(); - - cameras_close(s); -} - -void cameras_close(MultiCameraState *s) { - camera_close(&s->road_cam); - camera_close(&s->driver_cam); - for (int i = 0; i < FRAME_BUF_COUNT; i++) { - s->focus_bufs[i].free(); - s->stats_bufs[i].free(); - } - - delete s->lap_conv; - delete s->sm; - delete s->pm; -} diff --git a/selfdrive/camerad/cameras/camera_qcom.h b/selfdrive/camerad/cameras/camera_qcom.h deleted file mode 100644 index 87bbe4b7e7..0000000000 --- a/selfdrive/camerad/cameras/camera_qcom.h +++ /dev/null @@ -1,106 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "cereal/messaging/messaging.h" -#include "cereal/visionipc/visionbuf.h" -#include "selfdrive/camerad/cameras/camera_common.h" -#include "selfdrive/camerad/imgproc/utils.h" -#include "selfdrive/camerad/include/msm_cam_sensor.h" -#include "selfdrive/camerad/include/msmb_camera.h" -#include "selfdrive/camerad/include/msmb_isp.h" -#include "selfdrive/camerad/include/msmb_ispif.h" -#include "selfdrive/common/mat.h" -#include "selfdrive/common/util.h" - -#define FRAME_BUF_COUNT 4 -#define METADATA_BUF_COUNT 4 - -#define NUM_FOCUS 8 - -#define LP3_AF_DAC_DOWN 366 -#define LP3_AF_DAC_UP 634 -#define LP3_AF_DAC_M 440 -#define LP3_AF_DAC_3SIG 52 - -#define FOCUS_RECOVER_PATIENCE 50 // 2.5 seconds of complete blur -#define FOCUS_RECOVER_STEPS 240 // 6 seconds - -typedef struct CameraState CameraState; - -typedef int (*camera_apply_exposure_func)(CameraState *s, int gain, int integ_lines, uint32_t frame_length); - -typedef struct StreamState { - struct msm_isp_buf_request buf_request; - struct msm_vfe_axi_stream_request_cmd stream_req; - struct msm_isp_qbuf_info qbuf_info[FRAME_BUF_COUNT]; - VisionBuf *bufs; -} StreamState; - -typedef struct CameraState { - int camera_num; - int camera_id; - - int fps; - CameraInfo ci; - - unique_fd csid_fd; - unique_fd csiphy_fd; - unique_fd sensor_fd; - unique_fd isp_fd; - - struct msm_vfe_axi_stream_cfg_cmd stream_cfg; - - StreamState ss[3]; - CameraBuf buf; - - std::mutex frame_info_lock; - FrameMetadata frame_metadata[METADATA_BUF_COUNT]; - int frame_metadata_idx; - - // exposure - uint32_t pixel_clock, line_length_pclk; - uint32_t frame_length; - unsigned int max_gain; - float cur_exposure_frac, cur_gain_frac; - int cur_gain, cur_integ_lines; - - float measured_grey_fraction; - float target_grey_fraction; - - std::atomic digital_gain; - camera_apply_exposure_func apply_exposure; - - // rear camera only,used for focusing - unique_fd actuator_fd; - std::atomic focus_err; - std::atomic lens_true_pos; - std::atomic self_recover; // af recovery counter, neg is patience, pos is active - uint16_t cur_step_pos; - uint16_t cur_lens_pos; - int16_t focus[NUM_FOCUS]; - uint8_t confidence[NUM_FOCUS]; -} CameraState; - - -typedef struct MultiCameraState { - unique_fd ispif_fd; - unique_fd msmcfg_fd; - unique_fd v4l_fd; - uint16_t lapres[(ROI_X_MAX-ROI_X_MIN+1)*(ROI_Y_MAX-ROI_Y_MIN+1)]; - - VisionBuf focus_bufs[FRAME_BUF_COUNT]; - VisionBuf stats_bufs[FRAME_BUF_COUNT]; - - CameraState road_cam; - CameraState driver_cam; - - SubMaster *sm; - PubMaster *pm; - LapConv *lap_conv; -} MultiCameraState; - -void actuator_move(CameraState *s, uint16_t target); -int sensor_write_regs(CameraState *s, struct msm_camera_i2c_reg_array* arr, size_t size, int data_type); diff --git a/selfdrive/camerad/cameras/camera_qcom2.cc b/selfdrive/camerad/cameras/camera_qcom2.cc deleted file mode 100644 index f75e982be2..0000000000 --- a/selfdrive/camerad/cameras/camera_qcom2.cc +++ /dev/null @@ -1,1111 +0,0 @@ -#include "selfdrive/camerad/cameras/camera_qcom2.h" - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include "media/cam_defs.h" -#include "media/cam_isp.h" -#include "media/cam_isp_ife.h" -#include "media/cam_sensor.h" -#include "media/cam_sensor_cmn_header.h" -#include "media/cam_sync.h" -#include "selfdrive/common/swaglog.h" -#include "selfdrive/camerad/cameras/sensor2_i2c.h" - -extern ExitHandler do_exit; - -const size_t FRAME_WIDTH = 1928; -const size_t FRAME_HEIGHT = 1208; -const size_t FRAME_STRIDE = 2416; // for 10 bit output - -const int MIPI_SETTLE_CNT = 33; // Calculated by camera_freqs.py - -CameraInfo cameras_supported[CAMERA_ID_MAX] = { - [CAMERA_ID_AR0231] = { - .frame_width = FRAME_WIDTH, - .frame_height = FRAME_HEIGHT, - .frame_stride = FRAME_STRIDE, - .bayer = true, - .bayer_flip = 1, - .hdr = false - }, -}; - -const float DC_GAIN = 2.5; -const float sensor_analog_gains[] = { - 1.0/8.0, 2.0/8.0, 2.0/7.0, 3.0/7.0, // 0, 1, 2, 3 - 3.0/6.0, 4.0/6.0, 4.0/5.0, 5.0/5.0, // 4, 5, 6, 7 - 5.0/4.0, 6.0/4.0, 6.0/3.0, 7.0/3.0, // 8, 9, 10, 11 - 7.0/2.0, 8.0/2.0, 8.0/1.0}; // 12, 13, 14, 15 = bypass - -const int ANALOG_GAIN_MIN_IDX = 0x1; // 0.25x -const int ANALOG_GAIN_REC_IDX = 0x6; // 0.8x -const int ANALOG_GAIN_MAX_IDX = 0xD; // 4.0x - -const int EXPOSURE_TIME_MIN = 2; // with HDR, fastest ss -const int EXPOSURE_TIME_MAX = 1904; // with HDR, slowest ss - -// ************** low level camera helpers **************** -int cam_control(int fd, int op_code, void *handle, int size) { - struct cam_control camcontrol = {0}; - camcontrol.op_code = op_code; - camcontrol.handle = (uint64_t)handle; - if (size == 0) { - camcontrol.size = 8; - camcontrol.handle_type = CAM_HANDLE_MEM_HANDLE; - } else { - camcontrol.size = size; - camcontrol.handle_type = CAM_HANDLE_USER_POINTER; - } - - int ret = HANDLE_EINTR(ioctl(fd, VIDIOC_CAM_CONTROL, &camcontrol)); - if (ret == -1) { - printf("OP CODE ERR - %d \n", op_code); - perror("wat"); - } - return ret; -} - -std::optional device_acquire(int fd, int32_t session_handle, void *data) { - struct cam_acquire_dev_cmd cmd = { - .session_handle = session_handle, - .handle_type = CAM_HANDLE_USER_POINTER, - .num_resources = (uint32_t)(data ? 1 : 0), - .resource_hdl = (uint64_t)data, - }; - int err = cam_control(fd, CAM_ACQUIRE_DEV, &cmd, sizeof(cmd)); - return err == 0 ? std::make_optional(cmd.dev_handle) : std::nullopt; -}; - -int device_config(int fd, int32_t session_handle, int32_t dev_handle, uint64_t packet_handle) { - struct cam_config_dev_cmd cmd = { - .session_handle = session_handle, - .dev_handle = dev_handle, - .packet_handle = packet_handle, - }; - return cam_control(fd, CAM_CONFIG_DEV, &cmd, sizeof(cmd)); -} - -int device_control(int fd, int op_code, int session_handle, int dev_handle) { - // start stop and release are all the same - struct cam_start_stop_dev_cmd cmd { .session_handle = session_handle, .dev_handle = dev_handle }; - return cam_control(fd, op_code, &cmd, sizeof(cmd)); -} - -void *alloc_w_mmu_hdl(int video0_fd, int len, uint32_t *handle, int align = 8, int flags = CAM_MEM_FLAG_KMD_ACCESS | CAM_MEM_FLAG_UMD_ACCESS | CAM_MEM_FLAG_CMD_BUF_TYPE, - int mmu_hdl = 0, int mmu_hdl2 = 0) { - struct cam_mem_mgr_alloc_cmd mem_mgr_alloc_cmd = {0}; - mem_mgr_alloc_cmd.len = len; - mem_mgr_alloc_cmd.align = align; - mem_mgr_alloc_cmd.flags = flags; - mem_mgr_alloc_cmd.num_hdl = 0; - if (mmu_hdl != 0) { - mem_mgr_alloc_cmd.mmu_hdls[0] = mmu_hdl; - mem_mgr_alloc_cmd.num_hdl++; - } - if (mmu_hdl2 != 0) { - mem_mgr_alloc_cmd.mmu_hdls[1] = mmu_hdl2; - mem_mgr_alloc_cmd.num_hdl++; - } - - cam_control(video0_fd, CAM_REQ_MGR_ALLOC_BUF, &mem_mgr_alloc_cmd, sizeof(mem_mgr_alloc_cmd)); - *handle = mem_mgr_alloc_cmd.out.buf_handle; - - void *ptr = NULL; - if (mem_mgr_alloc_cmd.out.fd > 0) { - ptr = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, mem_mgr_alloc_cmd.out.fd, 0); - assert(ptr != MAP_FAILED); - } - - // LOGD("allocated: %x %d %llx mapped %p", mem_mgr_alloc_cmd.out.buf_handle, mem_mgr_alloc_cmd.out.fd, mem_mgr_alloc_cmd.out.vaddr, ptr); - - return ptr; -} - -void release(int video0_fd, uint32_t handle) { - int ret; - struct cam_mem_mgr_release_cmd mem_mgr_release_cmd = {0}; - mem_mgr_release_cmd.buf_handle = handle; - - ret = cam_control(video0_fd, CAM_REQ_MGR_RELEASE_BUF, &mem_mgr_release_cmd, sizeof(mem_mgr_release_cmd)); - assert(ret == 0); -} - -void release_fd(int video0_fd, uint32_t handle) { - // handle to fd - close(handle>>16); - release(video0_fd, handle); -} - -void clear_req_queue(int fd, int32_t session_hdl, int32_t link_hdl) { - struct cam_req_mgr_flush_info req_mgr_flush_request = {0}; - req_mgr_flush_request.session_hdl = session_hdl; - req_mgr_flush_request.link_hdl = link_hdl; - req_mgr_flush_request.flush_type = CAM_REQ_MGR_FLUSH_TYPE_ALL; - int ret; - ret = cam_control(fd, CAM_REQ_MGR_FLUSH_REQ, &req_mgr_flush_request, sizeof(req_mgr_flush_request)); - // LOGD("flushed all req: %d", ret); -} - -// ************** high level camera helpers **************** - -void sensors_poke(struct CameraState *s, int request_id) { - uint32_t cam_packet_handle = 0; - int size = sizeof(struct cam_packet); - struct cam_packet *pkt = (struct cam_packet *)alloc_w_mmu_hdl(s->multi_cam_state->video0_fd, size, &cam_packet_handle); - pkt->num_cmd_buf = 0; - pkt->kmd_cmd_buf_index = -1; - pkt->header.size = size; - pkt->header.op_code = 0x7f; - pkt->header.request_id = request_id; - - int ret = device_config(s->sensor_fd, s->session_handle, s->sensor_dev_handle, cam_packet_handle); - assert(ret == 0); - - munmap(pkt, size); - release_fd(s->multi_cam_state->video0_fd, cam_packet_handle); -} - -void sensors_i2c(struct CameraState *s, struct i2c_random_wr_payload* dat, int len, int op_code) { - // LOGD("sensors_i2c: %d", len); - uint32_t cam_packet_handle = 0; - int size = sizeof(struct cam_packet)+sizeof(struct cam_cmd_buf_desc)*1; - struct cam_packet *pkt = (struct cam_packet *)alloc_w_mmu_hdl(s->multi_cam_state->video0_fd, size, &cam_packet_handle); - pkt->num_cmd_buf = 1; - pkt->kmd_cmd_buf_index = -1; - pkt->header.size = size; - pkt->header.op_code = op_code; - struct cam_cmd_buf_desc *buf_desc = (struct cam_cmd_buf_desc *)&pkt->payload; - - buf_desc[0].size = buf_desc[0].length = sizeof(struct i2c_rdwr_header) + len*sizeof(struct i2c_random_wr_payload); - buf_desc[0].type = CAM_CMD_BUF_I2C; - - struct cam_cmd_i2c_random_wr *i2c_random_wr = (struct cam_cmd_i2c_random_wr *)alloc_w_mmu_hdl(s->multi_cam_state->video0_fd, buf_desc[0].size, (uint32_t*)&buf_desc[0].mem_handle); - i2c_random_wr->header.count = len; - i2c_random_wr->header.op_code = 1; - i2c_random_wr->header.cmd_type = CAMERA_SENSOR_CMD_TYPE_I2C_RNDM_WR; - i2c_random_wr->header.data_type = CAMERA_SENSOR_I2C_TYPE_WORD; - i2c_random_wr->header.addr_type = CAMERA_SENSOR_I2C_TYPE_WORD; - memcpy(i2c_random_wr->random_wr_payload, dat, len*sizeof(struct i2c_random_wr_payload)); - - int ret = device_config(s->sensor_fd, s->session_handle, s->sensor_dev_handle, cam_packet_handle); - assert(ret == 0); - - munmap(i2c_random_wr, buf_desc[0].size); - release_fd(s->multi_cam_state->video0_fd, buf_desc[0].mem_handle); - munmap(pkt, size); - release_fd(s->multi_cam_state->video0_fd, cam_packet_handle); -} -static cam_cmd_power *power_set_wait(cam_cmd_power *power, int16_t delay_ms) { - cam_cmd_unconditional_wait *unconditional_wait = (cam_cmd_unconditional_wait *)((char *)power + (sizeof(struct cam_cmd_power) + (power->count - 1) * sizeof(struct cam_power_settings))); - unconditional_wait->cmd_type = CAMERA_SENSOR_CMD_TYPE_WAIT; - unconditional_wait->delay = delay_ms; - unconditional_wait->op_code = CAMERA_SENSOR_WAIT_OP_SW_UCND; - return (struct cam_cmd_power *)(unconditional_wait + 1); -}; - -void sensors_init(int video0_fd, int sensor_fd, int camera_num) { - uint32_t cam_packet_handle = 0; - int size = sizeof(struct cam_packet)+sizeof(struct cam_cmd_buf_desc)*2; - struct cam_packet *pkt = (struct cam_packet *)alloc_w_mmu_hdl(video0_fd, size, &cam_packet_handle); - pkt->num_cmd_buf = 2; - pkt->kmd_cmd_buf_index = -1; - pkt->header.op_code = 0x1000003; - pkt->header.size = size; - struct cam_cmd_buf_desc *buf_desc = (struct cam_cmd_buf_desc *)&pkt->payload; - - buf_desc[0].size = buf_desc[0].length = sizeof(struct cam_cmd_i2c_info) + sizeof(struct cam_cmd_probe); - buf_desc[0].type = CAM_CMD_BUF_LEGACY; - struct cam_cmd_i2c_info *i2c_info = (struct cam_cmd_i2c_info *)alloc_w_mmu_hdl(video0_fd, buf_desc[0].size, (uint32_t*)&buf_desc[0].mem_handle); - auto probe = (struct cam_cmd_probe *)(i2c_info + 1); - - switch (camera_num) { - case 0: - // port 0 - i2c_info->slave_addr = 0x20; - probe->camera_id = 0; - break; - case 1: - // port 1 - i2c_info->slave_addr = 0x30; - probe->camera_id = 1; - break; - case 2: - // port 2 - i2c_info->slave_addr = 0x20; - probe->camera_id = 2; - break; - } - - // 0(I2C_STANDARD_MODE) = 100khz, 1(I2C_FAST_MODE) = 400khz - //i2c_info->i2c_freq_mode = I2C_STANDARD_MODE; - i2c_info->i2c_freq_mode = I2C_FAST_MODE; - i2c_info->cmd_type = CAMERA_SENSOR_CMD_TYPE_I2C_INFO; - - probe->data_type = CAMERA_SENSOR_I2C_TYPE_WORD; - probe->addr_type = CAMERA_SENSOR_I2C_TYPE_WORD; - probe->op_code = 3; // don't care? - probe->cmd_type = CAMERA_SENSOR_CMD_TYPE_PROBE; - probe->reg_addr = 0x3000; //0x300a; //0x300b; - probe->expected_data = 0x354; //0x7750; //0x885a; - probe->data_mask = 0; - - //buf_desc[1].size = buf_desc[1].length = 148; - buf_desc[1].size = buf_desc[1].length = 196; - buf_desc[1].type = CAM_CMD_BUF_I2C; - struct cam_cmd_power *power_settings = (struct cam_cmd_power *)alloc_w_mmu_hdl(video0_fd, buf_desc[1].size, (uint32_t*)&buf_desc[1].mem_handle); - memset(power_settings, 0, buf_desc[1].size); - // 7750 - /*power->count = 2; - power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_UP; - power->power_settings[0].power_seq_type = 2; - power->power_settings[1].power_seq_type = 8; - power = (void*)power + (sizeof(struct cam_cmd_power) + (power->count-1)*sizeof(struct cam_power_settings));*/ - - // 885a - struct cam_cmd_power *power = power_settings; - power->count = 4; - power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_UP; - power->power_settings[0].power_seq_type = 3; // clock?? - power->power_settings[1].power_seq_type = 1; // analog - power->power_settings[2].power_seq_type = 2; // digital - power->power_settings[3].power_seq_type = 8; // reset low - power = power_set_wait(power, 5); - - // set clock - power->count = 1; - power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_UP; - power->power_settings[0].power_seq_type = 0; - power->power_settings[0].config_val_low = 19200000; //Hz - power = power_set_wait(power, 10); - - // 8,1 is this reset? - power->count = 1; - power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_UP; - power->power_settings[0].power_seq_type = 8; - power->power_settings[0].config_val_low = 1; - power = power_set_wait(power, 100); - - // probe happens here - - // disable clock - power->count = 1; - power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_DOWN; - power->power_settings[0].power_seq_type = 0; - power->power_settings[0].config_val_low = 0; - power = power_set_wait(power, 1); - - // reset high - power->count = 1; - power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_DOWN; - power->power_settings[0].power_seq_type = 8; - power->power_settings[0].config_val_low = 1; - power = power_set_wait(power, 1); - - // reset low - power->count = 1; - power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_DOWN; - power->power_settings[0].power_seq_type = 8; - power->power_settings[0].config_val_low = 0; - power = power_set_wait(power, 1); - - // 7750 - /*power->count = 1; - power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_DOWN; - power->power_settings[0].power_seq_type = 2; - power = (void*)power + (sizeof(struct cam_cmd_power) + (power->count-1)*sizeof(struct cam_power_settings));*/ - - // 885a - power->count = 3; - power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_DOWN; - power->power_settings[0].power_seq_type = 2; - power->power_settings[1].power_seq_type = 1; - power->power_settings[2].power_seq_type = 3; - - LOGD("probing the sensor"); - int ret = cam_control(sensor_fd, CAM_SENSOR_PROBE_CMD, (void *)(uintptr_t)cam_packet_handle, 0); - assert(ret == 0); - - munmap(i2c_info, buf_desc[0].size); - release_fd(video0_fd, buf_desc[0].mem_handle); - munmap(power_settings, buf_desc[1].size); - release_fd(video0_fd, buf_desc[1].mem_handle); - munmap(pkt, size); - release_fd(video0_fd, cam_packet_handle); -} - -void config_isp(struct CameraState *s, int io_mem_handle, int fence, int request_id, int buf0_mem_handle, int buf0_offset) { - uint32_t cam_packet_handle = 0; - int size = sizeof(struct cam_packet)+sizeof(struct cam_cmd_buf_desc)*2; - if (io_mem_handle != 0) { - size += sizeof(struct cam_buf_io_cfg); - } - struct cam_packet *pkt = (struct cam_packet *)alloc_w_mmu_hdl(s->multi_cam_state->video0_fd, size, &cam_packet_handle); - pkt->num_cmd_buf = 2; - pkt->kmd_cmd_buf_index = 0; - // YUV has kmd_cmd_buf_offset = 1780 - // I guess this is the ISP command - // YUV also has patch_offset = 0x1030 and num_patches = 10 - - if (io_mem_handle != 0) { - pkt->io_configs_offset = sizeof(struct cam_cmd_buf_desc)*2; - pkt->num_io_configs = 1; - } - - if (io_mem_handle != 0) { - pkt->header.op_code = 0xf000001; - pkt->header.request_id = request_id; - } else { - pkt->header.op_code = 0xf000000; - } - pkt->header.size = size; - struct cam_cmd_buf_desc *buf_desc = (struct cam_cmd_buf_desc *)&pkt->payload; - struct cam_buf_io_cfg *io_cfg = (struct cam_buf_io_cfg *)((char*)&pkt->payload + pkt->io_configs_offset); - - // TODO: support MMU - buf_desc[0].size = 65624; - buf_desc[0].length = 0; - buf_desc[0].type = CAM_CMD_BUF_DIRECT; - buf_desc[0].meta_data = 3; - buf_desc[0].mem_handle = buf0_mem_handle; - buf_desc[0].offset = buf0_offset; - - // parsed by cam_isp_packet_generic_blob_handler - struct isp_packet { - uint32_t type_0; - cam_isp_resource_hfr_config resource_hfr; - - uint32_t type_1; - cam_isp_clock_config clock; - uint64_t extra_rdi_hz[3]; - - uint32_t type_2; - cam_isp_bw_config bw; - struct cam_isp_bw_vote extra_rdi_vote[6]; - } __attribute__((packed)) tmp; - memset(&tmp, 0, sizeof(tmp)); - - tmp.type_0 = CAM_ISP_GENERIC_BLOB_TYPE_HFR_CONFIG; - tmp.type_0 |= sizeof(cam_isp_resource_hfr_config) << 8; - static_assert(sizeof(cam_isp_resource_hfr_config) == 0x20); - tmp.resource_hfr = { - .num_ports = 1, // 10 for YUV (but I don't think we need them) - .port_hfr_config[0] = { - .resource_type = CAM_ISP_IFE_OUT_RES_RDI_0, // CAM_ISP_IFE_OUT_RES_FULL for YUV - .subsample_pattern = 1, - .subsample_period = 0, - .framedrop_pattern = 1, - .framedrop_period = 0, - }}; - - tmp.type_1 = CAM_ISP_GENERIC_BLOB_TYPE_CLOCK_CONFIG; - tmp.type_1 |= (sizeof(cam_isp_clock_config) + sizeof(tmp.extra_rdi_hz)) << 8; - static_assert((sizeof(cam_isp_clock_config) + sizeof(tmp.extra_rdi_hz)) == 0x38); - tmp.clock = { - .usage_type = 1, // dual mode - .num_rdi = 4, - .left_pix_hz = 404000000, - .right_pix_hz = 404000000, - .rdi_hz[0] = 404000000, - }; - - - tmp.type_2 = CAM_ISP_GENERIC_BLOB_TYPE_BW_CONFIG; - tmp.type_2 |= (sizeof(cam_isp_bw_config) + sizeof(tmp.extra_rdi_vote)) << 8; - static_assert((sizeof(cam_isp_bw_config) + sizeof(tmp.extra_rdi_vote)) == 0xe0); - tmp.bw = { - .usage_type = 1, // dual mode - .num_rdi = 4, - .left_pix_vote = { - .resource_id = 0, - .cam_bw_bps = 450000000, - .ext_bw_bps = 450000000, - }, - .rdi_vote[0] = { - .resource_id = 0, - .cam_bw_bps = 8706200000, - .ext_bw_bps = 8706200000, - }, - }; - - static_assert(offsetof(struct isp_packet, type_2) == 0x60); - - buf_desc[1].size = sizeof(tmp); - buf_desc[1].offset = io_mem_handle != 0 ? 0x60 : 0; - buf_desc[1].length = buf_desc[1].size - buf_desc[1].offset; - buf_desc[1].type = CAM_CMD_BUF_GENERIC; - buf_desc[1].meta_data = CAM_ISP_PACKET_META_GENERIC_BLOB_COMMON; - uint32_t *buf2 = (uint32_t *)alloc_w_mmu_hdl(s->multi_cam_state->video0_fd, buf_desc[1].size, (uint32_t*)&buf_desc[1].mem_handle, 0x20); - memcpy(buf2, &tmp, sizeof(tmp)); - - if (io_mem_handle != 0) { - io_cfg[0].mem_handle[0] = io_mem_handle; - io_cfg[0].planes[0] = (struct cam_plane_cfg){ - .width = FRAME_WIDTH, - .height = FRAME_HEIGHT, - .plane_stride = FRAME_STRIDE, - .slice_height = FRAME_HEIGHT, - .meta_stride = 0x0, // YUV has meta(stride=0x400, size=0x5000) - .meta_size = 0x0, - .meta_offset = 0x0, - .packer_config = 0x0, // 0xb for YUV - .mode_config = 0x0, // 0x9ef for YUV - .tile_config = 0x0, - .h_init = 0x0, - .v_init = 0x0, - }; - io_cfg[0].format = CAM_FORMAT_MIPI_RAW_10; // CAM_FORMAT_UBWC_TP10 for YUV - io_cfg[0].color_space = CAM_COLOR_SPACE_BASE; // CAM_COLOR_SPACE_BT601_FULL for YUV - io_cfg[0].color_pattern = 0x5; // 0x0 for YUV - io_cfg[0].bpp = 0xa; - io_cfg[0].resource_type = CAM_ISP_IFE_OUT_RES_RDI_0; // CAM_ISP_IFE_OUT_RES_FULL for YUV - io_cfg[0].fence = fence; - io_cfg[0].direction = CAM_BUF_OUTPUT; - io_cfg[0].subsample_pattern = 0x1; - io_cfg[0].framedrop_pattern = 0x1; - } - - int ret = device_config(s->multi_cam_state->isp_fd, s->session_handle, s->isp_dev_handle, cam_packet_handle); - assert(ret == 0); - if (ret != 0) { - printf("ISP CONFIG FAILED\n"); - } - - munmap(buf2, buf_desc[1].size); - release_fd(s->multi_cam_state->video0_fd, buf_desc[1].mem_handle); - // release_fd(s->multi_cam_state->video0_fd, buf_desc[0].mem_handle); - munmap(pkt, size); - release_fd(s->multi_cam_state->video0_fd, cam_packet_handle); -} - -void enqueue_buffer(struct CameraState *s, int i, bool dp) { - int ret; - int request_id = s->request_ids[i]; - - if (s->buf_handle[i]) { - release(s->multi_cam_state->video0_fd, s->buf_handle[i]); - // wait - struct cam_sync_wait sync_wait = {0}; - sync_wait.sync_obj = s->sync_objs[i]; - sync_wait.timeout_ms = 50; // max dt tolerance, typical should be 23 - ret = cam_control(s->multi_cam_state->video1_fd, CAM_SYNC_WAIT, &sync_wait, sizeof(sync_wait)); - // LOGD("fence wait: %d %d", ret, sync_wait.sync_obj); - - s->buf.camera_bufs_metadata[i].timestamp_eof = (uint64_t)nanos_since_boot(); // set true eof - if (dp) s->buf.queue(i); - - // destroy old output fence - struct cam_sync_info sync_destroy = {0}; - strcpy(sync_destroy.name, "NodeOutputPortFence"); - sync_destroy.sync_obj = s->sync_objs[i]; - ret = cam_control(s->multi_cam_state->video1_fd, CAM_SYNC_DESTROY, &sync_destroy, sizeof(sync_destroy)); - // LOGD("fence destroy: %d %d", ret, sync_destroy.sync_obj); - } - - // do stuff - struct cam_req_mgr_sched_request req_mgr_sched_request = {0}; - req_mgr_sched_request.session_hdl = s->session_handle; - req_mgr_sched_request.link_hdl = s->link_handle; - req_mgr_sched_request.req_id = request_id; - ret = cam_control(s->multi_cam_state->video0_fd, CAM_REQ_MGR_SCHED_REQ, &req_mgr_sched_request, sizeof(req_mgr_sched_request)); - // LOGD("sched req: %d %d", ret, request_id); - - // create output fence - struct cam_sync_info sync_create = {0}; - strcpy(sync_create.name, "NodeOutputPortFence"); - ret = cam_control(s->multi_cam_state->video1_fd, CAM_SYNC_CREATE, &sync_create, sizeof(sync_create)); - // LOGD("fence req: %d %d", ret, sync_create.sync_obj); - s->sync_objs[i] = sync_create.sync_obj; - - // configure ISP to put the image in place - struct cam_mem_mgr_map_cmd mem_mgr_map_cmd = {0}; - mem_mgr_map_cmd.mmu_hdls[0] = s->multi_cam_state->device_iommu; - mem_mgr_map_cmd.num_hdl = 1; - mem_mgr_map_cmd.flags = CAM_MEM_FLAG_HW_READ_WRITE; - mem_mgr_map_cmd.fd = s->buf.camera_bufs[i].fd; - ret = cam_control(s->multi_cam_state->video0_fd, CAM_REQ_MGR_MAP_BUF, &mem_mgr_map_cmd, sizeof(mem_mgr_map_cmd)); - // LOGD("map buf req: (fd: %d) 0x%x %d", s->bufs[i].fd, mem_mgr_map_cmd.out.buf_handle, ret); - s->buf_handle[i] = mem_mgr_map_cmd.out.buf_handle; - - // poke sensor - sensors_poke(s, request_id); - // LOGD("Poked sensor"); - - // push the buffer - config_isp(s, s->buf_handle[i], s->sync_objs[i], request_id, s->buf0_handle, 65632*(i+1)); -} - -void enqueue_req_multi(struct CameraState *s, int start, int n, bool dp) { - for (int i=start;irequest_ids[(i - 1) % FRAME_BUF_COUNT] = i; - enqueue_buffer(s, (i - 1) % FRAME_BUF_COUNT, dp); - } -} - -// ******************* camera ******************* - -static void camera_init(MultiCameraState *multi_cam_state, VisionIpcServer * v, CameraState *s, int camera_id, int camera_num, unsigned int fps, cl_device_id device_id, cl_context ctx, VisionStreamType rgb_type, VisionStreamType yuv_type) { - LOGD("camera init %d", camera_num); - s->multi_cam_state = multi_cam_state; - assert(camera_id < std::size(cameras_supported)); - s->ci = cameras_supported[camera_id]; - assert(s->ci.frame_width != 0); - - s->camera_num = camera_num; - - s->request_id_last = 0; - s->skipped = true; - - s->min_ev = EXPOSURE_TIME_MIN * sensor_analog_gains[ANALOG_GAIN_MIN_IDX]; - s->max_ev = EXPOSURE_TIME_MAX * sensor_analog_gains[ANALOG_GAIN_MAX_IDX] * DC_GAIN; - s->target_grey_fraction = 0.3; - - s->dc_gain_enabled = false; - s->gain_idx = ANALOG_GAIN_REC_IDX; - s->exposure_time = 5; - s->cur_ev[0] = s->cur_ev[1] = s->cur_ev[2] = (s->dc_gain_enabled ? DC_GAIN : 1) * sensor_analog_gains[s->gain_idx] * s->exposure_time; - - s->buf.init(device_id, ctx, s, v, FRAME_BUF_COUNT, rgb_type, yuv_type); -} - -static void camera_open(CameraState *s) { - s->sensor_fd = open_v4l_by_name_and_index("cam-sensor-driver", s->camera_num); - assert(s->sensor_fd >= 0); - LOGD("opened sensor for %d", s->camera_num); - - // probe the sensor - LOGD("-- Probing sensor %d", s->camera_num); - sensors_init(s->multi_cam_state->video0_fd, s->sensor_fd, s->camera_num); - - // create session - struct cam_req_mgr_session_info session_info = {}; - int ret = cam_control(s->multi_cam_state->video0_fd, CAM_REQ_MGR_CREATE_SESSION, &session_info, sizeof(session_info)); - LOGD("get session: %d 0x%X", ret, session_info.session_hdl); - s->session_handle = session_info.session_hdl; - - // access the sensor - LOGD("-- Accessing sensor"); - auto sensor_dev_handle = device_acquire(s->sensor_fd, s->session_handle, nullptr); - assert(sensor_dev_handle); - s->sensor_dev_handle = *sensor_dev_handle; - LOGD("acquire sensor dev"); - - struct cam_isp_in_port_info in_port_info = { - .res_type = (uint32_t[]){CAM_ISP_IFE_IN_RES_PHY_0, CAM_ISP_IFE_IN_RES_PHY_1, CAM_ISP_IFE_IN_RES_PHY_2}[s->camera_num], - - .lane_type = CAM_ISP_LANE_TYPE_DPHY, - .lane_num = 4, - .lane_cfg = 0x3210, - - .vc = 0x0, - // .dt = 0x2C; //CSI_RAW12 - .dt = 0x2B, //CSI_RAW10 - .format = CAM_FORMAT_MIPI_RAW_10, - - .test_pattern = 0x2, // 0x3? - .usage_type = 0x0, - - .left_start = 0, - .left_stop = FRAME_WIDTH - 1, - .left_width = FRAME_WIDTH, - - .right_start = 0, - .right_stop = FRAME_WIDTH - 1, - .right_width = FRAME_WIDTH, - - .line_start = 0, - .line_stop = FRAME_HEIGHT - 1, - .height = FRAME_HEIGHT, - - .pixel_clk = 0x0, - .batch_size = 0x0, - .dsp_mode = CAM_ISP_DSP_MODE_NONE, - .hbi_cnt = 0x0, - .custom_csid = 0x0, - - .num_out_res = 0x1, - .data[0] = (struct cam_isp_out_port_info){ - .res_type = CAM_ISP_IFE_OUT_RES_RDI_0, - .format = CAM_FORMAT_MIPI_RAW_10, - .width = FRAME_WIDTH, - .height = FRAME_HEIGHT, - .comp_grp_id = 0x0, .split_point = 0x0, .secure_mode = 0x0, - }, - }; - struct cam_isp_resource isp_resource = { - .resource_id = CAM_ISP_RES_ID_PORT, - .handle_type = CAM_HANDLE_USER_POINTER, - .res_hdl = (uint64_t)&in_port_info, - .length = sizeof(in_port_info), - }; - - auto isp_dev_handle = device_acquire(s->multi_cam_state->isp_fd, s->session_handle, &isp_resource); - assert(isp_dev_handle); - s->isp_dev_handle = *isp_dev_handle; - LOGD("acquire isp dev"); - - s->csiphy_fd = open_v4l_by_name_and_index("cam-csiphy-driver", s->camera_num); - assert(s->csiphy_fd >= 0); - LOGD("opened csiphy for %d", s->camera_num); - - struct cam_csiphy_acquire_dev_info csiphy_acquire_dev_info = {.combo_mode = 0}; - auto csiphy_dev_handle = device_acquire(s->csiphy_fd, s->session_handle, &csiphy_acquire_dev_info); - assert(csiphy_dev_handle); - s->csiphy_dev_handle = *csiphy_dev_handle; - LOGD("acquire csiphy dev"); - - // config ISP - alloc_w_mmu_hdl(s->multi_cam_state->video0_fd, 984480, (uint32_t*)&s->buf0_handle, 0x20, CAM_MEM_FLAG_HW_READ_WRITE | CAM_MEM_FLAG_KMD_ACCESS | CAM_MEM_FLAG_UMD_ACCESS | CAM_MEM_FLAG_CMD_BUF_TYPE, s->multi_cam_state->device_iommu, s->multi_cam_state->cdm_iommu); - config_isp(s, 0, 0, 1, s->buf0_handle, 0); - - LOG("-- Configuring sensor"); - sensors_i2c(s, init_array_ar0231, std::size(init_array_ar0231), CAM_SENSOR_PACKET_OPCODE_SENSOR_CONFIG); - //sensors_i2c(s, start_reg_array, std::size(start_reg_array), CAM_SENSOR_PACKET_OPCODE_SENSOR_STREAMON); - //sensors_i2c(s, stop_reg_array, std::size(stop_reg_array), CAM_SENSOR_PACKET_OPCODE_SENSOR_STREAMOFF); - - - // config csiphy - LOG("-- Config CSI PHY"); - { - uint32_t cam_packet_handle = 0; - int size = sizeof(struct cam_packet)+sizeof(struct cam_cmd_buf_desc)*1; - struct cam_packet *pkt = (struct cam_packet *)alloc_w_mmu_hdl(s->multi_cam_state->video0_fd, size, &cam_packet_handle); - pkt->num_cmd_buf = 1; - pkt->kmd_cmd_buf_index = -1; - pkt->header.size = size; - struct cam_cmd_buf_desc *buf_desc = (struct cam_cmd_buf_desc *)&pkt->payload; - - buf_desc[0].size = buf_desc[0].length = sizeof(struct cam_csiphy_info); - buf_desc[0].type = CAM_CMD_BUF_GENERIC; - - struct cam_csiphy_info *csiphy_info = (struct cam_csiphy_info *)alloc_w_mmu_hdl(s->multi_cam_state->video0_fd, buf_desc[0].size, (uint32_t*)&buf_desc[0].mem_handle); - csiphy_info->lane_mask = 0x1f; - csiphy_info->lane_assign = 0x3210;// skip clk. How is this 16 bit for 5 channels?? - csiphy_info->csiphy_3phase = 0x0; // no 3 phase, only 2 conductors per lane - csiphy_info->combo_mode = 0x0; - csiphy_info->lane_cnt = 0x4; - csiphy_info->secure_mode = 0x0; - csiphy_info->settle_time = MIPI_SETTLE_CNT * 200000000ULL; - csiphy_info->data_rate = 48000000; // Calculated by camera_freqs.py - - int ret_ = device_config(s->csiphy_fd, s->session_handle, s->csiphy_dev_handle, cam_packet_handle); - assert(ret_ == 0); - - munmap(csiphy_info, buf_desc[0].size); - release_fd(s->multi_cam_state->video0_fd, buf_desc[0].mem_handle); - munmap(pkt, size); - release_fd(s->multi_cam_state->video0_fd, cam_packet_handle); - } - - // link devices - LOG("-- Link devices"); - struct cam_req_mgr_link_info req_mgr_link_info = {0}; - req_mgr_link_info.session_hdl = s->session_handle; - req_mgr_link_info.num_devices = 2; - req_mgr_link_info.dev_hdls[0] = s->isp_dev_handle; - req_mgr_link_info.dev_hdls[1] = s->sensor_dev_handle; - ret = cam_control(s->multi_cam_state->video0_fd, CAM_REQ_MGR_LINK, &req_mgr_link_info, sizeof(req_mgr_link_info)); - s->link_handle = req_mgr_link_info.link_hdl; - LOGD("link: %d hdl: 0x%X", ret, s->link_handle); - - struct cam_req_mgr_link_control req_mgr_link_control = {0}; - req_mgr_link_control.ops = CAM_REQ_MGR_LINK_ACTIVATE; - req_mgr_link_control.session_hdl = s->session_handle; - req_mgr_link_control.num_links = 1; - req_mgr_link_control.link_hdls[0] = s->link_handle; - ret = cam_control(s->multi_cam_state->video0_fd, CAM_REQ_MGR_LINK_CONTROL, &req_mgr_link_control, sizeof(req_mgr_link_control)); - LOGD("link control: %d", ret); - - ret = device_control(s->csiphy_fd, CAM_START_DEV, s->session_handle, s->csiphy_dev_handle); - LOGD("start csiphy: %d", ret); - ret = device_control(s->multi_cam_state->isp_fd, CAM_START_DEV, s->session_handle, s->isp_dev_handle); - LOGD("start isp: %d", ret); - ret = device_control(s->sensor_fd, CAM_START_DEV, s->session_handle, s->sensor_dev_handle); - LOGD("start sensor: %d", ret); - - enqueue_req_multi(s, 1, FRAME_BUF_COUNT, 0); -} - -void cameras_init(VisionIpcServer *v, MultiCameraState *s, cl_device_id device_id, cl_context ctx) { - camera_init(s, v, &s->driver_cam, CAMERA_ID_AR0231, 2, 20, device_id, ctx, - VISION_STREAM_RGB_FRONT, VISION_STREAM_DRIVER); - printf("driver camera initted \n"); - if (!env_only_driver) { - camera_init(s, v, &s->road_cam, CAMERA_ID_AR0231, 1, 20, device_id, ctx, - VISION_STREAM_RGB_BACK, VISION_STREAM_ROAD); // swap left/right - printf("road camera initted \n"); - camera_init(s, v, &s->wide_road_cam, CAMERA_ID_AR0231, 0, 20, device_id, ctx, - VISION_STREAM_RGB_WIDE, VISION_STREAM_WIDE_ROAD); - printf("wide road camera initted \n"); - } - - s->sm = new SubMaster({"driverState"}); - s->pm = new PubMaster({"roadCameraState", "driverCameraState", "wideRoadCameraState", "thumbnail"}); -} - -void cameras_open(MultiCameraState *s) { - int ret; - - LOG("-- Opening devices"); - // video0 is req_mgr, the target of many ioctls - s->video0_fd = HANDLE_EINTR(open("/dev/v4l/by-path/platform-soc:qcom_cam-req-mgr-video-index0", O_RDWR | O_NONBLOCK)); - assert(s->video0_fd >= 0); - LOGD("opened video0"); - - // video1 is cam_sync, the target of some ioctls - s->video1_fd = HANDLE_EINTR(open("/dev/v4l/by-path/platform-cam_sync-video-index0", O_RDWR | O_NONBLOCK)); - assert(s->video1_fd >= 0); - LOGD("opened video1"); - - // looks like there's only one of these - s->isp_fd = HANDLE_EINTR(open("/dev/v4l-subdev1", O_RDWR | O_NONBLOCK)); - assert(s->isp_fd >= 0); - LOGD("opened isp"); - - // query icp for MMU handles - LOG("-- Query ICP for MMU handles"); - static struct cam_isp_query_cap_cmd isp_query_cap_cmd = {0}; - static struct cam_query_cap_cmd query_cap_cmd = {0}; - query_cap_cmd.handle_type = 1; - query_cap_cmd.caps_handle = (uint64_t)&isp_query_cap_cmd; - query_cap_cmd.size = sizeof(isp_query_cap_cmd); - ret = cam_control(s->isp_fd, CAM_QUERY_CAP, &query_cap_cmd, sizeof(query_cap_cmd)); - assert(ret == 0); - LOGD("using MMU handle: %x", isp_query_cap_cmd.device_iommu.non_secure); - LOGD("using MMU handle: %x", isp_query_cap_cmd.cdm_iommu.non_secure); - s->device_iommu = isp_query_cap_cmd.device_iommu.non_secure; - s->cdm_iommu = isp_query_cap_cmd.cdm_iommu.non_secure; - - // subscribe - LOG("-- Subscribing"); - static struct v4l2_event_subscription sub = {0}; - sub.type = V4L_EVENT_CAM_REQ_MGR_EVENT; - sub.id = 2; // should use boot time for sof - ret = HANDLE_EINTR(ioctl(s->video0_fd, VIDIOC_SUBSCRIBE_EVENT, &sub)); - printf("req mgr subscribe: %d\n", ret); - - camera_open(&s->driver_cam); - printf("driver camera opened \n"); - if (!env_only_driver) { - camera_open(&s->road_cam); - printf("road camera opened \n"); - camera_open(&s->wide_road_cam); - printf("wide road camera opened \n"); - } -} - -static void camera_close(CameraState *s) { - int ret; - - // stop devices - LOG("-- Stop devices"); - // ret = device_control(s->sensor_fd, CAM_STOP_DEV, s->session_handle, s->sensor_dev_handle); - // LOGD("stop sensor: %d", ret); - ret = device_control(s->multi_cam_state->isp_fd, CAM_STOP_DEV, s->session_handle, s->isp_dev_handle); - LOGD("stop isp: %d", ret); - ret = device_control(s->csiphy_fd, CAM_STOP_DEV, s->session_handle, s->csiphy_dev_handle); - LOGD("stop csiphy: %d", ret); - // link control stop - LOG("-- Stop link control"); - static struct cam_req_mgr_link_control req_mgr_link_control = {0}; - req_mgr_link_control.ops = CAM_REQ_MGR_LINK_DEACTIVATE; - req_mgr_link_control.session_hdl = s->session_handle; - req_mgr_link_control.num_links = 1; - req_mgr_link_control.link_hdls[0] = s->link_handle; - ret = cam_control(s->multi_cam_state->video0_fd, CAM_REQ_MGR_LINK_CONTROL, &req_mgr_link_control, sizeof(req_mgr_link_control)); - LOGD("link control stop: %d", ret); - - // unlink - LOG("-- Unlink"); - static struct cam_req_mgr_unlink_info req_mgr_unlink_info = {0}; - req_mgr_unlink_info.session_hdl = s->session_handle; - req_mgr_unlink_info.link_hdl = s->link_handle; - ret = cam_control(s->multi_cam_state->video0_fd, CAM_REQ_MGR_UNLINK, &req_mgr_unlink_info, sizeof(req_mgr_unlink_info)); - LOGD("unlink: %d", ret); - - // release devices - LOGD("-- Release devices"); - ret = device_control(s->sensor_fd, CAM_RELEASE_DEV, s->session_handle, s->sensor_dev_handle); - LOGD("release sensor: %d", ret); - ret = device_control(s->multi_cam_state->isp_fd, CAM_RELEASE_DEV, s->session_handle, s->isp_dev_handle); - LOGD("release isp: %d", ret); - ret = device_control(s->csiphy_fd, CAM_RELEASE_DEV, s->session_handle, s->csiphy_dev_handle); - LOGD("release csiphy: %d", ret); - - // destroyed session - struct cam_req_mgr_session_info session_info = {.session_hdl = s->session_handle}; - ret = cam_control(s->multi_cam_state->video0_fd, CAM_REQ_MGR_DESTROY_SESSION, &session_info, sizeof(session_info)); - LOGD("destroyed session: %d", ret); -} - -void cameras_close(MultiCameraState *s) { - camera_close(&s->driver_cam); - if (!env_only_driver) { - camera_close(&s->road_cam); - camera_close(&s->wide_road_cam); - } - - delete s->sm; - delete s->pm; -} - -// ******************* just a helper ******************* - -void handle_camera_event(CameraState *s, void *evdat) { - struct cam_req_mgr_message *event_data = (struct cam_req_mgr_message *)evdat; - - uint64_t timestamp = event_data->u.frame_msg.timestamp; - int main_id = event_data->u.frame_msg.frame_id; - int real_id = event_data->u.frame_msg.request_id; - - if (real_id != 0) { // next ready - if (real_id == 1) {s->idx_offset = main_id;} - int buf_idx = (real_id - 1) % FRAME_BUF_COUNT; - - // check for skipped frames - if (main_id > s->frame_id_last + 1 && !s->skipped) { - // realign - clear_req_queue(s->multi_cam_state->video0_fd, event_data->session_hdl, event_data->u.frame_msg.link_hdl); - enqueue_req_multi(s, real_id + 1, FRAME_BUF_COUNT - 1, 0); - s->skipped = true; - } else if (main_id == s->frame_id_last + 1) { - s->skipped = false; - } - - // check for dropped requests - if (real_id > s->request_id_last + 1) { - enqueue_req_multi(s, s->request_id_last + 1 + FRAME_BUF_COUNT, real_id - (s->request_id_last + 1), 0); - } - - // metas - s->frame_id_last = main_id; - s->request_id_last = real_id; - - auto &meta_data = s->buf.camera_bufs_metadata[buf_idx]; - meta_data.frame_id = main_id - s->idx_offset; - meta_data.timestamp_sof = timestamp; - s->exp_lock.lock(); - meta_data.gain = s->dc_gain_enabled ? s->analog_gain_frac * DC_GAIN : s->analog_gain_frac; - meta_data.high_conversion_gain = s->dc_gain_enabled; - meta_data.integ_lines = s->exposure_time; - meta_data.measured_grey_fraction = s->measured_grey_fraction; - meta_data.target_grey_fraction = s->target_grey_fraction; - s->exp_lock.unlock(); - - // dispatch - enqueue_req_multi(s, real_id + FRAME_BUF_COUNT, 1, 1); - } else { // not ready - // reset after half second of no response - if (main_id > s->frame_id_last + 10) { - clear_req_queue(s->multi_cam_state->video0_fd, event_data->session_hdl, event_data->u.frame_msg.link_hdl); - enqueue_req_multi(s, s->request_id_last + 1, FRAME_BUF_COUNT, 0); - s->frame_id_last = main_id; - s->skipped = true; - } - } -} - -static void set_camera_exposure(CameraState *s, float grey_frac) { - const float dt = 0.05; - - const float ts_grey = 10.0; - const float ts_ev = 0.05; - - const float k_grey = (dt / ts_grey) / (1.0 + dt / ts_grey); - const float k_ev = (dt / ts_ev) / (1.0 + dt / ts_ev); - - // It takes 3 frames for the commanded exposure settings to take effect. The first frame is already started by the time - // we reach this function, the other 2 are due to the register buffering in the sensor. - // Therefore we use the target EV from 3 frames ago, the grey fraction that was just measured was the result of that control action. - // TODO: Lower latency to 2 frames, by using the histogram outputed by the sensor we can do AE before the debayering is complete - - const float cur_ev = s->cur_ev[s->buf.cur_frame_data.frame_id % 3]; - - // Scale target grey between 0.1 and 0.4 depending on lighting conditions - float new_target_grey = std::clamp(0.4 - 0.3 * log2(1.0 + cur_ev) / log2(6000.0), 0.1, 0.4); - float target_grey = (1.0 - k_grey) * s->target_grey_fraction + k_grey * new_target_grey; - - float desired_ev = std::clamp(cur_ev * target_grey / grey_frac, s->min_ev, s->max_ev); - float k = (1.0 - k_ev) / 3.0; - desired_ev = (k * s->cur_ev[0]) + (k * s->cur_ev[1]) + (k * s->cur_ev[2]) + (k_ev * desired_ev); - - float best_ev_score = 1e6; - int new_g = 0; - int new_t = 0; - - // Hysteresis around high conversion gain - // We usually want this on since it results in lower noise, but turn off in very bright day scenes - bool enable_dc_gain = s->dc_gain_enabled; - if (!enable_dc_gain && target_grey < 0.2) { - enable_dc_gain = true; - } else if (enable_dc_gain && target_grey > 0.3) { - enable_dc_gain = false; - } - - // Simple brute force optimizer to choose sensor parameters - // to reach desired EV - for (int g = std::max((int)ANALOG_GAIN_MIN_IDX, s->gain_idx - 1); g <= std::min((int)ANALOG_GAIN_MAX_IDX, s->gain_idx + 1); g++) { - float gain = sensor_analog_gains[g] * (enable_dc_gain ? DC_GAIN : 1); - - // Compute optimal time for given gain - int t = std::clamp(int(std::round(desired_ev / gain)), EXPOSURE_TIME_MIN, EXPOSURE_TIME_MAX); - - // Only go below recomended gain when absolutely necessary to not overexpose - if (g < ANALOG_GAIN_REC_IDX && t > 20 && g < s->gain_idx) { - continue; - } - - // Compute error to desired ev - float score = std::abs(desired_ev - (t * gain)) * 10; - - // Going below recomended gain needs lower penalty to not overexpose - float m = g > ANALOG_GAIN_REC_IDX ? 5.0 : 0.1; - score += std::abs(g - (int)ANALOG_GAIN_REC_IDX) * m; - - // LOGE("cam: %d - gain: %d, t: %d (%.2f), score %.2f, score + gain %.2f, %.3f, %.3f", s->camera_num, g, t, desired_ev / gain, score, score + std::abs(g - s->gain_idx) * (score + 1.0) / 10.0, desired_ev, s->min_ev); - - // Small penalty on changing gain - score += std::abs(g - s->gain_idx) * (score + 1.0) / 10.0; - - if (score < best_ev_score) { - new_t = t; - new_g = g; - best_ev_score = score; - } - } - - s->exp_lock.lock(); - - s->measured_grey_fraction = grey_frac; - s->target_grey_fraction = target_grey; - - s->analog_gain_frac = sensor_analog_gains[new_g]; - s->gain_idx = new_g; - s->exposure_time = new_t; - s->dc_gain_enabled = enable_dc_gain; - - float gain = s->analog_gain_frac * (s->dc_gain_enabled ? DC_GAIN : 1.0); - s->cur_ev[s->buf.cur_frame_data.frame_id % 3] = s->exposure_time * gain; - - s->exp_lock.unlock(); - - // Processing a frame takes right about 50ms, so we need to wait a few ms - // so we don't send i2c commands around the frame start. - int ms = (nanos_since_boot() - s->buf.cur_frame_data.timestamp_sof) / 1000000; - if (ms < 60) { - util::sleep_for(60 - ms); - } - // LOGE("ae - camera %d, cur_t %.5f, sof %.5f, dt %.5f", s->camera_num, 1e-9 * nanos_since_boot(), 1e-9 * s->buf.cur_frame_data.timestamp_sof, 1e-9 * (nanos_since_boot() - s->buf.cur_frame_data.timestamp_sof)); - - uint16_t analog_gain_reg = 0xFF00 | (new_g << 4) | new_g; - struct i2c_random_wr_payload exp_reg_array[] = { - {0x3366, analog_gain_reg}, - {0x3362, (uint16_t)(s->dc_gain_enabled ? 0x1 : 0x0)}, - {0x3012, (uint16_t)s->exposure_time}, - }; - sensors_i2c(s, exp_reg_array, sizeof(exp_reg_array)/sizeof(struct i2c_random_wr_payload), - CAM_SENSOR_PACKET_OPCODE_SENSOR_CONFIG); - -} - -void camera_autoexposure(CameraState *s, float grey_frac) { - set_camera_exposure(s, grey_frac); -} - -// called by processing_thread -void process_road_camera(MultiCameraState *s, CameraState *c, int cnt) { - const CameraBuf *b = &c->buf; - - MessageBuilder msg; - auto framed = c == &s->road_cam ? msg.initEvent().initRoadCameraState() : msg.initEvent().initWideRoadCameraState(); - fill_frame_data(framed, b->cur_frame_data); - if ((c == &s->road_cam && env_send_road) || (c == &s->wide_road_cam && env_send_wide_road)) { - framed.setImage(get_frame_image(b)); - } - if (c == &s->road_cam) { - framed.setTransform(b->yuv_transform.v); - } - s->pm->send(c == &s->road_cam ? "roadCameraState" : "wideRoadCameraState", msg); - - const auto [x, y, w, h] = (c == &s->wide_road_cam) ? std::tuple(96, 250, 1734, 524) : std::tuple(96, 160, 1734, 986); - const int skip = 2; - camera_autoexposure(c, set_exposure_target(b, x, x + w, skip, y, y + h, skip)); -} - -void cameras_run(MultiCameraState *s) { - LOG("-- Starting threads"); - std::vector threads; - threads.push_back(start_process_thread(s, &s->driver_cam, common_process_driver_camera)); - if (!env_only_driver) { - threads.push_back(start_process_thread(s, &s->road_cam, process_road_camera)); - threads.push_back(start_process_thread(s, &s->wide_road_cam, process_road_camera)); - } - - // start devices - LOG("-- Starting devices"); - int start_reg_len = sizeof(start_reg_array) / sizeof(struct i2c_random_wr_payload); - sensors_i2c(&s->driver_cam, start_reg_array, start_reg_len, CAM_SENSOR_PACKET_OPCODE_SENSOR_CONFIG); - if (!env_only_driver) { - sensors_i2c(&s->road_cam, start_reg_array, start_reg_len, CAM_SENSOR_PACKET_OPCODE_SENSOR_CONFIG); - sensors_i2c(&s->wide_road_cam, start_reg_array, start_reg_len, CAM_SENSOR_PACKET_OPCODE_SENSOR_CONFIG); - } - - // poll events - LOG("-- Dequeueing Video events"); - while (!do_exit) { - struct pollfd fds[1] = {{0}}; - - fds[0].fd = s->video0_fd; - fds[0].events = POLLPRI; - - int ret = poll(fds, std::size(fds), 1000); - if (ret < 0) { - if (errno == EINTR || errno == EAGAIN) continue; - LOGE("poll failed (%d - %d)", ret, errno); - break; - } - - if (!fds[0].revents) continue; - - struct v4l2_event ev = {0}; - ret = HANDLE_EINTR(ioctl(fds[0].fd, VIDIOC_DQEVENT, &ev)); - if (ret == 0) { - if (ev.type == V4L_EVENT_CAM_REQ_MGR_EVENT) { - struct cam_req_mgr_message *event_data = (struct cam_req_mgr_message *)ev.u.data; - // LOGD("v4l2 event: sess_hdl 0x%X, link_hdl 0x%X, frame_id %d, req_id %lld, timestamp 0x%llx, sof_status %d\n", event_data->session_hdl, event_data->u.frame_msg.link_hdl, event_data->u.frame_msg.frame_id, event_data->u.frame_msg.request_id, event_data->u.frame_msg.timestamp, event_data->u.frame_msg.sof_status); - if (env_debug_frames) { - printf("sess_hdl 0x%X, link_hdl 0x%X, frame_id %lu, req_id %lu, timestamp 0x%lx, sof_status %d\n", event_data->session_hdl, event_data->u.frame_msg.link_hdl, event_data->u.frame_msg.frame_id, event_data->u.frame_msg.request_id, event_data->u.frame_msg.timestamp, event_data->u.frame_msg.sof_status); - } - - if (event_data->session_hdl == s->road_cam.session_handle) { - handle_camera_event(&s->road_cam, event_data); - } else if (event_data->session_hdl == s->wide_road_cam.session_handle) { - handle_camera_event(&s->wide_road_cam, event_data); - } else if (event_data->session_hdl == s->driver_cam.session_handle) { - handle_camera_event(&s->driver_cam, event_data); - } else { - printf("Unknown vidioc event source\n"); - assert(false); - } - } - } else { - LOGE("VIDIOC_DQEVENT failed, errno=%d", errno); - } - } - - LOG(" ************** STOPPING **************"); - - for (auto &t : threads) t.join(); - - cameras_close(s); -} diff --git a/selfdrive/camerad/cameras/camera_qcom2.h b/selfdrive/camerad/cameras/camera_qcom2.h deleted file mode 100644 index f8ab2da8ae..0000000000 --- a/selfdrive/camerad/cameras/camera_qcom2.h +++ /dev/null @@ -1,67 +0,0 @@ -#pragma once - -#include - -#include - -#include "selfdrive/camerad/cameras/camera_common.h" -#include "selfdrive/common/util.h" - -#define FRAME_BUF_COUNT 4 - -typedef struct CameraState { - MultiCameraState *multi_cam_state; - CameraInfo ci; - - std::mutex exp_lock; - - int exposure_time; - bool dc_gain_enabled; - float analog_gain_frac; - - float cur_ev[3]; - float min_ev, max_ev; - - float measured_grey_fraction; - float target_grey_fraction; - int gain_idx; - - unique_fd sensor_fd; - unique_fd csiphy_fd; - - int camera_num; - - int32_t session_handle; - int32_t sensor_dev_handle; - int32_t isp_dev_handle; - int32_t csiphy_dev_handle; - - int32_t link_handle; - - int buf0_handle; - int buf_handle[FRAME_BUF_COUNT]; - int sync_objs[FRAME_BUF_COUNT]; - int request_ids[FRAME_BUF_COUNT]; - int request_id_last; - int frame_id_last; - int idx_offset; - bool skipped; - - CameraBuf buf; -} CameraState; - -typedef struct MultiCameraState { - unique_fd video0_fd; - unique_fd video1_fd; - unique_fd isp_fd; - int device_iommu; - int cdm_iommu; - - - CameraState road_cam; - CameraState wide_road_cam; - CameraState driver_cam; - - SubMaster *sm; - PubMaster *pm; -} MultiCameraState; diff --git a/selfdrive/camerad/cameras/camera_replay.cc b/selfdrive/camerad/cameras/camera_replay.cc deleted file mode 100644 index b5b2e6ad29..0000000000 --- a/selfdrive/camerad/cameras/camera_replay.cc +++ /dev/null @@ -1,125 +0,0 @@ -#include "selfdrive/camerad/cameras/camera_replay.h" - -#include -#include - -#include "selfdrive/common/clutil.h" -#include "selfdrive/common/util.h" - -extern ExitHandler do_exit; - -void camera_autoexposure(CameraState *s, float grey_frac) {} - -namespace { - -const char *BASE_URL = "https://commadataci.blob.core.windows.net/openpilotci/"; - -const std::string road_camera_route = "0c94aa1e1296d7c6|2021-05-05--19-48-37"; -// const std::string driver_camera_route = "534ccd8a0950a00c|2021-06-08--12-15-37"; - -std::string get_url(std::string route_name, const std::string &camera, int segment_num) { - std::replace(route_name.begin(), route_name.end(), '|', '/'); - return util::string_format("%s%s/%d/%s.hevc", BASE_URL, route_name.c_str(), segment_num, camera.c_str()); -} - -void camera_init(VisionIpcServer *v, CameraState *s, int camera_id, unsigned int fps, cl_device_id device_id, cl_context ctx, VisionStreamType rgb_type, VisionStreamType yuv_type, const std::string &url) { - s->frame = new FrameReader(); - if (!s->frame->load(url)) { - printf("failed to load stream from %s", url.c_str()); - assert(0); - } - - CameraInfo ci = { - .frame_width = s->frame->width, - .frame_height = s->frame->height, - .frame_stride = s->frame->width * 3, - }; - s->ci = ci; - s->camera_num = camera_id; - s->fps = fps; - s->buf.init(device_id, ctx, s, v, FRAME_BUF_COUNT, rgb_type, yuv_type); -} - -void camera_close(CameraState *s) { - delete s->frame; -} - -void run_camera(CameraState *s) { - uint32_t stream_frame_id = 0, frame_id = 0; - size_t buf_idx = 0; - std::unique_ptr rgb_buf = std::make_unique(s->frame->getRGBSize()); - std::unique_ptr yuv_buf = std::make_unique(s->frame->getYUVSize()); - while (!do_exit) { - if (stream_frame_id == s->frame->getFrameCount()) { - // loop stream - stream_frame_id = 0; - } - if (s->frame->get(stream_frame_id++, rgb_buf.get(), yuv_buf.get())) { - s->buf.camera_bufs_metadata[buf_idx] = {.frame_id = frame_id}; - auto &buf = s->buf.camera_bufs[buf_idx]; - CL_CHECK(clEnqueueWriteBuffer(buf.copy_q, buf.buf_cl, CL_TRUE, 0, s->frame->getRGBSize(), rgb_buf.get(), 0, NULL, NULL)); - s->buf.queue(buf_idx); - ++frame_id; - buf_idx = (buf_idx + 1) % FRAME_BUF_COUNT; - } - util::sleep_for(1000 / s->fps); - } -} - -void road_camera_thread(CameraState *s) { - util::set_thread_name("replay_road_camera_thread"); - run_camera(s); -} - -// void driver_camera_thread(CameraState *s) { -// util::set_thread_name("replay_driver_camera_thread"); -// run_camera(s); -// } - -void process_road_camera(MultiCameraState *s, CameraState *c, int cnt) { - const CameraBuf *b = &c->buf; - MessageBuilder msg; - auto framed = msg.initEvent().initRoadCameraState(); - fill_frame_data(framed, b->cur_frame_data); - framed.setImage(kj::arrayPtr((const uint8_t *)b->cur_yuv_buf->addr, b->cur_yuv_buf->len)); - framed.setTransform(b->yuv_transform.v); - s->pm->send("roadCameraState", msg); -} - -// void process_driver_camera(MultiCameraState *s, CameraState *c, int cnt) { -// MessageBuilder msg; -// auto framed = msg.initEvent().initDriverCameraState(); -// framed.setFrameType(cereal::FrameData::FrameType::FRONT); -// fill_frame_data(framed, c->buf.cur_frame_data); -// s->pm->send("driverCameraState", msg); -// } - -} // namespace - -void cameras_init(VisionIpcServer *v, MultiCameraState *s, cl_device_id device_id, cl_context ctx) { - camera_init(v, &s->road_cam, CAMERA_ID_LGC920, 20, device_id, ctx, - VISION_STREAM_RGB_BACK, VISION_STREAM_ROAD, get_url(road_camera_route, "fcamera", 0)); - // camera_init(v, &s->driver_cam, CAMERA_ID_LGC615, 10, device_id, ctx, - // VISION_STREAM_RGB_FRONT, VISION_STREAM_DRIVER, get_url(driver_camera_route, "dcamera", 0)); - s->pm = new PubMaster({"roadCameraState", "driverCameraState", "thumbnail"}); -} - -void cameras_open(MultiCameraState *s) {} - -void cameras_close(MultiCameraState *s) { - camera_close(&s->road_cam); - camera_close(&s->driver_cam); - delete s->pm; -} - -void cameras_run(MultiCameraState *s) { - std::vector threads; - threads.push_back(start_process_thread(s, &s->road_cam, process_road_camera)); - // threads.push_back(start_process_thread(s, &s->driver_cam, process_driver_camera)); - // threads.push_back(std::thread(driver_camera_thread, &s->driver_cam)); - road_camera_thread(&s->road_cam); - - for (auto &t : threads) t.join(); - - cameras_close(s); -} diff --git a/selfdrive/camerad/cameras/camera_replay.h b/selfdrive/camerad/cameras/camera_replay.h deleted file mode 100644 index 7c41af0ab4..0000000000 --- a/selfdrive/camerad/cameras/camera_replay.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#include "selfdrive/camerad/cameras/camera_common.h" -#include "selfdrive/ui/replay/framereader.h" - -#define FRAME_BUF_COUNT 16 - -typedef struct CameraState { - int camera_num; - CameraInfo ci; - - int fps; - float digital_gain = 0; - - CameraBuf buf; - FrameReader *frame = nullptr; -} CameraState; - -typedef struct MultiCameraState { - CameraState road_cam; - CameraState driver_cam; - - SubMaster *sm = nullptr; - PubMaster *pm = nullptr; -} MultiCameraState; diff --git a/selfdrive/camerad/cameras/camera_webcam.cc b/selfdrive/camerad/cameras/camera_webcam.cc deleted file mode 100644 index 956f2dc88f..0000000000 --- a/selfdrive/camerad/cameras/camera_webcam.cc +++ /dev/null @@ -1,197 +0,0 @@ -#include "selfdrive/camerad/cameras/camera_webcam.h" - -#include - -#include -#include - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wundefined-inline" -#include -#include -#include -#include -#pragma clang diagnostic pop - -#include "selfdrive/common/clutil.h" -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/timing.h" -#include "selfdrive/common/util.h" - -// id of the video capturing device -const int ROAD_CAMERA_ID = util::getenv("ROADCAM_ID", 1); -const int DRIVER_CAMERA_ID = util::getenv("DRIVERCAM_ID", 2); - -#define FRAME_WIDTH 1164 -#define FRAME_HEIGHT 874 -#define FRAME_WIDTH_FRONT 1152 -#define FRAME_HEIGHT_FRONT 864 - -extern ExitHandler do_exit; - -namespace { - -CameraInfo cameras_supported[CAMERA_ID_MAX] = { - // road facing - [CAMERA_ID_LGC920] = { - .frame_width = FRAME_WIDTH, - .frame_height = FRAME_HEIGHT, - .frame_stride = FRAME_WIDTH*3, - .bayer = false, - .bayer_flip = false, - }, - // driver facing - [CAMERA_ID_LGC615] = { - .frame_width = FRAME_WIDTH_FRONT, - .frame_height = FRAME_HEIGHT_FRONT, - .frame_stride = FRAME_WIDTH_FRONT*3, - .bayer = false, - .bayer_flip = false, - }, -}; - -void camera_open(CameraState *s, bool rear) { - // empty -} - -void camera_close(CameraState *s) { - // empty -} - -void camera_init(VisionIpcServer * v, CameraState *s, int camera_id, unsigned int fps, cl_device_id device_id, cl_context ctx, VisionStreamType rgb_type, VisionStreamType yuv_type) { - assert(camera_id < std::size(cameras_supported)); - s->ci = cameras_supported[camera_id]; - assert(s->ci.frame_width != 0); - - s->camera_num = camera_id; - s->fps = fps; - s->buf.init(device_id, ctx, s, v, FRAME_BUF_COUNT, rgb_type, yuv_type); -} - -void run_camera(CameraState *s, cv::VideoCapture &video_cap, float *ts) { - assert(video_cap.isOpened()); - - cv::Size size(s->ci.frame_width, s->ci.frame_height); - const cv::Mat transform = cv::Mat(3, 3, CV_32F, ts); - uint32_t frame_id = 0; - size_t buf_idx = 0; - - while (!do_exit) { - cv::Mat frame_mat, transformed_mat; - video_cap >> frame_mat; - if (frame_mat.empty()) continue; - - cv::warpPerspective(frame_mat, transformed_mat, transform, size, cv::INTER_LINEAR, cv::BORDER_CONSTANT, 0); - - s->buf.camera_bufs_metadata[buf_idx] = {.frame_id = frame_id}; - - auto &buf = s->buf.camera_bufs[buf_idx]; - int transformed_size = transformed_mat.total() * transformed_mat.elemSize(); - CL_CHECK(clEnqueueWriteBuffer(buf.copy_q, buf.buf_cl, CL_TRUE, 0, transformed_size, transformed_mat.data, 0, NULL, NULL)); - - s->buf.queue(buf_idx); - - ++frame_id; - buf_idx = (buf_idx + 1) % FRAME_BUF_COUNT; - } -} - -static void road_camera_thread(CameraState *s) { - util::set_thread_name("webcam_road_camera_thread"); - - cv::VideoCapture cap_road(ROAD_CAMERA_ID, cv::CAP_V4L2); // road - cap_road.set(cv::CAP_PROP_FRAME_WIDTH, 853); - cap_road.set(cv::CAP_PROP_FRAME_HEIGHT, 480); - cap_road.set(cv::CAP_PROP_FPS, s->fps); - cap_road.set(cv::CAP_PROP_AUTOFOCUS, 0); // off - cap_road.set(cv::CAP_PROP_FOCUS, 0); // 0 - 255? - // cv::Rect roi_rear(160, 0, 960, 720); - - // transforms calculation see tools/webcam/warp_vis.py - float ts[9] = {1.50330396, 0.0, -59.40969163, - 0.0, 1.50330396, 76.20704846, - 0.0, 0.0, 1.0}; - // if camera upside down: - // float ts[9] = {-1.50330396, 0.0, 1223.4, - // 0.0, -1.50330396, 797.8, - // 0.0, 0.0, 1.0}; - - run_camera(s, cap_road, ts); -} - -void driver_camera_thread(CameraState *s) { - cv::VideoCapture cap_driver(DRIVER_CAMERA_ID, cv::CAP_V4L2); // driver - cap_driver.set(cv::CAP_PROP_FRAME_WIDTH, 853); - cap_driver.set(cv::CAP_PROP_FRAME_HEIGHT, 480); - cap_driver.set(cv::CAP_PROP_FPS, s->fps); - // cv::Rect roi_front(320, 0, 960, 720); - - // transforms calculation see tools/webcam/warp_vis.py - float ts[9] = {1.42070485, 0.0, -30.16740088, - 0.0, 1.42070485, 91.030837, - 0.0, 0.0, 1.0}; - // if camera upside down: - // float ts[9] = {-1.42070485, 0.0, 1182.2, - // 0.0, -1.42070485, 773.0, - // 0.0, 0.0, 1.0}; - run_camera(s, cap_driver, ts); -} - -} // namespace - -void cameras_init(VisionIpcServer *v, MultiCameraState *s, cl_device_id device_id, cl_context ctx) { - camera_init(v, &s->road_cam, CAMERA_ID_LGC920, 20, device_id, ctx, - VISION_STREAM_RGB_BACK, VISION_STREAM_ROAD); - camera_init(v, &s->driver_cam, CAMERA_ID_LGC615, 10, device_id, ctx, - VISION_STREAM_RGB_FRONT, VISION_STREAM_DRIVER); - s->pm = new PubMaster({"roadCameraState", "driverCameraState", "thumbnail"}); -} - -void camera_autoexposure(CameraState *s, float grey_frac) {} - -void cameras_open(MultiCameraState *s) { - // LOG("*** open driver camera ***"); - camera_open(&s->driver_cam, false); - // LOG("*** open road camera ***"); - camera_open(&s->road_cam, true); -} - -void cameras_close(MultiCameraState *s) { - camera_close(&s->road_cam); - camera_close(&s->driver_cam); - delete s->pm; -} - -void process_driver_camera(MultiCameraState *s, CameraState *c, int cnt) { - MessageBuilder msg; - auto framed = msg.initEvent().initDriverCameraState(); - framed.setFrameType(cereal::FrameData::FrameType::FRONT); - fill_frame_data(framed, c->buf.cur_frame_data); - s->pm->send("driverCameraState", msg); -} - -void process_road_camera(MultiCameraState *s, CameraState *c, int cnt) { - const CameraBuf *b = &c->buf; - MessageBuilder msg; - auto framed = msg.initEvent().initRoadCameraState(); - fill_frame_data(framed, b->cur_frame_data); - framed.setImage(kj::arrayPtr((const uint8_t *)b->cur_yuv_buf->addr, b->cur_yuv_buf->len)); - framed.setTransform(b->yuv_transform.v); - s->pm->send("roadCameraState", msg); -} - -void cameras_run(MultiCameraState *s) { - std::vector threads; - threads.push_back(start_process_thread(s, &s->road_cam, process_road_camera)); - threads.push_back(start_process_thread(s, &s->driver_cam, process_driver_camera)); - - std::thread t_rear = std::thread(road_camera_thread, &s->road_cam); - util::set_thread_name("webcam_thread"); - driver_camera_thread(&s->driver_cam); - - t_rear.join(); - - for (auto &t : threads) t.join(); - - cameras_close(s); -} diff --git a/selfdrive/camerad/cameras/camera_webcam.h b/selfdrive/camerad/cameras/camera_webcam.h deleted file mode 100644 index 819387f3d6..0000000000 --- a/selfdrive/camerad/cameras/camera_webcam.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once - -#ifdef __APPLE__ -#include -#else -#include -#endif - -#include "selfdrive/camerad/cameras/camera_common.h" - -#define FRAME_BUF_COUNT 16 - -typedef struct CameraState { - CameraInfo ci; - int camera_num; - int fps; - float digital_gain; - CameraBuf buf; -} CameraState; - - -typedef struct MultiCameraState { - CameraState road_cam; - CameraState driver_cam; - - SubMaster *sm; - PubMaster *pm; -} MultiCameraState; diff --git a/selfdrive/camerad/cameras/debayer.cl b/selfdrive/camerad/cameras/debayer.cl deleted file mode 100644 index 4e4b832203..0000000000 --- a/selfdrive/camerad/cameras/debayer.cl +++ /dev/null @@ -1,140 +0,0 @@ -const __constant float3 color_correction[3] = { - // Matrix from WBraw -> sRGBD65 (normalized) - (float3)( 1.62393627, -0.2092988, 0.00119886), - (float3)(-0.45734315, 1.5534676, -0.59296798), - (float3)(-0.16659312, -0.3441688, 1.59176912), -}; - -float3 color_correct(float3 x) { - float3 ret = (0,0,0); - - // white balance of daylight - x /= (float3)(0.4609375, 1.0, 0.546875); - x = max(0.0, min(1.0, x)); - - // fix up the colors - ret += x.x * color_correction[0]; - ret += x.y * color_correction[1]; - ret += x.z * color_correction[2]; - return ret; -} - -float3 srgb_gamma(float3 p) { - // go all out and add an sRGB gamma curve - const float3 ph = (1.0f + 0.055f)*pow(p, 1/2.4f) - 0.055f; - const float3 pl = p*12.92f; - return select(ph, pl, islessequal(p, 0.0031308f)); -} - -#if HDR - -__constant int dpcm_lookup[512] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -20, -21, -22, -23, -24, -25, -26, -27, -28, -29, -30, -31, 935, 951, 967, 983, 999, 1015, 1031, 1047, 1063, 1079, 1095, 1111, 1127, 1143, 1159, 1175, 1191, 1207, 1223, 1239, 1255, 1271, 1287, 1303, 1319, 1335, 1351, 1367, 1383, 1399, 1415, 1431, -935, -951, -967, -983, -999, -1015, -1031, -1047, -1063, -1079, -1095, -1111, -1127, -1143, -1159, -1175, -1191, -1207, -1223, -1239, -1255, -1271, -1287, -1303, -1319, -1335, -1351, -1367, -1383, -1399, -1415, -1431, 419, 427, 435, 443, 451, 459, 467, 475, 483, 491, 499, 507, 515, 523, 531, 539, 547, 555, 563, 571, 579, 587, 595, 603, 611, 619, 627, 635, 643, 651, 659, 667, 675, 683, 691, 699, 707, 715, 723, 731, 739, 747, 755, 763, 771, 779, 787, 795, 803, 811, 819, 827, 835, 843, 851, 859, 867, 875, 883, 891, 899, 907, 915, 923, -419, -427, -435, -443, -451, -459, -467, -475, -483, -491, -499, -507, -515, -523, -531, -539, -547, -555, -563, -571, -579, -587, -595, -603, -611, -619, -627, -635, -643, -651, -659, -667, -675, -683, -691, -699, -707, -715, -723, -731, -739, -747, -755, -763, -771, -779, -787, -795, -803, -811, -819, -827, -835, -843, -851, -859, -867, -875, -883, -891, -899, -907, -915, -923, 161, 165, 169, 173, 177, 181, 185, 189, 193, 197, 201, 205, 209, 213, 217, 221, 225, 229, 233, 237, 241, 245, 249, 253, 257, 261, 265, 269, 273, 277, 281, 285, 289, 293, 297, 301, 305, 309, 313, 317, 321, 325, 329, 333, 337, 341, 345, 349, 353, 357, 361, 365, 369, 373, 377, 381, 385, 389, 393, 397, 401, 405, 409, 413, -161, -165, -169, -173, -177, -181, -185, -189, -193, -197, -201, -205, -209, -213, -217, -221, -225, -229, -233, -237, -241, -245, -249, -253, -257, -261, -265, -269, -273, -277, -281, -285, -289, -293, -297, -301, -305, -309, -313, -317, -321, -325, -329, -333, -337, -341, -345, -349, -353, -357, -361, -365, -369, -373, -377, -381, -385, -389, -393, -397, -401, -405, -409, -413, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 154, 156, 158, -32, -34, -36, -38, -40, -42, -44, -46, -48, -50, -52, -54, -56, -58, -60, -62, -64, -66, -68, -70, -72, -74, -76, -78, -80, -82, -84, -86, -88, -90, -92, -94, -96, -98, -100, -102, -104, -106, -108, -110, -112, -114, -116, -118, -120, -122, -124, -126, -128, -130, -132, -134, -136, -138, -140, -142, -144, -146, -148, -150, -152, -154, -156, -158}; - -inline uint4 decompress(uint4 p, uint4 pl) { - uint4 r1 = (pl + (uint4)(dpcm_lookup[p.s0], dpcm_lookup[p.s1], dpcm_lookup[p.s2], dpcm_lookup[p.s3])); - uint4 r2 = ((p-0x200)<<5) | 0xF; - r2 += select((uint4)(0,0,0,0), (uint4)(1,1,1,1), r2 <= pl); - return select(r2, r1, p < 0x200); -} - -#endif - -__kernel void debayer10(__global uchar const * const in, - __global uchar * out, float digital_gain) -{ - const int oy = get_global_id(0); - if (oy >= RGB_HEIGHT) return; - const int iy = oy * 2; - -#if HDR - uint4 pint_last; - for (int ox = 0; ox < RGB_WIDTH; ox += 2) { -#else - int ox = get_global_id(1) * 2; - { -#endif - const int ix = (ox/2) * 5; - - // TODO: why doesn't this work for the frontview - /*const uchar8 v1 = vload8(0, &in[iy * FRAME_STRIDE + ix]); - const uchar ex1 = v1.s4; - const uchar8 v2 = vload8(0, &in[(iy+1) * FRAME_STRIDE + ix]); - const uchar ex2 = v2.s4;*/ - - const uchar4 v1 = vload4(0, &in[iy * FRAME_STRIDE + ix]); - const uchar ex1 = in[iy * FRAME_STRIDE + ix + 4]; - const uchar4 v2 = vload4(0, &in[(iy+1) * FRAME_STRIDE + ix]); - const uchar ex2 = in[(iy+1) * FRAME_STRIDE + ix + 4]; - - uint4 pinta[2]; - pinta[0] = (uint4)( - (((uint)v1.s0 << 2) + ( (ex1 >> 0) & 3)), - (((uint)v1.s1 << 2) + ( (ex1 >> 2) & 3)), - (((uint)v2.s0 << 2) + ( (ex2 >> 0) & 3)), - (((uint)v2.s1 << 2) + ( (ex2 >> 2) & 3))); - pinta[1] = (uint4)( - (((uint)v1.s2 << 2) + ( (ex1 >> 4) & 3)), - (((uint)v1.s3 << 2) + ( (ex1 >> 6) & 3)), - (((uint)v2.s2 << 2) + ( (ex2 >> 4) & 3)), - (((uint)v2.s3 << 2) + ( (ex2 >> 6) & 3))); - - #pragma unroll - for (uint px = 0; px < 2; px++) { - uint4 pint = pinta[px]; - -#if HDR - // decompress HDR - pint = (ox == 0 && px == 0) ? ((pint<<4) | 8) : decompress(pint, pint_last); - pint_last = pint; -#endif - - float4 p = convert_float4(pint); - - // 64 is the black level of the sensor, remove - // (changed to 56 for HDR) - const float black_level = 56.0f; - // TODO: switch to max here? - p = (p - black_level); - - // correct vignetting (no pow function?) - // see https://www.eecis.udel.edu/~jye/lab_research/09/JiUp.pdf the A (4th order) - const float r = ((oy - RGB_HEIGHT/2)*(oy - RGB_HEIGHT/2) + (ox - RGB_WIDTH/2)*(ox - RGB_WIDTH/2)); - const float fake_f = 700.0f; // should be 910, but this fits... - const float lil_a = (1.0f + r/(fake_f*fake_f)); - p = p * lil_a * lil_a; - - // rescale to 1.0 -#if HDR - p /= (16384.0f-black_level); -#else - p /= (1024.0f-black_level); -#endif - - // digital gain - p *= digital_gain; - - // use both green channels -#if BAYER_FLIP == 3 - float3 c1 = (float3)(p.s3, (p.s1+p.s2)/2.0f, p.s0); -#elif BAYER_FLIP == 2 - float3 c1 = (float3)(p.s2, (p.s0+p.s3)/2.0f, p.s1); -#elif BAYER_FLIP == 1 - float3 c1 = (float3)(p.s1, (p.s0+p.s3)/2.0f, p.s2); -#elif BAYER_FLIP == 0 - float3 c1 = (float3)(p.s0, (p.s1+p.s2)/2.0f, p.s3); -#endif - - // color correction - c1 = color_correct(c1); - -#if HDR - // srgb gamma isn't right for YUV, so it's disabled for now - c1 = srgb_gamma(c1); -#endif - - // output BGR - const int ooff = oy * RGB_STRIDE/3 + ox; - vstore3(convert_uchar3_sat(c1.zyx * 255.0f), ooff+px, out); - } - } -} diff --git a/selfdrive/camerad/cameras/real_debayer.cl b/selfdrive/camerad/cameras/real_debayer.cl deleted file mode 100644 index fe6a99f373..0000000000 --- a/selfdrive/camerad/cameras/real_debayer.cl +++ /dev/null @@ -1,207 +0,0 @@ -#pragma OPENCL EXTENSION cl_khr_fp16 : enable - -const half black_level = 42.0; - -const __constant half3 color_correction[3] = { - // post wb CCM - (half3)(1.82717181, -0.31231438, 0.07307673), - (half3)(-0.5743977, 1.36858544, -0.53183455), - (half3)(-0.25277411, -0.05627105, 1.45875782), -}; - -// tone mapping params -const half cpk = 0.75; -const half cpb = 0.125; -const half cpxk = 0.0025; -const half cpxb = 0.01; - -half mf(half x, half cp) { - half rk = 9 - 100*cp; - if (x > cp) { - return (rk * (x-cp) * (1-(cpk*cp+cpb)) * (1+1/(rk*(1-cp))) / (1+rk*(x-cp))) + cpk*cp + cpb; - } else if (x < cp) { - return (rk * (x-cp) * (cpk*cp+cpb) * (1+1/(rk*cp)) / (1-rk*(x-cp))) + cpk*cp + cpb; - } else { - return x; - } -} - -half3 color_correct(half3 rgb) { - half3 ret = (0,0,0); - half cpx = 0.01; - ret += (half)rgb.x * color_correction[0]; - ret += (half)rgb.y * color_correction[1]; - ret += (half)rgb.z * color_correction[2]; - ret.x = mf(ret.x, cpx); - ret.y = mf(ret.y, cpx); - ret.z = mf(ret.z, cpx); - ret = clamp(0.0h, 255.0h, ret*255.0h); - return ret; -} - -half val_from_10(const uchar * source, int gx, int gy) { - // parse 10bit - int start = gy * FRAME_STRIDE + (5 * (gx / 4)); - int offset = gx % 4; - uint major = (uint)source[start + offset] << 2; - uint minor = (source[start + 4] >> (2 * offset)) & 3; - half pv = (half)(major + minor); - - // normalize - pv = max(0.0h, pv - black_level); - pv *= 0.00101833h; // /= (1024.0f - black_level); - - // correct vignetting - if (CAM_NUM == 1) { // fcamera - gx = (gx - RGB_WIDTH/2); - gy = (gy - RGB_HEIGHT/2); - float r = gx*gx + gy*gy; - half s; - if (r < 62500) { - s = (half)(1.0f + 0.0000008f*r); - } else if (r < 490000) { - s = (half)(0.9625f + 0.0000014f*r); - } else if (r < 1102500) { - s = (half)(1.26434f + 0.0000000000016f*r*r); - } else { - s = (half)(0.53503625f + 0.0000000000022f*r*r); - } - pv = s * pv; - } - - pv = clamp(0.0h, 1.0h, pv); - return pv; -} - -half fabs_diff(half x, half y) { - return fabs(x-y); -} - -half phi(half x) { - // detection funtion - return 2 - x; - // if (x > 1) { - // return 1 / x; - // } else { - // return 2 - x; - // } -} - -__kernel void debayer10(const __global uchar * in, - __global uchar * out, - __local half * cached - ) -{ - const int x_global = get_global_id(0); - const int y_global = get_global_id(1); - - const int localRowLen = 2 + get_local_size(0); // 2 padding - const int x_local = get_local_id(0); // 0-15 - const int y_local = get_local_id(1); // 0-15 - const int localOffset = (y_local + 1) * localRowLen + x_local + 1; // max 18x18-1 - - int out_idx = 3 * x_global + 3 * y_global * RGB_WIDTH; - - half pv = val_from_10(in, x_global, y_global); - cached[localOffset] = pv; - - // don't care - if (x_global < 1 || x_global >= RGB_WIDTH - 1 || y_global < 1 || y_global >= RGB_HEIGHT - 1) { - return; - } - - // cache padding - int localColOffset = -1; - int globalColOffset = -1; - - // cache padding - if (x_local < 1) { - localColOffset = x_local; - globalColOffset = -1; - cached[(y_local + 1) * localRowLen + x_local] = val_from_10(in, x_global-1, y_global); - } else if (x_local >= get_local_size(0) - 1) { - localColOffset = x_local + 2; - globalColOffset = 1; - cached[localOffset + 1] = val_from_10(in, x_global+1, y_global); - } - - if (y_local < 1) { - cached[y_local * localRowLen + x_local + 1] = val_from_10(in, x_global, y_global-1); - if (localColOffset != -1) { - cached[y_local * localRowLen + localColOffset] = val_from_10(in, x_global+globalColOffset, y_global-1); - } - } else if (y_local >= get_local_size(1) - 1) { - cached[(y_local + 2) * localRowLen + x_local + 1] = val_from_10(in, x_global, y_global+1); - if (localColOffset != -1) { - cached[(y_local + 2) * localRowLen + localColOffset] = val_from_10(in, x_global+globalColOffset, y_global+1); - } - } - - // sync - barrier(CLK_LOCAL_MEM_FENCE); - - half d1 = cached[localOffset - localRowLen - 1]; - half d2 = cached[localOffset - localRowLen + 1]; - half d3 = cached[localOffset + localRowLen - 1]; - half d4 = cached[localOffset + localRowLen + 1]; - half n1 = cached[localOffset - localRowLen]; - half n2 = cached[localOffset + 1]; - half n3 = cached[localOffset + localRowLen]; - half n4 = cached[localOffset - 1]; - - half3 rgb; - - // a simplified version of https://opensignalprocessingjournal.com/contents/volumes/V6/TOSIGPJ-6-1/TOSIGPJ-6-1.pdf - if (x_global % 2 == 0) { - if (y_global % 2 == 0) { - rgb.y = pv; // G1(R) - half k1 = phi(fabs_diff(d1, pv) + fabs_diff(d2, pv)); - half k2 = phi(fabs_diff(d2, pv) + fabs_diff(d4, pv)); - half k3 = phi(fabs_diff(d3, pv) + fabs_diff(d4, pv)); - half k4 = phi(fabs_diff(d1, pv) + fabs_diff(d3, pv)); - // R_G1 - rgb.x = (k2*n2+k4*n4)/(k2+k4); - // B_G1 - rgb.z = (k1*n1+k3*n3)/(k1+k3); - } else { - rgb.z = pv; // B - half k1 = phi(fabs_diff(d1, d3) + fabs_diff(d2, d4)); - half k2 = phi(fabs_diff(n1, n4) + fabs_diff(n2, n3)); - half k3 = phi(fabs_diff(d1, d2) + fabs_diff(d3, d4)); - half k4 = phi(fabs_diff(n1, n2) + fabs_diff(n3, n4)); - // G_B - rgb.y = (k1*(n1+n3)*0.5+k3*(n2+n4)*0.5)/(k1+k3); - // R_B - rgb.x = (k2*(d2+d3)*0.5+k4*(d1+d4)*0.5)/(k2+k4); - } - } else { - if (y_global % 2 == 0) { - rgb.x = pv; // R - half k1 = phi(fabs_diff(d1, d3) + fabs_diff(d2, d4)); - half k2 = phi(fabs_diff(n1, n4) + fabs_diff(n2, n3)); - half k3 = phi(fabs_diff(d1, d2) + fabs_diff(d3, d4)); - half k4 = phi(fabs_diff(n1, n2) + fabs_diff(n3, n4)); - // G_R - rgb.y = (k1*(n1+n3)*0.5+k3*(n2+n4)*0.5)/(k1+k3); - // B_R - rgb.z = (k2*(d2+d3)*0.5+k4*(d1+d4)*0.5)/(k2+k4); - } else { - rgb.y = pv; // G2(B) - half k1 = phi(fabs_diff(d1, pv) + fabs_diff(d2, pv)); - half k2 = phi(fabs_diff(d2, pv) + fabs_diff(d4, pv)); - half k3 = phi(fabs_diff(d3, pv) + fabs_diff(d4, pv)); - half k4 = phi(fabs_diff(d1, pv) + fabs_diff(d3, pv)); - // R_G2 - rgb.x = (k1*n1+k3*n3)/(k1+k3); - // B_G2 - rgb.z = (k2*n2+k4*n4)/(k2+k4); - } - } - - rgb = clamp(0.0h, 1.0h, rgb); - rgb = color_correct(rgb); - - out[out_idx + 0] = (uchar)(rgb.z); - out[out_idx + 1] = (uchar)(rgb.y); - out[out_idx + 2] = (uchar)(rgb.x); -} diff --git a/selfdrive/camerad/cameras/sensor2_i2c.h b/selfdrive/camerad/cameras/sensor2_i2c.h deleted file mode 100644 index c3d8861a97..0000000000 --- a/selfdrive/camerad/cameras/sensor2_i2c.h +++ /dev/null @@ -1,124 +0,0 @@ -struct i2c_random_wr_payload start_reg_array[] = {{0x301A, 0x91C}}; -struct i2c_random_wr_payload stop_reg_array[] = {{0x301A, 0x918}}; - -struct i2c_random_wr_payload init_array_ar0231[] = { - {0x301A, 0x0018}, // RESET_REGISTER - - // CLOCK Settings - {0x302A, 0x0006}, // VT_PIX_CLK_DIV - {0x302C, 0x0001}, // VT_SYS_CLK_DIV - {0x302E, 0x0002}, // PRE_PLL_CLK_DIV - {0x3030, 0x0032}, // PLL_MULTIPLIER - {0x3036, 0x000A}, // OP_WORD_CLK_DIV - {0x3038, 0x0001}, // OP_SYS_CLK_DIV - - // FORMAT - {0x3040, 0xC000}, // READ_MODE - {0x3004, 0x0000}, // X_ADDR_START_ (A) - {0x308A, 0x0000}, // X_ADDR_START_ (B) - {0x3008, 0x0787}, // X_ADDR_END_ (A) - {0x308E, 0x0787}, // X_ADDR_END_ (B) - {0x3002, 0x0000}, // Y_ADDR_START_ (A) - {0x308C, 0x0000}, // Y_ADDR_START_ (B) - {0x3006, 0x04B7}, // Y_ADDR_END_ (A) - {0x3090, 0x04B7}, // Y_ADDR_END_ (B) - {0x3032, 0x0000}, // SCALING_MODE - {0x30A2, 0x0001}, // X_ODD_INC_ (A) - {0x30AE, 0x0001}, // X_ODD_INC_ (B) - {0x30A6, 0x0001}, // Y_ODD_INC_ (A) - {0x30A8, 0x0001}, // Y_ODD_INC_ (B) - {0x3402, 0x0F10}, // X_OUTPUT_CONTROL - {0x3404, 0x0970}, // Y_OUTPUT_CONTROL - {0x3064, 0x1802}, // SMIA_TEST - {0x30BA, 0x11F2}, // DIGITAL_CTRL - - // SLAV* MODE - {0x30CE, 0x0120}, - {0x340A, 0xE6}, // E6 // 0000 1110 0110 - {0x340C, 0x802}, // 2 // 0000 0000 0010 - - // Readout timing - {0x300C, 0x07B9}, // LINE_LENGTH_PCK (A) - {0x303E, 0x07B9}, // LINE_LENGTH_PCK (B) - {0x300A, 0x07E7}, // FRAME_LENGTH_LINES (A) - {0x30AA, 0x07E7}, // FRAME_LENGTH_LINES (B) - {0x3042, 0x0000}, // EXTRA_DELAY - - // Readout Settings - {0x31AE, 0x0204}, // SERIAL_FORMAT, 4-lane MIPI - {0x31AC, 0x0C0A}, // DATA_FORMAT_BITS, 12 -> 10 - {0x3342, 0x122B}, // MIPI_F1_PDT_EDT - {0x3346, 0x122B}, // MIPI_F2_PDT_EDT - {0x334A, 0x122B}, // MIPI_F3_PDT_EDT - {0x334E, 0x122B}, // MIPI_F4_PDT_EDT - {0x3344, 0x0011}, // MIPI_F1_VDT_VC - {0x3348, 0x0111}, // MIPI_F2_VDT_VC - {0x334C, 0x0211}, // MIPI_F3_VDT_VC - {0x3350, 0x0311}, // MIPI_F4_VDT_VC - {0x31B0, 0x0053}, // FRAME_PREAMBLE - {0x31B2, 0x003B}, // LINE_PREAMBLE - {0x301A, 0x001C}, // RESET_REGISTER - - // Noise Corrections - {0x3092, 0x0C24}, // ROW_NOISE_CONTROL - {0x337A, 0x0C80}, // DBLC_SCALE0 - {0x3370, 0x03B1}, // DBLC - {0x3044, 0x0400}, // DARK_CONTROL - - // Enable dead pixel correction using - // the 1D line correction scheme - {0x31E0, 0x0003}, - - // HDR Settings - {0x3082, 0x0004}, // OPERATION_MODE_CTRL (A) - {0x3084, 0x0004}, // OPERATION_MODE_CTRL (B) - - {0x3238, 0x0004}, // EXPOSURE_RATIO (A) - {0x323A, 0x0004}, // EXPOSURE_RATIO (B) - - {0x3014, 0x098E}, // FINE_INTEGRATION_TIME_ (A) - {0x3018, 0x098E}, // FINE_INTEGRATION_TIME_ (B) - - {0x321E, 0x098E}, // FINE_INTEGRATION_TIME2 (A) - {0x3220, 0x098E}, // FINE_INTEGRATION_TIME2 (B) - - {0x31D0, 0x0000}, // COMPANDING, no good in 10 bit? - {0x33DA, 0x0000}, // COMPANDING - {0x318E, 0x0200}, // PRE_HDR_GAIN_EN - - // DLO Settings - {0x3100, 0x4000}, // DLO_CONTROL0 - {0x3280, 0x0CCC}, // T1 G1 - {0x3282, 0x0CCC}, // T1 R - {0x3284, 0x0CCC}, // T1 B - {0x3286, 0x0CCC}, // T1 G2 - {0x3288, 0x0FA0}, // T2 G1 - {0x328A, 0x0FA0}, // T2 R - {0x328C, 0x0FA0}, // T2 B - {0x328E, 0x0FA0}, // T2 G2 - - // Initial Gains - {0x3022, 0x0001}, // GROUPED_PARAMETER_HOLD_ - {0x3366, 0xFF77}, // ANALOG_GAIN (1x) (A) - {0x3368, 0xFF77}, // ANALOG_GAIN (1x) (B) - - {0x3060, 0x3333}, // ANALOG_COLOR_GAIN - - {0x3362, 0x0000}, // DC GAIN (A & B) - - {0x305A, 0x00F8}, // red gain (A) - {0x3058, 0x0122}, // blue gain (A) - {0x3056, 0x009A}, // g1 gain (A) - {0x305C, 0x009A}, // g2 gain (A) - - {0x30C0, 0x00F8}, // red gain (B) - {0x30BE, 0x0122}, // blue gain (B) - {0x30BC, 0x009A}, // g1 gain (B) - {0x30C2, 0x009A}, // g2 gain (B) - - {0x3022, 0x0000}, // GROUPED_PARAMETER_HOLD_ - - // Initial Integration Time - {0x3012, 0x0005}, // (A) - {0x3016, 0x0005}, // (B) -}; diff --git a/selfdrive/camerad/cameras/sensor_i2c.h b/selfdrive/camerad/cameras/sensor_i2c.h deleted file mode 100644 index b46ebb370a..0000000000 --- a/selfdrive/camerad/cameras/sensor_i2c.h +++ /dev/null @@ -1,651 +0,0 @@ -static struct msm_camera_i2c_reg_array init_array_imx298[] = { - {0x101,0x0,0}, // IMAGE_ORIENT - {0x601,0x0,0}, // test pattern - //{0xb02,0,0}, // green correction? - // external clock setting - {0x136,0x18,0}, {0x137,0x0,0}, // EXCK_FREQ = Extclk_frequency_mhz - // global setting? - {0x30f4,0x1,0}, - {0x30f5,0x7a,0}, - {0x30f6,0x0,0}, - {0x30f7,0xec,0}, - {0x30fc,0x1,0}, - {0x3101,0x1,0}, - {0x5b2f,0x8,0}, - {0x5d32,0x5,0}, - {0x5d7c,0x0,0}, - {0x5d7d,0x0,0}, - {0x5db9,0x1,0}, - {0x5e43,0x0,0}, - {0x6300,0x0,0}, - {0x6301,0xea,0}, - {0x6302,0x0,0}, - {0x6303,0xb4,0}, - {0x6564,0x0,0}, - {0x6565,0xb6,0}, - {0x6566,0x0,0}, - {0x6567,0xe6,0}, - {0x6714,0x1,0}, - {0x6758,0xb,0}, - {0x6910,0x4,0}, - {0x6916,0x1,0}, - {0x6918,0x4,0}, - {0x691e,0x1,0}, - {0x6931,0x1,0}, - {0x6937,0x2,0}, - {0x693b,0x2,0}, - {0x6d00,0x4a,0}, - {0x6d01,0x41,0}, - {0x6d02,0x23,0}, - {0x6d05,0x4c,0}, - {0x6d06,0x10,0}, - {0x6d08,0x30,0}, - {0x6d09,0x38,0}, - {0x6d0a,0x2c,0}, - {0x6d0b,0x2d,0}, - {0x6d0c,0x34,0}, - {0x6d0d,0x42,0}, - {0x6d19,0x1c,0}, - {0x6d1a,0x71,0}, - {0x6d1b,0xc6,0}, - {0x6d1c,0x94,0}, - {0x6d24,0xe4,0}, - {0x6d30,0xa,0}, - {0x6d31,0x1,0}, - {0x6d33,0xb,0}, - {0x6d34,0x5,0}, - {0x6d35,0x0,0}, - {0x83c2,0x3,0}, - {0x83c3,0x8,0}, - {0x83c4,0x48,0}, - {0x83c7,0x8,0}, - {0x83cb,0x0,0}, - {0xb101,0xff,0}, - {0xb103,0xff,0}, - {0xb105,0xff,0}, - {0xb107,0xff,0}, - {0xb109,0xff,0}, - {0xb10b,0xff,0}, - {0xb10d,0xff,0}, - {0xb10f,0xff,0}, - {0xb111,0xff,0}, - {0xb163,0x3c,0}, - {0xc2a0,0x8,0}, - {0xc2a3,0x3,0}, - {0xc2a5,0x8,0}, - {0xc2a6,0x48,0}, - {0xc2a9,0x0,0}, - {0xf800,0x5e,0}, - {0xf801,0x5e,0}, - {0xf802,0xcd,0}, - {0xf803,0x20,0}, - {0xf804,0x55,0}, - {0xf805,0xd4,0}, - {0xf806,0x1f,0}, - {0xf808,0xf8,0}, - {0xf809,0x3a,0}, - {0xf80a,0xf1,0}, - {0xf80b,0x7e,0}, - {0xf80c,0x55,0}, - {0xf80d,0x38,0}, - {0xf80e,0xe3,0}, - {0xf810,0x74,0}, - {0xf811,0x41,0}, - {0xf812,0xbf,0}, - {0xf844,0x40,0}, - {0xf845,0xba,0}, - {0xf846,0x70,0}, - {0xf847,0x47,0}, - {0xf848,0xc0,0}, - {0xf849,0xba,0}, - {0xf84a,0x70,0}, - {0xf84b,0x47,0}, - {0xf84c,0x82,0}, - {0xf84d,0xf6,0}, - {0xf84e,0x32,0}, - {0xf84f,0xfd,0}, - {0xf851,0xf0,0}, - {0xf852,0x2,0}, - {0xf853,0xf8,0}, - {0xf854,0x81,0}, - {0xf855,0xf6,0}, - {0xf856,0xc0,0}, - {0xf857,0xff,0}, - {0xf858,0x10,0}, - {0xf859,0xb5,0}, - {0xf85a,0xd,0}, - {0xf85b,0x48,0}, - {0xf85c,0x40,0}, - {0xf85d,0x7a,0}, - {0xf85e,0x1,0}, - {0xf85f,0x28,0}, - {0xf860,0x15,0}, - {0xf861,0xd1,0}, - {0xf862,0xc,0}, - {0xf863,0x49,0}, - {0xf864,0xc,0}, - {0xf865,0x46,0}, - {0xf866,0x40,0}, - {0xf867,0x3c,0}, - {0xf868,0x48,0}, - {0xf869,0x8a,0}, - {0xf86a,0x62,0}, - {0xf86b,0x8a,0}, - {0xf86c,0x80,0}, - {0xf86d,0x1a,0}, - {0xf86e,0x8a,0}, - {0xf86f,0x89,0}, - {0xf871,0xb2,0}, - {0xf872,0x10,0}, - {0xf873,0x18,0}, - {0xf874,0xa,0}, - {0xf875,0x46,0}, - {0xf876,0x20,0}, - {0xf877,0x32,0}, - {0xf878,0x12,0}, - {0xf879,0x88,0}, - {0xf87a,0x90,0}, - {0xf87b,0x42,0}, - {0xf87d,0xda,0}, - {0xf87e,0x10,0}, - {0xf87f,0x46,0}, - {0xf880,0x80,0}, - {0xf881,0xb2,0}, - {0xf882,0x88,0}, - {0xf883,0x81,0}, - {0xf884,0x84,0}, - {0xf885,0xf6,0}, - {0xf886,0xd2,0}, - {0xf887,0xf9,0}, - {0xf888,0xe0,0}, - {0xf889,0x67,0}, - {0xf88a,0x85,0}, - {0xf88b,0xf6,0}, - {0xf88c,0xa1,0}, - {0xf88d,0xfc,0}, - {0xf88e,0x10,0}, - {0xf88f,0xbd,0}, - {0xf891,0x18,0}, - {0xf892,0x21,0}, - {0xf893,0x24,0}, - {0xf895,0x18,0}, - {0xf896,0x19,0}, - {0xf897,0xb4,0}, - {0x4e29,0x1,0}, - // PDAF stuff - {0x3166,0x1,0}, //AREA_EN_0 - {0x3167,0x1,0}, - {0x3168,0x1,0}, - {0x3169,0x1,0}, - {0x316a,0x1,0}, - {0x316b,0x1,0}, - {0x316c,0x1,0}, - {0x316d,0x1,0}, - {0x3158,0x2,0}, - {0x3159,0x2,0}, - {0x315a,0x2,0}, - {0x315b,0x3,0}, - {0x3013,0x7,0}, //RMSC_NR_MODE - {0x3035,0x1,0}, - {0x3051,0x0,0}, - {0x3056,0x2,0}, - {0x3057,0x1,0}, - {0x3060,0x0,0}, - {0x8435,0x0,0}, - {0x8455,0x0,0}, - {0x847c,0x0,0}, - {0x84fb,0x1,0}, - {0x9619,0xa0,0}, - {0x961b,0xa0,0}, - {0x961d,0xa0,0}, - {0x961f,0x20,0}, - {0x9621,0x20,0}, - {0x9623,0x20,0}, - {0x9625,0xa0,0}, - {0x9627,0xa0,0}, - {0x9629,0xa0,0}, - {0x962b,0x20,0}, - {0x962d,0x20,0}, - {0x962f,0x20,0}, - {0x9901,0x35,0}, - {0x9903,0x23,0}, - {0x9905,0x23,0}, - {0x9906,0x0,0}, - {0x9907,0x31,0}, - {0x9908,0x0,0}, - {0x9909,0x1b,0}, - {0x990a,0x0,0}, - {0x990b,0x15,0}, - {0x990d,0x3f,0}, - {0x990f,0x3f,0}, - {0x9911,0x3f,0}, - {0x9913,0x64,0}, - {0x9915,0x64,0}, - {0x9917,0x64,0}, - {0x9919,0x50,0}, - {0x991b,0x60,0}, - {0x991d,0x65,0}, - {0x991f,0x1,0}, - {0x9921,0x1,0}, - {0x9923,0x1,0}, - {0x9925,0x23,0}, - {0x9927,0x23,0}, - {0x9929,0x23,0}, - {0x992b,0x2f,0}, - {0x992d,0x1a,0}, - {0x992f,0x14,0}, - {0x9931,0x3f,0}, - {0x9933,0x3f,0}, - {0x9935,0x3f,0}, - {0x9937,0x6b,0}, - {0x9939,0x7c,0}, - {0x993b,0x81,0}, - {0x9943,0xf,0}, - {0x9945,0xf,0}, - {0x9947,0xf,0}, - {0x9949,0xf,0}, - {0x994b,0xf,0}, - {0x994d,0xf,0}, - {0x994f,0x42,0}, - {0x9951,0xf,0}, - {0x9953,0xb,0}, - {0x9955,0x5a,0}, - {0x9957,0x13,0}, - {0x9959,0xc,0}, - {0x995a,0x0,0}, - {0x995b,0x0,0}, - {0x995c,0x0,0}, - {0x996b,0x0,0}, - {0x996d,0x10,0}, - {0x996f,0x10,0}, - {0x9971,0xc8,0}, - {0x9973,0x32,0}, - {0x9975,0x4,0}, - {0x9976,0xa,0}, - {0x9977,0xa,0}, - {0x9978,0xa,0}, - {0x99a4,0x2f,0}, - {0x99a5,0x2f,0}, - {0x99a6,0x2f,0}, - {0x99a7,0xa,0}, - {0x99a8,0xa,0}, - {0x99a9,0xa,0}, - {0x99aa,0x2f,0}, - {0x99ab,0x2f,0}, - {0x99ac,0x2f,0}, - {0x99ad,0x0,0}, - {0x99ae,0x0,0}, - {0x99af,0x0,0}, - {0x99b0,0x40,0}, - {0x99b1,0x40,0}, - {0x99b2,0x40,0}, - {0x99b3,0x30,0}, - {0x99b4,0x30,0}, - {0x99b5,0x30,0}, - {0x99bb,0xa,0}, - {0x99bd,0xa,0}, - {0x99bf,0xa,0}, - {0x99c0,0x9,0}, - {0x99c1,0x9,0}, - {0x99c2,0x9,0}, - {0x99c6,0x3c,0}, - {0x99c7,0x3c,0}, - {0x99c8,0x3c,0}, - {0x99c9,0xff,0}, - {0x99ca,0xff,0}, - {0x99cb,0xff,0}, - {0x9b01,0x35,0}, - {0x9b03,0x14,0}, - {0x9b05,0x14,0}, - {0x9b07,0x31,0}, - {0x9b09,0x1b,0}, - {0x9b0b,0x15,0}, - {0x9b0d,0x1e,0}, - {0x9b0f,0x1e,0}, - {0x9b11,0x1e,0}, - {0x9b13,0x64,0}, - {0x9b15,0x64,0}, - {0x9b17,0x64,0}, - {0x9b19,0x50,0}, - {0x9b1b,0x60,0}, - {0x9b1d,0x65,0}, - {0x9b1f,0x1,0}, - {0x9b21,0x1,0}, - {0x9b23,0x1,0}, - {0x9b25,0x14,0}, - {0x9b27,0x14,0}, - {0x9b29,0x14,0}, - {0x9b2b,0x2f,0}, - {0x9b2d,0x1a,0}, - {0x9b2f,0x14,0}, - {0x9b31,0x1e,0}, - {0x9b33,0x1e,0}, - {0x9b35,0x1e,0}, - {0x9b37,0x6b,0}, - {0x9b39,0x7c,0}, - {0x9b3b,0x81,0}, - {0x9b43,0xf,0}, - {0x9b45,0xf,0}, - {0x9b47,0xf,0}, - {0x9b49,0xf,0}, - {0x9b4b,0xf,0}, - {0x9b4d,0xf,0}, - {0x9b4f,0x2d,0}, - {0x9b51,0xb,0}, - {0x9b53,0x8,0}, - {0x9b55,0x40,0}, - {0x9b57,0xd,0}, - {0x9b59,0x8,0}, - {0x9b5a,0x0,0}, - {0x9b5b,0x0,0}, - {0x9b5c,0x0,0}, - {0x9b6b,0x0,0}, - {0x9b6d,0x10,0}, - {0x9b6f,0x10,0}, - {0x9b71,0xc8,0}, - {0x9b73,0x32,0}, - {0x9b75,0x4,0}, - {0x9bb0,0x40,0}, - {0x9bb1,0x40,0}, - {0x9bb2,0x40,0}, - {0x9bb3,0x30,0}, - {0x9bb4,0x30,0}, - {0x9bb5,0x30,0}, - {0x9bbb,0xa,0}, - {0x9bbd,0xa,0}, - {0x9bbf,0xa,0}, - {0x9bc0,0x9,0}, - {0x9bc1,0x9,0}, - {0x9bc2,0x9,0}, - {0x9bc6,0x18,0}, - {0x9bc7,0x18,0}, - {0x9bc8,0x18,0}, - {0x9bc9,0xff,0}, - {0x9bca,0xff,0}, - {0x9bcb,0xff,0}, - {0xb2b2,0x1,0}, -}; - -static struct msm_camera_i2c_reg_array mode_setting_array_imx298[] = { -// i2c settings for mode 3 -// { -// .x_output = 2328, -// .y_output = 1748, -// .line_length_pclk = 5536, -// .frame_length_lines = 1802, -// .vt_pixel_clk = 299300000, -// .op_pixel_clk = 299300000, -// .binning_factor = 2, -// .min_fps = 15.000000, -// .max_fps = 30.020000, -// .mode = 1, -// .offset_x = 0, -// .offset_y = 0, -// .scale_factor = 1.000000, -// .is_pdaf_supported = 1, -// } - -// mode settings - -// hdr settings -{0x0114, 0x03, 0}, // CSI_LANE_MODE = 4-lane -/*{0x0220, 0x00, 0}, // HDR_MODE = disable -{0x0221, 0x11, 0}, // HDR_RESO_REDU_H/V = Full Pixel -{0x0222, 0x10, 0}, // EXPO_RATIO = 16*/ -{0x0220, 0x01, 0}, // HDR_MODE = enable with combined gain and 16x ratio -{0x0221, 0x22, 0}, // HDR_RESO_REDU_H/V = 2 binning -{0x0222, 0x10, 0}, // EXPO_RATIO = 16 - -{0x0340, 0x07, 0}, {0x0341, 0x0a, 0}, // FRM_LENGTH = frame_length_lines = 1802 -{0x0342, 0x15, 0}, {0x0343, 0xa0, 0}, // LINE_LENGTH = line_length_pclk = 5536 -{0x0344, 0x00, 0}, {0x0345, 0x00, 0}, // x_addr_start -{0x0346, 0x00, 0}, {0x0347, 0x00, 0}, // y_addr_start -{0x0348, 0x12, 0}, {0x0349, 0x2f, 0}, // x_addr_end -{0x034a, 0x0d, 0}, {0x034b, 0xa7, 0}, // y_addr_end -{0x0381, 0x01, 0}, // x_even_inc -{0x0383, 0x01, 0}, // x_odd_inc -{0x0385, 0x01, 0}, // y_even_inc -{0x0387, 0x01, 0}, // y_odd_inc -{0x0900, 0x01, 0}, // BINNING_MODE = enable -{0x0901, 0x22, 0}, // BINING_TYPE_H/V = 2binning -{0x0902, 0x00, 0}, // binning_weighting = average - -{0x0b06, 1, 0}, // SING_DEF_CORR_EN -{0x0b0a, 1, 0}, // combined defect correct - -{0x3010, 0x66, 0}, // HDR_OUTPUT_CTRL = ATR + HDR compose + DPC1D + DCP2D -{0x3011, 0x01, 0}, // HDR_OUTPUT_CTRL2 = PD enable -{0x30c0, 0x11, 0}, // RED_GAIN_CB? -{0x300d, 0x00, 0}, // FORCE_FDSUM = disable -{0x30fd, 0x00, 0}, -{0x8493, 0x00, 0}, -{0x8863, 0x00, 0}, -{0x90d7, 0x19, 0}, - -// set black level -{0x3090, 1, 0}, -{0x3092, 0, 0}, -{0x3093, 0x38, 0}, - -// output size settings -{0x0112, 0x0a, 0}, {0x0113, 0x0a, 0}, // CS_DT_FMT_H = 0x0a0a (RAW10 output) -{0x034c, 0x09, 0}, {0x034d, 0x18, 0}, // X_OUT_SIZE = 2328 (1164*2) -{0x034e, 0x06, 0}, {0x034f, 0xd4, 0}, // Y_OUT_SIZE = 1748 (874*2) -{0x0401, 0x00, 0}, // SCALING_MODE -{0x0404, 0x00, 0}, {0x0405, 0x10, 0}, // SCALE_M -{0x0408, 0x00, 0}, {0x0409, 0x00, 0}, // DCROP_XOFS -{0x040a, 0x00, 0}, {0x040b, 0x00, 0}, // DCROP_YOFS -{0x040c, 0x09, 0}, {0x040d, 0x18, 0}, // DCROP_WIDTH -{0x040e, 0x06, 0}, {0x040f, 0xd4, 0}, // DCROP_HIGT - -// clock settings -// 299300000 -/* -{0x0301, 0x05, 0}, // VT_PIX_CLK_DIV -{0x0303, 0x02, 0}, // VT_SYS_CLK_DIV -{0x0305, 0x04, 0}, // PRE_PLL_CLK_DIV -{0x0306, 0x00, 0}, {0x0307, 0x7d, 0}, // PLL_MULTIPLIER . mode 1: 0xf6 -{0x0309, 0x0a, 0}, // OP_PIX_CLK_DIV -{0x030b, 0x01, 0}, // OP_SYS_CLK_DIV -{0x030d, 0x0f, 0}, // PREPLLCK_OP_DIV -{0x030e, 0x03, 0}, {0x030f, 0x41, 0}, // PLL_OP_MPY -{0x0310, 0x00, 0}, // PLL_MULT_DRIV -*/ -// 600000000 -{0x0301, 0x05, 0}, -{0x0303, 0x02, 0}, -{0x0305, 0x04, 0}, -{0x0306, 0x00, 0}, -{0x0307, 0xfa, 0}, -{0x0309, 0x0a, 0}, -{0x030b, 0x01, 0}, -{0x030d, 0x0f, 0}, -{0x030e, 0x03, 0}, {0x030f, 0x41, 0}, -{0x0310, 0x00, 0}, - -// data rate settings -/*{0x0820, 0x0b, 0}, // requested_link_bit_rate_mbps = 3000 -{0x0821, 0xb8, 0}, -{0x0822, 0x00, 0}, -{0x0823, 0x00, 0},*/ -{0x0820, 0x17, 0}, // requested_link_bit_rate_mbps = 6000 -{0x0821, 0x70, 0}, -{0x0822, 0x00, 0}, -{0x0823, 0x00, 0}, - -//integration time settings -{0x0202, 0x07, 0}, {0x0203, 0x00, 0}, // INTEG_TIME = 1792 -{0x0224, 0x01, 0}, {0x0225, 0xf4, 0}, // ST_COARSE_INTEG_TIME = 506 - -// gain settings -{0x0204, 0x00, 0}, {0x0205, 0x00, 0}, // ANA_GAIN_GLOBAL = 512 / (512 - X) -{0x0216, 0x00, 0}, {0x0217, 0x00, 0}, // ST_ANA_GAIN_GLOBAL[8] -{0x020e, 0x01, 0}, {0x020f, 0x00, 0}, // DIG_GAIN_GR -{0x0210, 0x01, 0}, {0x0211, 0x00, 0}, // DIG_GAIN_R -{0x0212, 0x01, 0}, {0x0213, 0x00, 0}, // DIG_GAIN_B -{0x0214, 0x01, 0}, {0x0215, 0x00, 0}, // DIG_GAIN_GB - -// HDR white balance settings (ABS_GAIN) -{0xb8e, 0x01, 0}, {0xb8f, 0x00, 0}, // GR -{0xb90, 0x02, 0}, {0xb91, 0x2b, 0}, // R -{0xb92, 0x01, 0}, {0xb93, 0xd4, 0}, // B -{0xb94, 0x01, 0}, {0xb95, 0x00, 0}, // GB - -// phase detection settings -{0x3058, 0x00, 0}, // NML_NR_EN -{0x3103, 0x01, 0}, // NML_PD_CAL_ENABLE = enable -{0x3108, 0x00, 0}, {0x3109, 0x2c, 0}, //PD_AREA_X_OFFSET -{0x310a, 0x00, 0}, {0x310b, 0x24, 0}, //PD_AREA_Y_OFFSET -{0x310c, 0x01, 0}, {0x310d, 0xa4, 0}, //PD_AREA_WIDTH -{0x310e, 0x01, 0}, {0x310f, 0xa4, 0}, //PD_AREA_HEIGHT -// whole size is 0x918 x 0x6d4 -{0x3110, 0x03, 0}, // PD_AREA_0 = 0x375-0x4d1, 0x258-0x3b6 -{0x3111, 0x75, 0}, -{0x3112, 0x02, 0}, -{0x3113, 0x58, 0}, -{0x3114, 0x04, 0}, -{0x3115, 0xd1, 0}, -{0x3116, 0x03, 0}, -{0x3117, 0xb6, 0}, -{0x3118, 0x04, 0}, // PD_AREA_1 = 0x446-0x5a2, 0x258-0x3b6 -{0x3119, 0x46, 0}, -{0x311a, 0x02, 0}, -{0x311b, 0x58, 0}, -{0x311c, 0x05, 0}, -{0x311d, 0xa2, 0}, -{0x311e, 0x03, 0}, -{0x311f, 0xb6, 0}, -{0x3120, 0x03, 0}, // PD_AREA_2 = 0x375-0x4d1, 0x32a-0x488 -{0x3121, 0x75, 0}, -{0x3122, 0x03, 0}, -{0x3123, 0x2a, 0}, -{0x3124, 0x04, 0}, -{0x3125, 0xd1, 0}, -{0x3126, 0x04, 0}, -{0x3127, 0x88, 0}, -{0x3128, 0x04, 0}, // PD_AREA_3 = 0x446-0x5a2, 0x32a-0x488 -{0x3129, 0x46, 0}, -{0x312a, 0x03, 0}, -{0x312b, 0x2a, 0}, -{0x312c, 0x05, 0}, -{0x312d, 0xa2, 0}, -{0x312e, 0x04, 0}, -{0x312f, 0x88, 0}, -{0x3130, 0x03, 0}, // PD_AREA_4 = 0x375-0x5a2, 0x258-0x488 -{0x3131, 0x75, 0}, -{0x3132, 0x02, 0}, -{0x3133, 0x58, 0}, -{0x3134, 0x05, 0}, -{0x3135, 0xa2, 0}, -{0x3136, 0x04, 0}, -{0x3137, 0x88, 0}, -{0x3138, 0x02, 0}, // PD_AREA_5 = 0x2ba-0x65d, 0x210-0x4d0 -{0x3139, 0xba, 0}, -{0x313a, 0x02, 0}, -{0x313b, 0x10, 0}, -{0x313c, 0x06, 0}, -{0x313d, 0x5d, 0}, -{0x313e, 0x04, 0}, -{0x313f, 0xd0, 0}, -{0x3140, 0x00, 0}, // PD_AREA_6 = 0xa1-0x876, 0x6b-0x676 -{0x3141, 0xa1, 0}, -{0x3142, 0x00, 0}, -{0x3143, 0x6b, 0}, -{0x3144, 0x08, 0}, -{0x3145, 0x76, 0}, -{0x3146, 0x06, 0}, -{0x3147, 0x76, 0}, -{0x3148, 0x00, 0}, // PD_AREA_7 = 0xa1-0x876, 0x5e-0x34c -{0x3149, 0xa1, 0}, -{0x314a, 0x00, 0}, -{0x314b, 0x5e, 0}, -{0x314c, 0x08, 0}, -{0x314d, 0x76, 0}, -{0x314e, 0x03, 0}, -{0x314f, 0x4c, 0}, -{0x3165, 0x02, 0}, // AREA_EN_0 = free area -}; - -// static struct msm_camera_i2c_reg_array reg_array3[] = { -// // REG_HOLD ON -// {0x104,0x1,0}, -// // from regression -// {0x3002,0x0,0}, -// // FRM_LENGTH, 1802 vs 3554 -// // {0x340,0x7,0}, {0x341,0xa,0}, // camera start {0x340,0xd,0}, {0x341,0xe2,0}, -// // INTEG_TIME aka coarse_int_time_addr aka shutter speed -// {0x202,0x03,0}, {0x203,0xda,0}, -// // global_gain_addr -// {0x204,0x0,0}, {0x205,0x0,0}, - -// //?? -// {0x20e,0x1,0}, {0x20f,0x0,0}, -// {0x210,0x1,0}, {0x211,0x0,0}, -// {0x212,0x1,0}, {0x213,0x0,0}, -// {0x214,0x1,0}, {0x215,0x0,0}, - -// // REG_HOLD: mode setting -// {0x104,0x0,0}, -// }; - -// start, remove standby mode -static struct msm_camera_i2c_reg_array start_reg_array[] = {{0x100,0x1,0}}; - -// stop, enable standby mode -static struct msm_camera_i2c_reg_array stop_reg_array[] = {{0x100,0x0,0}}; - -/* -// still mode settings: - {0x847f, 0x0c0c,}, //_M_EQCTL - - {0x8436, 0xfd7f,}, //_M_Kgxdr - {0x8440, 0xf07f,}, //_M_X_LMT - {0x8443, 0xb41e,}, //_M_X_TGT - {0x841b, 0x4001,}, //_M_Kgx10 - - {0x84b6, 0xfd7f,}, //_M_Kgydr - {0x84c0, 0xf07f,}, //_M_Y_LMT - {0x84c3, 0xb41e,}, //_M_Y_TGT - {0x849b, 0x4001,}, //_M_Kgy10 - - {0x8438, 0x2d0f,}, //_M_Kgx11 - {0x84b8, 0x2d0f,}, //_M_Kgy11 - {0x8447, 0x002b,}, //_M_KgxTG - {0x84c7, 0x002b,}, //_M_KgyTG - - {0x847f, 0x0d0d,}, //_M_EQCTL -*/ - -static struct msm_camera_i2c_reg_array init_array_ov8865[] = { -// round 1 -//{0x103,0x1,0}, // software reset -{0x100,0x0,0}, // standby on -{0x3638,0xff,0}, -{0x302,0x1e,0}, {0x303,0x0,0}, {0x304,0x3,0}, {0x30d,0x1e,0}, {0x30e,0x0,0}, {0x30f,0x9,0}, {0x312,0x1,0}, {0x31e,0xc,0}, // PLL control -{0x3015,0x1,0}, {0x3018,0x72,0}, {0x3020,0x93,0}, {0x3022,0x1,0}, -{0x3031,0xa,0}, // 10-bit mode -{0x3106,0x1,0}, {0x3305,0xf1,0}, {0x3308,0x0,0}, {0x3309,0x28,0}, {0x330a,0x0,0}, {0x330b,0x20,0}, {0x330c,0x0,0}, {0x330d,0x0,0}, {0x330e,0x0,0}, {0x330f,0x40,0}, {0x3307,0x4,0}, {0x3604,0x4,0}, {0x3602,0x30,0}, {0x3605,0x0,0}, {0x3607,0x20,0}, {0x3608,0x11,0}, {0x3609,0x68,0}, {0x360a,0x40,0}, {0x360c,0xdd,0}, {0x360e,0xc,0}, {0x3610,0x7,0}, {0x3612,0x86,0}, {0x3613,0x58,0}, {0x3614,0x28,0}, {0x3617,0x40,0}, {0x3618,0x5a,0}, {0x3619,0x9b,0}, {0x361c,0x0,0}, {0x361d,0x60,0}, {0x3631,0x60,0}, {0x3633,0x10,0}, {0x3634,0x10,0}, {0x3635,0x10,0}, {0x3636,0x10,0}, {0x3641,0x55,0}, {0x3646,0x86,0}, {0x3647,0x27,0}, {0x364a,0x1b,0}, {0x3500,0x0,0}, {0x3501,0x4c,0}, {0x3502,0x0,0}, {0x3503,0x0,0}, {0x3508,0x2,0}, -{0x3509,0x0,0}, // AEC GAIN -{0x3700,0x24,0}, {0x3701,0xc,0}, {0x3702,0x28,0}, {0x3703,0x19,0}, {0x3704,0x14,0}, {0x3705,0x0,0}, {0x3706,0x38,0}, {0x3707,0x4,0}, {0x3708,0x24,0}, {0x3709,0x40,0}, {0x370a,0x0,0}, {0x370b,0xb8,0}, {0x370c,0x4,0}, {0x3718,0x12,0}, {0x3719,0x31,0}, {0x3712,0x42,0}, {0x3714,0x12,0}, {0x371e,0x19,0}, {0x371f,0x40,0}, {0x3720,0x5,0}, {0x3721,0x5,0}, {0x3724,0x2,0}, {0x3725,0x2,0}, {0x3726,0x6,0}, {0x3728,0x5,0}, {0x3729,0x2,0}, {0x372a,0x3,0}, {0x372b,0x53,0}, {0x372c,0xa3,0}, {0x372d,0x53,0}, {0x372e,0x6,0}, {0x372f,0x10,0}, {0x3730,0x1,0}, {0x3731,0x6,0}, {0x3732,0x14,0}, {0x3733,0x10,0}, {0x3734,0x40,0}, {0x3736,0x20,0}, {0x373a,0x2,0}, {0x373b,0xc,0}, {0x373c,0xa,0}, {0x373e,0x3,0}, {0x3755,0x40,0}, {0x3758,0x0,0}, {0x3759,0x4c,0}, {0x375a,0x6,0}, {0x375b,0x13,0}, {0x375c,0x40,0}, {0x375d,0x2,0}, {0x375e,0x0,0}, {0x375f,0x14,0}, {0x3767,0x1c,0}, {0x3768,0x4,0}, {0x3769,0x20,0}, {0x376c,0xc0,0}, {0x376d,0xc0,0}, {0x376a,0x8,0}, {0x3761,0x0,0}, {0x3762,0x0,0}, {0x3763,0x0,0}, {0x3766,0xff,0}, {0x376b,0x42,0}, {0x3772,0x23,0}, {0x3773,0x2,0}, {0x3774,0x16,0}, {0x3775,0x12,0}, {0x3776,0x8,0}, {0x37a0,0x44,0}, {0x37a1,0x3d,0}, {0x37a2,0x3d,0}, {0x37a3,0x1,0}, {0x37a4,0x0,0}, {0x37a5,0x8,0}, {0x37a6,0x0,0}, {0x37a7,0x44,0}, {0x37a8,0x58,0}, {0x37a9,0x58,0}, {0x3760,0x0,0}, {0x376f,0x1,0}, {0x37aa,0x44,0}, {0x37ab,0x2e,0}, {0x37ac,0x2e,0}, {0x37ad,0x33,0}, {0x37ae,0xd,0}, {0x37af,0xd,0}, {0x37b0,0x0,0}, {0x37b1,0x0,0}, {0x37b2,0x0,0}, {0x37b3,0x42,0}, {0x37b4,0x42,0}, {0x37b5,0x33,0}, {0x37b6,0x0,0}, {0x37b7,0x0,0}, {0x37b8,0x0,0}, {0x37b9,0xff,0}, {0x3800,0x0,0}, {0x3801,0xc,0}, {0x3802,0x0,0}, {0x3803,0xc,0}, -{0x3804,0xc,0}, {0x3805,0xd3,0}, // 3283 -{0x3806,0x9,0}, {0x3807,0xa3,0}, // 2467 -{0x3808,0x6,0}, {0x3809,0x60,0}, // 0x660 = 1632 (width) -{0x380a,0x4,0}, {0x380b,0xc8,0}, // 0x4c8 = 1224 (height) -{0x380c,0x6,0}, {0x380d,0x42,0}, // line_length_pck -{0x380e,0x5,0}, {0x380f,0xda,0}, // frame_length_lines -{0x3810,0x0,0}, {0x3811,0x4,0}, {0x3813,0x4,0}, -{0x3814,0x3,0}, {0x3815,0x1,0}, // H-binning -{0x3820,0x6,0}, // format1 -{0x3821,0x40,0}, // format2 -{0x382a,0x3,0}, {0x382b,0x1,0}, // V-binning -{0x382d,0x7f,0}, {0x3830,0x8,0}, {0x3836,0x2,0}, {0x3837,0x18,0}, -{0x3841,0xff,0}, -{0x3846,0x88,0}, {0x3d85,0x6,0}, {0x3d8c,0x75,0}, {0x3d8d,0xef,0}, {0x3f08,0xb,0}, {0x4000,0xf1,0}, {0x4001,0x14,0}, {0x4005,0x10,0}, {0x4006,0x1,0}, {0x4007,0x1,0}, {0x400b,0xc,0}, {0x400d,0x10,0}, {0x401b,0x0,0}, {0x401d,0x0,0}, {0x4020,0x0,0}, {0x4021,0x0,0}, {0x4022,0x4,0}, {0x4023,0x1f,0}, {0x4024,0x6,0}, {0x4025,0x20,0}, {0x4026,0x6,0}, {0x4027,0x4f,0}, {0x4028,0x0,0}, {0x4029,0x2,0}, {0x402a,0x4,0}, {0x402b,0x4,0}, {0x402c,0x2,0}, {0x402d,0x2,0}, {0x402e,0x8,0}, {0x402f,0x2,0}, {0x401f,0x0,0}, {0x4034,0x3f,0}, {0x4300,0xff,0}, {0x4301,0x0,0}, {0x4302,0xf,0}, {0x4500,0x40,0}, {0x4503,0x10,0}, {0x4601,0x74,0}, {0x481f,0x32,0}, {0x4837,0x15,0}, {0x4850,0x10,0}, {0x4851,0x32,0}, {0x4b00,0x2a,0}, {0x4b0d,0x0,0}, {0x4d00,0x4,0}, {0x4d01,0x18,0}, {0x4d02,0xc3,0}, {0x4d03,0xff,0}, {0x4d04,0xff,0}, {0x4d05,0xff,0}, {0x5000,0x96,0}, {0x5001,0x1,0}, {0x5002,0x8,0}, {0x5901,0x0,0}, -{0x5e00,0x0,0}, -//{0x5e00,0x80,0}, -{0x5e01,0x41,0}, {0x5b00,0x2,0}, {0x5b01,0xd0,0}, {0x5b02,0x3,0}, {0x5b03,0xff,0}, {0x5b05,0x6c,0}, {0x5780,0xfc,0}, {0x5781,0xdf,0}, {0x5782,0x3f,0}, {0x5783,0x8,0}, {0x5784,0xc,0}, {0x5786,0x20,0}, {0x5787,0x40,0}, {0x5788,0x8,0}, {0x5789,0x8,0}, {0x578a,0x2,0}, {0x578b,0x1,0}, {0x578c,0x1,0}, {0x578d,0xc,0}, {0x578e,0x2,0}, {0x578f,0x1,0}, {0x5790,0x1,0}, {0x5800,0x1d,0}, {0x5801,0xe,0}, {0x5802,0xc,0}, {0x5803,0xc,0}, {0x5804,0xf,0}, {0x5805,0x22,0}, {0x5806,0xa,0}, {0x5807,0x6,0}, {0x5808,0x5,0}, {0x5809,0x5,0}, {0x580a,0x7,0}, {0x580b,0xa,0}, {0x580c,0x6,0}, {0x580d,0x2,0}, {0x580e,0x0,0}, {0x580f,0x0,0}, {0x5810,0x3,0}, {0x5811,0x7,0}, {0x5812,0x6,0}, {0x5813,0x2,0}, {0x5814,0x0,0}, {0x5815,0x0,0}, {0x5816,0x3,0}, {0x5817,0x7,0}, {0x5818,0x9,0}, {0x5819,0x6,0}, {0x581a,0x4,0}, {0x581b,0x4,0}, {0x581c,0x6,0}, {0x581d,0xa,0}, {0x581e,0x19,0}, {0x581f,0xd,0}, {0x5820,0xb,0}, {0x5821,0xb,0}, {0x5822,0xe,0}, {0x5823,0x22,0}, {0x5824,0x23,0}, {0x5825,0x28,0}, {0x5826,0x29,0}, {0x5827,0x27,0}, {0x5828,0x13,0}, {0x5829,0x26,0}, {0x582a,0x33,0}, {0x582b,0x32,0}, {0x582c,0x33,0}, {0x582d,0x16,0}, {0x582e,0x14,0}, {0x582f,0x30,0}, {0x5830,0x31,0}, {0x5831,0x30,0}, {0x5832,0x15,0}, {0x5833,0x26,0}, {0x5834,0x23,0}, {0x5835,0x21,0}, {0x5836,0x23,0}, {0x5837,0x5,0}, {0x5838,0x36,0}, {0x5839,0x27,0}, {0x583a,0x28,0}, {0x583b,0x26,0}, {0x583c,0x24,0}, {0x583d,0xdf,0}, -//{0x100,0x1,0}, -// round 2 (color calibration) -{0x7010,0x0,0}, {0x7011,0x0,0}, {0x7012,0x0,0}, {0x7013,0x0,0}, {0x7014,0x0,0}, {0x7015,0x0,0}, {0x7016,0x0,0}, {0x7017,0x0,0}, {0x7018,0x0,0}, {0x7019,0x0,0}, {0x701a,0x0,0}, {0x701b,0x0,0}, {0x701c,0x0,0}, {0x701d,0x0,0}, {0x701e,0x0,0}, {0x701f,0x0,0}, {0x7020,0x0,0}, {0x7021,0x0,0}, {0x7022,0x0,0}, {0x7023,0x0,0}, {0x7024,0x0,0}, {0x7025,0x0,0}, {0x7026,0x0,0}, {0x7027,0x0,0}, {0x7028,0x0,0}, {0x7029,0x0,0}, {0x702a,0x0,0}, {0x702b,0x0,0}, {0x702c,0x0,0}, {0x702d,0x0,0}, {0x702e,0x0,0}, {0x702f,0x0,0}, {0x7030,0x0,0}, {0x7031,0x0,0}, {0x7032,0x0,0}, {0x7033,0x0,0}, {0x7034,0x0,0}, {0x7035,0x0,0}, {0x7036,0x0,0}, {0x7037,0x0,0}, {0x7038,0x0,0}, {0x7039,0x0,0}, {0x703a,0x0,0}, {0x703b,0x0,0}, {0x703c,0x0,0}, {0x703d,0x0,0}, {0x703e,0x0,0}, {0x703f,0x0,0}, {0x7040,0x0,0}, {0x7041,0x0,0}, {0x7042,0x0,0}, {0x7043,0x0,0}, {0x7044,0x0,0}, {0x7045,0x0,0}, {0x7046,0x0,0}, {0x7047,0x0,0}, {0x7048,0x0,0}, {0x7049,0x0,0}, {0x704a,0x0,0}, {0x704b,0x0,0}, {0x704c,0x0,0}, {0x704d,0x0,0}, {0x704e,0x0,0}, {0x704f,0x0,0}, {0x7050,0x0,0}, {0x7051,0x0,0}, {0x7052,0x0,0}, {0x7053,0x0,0}, {0x7054,0x0,0}, {0x7055,0x0,0}, {0x7056,0x0,0}, {0x7057,0x0,0}, {0x7058,0x0,0}, {0x7059,0x0,0}, {0x705a,0x0,0}, {0x705b,0x0,0}, {0x705c,0x0,0}, {0x705d,0x0,0}, {0x705e,0x0,0}, {0x705f,0x0,0}, {0x7060,0x0,0}, {0x7061,0x0,0}, {0x7062,0x0,0}, {0x7063,0x0,0}, {0x7064,0x0,0}, {0x7065,0x0,0}, {0x7066,0x0,0}, {0x7067,0x0,0}, {0x7068,0x0,0}, {0x7069,0x0,0}, {0x706a,0x0,0}, {0x706b,0x0,0}, {0x706c,0x0,0}, {0x706d,0x0,0}, {0x706e,0x0,0}, {0x706f,0x0,0}, {0x7070,0x0,0}, {0x7071,0x0,0}, {0x7072,0x0,0}, {0x7073,0x0,0}, {0x7074,0x0,0}, {0x7075,0x0,0}, {0x7076,0x0,0}, {0x7077,0x0,0}, {0x7078,0x0,0}, {0x7079,0x0,0}, {0x707a,0x0,0}, {0x707b,0x0,0}, {0x707c,0x0,0}, {0x707d,0x0,0}, {0x707e,0x0,0}, {0x707f,0x0,0}, {0x7080,0x0,0}, {0x7081,0x0,0}, {0x7082,0x0,0}, {0x7083,0x0,0}, {0x7084,0x0,0}, {0x7085,0x0,0}, {0x7086,0x0,0}, {0x7087,0x0,0}, {0x7088,0x0,0}, {0x7089,0x0,0}, {0x708a,0x0,0}, {0x708b,0x0,0}, {0x708c,0x0,0}, {0x708d,0x0,0}, {0x708e,0x0,0}, {0x708f,0x0,0}, {0x7090,0x0,0}, {0x7091,0x0,0}, {0x7092,0x0,0}, {0x7093,0x0,0}, {0x7094,0x0,0}, {0x7095,0x0,0}, {0x7096,0x0,0}, {0x7097,0x0,0}, {0x7098,0x0,0}, {0x7099,0x0,0}, {0x709a,0x0,0}, {0x709b,0x0,0}, {0x709c,0x0,0}, {0x709d,0x0,0}, {0x709e,0x0,0}, {0x709f,0x0,0}, {0x70a0,0x0,0}, {0x70a1,0x0,0}, {0x70a2,0x0,0}, {0x70a3,0x0,0}, {0x70a4,0x0,0}, {0x70a5,0x0,0}, {0x70a6,0x0,0}, {0x70a7,0x0,0}, {0x70a8,0x0,0}, {0x70a9,0x0,0}, {0x70aa,0x0,0}, {0x70ab,0x0,0}, {0x70ac,0x0,0}, {0x70ad,0x0,0}, {0x70ae,0x0,0}, {0x70af,0x0,0}, {0x70b0,0x0,0}, {0x70b1,0x0,0}, {0x70b2,0x0,0}, {0x70b3,0x0,0}, {0x70b4,0x0,0}, {0x70b5,0x0,0}, {0x70b6,0x0,0}, {0x70b7,0x0,0}, {0x70b8,0x0,0}, {0x70b9,0x0,0}, {0x70ba,0x0,0}, {0x70bb,0x0,0}, {0x70bc,0x0,0}, {0x70bd,0x0,0}, {0x70be,0x0,0}, {0x70bf,0x0,0}, {0x70c0,0x0,0}, {0x70c1,0x0,0}, {0x70c2,0x0,0}, {0x70c3,0x0,0}, {0x70c4,0x0,0}, {0x70c5,0x0,0}, {0x70c6,0x0,0}, {0x70c7,0x0,0}, {0x70c8,0x0,0}, {0x70c9,0x0,0}, {0x70ca,0x0,0}, {0x70cb,0x0,0}, {0x70cc,0x0,0}, {0x70cd,0x0,0}, {0x70ce,0x0,0}, {0x70cf,0x0,0}, {0x70d0,0x0,0}, {0x70d1,0x0,0}, {0x70d2,0x0,0}, {0x70d3,0x0,0}, {0x70d4,0x0,0}, {0x70d5,0x0,0}, {0x70d6,0x0,0}, {0x70d7,0x0,0}, {0x70d8,0x0,0}, {0x70d9,0x0,0}, {0x70da,0x0,0}, {0x70db,0x0,0}, {0x70dc,0x0,0}, {0x70dd,0x0,0}, {0x70de,0x0,0}, {0x70df,0x0,0}, {0x70e0,0x0,0}, {0x70e1,0x0,0}, {0x70e2,0x0,0}, {0x70e3,0x0,0}, {0x70e4,0x0,0}, {0x70e5,0x0,0}, {0x70e6,0x0,0}, {0x70e7,0x0,0}, {0x70e8,0x0,0}, {0x70e9,0x0,0}, {0x70ea,0x0,0}, {0x70eb,0x0,0}, {0x70ec,0x0,0}, {0x70ed,0x0,0}, {0x70ee,0x0,0}, {0x70ef,0x0,0}, {0x70f0,0x0,0}, {0x70f1,0x0,0}, {0x70f2,0x0,0}, {0x70f3,0x0,0}, {0x70f4,0x0,0}, {0x70f5,0x0,0}, {0x70f6,0x0,0}, {0x70f7,0x0,0}, {0x70f8,0x0,0}, {0x70f9,0x0,0}, {0x70fa,0x0,0}, {0x70fb,0x0,0}, {0x70fc,0x0,0}, {0x70fd,0x0,0}, {0x70fe,0x0,0}, {0x70ff,0x0,0}, {0x7100,0x0,0}, {0x7101,0x0,0}, {0x7102,0x0,0}, {0x7103,0x0,0}, {0x7104,0x0,0}, {0x7105,0x0,0}, {0x7106,0x0,0}, {0x7107,0x0,0}, {0x7108,0x0,0}, {0x7109,0x0,0}, {0x710a,0x0,0}, {0x710b,0x0,0}, {0x710c,0x0,0}, {0x710d,0x0,0}, {0x710e,0x0,0}, {0x710f,0x0,0}, {0x7110,0x0,0}, {0x7111,0x0,0}, {0x7112,0x0,0}, {0x7113,0x0,0}, {0x7114,0x0,0}, {0x7115,0x0,0}, {0x7116,0x0,0}, {0x7117,0x0,0}, {0x7118,0x0,0}, {0x7119,0x0,0}, {0x711a,0x0,0}, {0x711b,0x0,0}, {0x711c,0x0,0}, {0x711d,0x0,0}, {0x711e,0x0,0}, {0x711f,0x0,0}, {0x7120,0x0,0}, {0x7121,0x0,0}, {0x7122,0x0,0}, {0x7123,0x0,0}, {0x7124,0x0,0}, {0x7125,0x0,0}, {0x7126,0x0,0}, {0x7127,0x0,0}, {0x7128,0x0,0}, {0x7129,0x0,0}, {0x712a,0x0,0}, {0x712b,0x0,0}, {0x712c,0x0,0}, {0x712d,0x0,0}, {0x712e,0x0,0}, {0x712f,0x0,0}, {0x7130,0x0,0}, {0x7131,0x0,0}, {0x7132,0x0,0}, {0x501a,0x10,0}, {0x501b,0xd,0}, {0x501c,0x10,0}, {0x501d,0x13,0}, {0x5000,0x96,0}, {0x5800,0x14,0}, {0x5801,0xd,0}, {0x5802,0xa,0}, {0x5803,0xa,0}, {0x5804,0xd,0}, {0x5805,0x13,0}, {0x5806,0xa,0}, {0x5807,0x5,0}, {0x5808,0x3,0}, {0x5809,0x3,0}, {0x580a,0x5,0}, {0x580b,0x9,0}, {0x580c,0x6,0}, {0x580d,0x2,0}, {0x580e,0x0,0}, {0x580f,0x0,0}, {0x5810,0x2,0}, {0x5811,0x5,0}, {0x5812,0x6,0}, {0x5813,0x2,0}, {0x5814,0x0,0}, {0x5815,0x0,0}, {0x5816,0x2,0}, {0x5817,0x5,0}, {0x5818,0xb,0}, {0x5819,0x6,0}, {0x581a,0x3,0}, {0x581b,0x3,0}, {0x581c,0x5,0}, {0x581d,0xa,0}, {0x581e,0x16,0}, {0x581f,0xf,0}, {0x5820,0xb,0}, {0x5821,0xb,0}, {0x5822,0xf,0}, {0x5823,0x15,0}, {0x5824,0x32,0}, {0x5825,0x23,0}, {0x5826,0x23,0}, {0x5827,0x23,0}, {0x5828,0x22,0}, {0x5829,0x21,0}, {0x582a,0x21,0}, {0x582b,0x22,0}, {0x582c,0x21,0},{0x582d,0x11,0}, {0x582e,0x22,0}, {0x582f,0x31,0}, {0x5830,0x41,0}, {0x5831,0x31,0}, {0x5832,0x1,0}, {0x5833,0x21,0}, {0x5834,0x21,0}, {0x5835,0x21,0}, {0x5836,0x11,0}, {0x5837,0x11,0}, {0x5838,0x22,0}, {0x5839,0x22,0}, {0x583a,0x12,0}, {0x583b,0x22,0}, {0x583c,0x22,0}, {0x583d,0xdf,0}, -}; - diff --git a/selfdrive/camerad/main.cc b/selfdrive/camerad/main.cc deleted file mode 100644 index 668410d6f7..0000000000 --- a/selfdrive/camerad/main.cc +++ /dev/null @@ -1,20 +0,0 @@ -#include "selfdrive/camerad/cameras/camera_common.h" - -#include - -#include "selfdrive/common/params.h" -#include "selfdrive/common/util.h" -#include "selfdrive/hardware/hw.h" - -int main(int argc, char *argv[]) { - if (!Hardware::PC()) { - int ret; - ret = util::set_realtime_priority(53); - assert(ret == 0); - ret = util::set_core_affinity({Hardware::EON() ? 2 : 6}); - assert(ret == 0 || Params().getBool("IsOffroad")); // failure ok while offroad due to offlining cores - } - - camerad_thread(); - return 0; -} diff --git a/selfdrive/camerad/test/test_camerad.py b/selfdrive/camerad/test/test_camerad.py deleted file mode 100755 index ff37ad1f31..0000000000 --- a/selfdrive/camerad/test/test_camerad.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python3 - -import time -import unittest - -import cereal.messaging as messaging -from selfdrive.test.helpers import with_processes - -# only tests for EON and TICI -from selfdrive.hardware import EON, TICI - -TEST_TIMESPAN = 30 # random.randint(60, 180) # seconds -SKIP_FRAME_TOLERANCE = 0 -LAG_FRAME_TOLERANCE = 2 # ms - -FPS_BASELINE = 20 -CAMERAS = { - "roadCameraState": FPS_BASELINE, - "driverCameraState": FPS_BASELINE // 2, -} - -if TICI: - CAMERAS["driverCameraState"] = FPS_BASELINE - CAMERAS["wideRoadCameraState"] = FPS_BASELINE - -class TestCamerad(unittest.TestCase): - @classmethod - def setUpClass(cls): - if not (EON or TICI): - raise unittest.SkipTest - - @with_processes(['camerad']) - def test_frame_packets(self): - print("checking frame pkts continuity") - print(TEST_TIMESPAN) - - sm = messaging.SubMaster([socket_name for socket_name in CAMERAS]) - - last_frame_id = dict.fromkeys(CAMERAS, None) - last_ts = dict.fromkeys(CAMERAS, None) - start_time_sec = time.time() - while time.time()- start_time_sec < TEST_TIMESPAN: - sm.update() - - for camera in CAMERAS: - if sm.updated[camera]: - ct = (sm[camera].timestampEof if not TICI else sm[camera].timestampSof) / 1e6 - if last_frame_id[camera] is None: - last_frame_id[camera] = sm[camera].frameId - last_ts[camera] = ct - continue - - dfid = sm[camera].frameId - last_frame_id[camera] - self.assertTrue(abs(dfid - 1) <= SKIP_FRAME_TOLERANCE, "%s frame id diff is %d" % (camera, dfid)) - - dts = ct - last_ts[camera] - self.assertTrue(abs(dts - (1000/CAMERAS[camera])) < LAG_FRAME_TOLERANCE, f"{camera} frame t(ms) diff is {dts:f}") - - last_frame_id[camera] = sm[camera].frameId - last_ts[camera] = ct - - time.sleep(0.01) - -if __name__ == "__main__": - unittest.main() diff --git a/selfdrive/camerad/transforms/rgb_to_yuv.cc b/selfdrive/camerad/transforms/rgb_to_yuv.cc deleted file mode 100644 index 63e032e2dc..0000000000 --- a/selfdrive/camerad/transforms/rgb_to_yuv.cc +++ /dev/null @@ -1,36 +0,0 @@ -#include "selfdrive/camerad/transforms/rgb_to_yuv.h" - -#include -#include - -Rgb2Yuv::Rgb2Yuv(cl_context ctx, cl_device_id device_id, int width, int height, int rgb_stride) { - assert(width % 2 == 0 && height % 2 == 0); - char args[1024]; - snprintf(args, sizeof(args), - "-cl-fast-relaxed-math -cl-denorms-are-zero " -#ifdef CL_DEBUG - "-DCL_DEBUG " -#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 = cl_program_from_file(ctx, device_id, "transforms/rgb_to_yuv.cl", args); - krnl = CL_CHECK_ERR(clCreateKernel(prg, "rgb_to_yuv", &err)); - CL_CHECK(clReleaseProgram(prg)); - - work_size[0] = (width + (width % 4 == 0 ? 0 : (4 - width % 4))) / 4; - work_size[1] = (height + (height % 4 == 0 ? 0 : (4 - height % 4))) / 4; -} - -Rgb2Yuv::~Rgb2Yuv() { - CL_CHECK(clReleaseKernel(krnl)); -} - -void Rgb2Yuv::queue(cl_command_queue q, cl_mem rgb_cl, cl_mem yuv_cl) { - CL_CHECK(clSetKernelArg(krnl, 0, sizeof(cl_mem), &rgb_cl)); - CL_CHECK(clSetKernelArg(krnl, 1, sizeof(cl_mem), &yuv_cl)); - cl_event event; - CL_CHECK(clEnqueueNDRangeKernel(q, krnl, 2, NULL, &work_size[0], NULL, 0, 0, &event)); - CL_CHECK(clWaitForEvents(1, &event)); - CL_CHECK(clReleaseEvent(event)); -} diff --git a/selfdrive/camerad/transforms/rgb_to_yuv.h b/selfdrive/camerad/transforms/rgb_to_yuv.h deleted file mode 100644 index 3bb50669ef..0000000000 --- a/selfdrive/camerad/transforms/rgb_to_yuv.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include "selfdrive/common/clutil.h" - -class Rgb2Yuv { -public: - Rgb2Yuv(cl_context ctx, cl_device_id device_id, int width, int height, int rgb_stride); - ~Rgb2Yuv(); - void queue(cl_command_queue q, cl_mem rgb_cl, cl_mem yuv_cl); -private: - size_t work_size[2]; - cl_kernel krnl; -}; - diff --git a/selfdrive/camerad/transforms/rgb_to_yuv_test.cc b/selfdrive/camerad/transforms/rgb_to_yuv_test.cc deleted file mode 100644 index 74db2bc1c2..0000000000 --- a/selfdrive/camerad/transforms/rgb_to_yuv_test.cc +++ /dev/null @@ -1,191 +0,0 @@ -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef ANDROID - -#define MAXE 0 -#include - -#else -// The libyuv implementation on ARM is slightly different than on x86 -// Our implementation matches the ARM version, so accept errors of 1 -#define MAXE 1 - -#endif - -#include - -#include "libyuv.h" -#include "selfdrive/camerad/transforms/rgb_to_yuv.h" -#include "selfdrive/common/clutil.h" - -static inline double millis_since_boot() { - struct timespec t; - clock_gettime(CLOCK_BOOTTIME, &t); - return t.tv_sec * 1000.0 + t.tv_nsec * 1e-6; -} - -void cl_init(cl_device_id &device_id, cl_context &context) { - device_id = cl_get_device_id(CL_DEVICE_TYPE_DEFAULT); - context = CL_CHECK_ERR(clCreateContext(NULL, 1, &device_id, NULL, NULL, &err)); -} - - -bool compare_results(uint8_t *a, uint8_t *b, int len, int stride, int width, int height, uint8_t *rgb) { - int min_diff = 0., max_diff = 0., max_e = 0.; - int e1 = 0, e0 = 0; - int e0y = 0, e0u = 0, e0v = 0, e1y = 0, e1u = 0, e1v = 0; - int max_e_i = 0; - for (int i = 0;i < len;i++) { - int e = ((int)a[i]) - ((int)b[i]); - if(e < min_diff) { - min_diff = e; - } - if(e > max_diff) { - max_diff = e; - } - int e_abs = std::abs(e); - if(e_abs > max_e) { - max_e = e_abs; - max_e_i = i; - } - if(e_abs < 1) { - e0++; - if(i < stride * height) - e0y++; - else if(i < stride * height + stride * height / 4) - e0u++; - else - e0v++; - } else { - e1++; - if(i < stride * height) - e1y++; - else if(i < stride * height + stride * height / 4) - e1u++; - else - e1v++; - } - } - //printf("max diff : %d, min diff : %d, e < 1: %d, e >= 1: %d\n", max_diff, min_diff, e0, e1); - //printf("Y: e < 1: %d, e >= 1: %d, U: e < 1: %d, e >= 1: %d, V: e < 1: %d, e >= 1: %d\n", e0y, e1y, e0u, e1u, e0v, e1v); - if(max_e <= MAXE) { - return true; - } - int row = max_e_i / stride; - if(row < height) { - printf("max error is Y: %d = (libyuv: %u - cl: %u), row: %d, col: %d\n", max_e, a[max_e_i], b[max_e_i], row, max_e_i % stride); - } else if(row >= height && row < (height + height / 4)) { - printf("max error is U: %d = %u - %u, row: %d, col: %d\n", max_e, a[max_e_i], b[max_e_i], (row - height) / 2, max_e_i % stride / 2); - } else { - printf("max error is V: %d = %u - %u, row: %d, col: %d\n", max_e, a[max_e_i], b[max_e_i], (row - height - height / 4) / 2, max_e_i % stride / 2); - } - return false; -} - -int main(int argc, char** argv) { - srand(1337); - - cl_device_id device_id; - cl_context context; - cl_init(device_id, context) ; - - int err; - const cl_queue_properties props[] = {0}; //CL_QUEUE_PRIORITY_KHR, CL_QUEUE_PRIORITY_HIGH_KHR, 0}; - cl_command_queue q = clCreateCommandQueueWithProperties(context, device_id, props, &err); - if(err != 0) { - std::cout << "clCreateCommandQueueWithProperties error: " << err << std::endl; - } - - int width = 1164; - int height = 874; - - int opt = 0; - while ((opt = getopt(argc, argv, "f")) != -1) - { - switch (opt) - { - case 'f': - std::cout << "Using front camera dimensions" << std::endl; - int width = 1152; - int height = 846; - } - } - - std::cout << "Width: " << width << " Height: " << height << std::endl; - uint8_t *rgb_frame = new uint8_t[width * height * 3]; - - - RGBToYUVState rgb_to_yuv_state; - rgb_to_yuv_init(&rgb_to_yuv_state, context, device_id, width, height, width * 3); - - int frame_yuv_buf_size = width * height * 3 / 2; - cl_mem yuv_cl = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, frame_yuv_buf_size, (void*)NULL, &err)); - uint8_t *frame_yuv_buf = new uint8_t[frame_yuv_buf_size]; - uint8_t *frame_yuv_ptr_y = frame_yuv_buf; - uint8_t *frame_yuv_ptr_u = frame_yuv_buf + (width * height); - uint8_t *frame_yuv_ptr_v = frame_yuv_ptr_u + ((width/2) * (height/2)); - - cl_mem rgb_cl = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, width * height * 3, (void*)NULL, &err)); - int mismatched = 0; - int counter = 0; - srand (time(NULL)); - - for (int i = 0; i < 100; i++) { - for (int i = 0; i < width * height * 3; i++) { - rgb_frame[i] = (uint8_t)rand(); - } - - double t1 = millis_since_boot(); - libyuv::RGB24ToI420((uint8_t*)rgb_frame, width * 3, - frame_yuv_ptr_y, width, - frame_yuv_ptr_u, width/2, - frame_yuv_ptr_v, width/2, - width, height); - double t2 = millis_since_boot(); - //printf("Libyuv: rgb to yuv: %.2fms\n", t2-t1); - - clEnqueueWriteBuffer(q, rgb_cl, CL_TRUE, 0, width * height * 3, (void *)rgb_frame, 0, NULL, NULL); - t1 = millis_since_boot(); - rgb_to_yuv_queue(&rgb_to_yuv_state, q, rgb_cl, yuv_cl); - t2 = millis_since_boot(); - - //printf("OpenCL: rgb to yuv: %.2fms\n", t2-t1); - uint8_t *yyy = (uint8_t *)clEnqueueMapBuffer(q, yuv_cl, CL_TRUE, - CL_MAP_READ, 0, frame_yuv_buf_size, - 0, NULL, NULL, &err); - if(!compare_results(frame_yuv_ptr_y, yyy, frame_yuv_buf_size, width, width, height, (uint8_t*)rgb_frame)) - mismatched++; - clEnqueueUnmapMemObject(q, yuv_cl, yyy, 0, NULL, NULL); - - // std::this_thread::sleep_for(std::chrono::milliseconds(20)); - if(counter++ % 100 == 0) - printf("Matched: %d, Mismatched: %d\n", counter - mismatched, mismatched); - - } - printf("Matched: %d, Mismatched: %d\n", counter - mismatched, mismatched); - - delete[] frame_yuv_buf; - rgb_to_yuv_destroy(&rgb_to_yuv_state); - clReleaseContext(context); - delete[] rgb_frame; - - if (mismatched == 0) - return 0; - else - return -1; -} diff --git a/selfdrive/car/CARS_template.md b/selfdrive/car/CARS_template.md new file mode 100644 index 0000000000..2fce0f9036 --- /dev/null +++ b/selfdrive/car/CARS_template.md @@ -0,0 +1,66 @@ +{% set footnote_tag = '[{}](#footnotes)' -%} +{% set star_icon = '[![star](assets/icon-star-{}.svg)](##)' -%} + + + +# Supported Cars + +A supported vehicle is one that just works when you install a comma three. All supported cars provide a better experience than any stock system. + +# {{all_car_info | length}} Supported Cars + +|{{Column | map(attribute='value') | join('|')}}| +|---|---|---|{% for _ in range((Column | length) - 3) %}{{':---:|'}}{% endfor +%} +{% for car_info in all_car_info %} +|{% for column in Column %}{{car_info.get_column(column, star_icon, footnote_tag)}}|{% endfor %} + +{% endfor %} + + +{% for footnote in footnotes %} +{{loop.index}}{{footnote}}
+{% endfor %} + +## Community Maintained Cars +Although they're not upstream, the community has openpilot running on other makes and models. See the 'Community Supported Models' section of each make [on our wiki](https://wiki.comma.ai/). + +# Don't see your car here? + +**openpilot can support many more cars than it currently does.** There are a few reasons your car may not be supported. +If your car doesn't fit into any of the incompatibility criteria here, then there's a good chance it can be supported! We're adding support for new cars all the time. **We don't have a roadmap for car support**, and in fact, most car support comes from users like you! + +### Which cars are able to be supported? + +openpilot uses the existing steering, gas, and brake interfaces in your car. If your car lacks any one of these interfaces, openpilot will not be able to control the car. If your car has [ACC](https://en.wikipedia.org/wiki/Adaptive_cruise_control) and any form of [LKAS](https://en.wikipedia.org/wiki/Automated_Lane_Keeping_Systems)/[LCA](https://en.wikipedia.org/wiki/Lane_centering), then it almost certainly has these interfaces. These features generally started shipping on cars around 2016. Note that manufacturers will often make their own [marketing terms](https://en.wikipedia.org/wiki/Adaptive_cruise_control#Vehicle_models_supporting_adaptive_cruise_control) for these features, such as Hyundai's "Smart Cruise Control" branding of Adaptive Cruise Control. + +If your car has the following packages or features, then it's a good candidate for support. + +| Make | Required Package/Features | +| ---- | ------------------------- | +| Acura | Any car with AcuraWatch Plus will work. AcuraWatch Plus comes standard on many newer models. | +| Honda | Any car with Honda Sensing will work. Honda Sensing comes standard on many newer models. | +| Subaru | Any car with EyeSight will work. EyeSight comes standard on many newer models. | +| Nissan | Any car with ProPILOT will likely work. | +| Toyota & Lexus | Any car that has Toyota/Lexus Safety Sense with "Lane Departure Alert with Steering Assist (LDA w/SA)" and/or "Lane Tracing Assist (LTA)" will work. Note that LDA without Steering Assist will not work. These features come standard on most newer models. | +| Hyundai, Kia, & Genesis | Any car with Smart Cruise Control (SCC) and Lane Following Assist (LFA) or Lane Keeping Assist (LKAS) will work. LKAS/LFA comes standard on most newer models. Any form of SCC will work, such as NSCC. | +| Chrysler, Jeep, & Ram | Any car with LaneSense and Adaptive Cruise Control will likely work. These come standard on many newer models. | + +### FlexRay + +All the cars that openpilot supports use a [CAN bus](https://en.wikipedia.org/wiki/CAN_bus) for communication between all the car's computers, however a CAN bus isn't the only way that the cars in your computer can communicate. Most, if not all, vehicles from the following manufacturers use [FlexRay](https://en.wikipedia.org/wiki/FlexRay) instead of a CAN bus: **BMW, Mercedes, Audi, Land Rover, and some Volvo**. These cars may one day be supported, but we have no immediate plans to support FlexRay. + +### Toyota Security + +openpilot does not yet support these Toyota models due to a new message authentication method. +[Vote](https://comma.ai/shop/products/vote) if you'd like to see openpilot support on these models. + +* Toyota RAV4 Prime 2021+ +* Toyota Sienna 2021+ +* Toyota Venza 2021+ +* Toyota Sequoia 2023+ +* Toyota Tundra 2022+ +* Toyota Corolla Cross 2022+ (only US model) +* Lexus NX 2022+ +* Toyota bZ4x 2023+ +* Subaru Solterra 2023+ + diff --git a/selfdrive/car/README.MD b/selfdrive/car/README.MD index 244757c136..de4db0ee50 100644 --- a/selfdrive/car/README.MD +++ b/selfdrive/car/README.MD @@ -1,5 +1,5 @@ ## Port structure -##### interace.py +##### interface.py Generic interface to send and receive messages from CAN (controlsd uses this to communicate with car) ##### carcontroller.py Builds CAN messages to send to car diff --git a/selfdrive/car/__init__.py b/selfdrive/car/__init__.py index 408e0d075f..491c551b1b 100644 --- a/selfdrive/car/__init__.py +++ b/selfdrive/car/__init__.py @@ -1,13 +1,39 @@ # functions common among cars +import capnp + from cereal import car from common.numpy_fast import clip +from typing import Dict # kg of standard extra cargo to count for drive, gas, etc... STD_CARGO_KG = 136. +ButtonType = car.CarState.ButtonEvent.Type +EventName = car.CarEvent.EventName + + +def apply_hysteresis(val: float, val_steady: float, hyst_gap: float) -> float: + if val > val_steady + hyst_gap: + val_steady = val - hyst_gap + elif val < val_steady - hyst_gap: + val_steady = val + hyst_gap + return val_steady + + +def create_button_event(cur_but: int, prev_but: int, buttons_dict: Dict[int, capnp.lib.capnp._EnumModule], + unpressed: int = 0) -> capnp.lib.capnp._DynamicStructBuilder: + if cur_but != unpressed: + be = car.CarState.ButtonEvent(pressed=True) + but = cur_but + else: + be = car.CarState.ButtonEvent(pressed=False) + but = prev_but + be.type = buttons_dict.get(but, ButtonType.unknown) + return be + def gen_empty_fingerprint(): - return {i: {} for i in range(0, 4)} + return {i: {} for i in range(0, 8)} # FIXME: hardcoding honda civic 2016 touring params so they can be used to @@ -41,7 +67,7 @@ def scale_tire_stiffness(mass, wheelbase, center_to_front, tire_stiffness_factor return tire_stiffness_front, tire_stiffness_rear -def dbc_dict(pt_dbc, radar_dbc, chassis_dbc=None, body_dbc=None): +def dbc_dict(pt_dbc, radar_dbc, chassis_dbc=None, body_dbc=None) -> Dict[str, str]: return {'pt': pt_dbc, 'radar': radar_dbc, 'chassis': chassis_dbc, 'body': body_dbc} diff --git a/selfdrive/camerad/__init__.py b/selfdrive/car/body/__init__.py similarity index 100% rename from selfdrive/camerad/__init__.py rename to selfdrive/car/body/__init__.py diff --git a/selfdrive/car/body/bodycan.py b/selfdrive/car/body/bodycan.py new file mode 100644 index 0000000000..580e5025ad --- /dev/null +++ b/selfdrive/car/body/bodycan.py @@ -0,0 +1,7 @@ +def create_control(packer, torque_l, torque_r): + values = { + "TORQUE_L": torque_l, + "TORQUE_R": torque_r, + } + + return packer.make_can_msg("TORQUE_CMD", 0, values) diff --git a/selfdrive/car/body/carcontroller.py b/selfdrive/car/body/carcontroller.py new file mode 100644 index 0000000000..0d5d780bd3 --- /dev/null +++ b/selfdrive/car/body/carcontroller.py @@ -0,0 +1,90 @@ +import numpy as np + +from common.realtime import DT_CTRL +from opendbc.can.packer import CANPacker +from selfdrive.car.body import bodycan +from selfdrive.car.body.values import SPEED_FROM_RPM +from selfdrive.controls.lib.pid import PIDController + + +MAX_TORQUE = 500 +MAX_TORQUE_RATE = 50 +MAX_ANGLE_ERROR = np.radians(7) +MAX_POS_INTEGRATOR = 0.2 # meters +MAX_TURN_INTEGRATOR = 0.1 # meters + + +class CarController: + def __init__(self, dbc_name, CP, VM): + self.frame = 0 + self.packer = CANPacker(dbc_name) + + # Speed, balance and turn PIDs + self.speed_pid = PIDController(0.115, k_i=0.23, rate=1/DT_CTRL) + self.balance_pid = PIDController(1300, k_i=0, k_d=280, rate=1/DT_CTRL) + self.turn_pid = PIDController(110, k_i=11.5, rate=1/DT_CTRL) + + self.torque_r_filtered = 0. + self.torque_l_filtered = 0. + + @staticmethod + def deadband_filter(torque, deadband): + if torque > 0: + torque += deadband + else: + torque -= deadband + return torque + + def update(self, CC, CS): + + torque_l = 0 + torque_r = 0 + + llk_valid = len(CC.orientationNED) > 0 and len(CC.angularVelocity) > 0 + if CC.enabled and llk_valid: + # Read these from the joystick + # TODO: this isn't acceleration, okay? + speed_desired = CC.actuators.accel / 5. + speed_diff_desired = -CC.actuators.steer + + speed_measured = SPEED_FROM_RPM * (CS.out.wheelSpeeds.fl + CS.out.wheelSpeeds.fr) / 2. + speed_error = speed_desired - speed_measured + + freeze_integrator = ((speed_error < 0 and self.speed_pid.error_integral <= -MAX_POS_INTEGRATOR) or + (speed_error > 0 and self.speed_pid.error_integral >= MAX_POS_INTEGRATOR)) + angle_setpoint = self.speed_pid.update(speed_error, freeze_integrator=freeze_integrator) + + # Clip angle error, this is enough to get up from stands + angle_error = np.clip((-CC.orientationNED[1]) - angle_setpoint, -MAX_ANGLE_ERROR, MAX_ANGLE_ERROR) + angle_error_rate = np.clip(-CC.angularVelocity[1], -1., 1.) + torque = self.balance_pid.update(angle_error, error_rate=angle_error_rate) + + speed_diff_measured = SPEED_FROM_RPM * (CS.out.wheelSpeeds.fl - CS.out.wheelSpeeds.fr) + turn_error = speed_diff_measured - speed_diff_desired + freeze_integrator = ((turn_error < 0 and self.turn_pid.error_integral <= -MAX_TURN_INTEGRATOR) or + (turn_error > 0 and self.turn_pid.error_integral >= MAX_TURN_INTEGRATOR)) + torque_diff = self.turn_pid.update(turn_error, freeze_integrator=freeze_integrator) + + # Combine 2 PIDs outputs + torque_r = torque + torque_diff + torque_l = torque - torque_diff + + # Torque rate limits + self.torque_r_filtered = np.clip(self.deadband_filter(torque_r, 10), + self.torque_r_filtered - MAX_TORQUE_RATE, + self.torque_r_filtered + MAX_TORQUE_RATE) + self.torque_l_filtered = np.clip(self.deadband_filter(torque_l, 10), + self.torque_l_filtered - MAX_TORQUE_RATE, + self.torque_l_filtered + MAX_TORQUE_RATE) + torque_r = int(np.clip(self.torque_r_filtered, -MAX_TORQUE, MAX_TORQUE)) + torque_l = int(np.clip(self.torque_l_filtered, -MAX_TORQUE, MAX_TORQUE)) + + can_sends = [] + can_sends.append(bodycan.create_control(self.packer, torque_l, torque_r)) + + new_actuators = CC.actuators.copy() + new_actuators.accel = torque_l + new_actuators.steer = torque_r + + self.frame += 1 + return new_actuators, can_sends diff --git a/selfdrive/car/body/carstate.py b/selfdrive/car/body/carstate.py new file mode 100644 index 0000000000..dbbd85950d --- /dev/null +++ b/selfdrive/car/body/carstate.py @@ -0,0 +1,60 @@ +from cereal import car +from opendbc.can.parser import CANParser +from selfdrive.car.interfaces import CarStateBase +from selfdrive.car.body.values import DBC + +STARTUP_TICKS = 100 + +class CarState(CarStateBase): + def update(self, cp): + ret = car.CarState.new_message() + + ret.wheelSpeeds.fl = cp.vl['MOTORS_DATA']['SPEED_L'] + ret.wheelSpeeds.fr = cp.vl['MOTORS_DATA']['SPEED_R'] + + ret.vEgoRaw = ((ret.wheelSpeeds.fl + ret.wheelSpeeds.fr) / 2.) * self.CP.wheelSpeedFactor + + ret.vEgo, ret.aEgo = self.update_speed_kf(ret.vEgoRaw) + ret.standstill = False + + ret.steerFaultPermanent = any([cp.vl['VAR_VALUES']['MOTOR_ERR_L'], cp.vl['VAR_VALUES']['MOTOR_ERR_R'], + cp.vl['VAR_VALUES']['FAULT']]) + + ret.charging = cp.vl["BODY_DATA"]["CHARGER_CONNECTED"] == 1 + ret.fuelGauge = cp.vl["BODY_DATA"]["BATT_PERCENTAGE"] / 100 + + # irrelevant for non-car + ret.gearShifter = car.CarState.GearShifter.drive + ret.cruiseState.enabled = True + ret.cruiseState.available = True + + return ret + + @staticmethod + def get_can_parser(CP): + signals = [ + # sig_name, sig_address + ("SPEED_L", "MOTORS_DATA"), + ("SPEED_R", "MOTORS_DATA"), + ("ELEC_ANGLE_L", "MOTORS_DATA"), + ("ELEC_ANGLE_R", "MOTORS_DATA"), + ("COUNTER", "MOTORS_DATA"), + ("CHECKSUM", "MOTORS_DATA"), + ("IGNITION", "VAR_VALUES"), + ("ENABLE_MOTORS", "VAR_VALUES"), + ("FAULT", "VAR_VALUES"), + ("MOTOR_ERR_L", "VAR_VALUES"), + ("MOTOR_ERR_R", "VAR_VALUES"), + ("MCU_TEMP", "BODY_DATA"), + ("BATT_VOLTAGE", "BODY_DATA"), + ("BATT_PERCENTAGE", "BODY_DATA"), + ("CHARGER_CONNECTED", "BODY_DATA"), + ] + + checks = [ + ("MOTORS_DATA", 100), + ("VAR_VALUES", 10), + ("BODY_DATA", 1), + ] + + return CANParser(DBC[CP.carFingerprint]["pt"], signals, checks, 0) diff --git a/selfdrive/car/body/interface.py b/selfdrive/car/body/interface.py new file mode 100644 index 0000000000..bc5b36e2ee --- /dev/null +++ b/selfdrive/car/body/interface.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +import math +from cereal import car +from common.realtime import DT_CTRL +from selfdrive.car import get_safety_config +from selfdrive.car.interfaces import CarInterfaceBase +from selfdrive.car.body.values import SPEED_FROM_RPM + +class CarInterface(CarInterfaceBase): + @staticmethod + def _get_params(ret, candidate, fingerprint, car_fw, experimental_long): + ret.notCar = True + ret.carName = "body" + ret.safetyConfigs = [get_safety_config(car.CarParams.SafetyModel.body)] + + ret.minSteerSpeed = -math.inf + ret.maxLateralAccel = math.inf # TODO: set to a reasonable value + ret.steerRatio = 0.5 + ret.steerLimitTimer = 1.0 + ret.steerActuatorDelay = 0. + + ret.mass = 9 + ret.wheelbase = 0.406 + ret.wheelSpeedFactor = SPEED_FROM_RPM + ret.centerToFront = ret.wheelbase * 0.44 + + ret.radarOffCan = True + ret.openpilotLongitudinalControl = True + ret.steerControlType = car.CarParams.SteerControlType.angle + + return ret + + def _update(self, c): + ret = self.CS.update(self.cp) + + # wait for everything to init first + if self.frame > int(5. / DT_CTRL): + # body always wants to enable + ret.init('events', 1) + ret.events[0].name = car.CarEvent.EventName.pcmEnable + ret.events[0].enable = True + self.frame += 1 + + return ret + + def apply(self, c): + return self.CC.update(c, self.CS) diff --git a/selfdrive/car/body/radar_interface.py b/selfdrive/car/body/radar_interface.py new file mode 100644 index 0000000000..b2f7651136 --- /dev/null +++ b/selfdrive/car/body/radar_interface.py @@ -0,0 +1,5 @@ +#!/usr/bin/env python3 +from selfdrive.car.interfaces import RadarInterfaceBase + +class RadarInterface(RadarInterfaceBase): + pass diff --git a/selfdrive/car/body/values.py b/selfdrive/car/body/values.py new file mode 100644 index 0000000000..548039bc70 --- /dev/null +++ b/selfdrive/car/body/values.py @@ -0,0 +1,62 @@ +from typing import Dict + +from cereal import car +from selfdrive.car import dbc_dict +from selfdrive.car.docs_definitions import CarInfo +from selfdrive.car.fw_query_definitions import FwQueryConfig, Request, StdQueries + +Ecu = car.CarParams.Ecu + +SPEED_FROM_RPM = 0.008587 + + +class CarControllerParams: + ANGLE_DELTA_BP = [0., 5., 15.] + ANGLE_DELTA_V = [5., .8, .15] # windup limit + ANGLE_DELTA_VU = [5., 3.5, 0.4] # unwind limit + LKAS_MAX_TORQUE = 1 # A value of 1 is easy to overpower + STEER_THRESHOLD = 1.0 + + +class CAR: + BODY = "COMMA BODY" + + +CAR_INFO: Dict[str, CarInfo] = { + CAR.BODY: CarInfo("comma body", package="All"), +} + +FINGERPRINTS = { + CAR.BODY: [{ + 513: 8, 516: 8, 514: 3, 515: 4, + }], +} + +FW_QUERY_CONFIG = FwQueryConfig( + requests=[ + Request( + [StdQueries.TESTER_PRESENT_REQUEST, StdQueries.UDS_VERSION_REQUEST], + [StdQueries.TESTER_PRESENT_RESPONSE, StdQueries.UDS_VERSION_RESPONSE], + bus=0, + ), + ], +) + +FW_VERSIONS = { + CAR.BODY: { + (Ecu.engine, 0x720, None): [ + b'0.0.01', + b'02/27/2022', + b'0.3.00a', + ], + # git hash of the firmware used + (Ecu.debug, 0x721, None): [ + b'166bd860', + b'dc780f85', + ], + }, +} + +DBC = { + CAR.BODY: dbc_dict('comma_body', None), +} diff --git a/selfdrive/car/car_helpers.py b/selfdrive/car/car_helpers.py index 90bfdd8a93..61e7a3d55d 100644 --- a/selfdrive/car/car_helpers.py +++ b/selfdrive/car/car_helpers.py @@ -1,15 +1,18 @@ import os +from typing import Dict, List + +from cereal import car from common.params import Params from common.basedir import BASEDIR -from selfdrive.version import is_comma_remote, is_tested_branch +from system.version import is_comma_remote, is_tested_branch +from selfdrive.car.interfaces import get_interface_attr from selfdrive.car.fingerprints import eliminate_incompatible_cars, all_legacy_fingerprint_cars -from selfdrive.car.vin import get_vin, VIN_UNKNOWN -from selfdrive.car.fw_versions import get_fw_versions, match_fw_to_car -from selfdrive.swaglog import cloudlog +from selfdrive.car.vin import get_vin, is_valid_vin, VIN_UNKNOWN +from selfdrive.car.fw_versions import get_fw_versions_ordered, match_fw_to_car, get_present_ecus +from system.swaglog import cloudlog import cereal.messaging as messaging from selfdrive.car import gen_empty_fingerprint -from cereal import car EventName = car.CarEvent.EventName @@ -57,19 +60,12 @@ def load_interfaces(brand_names): return ret -def _get_interface_names(): - # read all the folders in selfdrive/car and return a dict where: - # - keys are all the car names that which we have an interface for - # - values are lists of spefic car models for a given car +def _get_interface_names() -> Dict[str, List[str]]: + # returns a dict of brand name and its respective models brand_names = {} - for car_folder in [x[0] for x in os.walk(BASEDIR + '/selfdrive/car')]: - try: - brand_name = car_folder.split('/')[-1] - model_names = __import__(f'selfdrive.car.{brand_name}.values', fromlist=['CAR']).CAR - model_names = [getattr(model_names, c) for c in model_names.__dict__.keys() if not c.startswith("__")] - brand_names[brand_name] = model_names - except (ImportError, OSError): - pass + for brand_name, model_names in get_interface_attr("CAR").items(): + model_names = [getattr(model_names, c) for c in model_names.__dict__.keys() if not c.startswith("__")] + brand_names[brand_name] = model_names return brand_names @@ -80,12 +76,13 @@ interfaces = load_interfaces(interface_names) # **** for use live only **** -def fingerprint(logcan, sendcan): +def fingerprint(logcan, sendcan, num_pandas): fixed_fingerprint = os.environ.get('FINGERPRINT', "") skip_fw_query = os.environ.get('SKIP_FW_QUERY', False) + ecu_rx_addrs = set() - if not fixed_fingerprint and not skip_fw_query: - # Vin query only reliably works thorugh OBDII + if not skip_fw_query: + # Vin query only reliably works through OBDII bus = 1 cached_params = Params().get("CarParamsCache") @@ -96,28 +93,38 @@ def fingerprint(logcan, sendcan): if cached_params is not None and len(cached_params.carFw) > 0 and cached_params.carVin is not VIN_UNKNOWN: cloudlog.warning("Using cached CarParams") - vin = cached_params.carVin + vin, vin_rx_addr = cached_params.carVin, 0 car_fw = list(cached_params.carFw) + cached = True else: cloudlog.warning("Getting VIN & FW versions") - _, vin = get_vin(logcan, sendcan, bus) - car_fw = get_fw_versions(logcan, sendcan, bus) + vin_rx_addr, vin = get_vin(logcan, sendcan, bus) + ecu_rx_addrs = get_present_ecus(logcan, sendcan) + car_fw = get_fw_versions_ordered(logcan, sendcan, ecu_rx_addrs, num_pandas=num_pandas) + cached = False exact_fw_match, fw_candidates = match_fw_to_car(car_fw) else: - vin = VIN_UNKNOWN + vin, vin_rx_addr = VIN_UNKNOWN, 0 exact_fw_match, fw_candidates, car_fw = True, set(), [] + cached = False + if not is_valid_vin(vin): + cloudlog.event("Malformed VIN", vin=vin, error=True) + vin = VIN_UNKNOWN cloudlog.warning("VIN %s", vin) Params().put("CarVin", vin) finger = gen_empty_fingerprint() candidate_cars = {i: all_legacy_fingerprint_cars() for i in [0, 1]} # attempt fingerprint on both bus 0 and 1 frame = 0 - frame_fingerprint = 10 # 0.1s + frame_fingerprint = 100 # 1s car_fingerprint = None done = False + # drain CAN socket so we always get the latest messages + messaging.drain_sock_raw(logcan) + while not done: a = get_one_can(logcan) @@ -161,23 +168,25 @@ def fingerprint(logcan, sendcan): car_fingerprint = fixed_fingerprint source = car.CarParams.FingerprintSource.fixed - cloudlog.event("fingerprinted", car_fingerprint=car_fingerprint, - source=source, fuzzy=not exact_match, fw_count=len(car_fw)) + cloudlog.event("fingerprinted", car_fingerprint=car_fingerprint, source=source, fuzzy=not exact_match, cached=cached, + fw_count=len(car_fw), ecu_responses=list(ecu_rx_addrs), vin_rx_addr=vin_rx_addr, error=True) return car_fingerprint, finger, vin, car_fw, source, exact_match -def get_car(logcan, sendcan): - candidate, fingerprints, vin, car_fw, source, exact_match = fingerprint(logcan, sendcan) +def get_car(logcan, sendcan, num_pandas=1): + candidate, fingerprints, vin, car_fw, source, exact_match = fingerprint(logcan, sendcan, num_pandas) if candidate is None: cloudlog.warning("car doesn't match any fingerprints: %r", fingerprints) candidate = "mock" + experimental_long = Params().get_bool("ExperimentalLongitudinalEnabled") + CarInterface, CarController, CarState = interfaces[candidate] - car_params = CarInterface.get_params(candidate, fingerprints, car_fw) - car_params.carVin = vin - car_params.carFw = car_fw - car_params.fingerprintSource = source - car_params.fuzzyFingerprint = not exact_match + CP = CarInterface.get_params(candidate, fingerprints, car_fw, experimental_long) + CP.carVin = vin + CP.carFw = car_fw + CP.fingerprintSource = source + CP.fuzzyFingerprint = not exact_match - return CarInterface(car_params, CarController, CarState), car_params + return CarInterface(CP, CarController, CarState), CP diff --git a/selfdrive/car/chrysler/carcontroller.py b/selfdrive/car/chrysler/carcontroller.py index d491ccd4b9..879da88123 100644 --- a/selfdrive/car/chrysler/carcontroller.py +++ b/selfdrive/car/chrysler/carcontroller.py @@ -1,73 +1,82 @@ -from cereal import car -from selfdrive.car import apply_toyota_steer_torque_limits -from selfdrive.car.chrysler.chryslercan import create_lkas_hud, create_lkas_command, \ - create_wheel_buttons -from selfdrive.car.chrysler.values import CAR, CarControllerParams from opendbc.can.packer import CANPacker +from common.realtime import DT_CTRL +from selfdrive.car import apply_toyota_steer_torque_limits +from selfdrive.car.chrysler.chryslercan import create_lkas_hud, create_lkas_command, create_cruise_buttons +from selfdrive.car.chrysler.values import RAM_CARS, CarControllerParams, ChryslerFlags + -class CarController(): +class CarController: def __init__(self, dbc_name, CP, VM): + self.CP = CP self.apply_steer_last = 0 - self.ccframe = 0 - self.prev_frame = -1 + self.frame = 0 + self.hud_count = 0 - self.car_fingerprint = CP.carFingerprint - self.gone_fast_yet = False - self.steer_rate_limited = False + self.last_lkas_falling_edge = 0 + self.lkas_control_bit_prev = False + self.last_button_frame = 0 self.packer = CANPacker(dbc_name) + self.params = CarControllerParams(CP) - def update(self, enabled, CS, actuators, pcm_cancel_cmd, hud_alert): - # this seems needed to avoid steering faults and to force the sync with the EPS counter - frame = CS.lkas_counter - if self.prev_frame == frame: - return car.CarControl.Actuators.new_message(), [] - - # steer torque - new_steer = int(round(actuators.steer * CarControllerParams.STEER_MAX)) - apply_steer = apply_toyota_steer_torque_limits(new_steer, self.apply_steer_last, - CS.out.steeringTorqueEps, CarControllerParams) - self.steer_rate_limited = new_steer != apply_steer + def update(self, CC, CS): + can_sends = [] - moving_fast = CS.out.vEgo > CS.CP.minSteerSpeed # for status message - if CS.out.vEgo > (CS.CP.minSteerSpeed - 0.5): # for command high bit - self.gone_fast_yet = True - elif self.car_fingerprint in (CAR.PACIFICA_2019_HYBRID, CAR.PACIFICA_2020, CAR.JEEP_CHEROKEE_2019): - if CS.out.vEgo < (CS.CP.minSteerSpeed - 3.0): - self.gone_fast_yet = False # < 14.5m/s stock turns off this bit, but fine down to 13.5 - lkas_active = moving_fast and enabled + lkas_active = CC.latActive and self.lkas_control_bit_prev - if not lkas_active: - apply_steer = 0 + # cruise buttons + if (self.frame - self.last_button_frame)*DT_CTRL > 0.05: + das_bus = 2 if self.CP.carFingerprint in RAM_CARS else 0 - self.apply_steer_last = apply_steer + # ACC cancellation + if CC.cruiseControl.cancel: + self.last_button_frame = self.frame + can_sends.append(create_cruise_buttons(self.packer, CS.button_counter + 1, das_bus, cancel=True)) - can_sends = [] + # ACC resume from standstill + elif CC.cruiseControl.resume: + self.last_button_frame = self.frame + can_sends.append(create_cruise_buttons(self.packer, CS.button_counter + 1, das_bus, resume=True)) - #*** control msgs *** - - if pcm_cancel_cmd: - # TODO: would be better to start from frame_2b3 - new_msg = create_wheel_buttons(self.packer, self.ccframe, cancel=True) - can_sends.append(new_msg) - - # LKAS_HEARTBIT is forwarded by Panda so no need to send it here. - # frame is 100Hz (0.01s period) - if (self.ccframe % 25 == 0): # 0.25s period - if (CS.lkas_car_model != -1): - new_msg = create_lkas_hud( - self.packer, CS.out.gearShifter, lkas_active, hud_alert, - self.hud_count, CS.lkas_car_model) - can_sends.append(new_msg) + # HUD alerts + if self.frame % 25 == 0: + if CS.lkas_car_model != -1: + can_sends.append(create_lkas_hud(self.packer, self.CP, lkas_active, CC.hudControl.visualAlert, self.hud_count, CS.lkas_car_model, CS.auto_high_beam)) self.hud_count += 1 - new_msg = create_lkas_command(self.packer, int(apply_steer), self.gone_fast_yet, frame) - can_sends.append(new_msg) + # steering + if self.frame % 2 == 0: + + # TODO: can we make this more sane? why is it different for all the cars? + lkas_control_bit = self.lkas_control_bit_prev + if CS.out.vEgo > self.CP.minSteerSpeed: + lkas_control_bit = True + elif self.CP.flags & ChryslerFlags.HIGHER_MIN_STEERING_SPEED: + if CS.out.vEgo < (self.CP.minSteerSpeed - 3.0): + lkas_control_bit = False + elif self.CP.carFingerprint in RAM_CARS: + if CS.out.vEgo < (self.CP.minSteerSpeed - 0.5): + lkas_control_bit = False + + # EPS faults if LKAS re-enables too quickly + lkas_control_bit = lkas_control_bit and (self.frame - self.last_lkas_falling_edge > 200) + + if not lkas_control_bit and self.lkas_control_bit_prev: + self.last_lkas_falling_edge = self.frame + self.lkas_control_bit_prev = lkas_control_bit + + # steer torque + new_steer = int(round(CC.actuators.steer * self.params.STEER_MAX)) + apply_steer = apply_toyota_steer_torque_limits(new_steer, self.apply_steer_last, CS.out.steeringTorqueEps, self.params) + if not lkas_active or not lkas_control_bit: + apply_steer = 0 + self.apply_steer_last = apply_steer + + can_sends.append(create_lkas_command(self.packer, self.CP, int(apply_steer), lkas_control_bit)) - self.ccframe += 1 - self.prev_frame = frame + self.frame += 1 - new_actuators = actuators.copy() - new_actuators.steer = apply_steer / CarControllerParams.STEER_MAX + new_actuators = CC.actuators.copy() + new_actuators.steer = self.apply_steer_last / self.params.STEER_MAX return new_actuators, can_sends diff --git a/selfdrive/car/chrysler/carstate.py b/selfdrive/car/chrysler/carstate.py index 30a0bf6a3a..0f0d30782a 100644 --- a/selfdrive/car/chrysler/carstate.py +++ b/selfdrive/car/chrysler/carstate.py @@ -1,147 +1,205 @@ from cereal import car +from common.conversions import Conversions as CV from opendbc.can.parser import CANParser from opendbc.can.can_define import CANDefine -from selfdrive.config import Conversions as CV from selfdrive.car.interfaces import CarStateBase -from selfdrive.car.chrysler.values import DBC, STEER_THRESHOLD +from selfdrive.car.chrysler.values import DBC, STEER_THRESHOLD, RAM_CARS class CarState(CarStateBase): def __init__(self, CP): super().__init__(CP) + self.CP = CP can_define = CANDefine(DBC[CP.carFingerprint]["pt"]) - self.shifter_values = can_define.dv["GEAR"]["PRNDL"] + + self.auto_high_beam = 0 + self.button_counter = 0 + self.lkas_car_model = -1 + + if CP.carFingerprint in RAM_CARS: + self.shifter_values = can_define.dv["Transmission_Status"]["Gear_State"] + else: + self.shifter_values = can_define.dv["GEAR"]["PRNDL"] def update(self, cp, cp_cam): ret = car.CarState.new_message() - self.frame = int(cp.vl["EPS_STATUS"]["COUNTER"]) + # lock info + ret.doorOpen = any([cp.vl["BCM_1"]["DOOR_OPEN_FL"], + cp.vl["BCM_1"]["DOOR_OPEN_FR"], + cp.vl["BCM_1"]["DOOR_OPEN_RL"], + cp.vl["BCM_1"]["DOOR_OPEN_RR"]]) + ret.seatbeltUnlatched = cp.vl["ORC_1"]["SEATBELT_DRIVER_UNLATCHED"] == 1 - ret.doorOpen = any([cp.vl["DOORS"]["DOOR_OPEN_FL"], - cp.vl["DOORS"]["DOOR_OPEN_FR"], - cp.vl["DOORS"]["DOOR_OPEN_RL"], - cp.vl["DOORS"]["DOOR_OPEN_RR"]]) - ret.seatbeltUnlatched = cp.vl["SEATBELT_STATUS"]["SEATBELT_DRIVER_UNLATCHED"] == 1 - - ret.brakePressed = cp.vl["BRAKE_2"]["BRAKE_PRESSED_2"] == 5 # human-only + # brake pedal ret.brake = 0 - ret.gas = cp.vl["ACCEL_GAS_134"]["ACCEL_134"] - ret.gasPressed = ret.gas > 1e-5 + ret.brakePressed = cp.vl["ESP_1"]['Brake_Pedal_State'] == 1 # Physical brake pedal switch - ret.espDisabled = (cp.vl["TRACTION_BUTTON"]["TRACTION_OFF"] == 1) + # gas pedal + ret.gas = cp.vl["ECM_5"]["Accelerator_Position"] + ret.gasPressed = ret.gas > 1e-5 + # car speed + if self.CP.carFingerprint in RAM_CARS: + ret.vEgoRaw = cp.vl["ESP_8"]["Vehicle_Speed"] * CV.KPH_TO_MS + ret.gearShifter = self.parse_gear_shifter(self.shifter_values.get(cp.vl["Transmission_Status"]["Gear_State"], None)) + else: + ret.vEgoRaw = (cp.vl["SPEED_1"]["SPEED_LEFT"] + cp.vl["SPEED_1"]["SPEED_RIGHT"]) / 2. + ret.gearShifter = self.parse_gear_shifter(self.shifter_values.get(cp.vl["GEAR"]["PRNDL"], None)) + ret.vEgo, ret.aEgo = self.update_speed_kf(ret.vEgoRaw) + ret.standstill = not ret.vEgoRaw > 0.001 ret.wheelSpeeds = self.get_wheel_speeds( - cp.vl["WHEEL_SPEEDS"]["WHEEL_SPEED_FL"], - cp.vl["WHEEL_SPEEDS"]["WHEEL_SPEED_FR"], - cp.vl["WHEEL_SPEEDS"]["WHEEL_SPEED_RL"], - cp.vl["WHEEL_SPEEDS"]["WHEEL_SPEED_RR"], + cp.vl["ESP_6"]["WHEEL_SPEED_FL"], + cp.vl["ESP_6"]["WHEEL_SPEED_FR"], + cp.vl["ESP_6"]["WHEEL_SPEED_RL"], + cp.vl["ESP_6"]["WHEEL_SPEED_RR"], unit=1, ) - ret.vEgoRaw = (cp.vl["SPEED_1"]["SPEED_LEFT"] + cp.vl["SPEED_1"]["SPEED_RIGHT"]) / 2. - ret.vEgo, ret.aEgo = self.update_speed_kf(ret.vEgoRaw) - ret.standstill = not ret.vEgoRaw > 0.001 - ret.leftBlinker = cp.vl["STEERING_LEVERS"]["TURN_SIGNALS"] == 1 - ret.rightBlinker = cp.vl["STEERING_LEVERS"]["TURN_SIGNALS"] == 2 - ret.steeringAngleDeg = cp.vl["STEERING"]["STEER_ANGLE"] + # button presses + ret.leftBlinker, ret.rightBlinker = self.update_blinker_from_stalk(200, cp.vl["STEERING_LEVERS"]["TURN_SIGNALS"] == 1, + cp.vl["STEERING_LEVERS"]["TURN_SIGNALS"] == 2) + ret.genericToggle = cp.vl["STEERING_LEVERS"]["HIGH_BEAM_PRESSED"] == 1 + + # steering wheel + ret.steeringAngleDeg = cp.vl["STEERING"]["STEERING_ANGLE"] + cp.vl["STEERING"]["STEERING_ANGLE_HP"] ret.steeringRateDeg = cp.vl["STEERING"]["STEERING_RATE"] - ret.gearShifter = self.parse_gear_shifter(self.shifter_values.get(cp.vl["GEAR"]["PRNDL"], None)) + ret.steeringTorque = cp.vl["EPS_2"]["COLUMN_TORQUE"] + ret.steeringTorqueEps = cp.vl["EPS_2"]["EPS_TORQUE_MOTOR"] + ret.steeringPressed = abs(ret.steeringTorque) > STEER_THRESHOLD - ret.cruiseState.enabled = cp.vl["ACC_2"]["ACC_STATUS_2"] == 7 # ACC is green. - ret.cruiseState.available = ret.cruiseState.enabled # FIXME: for now same as enabled - ret.cruiseState.speed = cp.vl["DASHBOARD"]["ACC_SPEED_CONFIG_KPH"] * CV.KPH_TO_MS - # CRUISE_STATE is a three bit msg, 0 is off, 1 and 2 are Non-ACC mode, 3 and 4 are ACC mode, find if there are other states too - ret.cruiseState.nonAdaptive = cp.vl["DASHBOARD"]["CRUISE_STATE"] in (1, 2) + # cruise state + cp_cruise = cp_cam if self.CP.carFingerprint in RAM_CARS else cp - ret.steeringTorque = cp.vl["EPS_STATUS"]["TORQUE_DRIVER"] - ret.steeringTorqueEps = cp.vl["EPS_STATUS"]["TORQUE_MOTOR"] - ret.steeringPressed = abs(ret.steeringTorque) > STEER_THRESHOLD - steer_state = cp.vl["EPS_STATUS"]["LKAS_STATE"] - ret.steerError = steer_state == 4 or (steer_state == 0 and ret.vEgo > self.CP.minSteerSpeed) + ret.cruiseState.available = cp_cruise.vl["DAS_3"]["ACC_AVAILABLE"] == 1 + ret.cruiseState.enabled = cp_cruise.vl["DAS_3"]["ACC_ACTIVE"] == 1 + ret.cruiseState.speed = cp_cruise.vl["DAS_4"]["ACC_SET_SPEED_KPH"] * CV.KPH_TO_MS + ret.cruiseState.nonAdaptive = cp_cruise.vl["DAS_4"]["ACC_STATE"] in (1, 2) # 1 NormalCCOn and 2 NormalCCSet + ret.cruiseState.standstill = cp_cruise.vl["DAS_3"]["ACC_STANDSTILL"] == 1 + ret.accFaulted = cp_cruise.vl["DAS_3"]["ACC_FAULTED"] != 0 - ret.genericToggle = bool(cp.vl["STEERING_LEVERS"]["HIGH_BEAM_FLASH"]) + if self.CP.carFingerprint in RAM_CARS: + self.auto_high_beam = cp_cam.vl["DAS_6"]['AUTO_HIGH_BEAM_ON'] # Auto High Beam isn't Located in this message on chrysler or jeep currently located in 729 message + ret.steerFaultTemporary = cp.vl["EPS_3"]["DASM_FAULT"] == 1 + else: + ret.steerFaultPermanent = cp.vl["EPS_2"]["LKAS_STATE"] == 4 + # blindspot sensors if self.CP.enableBsm: - ret.leftBlindspot = cp.vl["BLIND_SPOT_WARNINGS"]["BLIND_SPOT_LEFT"] == 1 - ret.rightBlindspot = cp.vl["BLIND_SPOT_WARNINGS"]["BLIND_SPOT_RIGHT"] == 1 + ret.leftBlindspot = cp.vl["BSM_1"]["LEFT_STATUS"] == 1 + ret.rightBlindspot = cp.vl["BSM_1"]["RIGHT_STATUS"] == 1 - self.lkas_counter = cp_cam.vl["LKAS_COMMAND"]["COUNTER"] - self.lkas_car_model = cp_cam.vl["LKAS_HUD"]["CAR_MODEL"] - self.lkas_status_ok = cp_cam.vl["LKAS_HEARTBIT"]["LKAS_STATUS_OK"] + self.lkas_car_model = cp_cam.vl["DAS_6"]["CAR_MODEL"] + self.button_counter = cp.vl["CRUISE_BUTTONS"]["COUNTER"] return ret + @staticmethod + def get_cruise_signals(): + signals = [ + ("ACC_AVAILABLE", "DAS_3"), + ("ACC_ACTIVE", "DAS_3"), + ("ACC_FAULTED", "DAS_3"), + ("ACC_STANDSTILL", "DAS_3"), + ("COUNTER", "DAS_3"), + ("ACC_SET_SPEED_KPH", "DAS_4"), + ("ACC_STATE", "DAS_4"), + ] + checks = [ + ("DAS_3", 50), + ("DAS_4", 50), + ] + return signals, checks + @staticmethod def get_can_parser(CP): signals = [ # sig_name, sig_address - ("PRNDL", "GEAR"), - ("DOOR_OPEN_FL", "DOORS"), - ("DOOR_OPEN_FR", "DOORS"), - ("DOOR_OPEN_RL", "DOORS"), - ("DOOR_OPEN_RR", "DOORS"), - ("BRAKE_PRESSED_2", "BRAKE_2"), - ("ACCEL_134", "ACCEL_GAS_134"), - ("SPEED_LEFT", "SPEED_1"), - ("SPEED_RIGHT", "SPEED_1"), - ("WHEEL_SPEED_FL", "WHEEL_SPEEDS"), - ("WHEEL_SPEED_RR", "WHEEL_SPEEDS"), - ("WHEEL_SPEED_RL", "WHEEL_SPEEDS"), - ("WHEEL_SPEED_FR", "WHEEL_SPEEDS"), - ("STEER_ANGLE", "STEERING"), + ("DOOR_OPEN_FL", "BCM_1"), + ("DOOR_OPEN_FR", "BCM_1"), + ("DOOR_OPEN_RL", "BCM_1"), + ("DOOR_OPEN_RR", "BCM_1"), + ("Brake_Pedal_State", "ESP_1"), + ("Accelerator_Position", "ECM_5"), + ("WHEEL_SPEED_FL", "ESP_6"), + ("WHEEL_SPEED_RR", "ESP_6"), + ("WHEEL_SPEED_RL", "ESP_6"), + ("WHEEL_SPEED_FR", "ESP_6"), + ("STEERING_ANGLE", "STEERING"), + ("STEERING_ANGLE_HP", "STEERING"), ("STEERING_RATE", "STEERING"), ("TURN_SIGNALS", "STEERING_LEVERS"), - ("ACC_STATUS_2", "ACC_2"), - ("HIGH_BEAM_FLASH", "STEERING_LEVERS"), - ("ACC_SPEED_CONFIG_KPH", "DASHBOARD"), - ("CRUISE_STATE", "DASHBOARD"), - ("TORQUE_DRIVER", "EPS_STATUS"), - ("TORQUE_MOTOR", "EPS_STATUS"), - ("LKAS_STATE", "EPS_STATUS"), - ("COUNTER", "EPS_STATUS",), - ("TRACTION_OFF", "TRACTION_BUTTON"), - ("SEATBELT_DRIVER_UNLATCHED", "SEATBELT_STATUS"), + ("HIGH_BEAM_PRESSED", "STEERING_LEVERS"), + ("SEATBELT_DRIVER_UNLATCHED", "ORC_1"), + ("COUNTER", "EPS_2",), + ("COLUMN_TORQUE", "EPS_2"), + ("EPS_TORQUE_MOTOR", "EPS_2"), + ("LKAS_STATE", "EPS_2"), + ("COUNTER", "CRUISE_BUTTONS"), ] checks = [ # sig_address, frequency - ("BRAKE_2", 50), - ("EPS_STATUS", 100), - ("SPEED_1", 100), - ("WHEEL_SPEEDS", 50), + ("ESP_1", 50), + ("EPS_2", 100), + ("ESP_6", 50), ("STEERING", 100), - ("ACC_2", 50), - ("GEAR", 50), - ("ACCEL_GAS_134", 50), - ("DASHBOARD", 15), + ("ECM_5", 50), + ("CRUISE_BUTTONS", 50), ("STEERING_LEVERS", 10), - ("SEATBELT_STATUS", 2), - ("DOORS", 1), - ("TRACTION_BUTTON", 1), + ("ORC_1", 2), + ("BCM_1", 1), ] if CP.enableBsm: signals += [ - ("BLIND_SPOT_RIGHT", "BLIND_SPOT_WARNINGS"), - ("BLIND_SPOT_LEFT", "BLIND_SPOT_WARNINGS"), + ("RIGHT_STATUS", "BSM_1"), + ("LEFT_STATUS", "BSM_1"), + ] + checks.append(("BSM_1", 2)) + + if CP.carFingerprint in RAM_CARS: + signals += [ + ("DASM_FAULT", "EPS_3"), + ("Vehicle_Speed", "ESP_8"), + ("Gear_State", "Transmission_Status"), + ] + checks += [ + ("ESP_8", 50), + ("EPS_3", 50), + ("Transmission_Status", 50), + ] + else: + signals += [ + ("PRNDL", "GEAR"), + ("SPEED_LEFT", "SPEED_1"), + ("SPEED_RIGHT", "SPEED_1"), ] - checks.append(("BLIND_SPOT_WARNINGS", 2)) + checks += [ + ("GEAR", 50), + ("SPEED_1", 100), + ] + signals += CarState.get_cruise_signals()[0] + checks += CarState.get_cruise_signals()[1] return CANParser(DBC[CP.carFingerprint]["pt"], signals, checks, 0) @staticmethod def get_cam_can_parser(CP): signals = [ - # sig_name, sig_address - ("COUNTER", "LKAS_COMMAND"), - ("CAR_MODEL", "LKAS_HUD"), - ("LKAS_STATUS_OK", "LKAS_HEARTBIT") + # sig_name, sig_address, default + ("CAR_MODEL", "DAS_6"), ] checks = [ - ("LKAS_COMMAND", 100), - ("LKAS_HEARTBIT", 10), - ("LKAS_HUD", 4), + ("DAS_6", 4), ] + if CP.carFingerprint in RAM_CARS: + signals += [ + ("AUTO_HIGH_BEAM_ON", "DAS_6"), + ] + signals += CarState.get_cruise_signals()[0] + checks += CarState.get_cruise_signals()[1] + return CANParser(DBC[CP.carFingerprint]["pt"], signals, checks, 2) diff --git a/selfdrive/car/chrysler/chryslercan.py b/selfdrive/car/chrysler/chryslercan.py index 4d5226570c..10ed73e9f2 100644 --- a/selfdrive/car/chrysler/chryslercan.py +++ b/selfdrive/car/chrysler/chryslercan.py @@ -1,57 +1,71 @@ from cereal import car -from selfdrive.car import make_can_msg - +from selfdrive.car.chrysler.values import RAM_CARS GearShifter = car.CarState.GearShifter VisualAlert = car.CarControl.HUDControl.VisualAlert -def create_lkas_hud(packer, gear, lkas_active, hud_alert, hud_count, lkas_car_model): - # LKAS_HUD 0x2a6 (678) Controls what lane-keeping icon is displayed. +def create_lkas_hud(packer, CP, lkas_active, hud_alert, hud_count, car_model, auto_high_beam): + # LKAS_HUD - Controls what lane-keeping icon is displayed + + # == Color == + # 0 hidden? + # 1 white + # 2 green + # 3 ldw - if hud_alert in (VisualAlert.steerRequired, VisualAlert.ldw): - msg = b'\x00\x00\x00\x03\x00\x00\x00\x00' - return make_can_msg(0x2a6, msg, 0) + # == Lines == + # 03 white Lines + # 04 grey lines + # 09 left lane close + # 0A right lane close + # 0B left Lane very close + # 0C right Lane very close + # 0D left cross cross + # 0E right lane cross - color = 1 # default values are for park or neutral in 2017 are 0 0, but trying 1 1 for 2019 - lines = 1 - alerts = 0 + # == Alerts == + # 7 Normal + # 6 lane departure place hands on wheel + + color = 2 if lkas_active else 1 + lines = 3 if lkas_active else 0 + alerts = 7 if lkas_active else 0 if hud_count < (1 * 4): # first 3 seconds, 4Hz alerts = 1 - # CAR.PACIFICA_2018_HYBRID and CAR.PACIFICA_2019_HYBRID - # had color = 1 and lines = 1 but trying 2017 hybrid style for now. - if gear in (GearShifter.drive, GearShifter.reverse, GearShifter.low): - if lkas_active: - color = 2 # control active, display green. - lines = 6 - else: - color = 1 # control off, display white. - lines = 1 + + if hud_alert in (VisualAlert.ldw, VisualAlert.steerRequired): + color = 4 + lines = 0 + alerts = 6 values = { - "LKAS_ICON_COLOR": color, # byte 0, last 2 bits - "CAR_MODEL": lkas_car_model, # byte 1 - "LKAS_LANE_LINES": lines, # byte 2, last 4 bits - "LKAS_ALERTS": alerts, # byte 3, last 4 bits - } + "LKAS_ICON_COLOR": color, + "CAR_MODEL": car_model, + "LKAS_LANE_LINES": lines, + "LKAS_ALERTS": alerts, + } + + if CP.carFingerprint in RAM_CARS: + values['AUTO_HIGH_BEAM_ON'] = auto_high_beam - return packer.make_can_msg("LKAS_HUD", 0, values) # 0x2a6 + return packer.make_can_msg("DAS_6", 0, values) -def create_lkas_command(packer, apply_steer, moving_fast, frame): - # LKAS_COMMAND 0x292 (658) Lane-keeping signal to turn the wheel. +def create_lkas_command(packer, CP, apply_steer, lkas_control_bit): + # LKAS_COMMAND Lane-keeping signal to turn the wheel + enabled_val = 2 if CP.carFingerprint in RAM_CARS else 1 values = { - "LKAS_STEERING_TORQUE": apply_steer, - "LKAS_HIGH_TORQUE": int(moving_fast), - "COUNTER": frame % 0x10, + "STEERING_TORQUE": apply_steer, + "LKAS_CONTROL_BIT": enabled_val if lkas_control_bit else 0, } return packer.make_can_msg("LKAS_COMMAND", 0, values) -def create_wheel_buttons(packer, frame, cancel=False): - # WHEEL_BUTTONS (571) Message sent to cancel ACC. +def create_cruise_buttons(packer, frame, bus, cancel=False, resume=False): values = { - "ACC_CANCEL": cancel, - "COUNTER": frame % 10 + "ACC_Cancel": cancel, + "ACC_Resume": resume, + "COUNTER": frame % 0x10, } - return packer.make_can_msg("WHEEL_BUTTONS", 0, values) + return packer.make_can_msg("CRUISE_BUTTONS", bus, values) diff --git a/selfdrive/car/chrysler/interface.py b/selfdrive/car/chrysler/interface.py index aead037815..2f058165ac 100755 --- a/selfdrive/car/chrysler/interface.py +++ b/selfdrive/car/chrysler/interface.py @@ -1,82 +1,104 @@ #!/usr/bin/env python3 from cereal import car -from selfdrive.car.chrysler.values import CAR -from selfdrive.car import STD_CARGO_KG, scale_rot_inertia, scale_tire_stiffness, gen_empty_fingerprint, get_safety_config +from panda import Panda +from selfdrive.car import STD_CARGO_KG, get_safety_config +from selfdrive.car.chrysler.values import CAR, DBC, RAM_HD, RAM_DT, RAM_CARS, ChryslerFlags from selfdrive.car.interfaces import CarInterfaceBase class CarInterface(CarInterfaceBase): @staticmethod - def get_params(candidate, fingerprint=gen_empty_fingerprint(), car_fw=None): - ret = CarInterfaceBase.get_std_params(candidate, fingerprint) + def _get_params(ret, candidate, fingerprint, car_fw, experimental_long): ret.carName = "chrysler" - ret.safetyConfigs = [get_safety_config(car.CarParams.SafetyModel.chrysler)] + ret.dashcamOnly = candidate in RAM_HD - # Speed conversion: 20, 45 mph - ret.wheelbase = 3.089 # in meters for Pacifica Hybrid 2017 - ret.steerRatio = 16.2 # Pacifica Hybrid 2017 - ret.mass = 2242. + 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 + ret.radarOffCan = DBC[candidate]['radar'] is None ret.steerActuatorDelay = 0.1 - ret.steerRateCost = 0.7 ret.steerLimitTimer = 0.4 - if candidate in (CAR.JEEP_CHEROKEE, CAR.JEEP_CHEROKEE_2019): - ret.wheelbase = 2.91 # in meters - ret.steerRatio = 12.7 - ret.steerActuatorDelay = 0.2 # in seconds - - ret.centerToFront = ret.wheelbase * 0.44 + # safety config + ret.safetyConfigs = [get_safety_config(car.CarParams.SafetyModel.chrysler)] + if candidate in RAM_HD: + ret.safetyConfigs[0].safetyParam |= Panda.FLAG_CHRYSLER_RAM_HD + elif candidate in RAM_DT: + ret.safetyConfigs[0].safetyParam |= Panda.FLAG_CHRYSLER_RAM_DT ret.minSteerSpeed = 3.8 # m/s - if candidate in (CAR.PACIFICA_2019_HYBRID, CAR.PACIFICA_2020, CAR.JEEP_CHEROKEE_2019): - # TODO allow 2019 cars to steer down to 13 m/s if already engaged. + if candidate not in RAM_CARS: + # Newer FW versions standard on the following platforms, or flashed by a dealer onto older platforms have a higher minimum steering speed. + new_eps_platform = candidate in (CAR.PACIFICA_2019_HYBRID, CAR.PACIFICA_2020, CAR.JEEP_CHEROKEE_2019) + new_eps_firmware = any(fw.ecu == 'eps' and fw.fwVersion[:4] >= b"6841" for fw in car_fw) + if new_eps_platform or new_eps_firmware: + ret.flags |= ChryslerFlags.HIGHER_MIN_STEERING_SPEED.value + + # Chrysler + if candidate in (CAR.PACIFICA_2017_HYBRID, CAR.PACIFICA_2018, CAR.PACIFICA_2018_HYBRID, CAR.PACIFICA_2019_HYBRID, CAR.PACIFICA_2020): + ret.mass = 2242. + STD_CARGO_KG + ret.wheelbase = 3.089 + ret.steerRatio = 16.2 # 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 + + # Jeep + elif candidate in (CAR.JEEP_CHEROKEE, CAR.JEEP_CHEROKEE_2019): + ret.mass = 1778 + STD_CARGO_KG + ret.wheelbase = 2.71 + ret.steerRatio = 16.7 + ret.steerActuatorDelay = 0.2 + 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 + + # Ram + elif candidate == CAR.RAM_1500: + ret.steerActuatorDelay = 0.2 + ret.wheelbase = 3.88 + ret.steerRatio = 16.3 + ret.mass = 2493. + STD_CARGO_KG + CarInterfaceBase.configure_torque_tune(candidate, ret.lateralTuning) + ret.minSteerSpeed = 14.5 + for fw in car_fw: + if fw.ecu == 'eps' and fw.fwVersion.startswith((b"68312176", b"68273275")): + ret.minSteerSpeed = 0. + + elif candidate == CAR.RAM_HD: + ret.steerActuatorDelay = 0.2 + ret.wheelbase = 3.785 + ret.steerRatio = 15.61 + ret.mass = 3405. + STD_CARGO_KG + ret.minSteerSpeed = 16 + CarInterfaceBase.configure_torque_tune(candidate, ret.lateralTuning, 1.0, False) + + else: + raise ValueError(f"Unsupported car: {candidate}") + + if ret.flags & ChryslerFlags.HIGHER_MIN_STEERING_SPEED: + # TODO: allow these cars to steer down to 13 m/s if already engaged. ret.minSteerSpeed = 17.5 # m/s 17 on the way up, 13 on the way down once engaged. - # starting with reasonable value for civic and scaling by mass and wheelbase - ret.rotationalInertia = scale_rot_inertia(ret.mass, ret.wheelbase) - - # TODO: start from empirically derived lateral slip stiffness for the civic and scale by - # mass and CG position, so all cars will have approximately similar dyn behaviors - ret.tireStiffnessFront, ret.tireStiffnessRear = scale_tire_stiffness(ret.mass, ret.wheelbase, ret.centerToFront) - + ret.centerToFront = ret.wheelbase * 0.44 ret.enableBsm = 720 in fingerprint[0] return ret - # returns a car.CarState - def update(self, c, can_strings): - # ******************* do can recv ******************* - self.cp.update_strings(can_strings) - self.cp_cam.update_strings(can_strings) - + def _update(self, c): ret = self.CS.update(self.cp, self.cp_cam) - ret.canValid = self.cp.can_valid and self.cp_cam.can_valid - - # speeds - ret.steeringRateLimited = self.CC.steer_rate_limited if self.CC is not None else False - # events events = self.create_common_events(ret, extra_gears=[car.CarState.GearShifter.low]) - if ret.vEgo < self.CP.minSteerSpeed: + # Low speed steer alert hysteresis logic + if self.CP.minSteerSpeed > 0. and ret.vEgo < (self.CP.minSteerSpeed + 0.5): + self.low_speed_alert = True + elif ret.vEgo > (self.CP.minSteerSpeed + 1.): + self.low_speed_alert = False + if self.low_speed_alert: events.add(car.CarEvent.EventName.belowSteerSpeed) ret.events = events.to_msg() - # copy back carState packet to CS - self.CS.out = ret.as_reader() - - return self.CS.out + return ret - # pass in a car.CarControl - # to be called @ 100hz def apply(self, c): - - if (self.CS.frame == -1): - return car.CarControl.Actuators.new_message(), [] # if we haven't seen a frame 220, then do not update. - - return self.CC.update(c.enabled, self.CS, c.actuators, c.cruiseControl.cancel, c.hudControl.visualAlert) + return self.CC.update(c, self.CS) diff --git a/selfdrive/car/chrysler/radar_interface.py b/selfdrive/car/chrysler/radar_interface.py index 8882dc2d91..348e3c3632 100755 --- a/selfdrive/car/chrysler/radar_interface.py +++ b/selfdrive/car/chrysler/radar_interface.py @@ -10,6 +10,10 @@ LAST_MSG = max(RADAR_MSGS_C + RADAR_MSGS_D) NUMBER_MSGS = len(RADAR_MSGS_C) + len(RADAR_MSGS_D) def _create_radar_can_parser(car_fingerprint): + dbc = DBC[car_fingerprint]['radar'] + if dbc is None: + return None + msg_n = len(RADAR_MSGS_C) # list of [(signal name, message name or number), (...)] # [('RADAR_STATE', 1024), @@ -46,6 +50,9 @@ class RadarInterface(RadarInterfaceBase): self.trigger_msg = LAST_MSG def update(self, can_strings): + if self.rcp is None: + return super().update(None) + vls = self.rcp.update_strings(can_strings) self.updated_messages.update(vls) @@ -81,4 +88,4 @@ class RadarInterface(RadarInterfaceBase): ret.points = [x for x in self.pts.values() if x.dRel != 0] self.updated_messages.clear() - return ret + return ret \ No newline at end of file diff --git a/selfdrive/car/chrysler/values.py b/selfdrive/car/chrysler/values.py index 3fd32e9bc7..02261a0b63 100644 --- a/selfdrive/car/chrysler/values.py +++ b/selfdrive/car/chrysler/values.py @@ -1,23 +1,83 @@ -from selfdrive.car import dbc_dict +from enum import IntFlag +from dataclasses import dataclass +from enum import Enum +from typing import Dict, List, Optional, Union + from cereal import car +from panda.python import uds +from selfdrive.car import dbc_dict +from selfdrive.car.docs_definitions import CarInfo, Harness +from selfdrive.car.fw_query_definitions import FwQueryConfig, Request, p16 + Ecu = car.CarParams.Ecu -class CarControllerParams: - STEER_MAX = 261 # 262 faults - STEER_DELTA_UP = 3 # 3 is stock. 100 is fine. 200 is too much it seems - STEER_DELTA_DOWN = 3 # no faults on the way down it seems - STEER_ERROR_MAX = 80 + +class ChryslerFlags(IntFlag): + HIGHER_MIN_STEERING_SPEED = 1 class CAR: + # Chrysler PACIFICA_2017_HYBRID = "CHRYSLER PACIFICA HYBRID 2017" PACIFICA_2018_HYBRID = "CHRYSLER PACIFICA HYBRID 2018" PACIFICA_2019_HYBRID = "CHRYSLER PACIFICA HYBRID 2019" - PACIFICA_2018 = "CHRYSLER PACIFICA 2018" # includes 2017 Pacifica + PACIFICA_2018 = "CHRYSLER PACIFICA 2018" PACIFICA_2020 = "CHRYSLER PACIFICA 2020" - JEEP_CHEROKEE = "JEEP GRAND CHEROKEE V6 2018" # includes 2017 Trailhawk + + # Jeep + JEEP_CHEROKEE = "JEEP GRAND CHEROKEE V6 2018" # includes 2017 Trailhawk JEEP_CHEROKEE_2019 = "JEEP GRAND CHEROKEE 2019" # includes 2020 Trailhawk + # Ram + RAM_1500 = "RAM 1500 5TH GEN" + RAM_HD = "RAM HD 5TH GEN" + + +class CarControllerParams: + def __init__(self, CP): + self.STEER_ERROR_MAX = 80 + if CP.carFingerprint in RAM_HD: + self.STEER_DELTA_UP = 14 + self.STEER_DELTA_DOWN = 14 + self.STEER_MAX = 361 # higher than this faults the EPS + elif CP.carFingerprint in RAM_DT: + self.STEER_DELTA_UP = 6 + self.STEER_DELTA_DOWN = 6 + self.STEER_MAX = 261 # EPS allows more, up to 350? + else: + self.STEER_DELTA_UP = 3 + self.STEER_DELTA_DOWN = 3 + self.STEER_MAX = 261 # higher than this faults the EPS + +STEER_THRESHOLD = 120 + +RAM_DT = {CAR.RAM_1500, } +RAM_HD = {CAR.RAM_HD, } +RAM_CARS = RAM_DT | RAM_HD + +@dataclass +class ChryslerCarInfo(CarInfo): + package: str = "Adaptive Cruise Control (ACC)" + harness: Enum = Harness.fca + +CAR_INFO: Dict[str, Optional[Union[ChryslerCarInfo, List[ChryslerCarInfo]]]] = { + CAR.PACIFICA_2017_HYBRID: ChryslerCarInfo("Chrysler Pacifica Hybrid 2017-18"), + CAR.PACIFICA_2018_HYBRID: None, # same platforms + CAR.PACIFICA_2019_HYBRID: ChryslerCarInfo("Chrysler Pacifica Hybrid 2019-22"), + CAR.PACIFICA_2018: ChryslerCarInfo("Chrysler Pacifica 2017-18"), + CAR.PACIFICA_2020: [ + ChryslerCarInfo("Chrysler Pacifica 2019-20"), + ChryslerCarInfo("Chrysler Pacifica 2021", package="All"), + ], + CAR.JEEP_CHEROKEE: ChryslerCarInfo("Jeep Grand Cherokee 2016-18", video_link="https://www.youtube.com/watch?v=eLR9o2JkuRk"), + CAR.JEEP_CHEROKEE_2019: ChryslerCarInfo("Jeep Grand Cherokee 2019-21", video_link="https://www.youtube.com/watch?v=jBe4lWnRSu4"), + CAR.RAM_1500: ChryslerCarInfo("Ram 1500 2019-22", harness=Harness.ram), + CAR.RAM_HD: [ + ChryslerCarInfo("Ram 2500 2020-22", harness=Harness.ram), + ChryslerCarInfo("Ram 3500 2020-22", harness=Harness.ram), + ], +} + # Unique CAN messages: # Only the hybrids have 270: 8 # Only the gas have 55: 8, 416: 7 @@ -62,10 +122,14 @@ FINGERPRINTS = { }, # Based on "8190c7275a24557b|2020-02-24--09-57-23" { - 168: 8, 257: 5, 258: 8, 264: 8, 268: 8, 270: 8, 274: 2, 280: 8, 284: 8, 288: 7, 290: 6, 291: 8, 292: 8, 294: 8, 300: 8, 308: 8, 320: 8, 324: 8, 331: 8, 332: 8, 344: 8, 368: 8, 376: 3, 384: 8, 388: 4, 448: 6, 456: 4, 464: 8, 469: 8, 480: 8, 500: 8, 501: 8, 512: 8, 514: 8, 515: 7, 516: 7, 517: 7, 518: 7, 520: 8, 524: 8, 526: 6, 528: 8, 532: 8, 542: 8, 544: 8, 557: 8, 559: 8, 560: 8, 564: 8, 571: 3, 579: 8, 584: 8, 608: 8, 624: 8, 625: 8, 632: 8, 639: 8, 640: 1, 650: 8, 653: 8, 654: 8, 655: 8, 656: 4, 658: 6, 660: 8, 669: 3, 671: 8, 672: 8, 678: 8, 680: 8, 683: 8, 701: 8, 703: 8, 704: 8, 705: 8, 706: 8, 709: 8, 710: 8, 711: 8, 719: 8, 720: 6, 729: 5, 736: 8, 737: 8, 738: 8, 746: 5, 752: 2, 754: 8, 760: 8, 764: 8, 766: 8, 770: 8, 773: 8, 779: 8, 782: 8, 784: 8, 792: 8, 793: 8, 794: 8, 795: 8, 796: 8, 797: 8, 798: 8, 799: 8, 800: 8, 801: 8, 802: 8, 803: 8, 804: 8, 805: 8, 807: 8, 808: 8, 816: 8, 817: 8, 820: 8, 825: 2, 826: 8, 832: 8, 838: 2, 847: 1, 848: 8, 853: 8, 856: 4, 860: 6, 863: 8, 878: 8, 882: 8, 886: 8, 897: 8, 906: 8, 908: 8, 924: 8, 926: 3, 929: 8, 937: 8, 938: 8, 939: 8, 940: 8, 941: 8, 942: 8, 943: 8, 947: 8, 948: 8, 958: 8, 959: 8, 962: 8, 969: 4, 973: 8, 974: 5, 979: 8, 980: 8, 981: 8, 982: 8, 983: 8, 984: 8, 992: 8, 993: 7, 995: 8, 996: 8, 1000: 8, 1001: 8, 1002: 8, 1003: 8, 1008: 8, 1009: 8, 1010: 8, 1011: 8, 1012: 8, 1013: 8, 1014: 8, 1015: 8, 1024: 8, 1025: 8, 1026: 8, 1031: 8, 1033: 8, 1050: 8, 1059: 8, 1082: 8, 1083: 8, 1098: 8, 1100: 8, 1216: 8, 1218: 8, 1220: 8, 1225: 8, 1235: 8, 1242: 8, 1246: 8, 1250: 8, 1251: 8, 1252: 8, 1258: 8, 1259: 8, 1260: 8, 1262: 8, 1284: 8, 1568: 8, 1570: 8, 1856: 8, 1858: 8, 1860: 8, 1863: 8, 1865: 8, 1875: 8, 1882: 8, 1886: 8, 1890: 8, 1891: 8, 1892: 8, 1898: 8, 1899: 8, 1900: 8, 1902: 8, 2015: 8, 2016: 8, 2017: 8, 2018: 8, 2019: 8, 2020: 8, 2023: 8, 2024: 8, 2026: 8, 2027: 8, 2028: 8, 2031: 8 + 168: 8, 257: 5, 258: 8, 264: 8, 268: 8, 270: 8, 274: 2, 280: 8, 284: 8, 288: 7, 290: 6, 291: 8, 292: 8, 294: 8, 300: 8, 308: 8, 320: 8, 324: 8, 331: 8, 332: 8, 344: 8, 368: 8, 376: 3, 384: 8, 388: 4, 448: 6, 456: 4, 464: 8, 469: 8, 480: 8, 500: 8, 501: 8, 512: 8, 514: 8, 515: 7, 516: 7, 517: 7, 518: 7, 520: 8, 524: 8, 526: 6, 528: 8, 532: 8, 542: 8, 544: 8, 557: 8, 559: 8, 560: 8, 564: 8, 571: 3, 579: 8, 584: 8, 608: 8, 624: 8, 625: 8, 632: 8, 639: 8, 640: 1, 650: 8, 653: 8, 654: 8, 655: 8, 656: 4, 658: 6, 660: 8, 669: 3, 671: 8, 672: 8, 678: 8, 680: 8, 683: 8, 701: 8, 703: 8, 704: 8, 705: 8, 706: 8, 709: 8, 710: 8, 711: 8, 719: 8, 720: 6, 729: 5, 736: 8, 737: 8, 738: 8, 746: 5, 752: 2, 754: 8, 760: 8, 764: 8, 766: 8, 770: 8, 773: 8, 779: 8, 782: 8, 784: 8, 792: 8, 793: 8, 794: 8, 795: 8, 796: 8, 797: 8, 798: 8, 799: 8, 800: 8, 801: 8, 802: 8, 803: 8, 804: 8, 805: 8, 807: 8, 808: 8, 816: 8, 817: 8, 820: 8, 825: 2, 826: 8, 832: 8, 838: 2, 847: 1, 848: 8, 853: 8, 856: 4, 860: 6, 863: 8, 878: 8, 882: 8, 886: 8, 897: 8, 906: 8, 908: 8, 924: 8, 926: 3, 929: 8, 937: 8, 938: 8, 939: 8, 940: 8, 941: 8, 942: 8, 943: 8, 947: 8, 948: 8, 958: 8, 959: 8, 962: 8, 969: 4, 973: 8, 974: 5, 979: 8, 980: 8, 981: 8, 982: 8, 983: 8, 984: 8, 992: 8, 993: 7, 995: 8, 996: 8, 1000: 8, 1001: 8, 1002: 8, 1003: 8, 1008: 8, 1009: 8, 1010: 8, 1011: 8, 1012: 8, 1013: 8, 1014: 8, 1015: 8, 1024: 8, 1025: 8, 1026: 8, 1031: 8, 1033: 8, 1050: 8, 1059: 8, 1082: 8, 1083: 8, 1098: 8, 1100: 8, 1216: 8, 1218: 8, 1220: 8, 1225: 8, 1235: 8, 1242: 8, 1246: 8, 1250: 8, 1251: 8, 1252: 8, 1258: 8, 1259: 8, 1260: 8, 1262: 8, 1284: 8, 1536: 8, 1568: 8, 1570: 8, 1856: 8, 1858: 8, 1860: 8, 1863: 8, 1865: 8, 1875: 8, 1882: 8, 1886: 8, 1890: 8, 1891: 8, 1892: 8, 1898: 8, 1899: 8, 1900: 8, 1902: 8, 2015: 8, 2016: 8, 2017: 8, 2018: 8, 2019: 8, 2020: 8, 2023: 8, 2024: 8, 2026: 8, 2027: 8, 2028: 8, 2031: 8 }], CAR.JEEP_CHEROKEE: [{ 55: 8, 168: 8, 181: 8, 256: 4, 257: 5, 258: 8, 264: 8, 268: 8, 272: 6, 273: 6, 274: 2, 280: 8, 284: 8, 288: 7, 290: 6, 292: 8, 300: 8, 308: 8, 320: 8, 324: 8, 331: 8, 332: 8, 344: 8, 352: 8, 362: 8, 368: 8, 376: 3, 384: 8, 388: 4, 416: 7, 448: 6, 456: 4, 464: 8, 500: 8, 501: 8, 512: 8, 514: 8, 520: 8, 532: 8, 544: 8, 557: 8, 559: 8, 560: 4, 564: 4, 571: 3, 579: 8, 584: 8, 608: 8, 618: 8, 624: 8, 625: 8, 632: 8, 639: 8, 656: 4, 658: 6, 660: 8, 671: 8, 672: 8, 676: 8, 678: 8, 680: 8, 683: 8, 684: 8, 703: 8, 705: 8, 706: 8, 709: 8, 710: 8, 719: 8, 720: 6, 729: 5, 736: 8, 737: 8, 738: 8, 746: 5, 752: 2, 754: 8, 760: 8, 761: 8, 764: 8, 766: 8, 773: 8, 776: 8, 779: 8, 782: 8, 783: 8, 784: 8, 785: 8, 788: 3, 792: 8, 799: 8, 800: 8, 804: 8, 806: 2, 808: 8, 810: 8, 816: 8, 817: 8, 820: 8, 825: 2, 826: 8, 831: 6, 832: 8, 838: 2, 840: 8, 844: 5, 847: 1, 848: 8, 853: 8, 856: 4, 860: 6, 863: 8, 874: 2, 882: 8, 897: 8, 906: 8, 924: 8, 937: 8, 938: 8, 939: 8, 940: 8, 941: 8, 942: 8, 943: 8, 947: 8, 948: 8, 956: 8, 968: 8, 969: 4, 970: 8, 973: 8, 974: 5, 975: 8, 976: 8, 977: 4, 979: 8, 980: 8, 981: 8, 982: 8, 983: 8, 984: 8, 992: 8, 993: 7, 995: 8, 996: 8, 1000: 8, 1001: 8, 1002: 8, 1003: 8, 1008: 8, 1009: 8, 1010: 8, 1011: 8, 1012: 8, 1013: 8, 1014: 8, 1015: 8, 1024: 8, 1025: 8, 1026: 8, 1031: 8, 1033: 8, 1050: 8, 1059: 8, 1062: 8, 1098: 8, 1100: 8, 1543: 8, 1562: 8, 2015: 8, 2016: 8, 2017: 8, 2024: 8, 2025: 8 + }, + # Based on c88f65eeaee4003a|2022-08-04--15-37-16 + { + 257: 5, 258: 8, 264: 8, 268: 8, 274: 2, 280: 8, 284: 8, 288: 7, 290: 6, 292: 8, 300: 8, 308: 8, 320: 8, 324: 8, 331: 8, 332: 8, 344: 8, 352: 8, 362: 8, 368: 8, 376: 3, 384: 8, 388: 4, 416: 7, 448: 6, 456: 4, 464: 8, 500: 8, 501: 8, 512: 8, 514: 8, 520: 8, 532: 8, 544: 8, 557: 8, 559: 8, 560: 4, 564: 4, 571: 3, 584: 8, 608: 8, 624: 8, 625: 8, 632: 8, 639: 8, 658: 6, 660: 8, 671: 8, 672: 8, 678: 8, 680: 8, 684: 8, 703: 8, 705: 8, 706: 8, 709: 8, 710: 8, 719: 8, 720: 6, 729: 5, 736: 8, 737: 8, 746: 5, 752: 2, 760: 8, 761: 8, 764: 8, 766: 8, 773: 8, 776: 8, 779: 8, 783: 8, 784: 8, 792: 8, 799: 8, 800: 8, 804: 8, 806: 2, 810: 8, 816: 8, 817: 8, 820: 8, 825: 2, 826: 8, 831: 6, 832: 8, 838: 2, 844: 5, 848: 8, 853: 8, 856: 4, 860: 6, 863: 8, 882: 8, 897: 8, 924: 3, 937: 8, 947: 8, 948: 8, 969: 4, 974: 5, 977: 4, 979: 8, 980: 8, 981: 8, 982: 8, 983: 8, 984: 8, 992: 8, 993: 7, 995: 8, 996: 8, 1000: 8, 1001: 8, 1002: 8, 1003: 8, 1008: 8, 1009: 8, 1010: 8, 1011: 8, 1012: 8, 1013: 8, 1014: 8, 1015: 8, 1024: 8, 1025: 8, 1026: 8, 1031: 8, 1033: 8, 1050: 8, 1059: 8, 1062: 8, 1098: 8, 1100: 8, 1216: 8, 1218: 8, 1220: 8, 1223: 8, 1235: 8, 1242: 8, 1252: 8, 1792: 8, 1798: 8, 1799: 8, 1810: 8, 1813: 8, 1824: 8, 1825: 8, 1840: 8, 1856: 8, 1858: 8, 1859: 8, 1860: 8, 1862: 8, 1863: 8, 1872: 8, 1875: 8, 1879: 8, 1882: 8, 1888: 8, 1892: 8, 1927: 8, 1937: 8, 1953: 8, 1968: 8, 1988: 8, 2000: 8, 2001: 8, 2004: 8, 2015: 8, 2016: 8, 2017: 8, 2024: 8, 2025: 8 }], CAR.JEEP_CHEROKEE_2019: [{ # Jeep Grand Cherokee 2019, including most 2020 models @@ -73,15 +137,142 @@ FINGERPRINTS = { }], } +CHRYSLER_VERSION_REQUEST = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER]) + \ + p16(0xf132) +CHRYSLER_VERSION_RESPONSE = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER + 0x40]) + \ + p16(0xf132) -DBC = { - CAR.PACIFICA_2017_HYBRID: dbc_dict('chrysler_pacifica_2017_hybrid', 'chrysler_pacifica_2017_hybrid_private_fusion'), - CAR.PACIFICA_2018: dbc_dict('chrysler_pacifica_2017_hybrid', 'chrysler_pacifica_2017_hybrid_private_fusion'), - CAR.PACIFICA_2020: dbc_dict('chrysler_pacifica_2017_hybrid', 'chrysler_pacifica_2017_hybrid_private_fusion'), - CAR.PACIFICA_2018_HYBRID: dbc_dict('chrysler_pacifica_2017_hybrid', 'chrysler_pacifica_2017_hybrid_private_fusion'), - CAR.PACIFICA_2019_HYBRID: dbc_dict('chrysler_pacifica_2017_hybrid', 'chrysler_pacifica_2017_hybrid_private_fusion'), - CAR.JEEP_CHEROKEE: dbc_dict('chrysler_pacifica_2017_hybrid', 'chrysler_pacifica_2017_hybrid_private_fusion'), - CAR.JEEP_CHEROKEE_2019: dbc_dict('chrysler_pacifica_2017_hybrid', 'chrysler_pacifica_2017_hybrid_private_fusion'), +CHRYSLER_SOFTWARE_VERSION_REQUEST = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER]) + \ + p16(uds.DATA_IDENTIFIER_TYPE.SYSTEM_SUPPLIER_ECU_SOFTWARE_NUMBER) +CHRYSLER_SOFTWARE_VERSION_RESPONSE = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER + 0x40]) + \ + p16(uds.DATA_IDENTIFIER_TYPE.SYSTEM_SUPPLIER_ECU_SOFTWARE_NUMBER) + +CHRYSLER_RX_OFFSET = -0x280 + +FW_QUERY_CONFIG = FwQueryConfig( + requests=[ + Request( + [CHRYSLER_VERSION_REQUEST], + [CHRYSLER_VERSION_RESPONSE], + whitelist_ecus=[Ecu.abs, Ecu.eps, Ecu.srs, Ecu.fwdRadar, Ecu.fwdCamera, Ecu.combinationMeter], + rx_offset=CHRYSLER_RX_OFFSET, + bus=0, + ), + Request( + [CHRYSLER_VERSION_REQUEST], + [CHRYSLER_VERSION_RESPONSE], + whitelist_ecus=[Ecu.abs, Ecu.hcp, Ecu.engine, Ecu.transmission], + bus=0, + ), + Request( + [CHRYSLER_SOFTWARE_VERSION_REQUEST], + [CHRYSLER_SOFTWARE_VERSION_RESPONSE], + whitelist_ecus=[Ecu.engine, Ecu.transmission], + bus=0, + ), + ], + extra_ecus=[ + (Ecu.hcp, 0x7e2, None), # manages transmission on hybrids + (Ecu.abs, 0x7e4, None), # alt address for abs on hybrids + ], +) + +FW_VERSIONS = { + CAR.RAM_1500: { + (Ecu.combinationMeter, 0x742, None): [ + b'68294063AH', + b'68294063AG', + b'68434860AC', + b'68527375AD', + b'68453503AC', + ], + (Ecu.srs, 0x744, None): [ + b'68441329AB', + b'68490898AA', + b'68428609AB', + b'68500728AA', + ], + (Ecu.abs, 0x747, None): [ + b'68432418AD', + b'68432418AB', + b'68436004AE', + b'68438454AD', + b'68436004AD', + b'68535469AB', + b'68438454AC', + ], + (Ecu.fwdRadar, 0x753, None): [ + b'68320950AL', + b'68320950AJ', + b'68454268AB', + b'68475160AG', + b'04672892AB', + b'68475160AE', + ], + (Ecu.eps, 0x75A, None): [ + b'68273275AG', + b'68469901AA', + b'68552788AA', + ], + (Ecu.engine, 0x7e0, None): [ + b'68448163AJ', + b'68500630AD', + b'68539650AD', + b'68378758AM ', + ], + (Ecu.transmission, 0x7e1, None): [ + b'68360078AL', + b'68384328AD', + b'68360085AL', + b'68360081AM', + b'68502994AD', + b'68445533AB', + b'68540431AB', + b'68484467AC', + ], + }, + + CAR.RAM_HD: { + (Ecu.combinationMeter, 0x742, None): [ + b'68361606AH', + b'68492693AD', + ], + (Ecu.srs, 0x744, None): [ + b'68399794AC', + b'68428503AA', + b'68428505AA', + ], + (Ecu.abs, 0x747, None): [ + b'68334977AH', + b'68504022AB', + b'68530686AB', + b'68504022AC', + ], + (Ecu.fwdRadar, 0x753, None): [ + b'04672895AB', + b'56029827AG', + b'68484694AE', + ], + (Ecu.eps, 0x761, None): [ + b'68421036AC', + b'68507906AB', + ], + (Ecu.engine, 0x7e0, None): [ + b'52421132AF', + b'M2370131MB', + b'M2421132MB', + ], + }, } -STEER_THRESHOLD = 120 +DBC = { + CAR.PACIFICA_2017_HYBRID: dbc_dict('chrysler_pacifica_2017_hybrid_generated', 'chrysler_pacifica_2017_hybrid_private_fusion'), + CAR.PACIFICA_2018: dbc_dict('chrysler_pacifica_2017_hybrid_generated', 'chrysler_pacifica_2017_hybrid_private_fusion'), + CAR.PACIFICA_2020: dbc_dict('chrysler_pacifica_2017_hybrid_generated', 'chrysler_pacifica_2017_hybrid_private_fusion'), + CAR.PACIFICA_2018_HYBRID: dbc_dict('chrysler_pacifica_2017_hybrid_generated', 'chrysler_pacifica_2017_hybrid_private_fusion'), + CAR.PACIFICA_2019_HYBRID: dbc_dict('chrysler_pacifica_2017_hybrid_generated', 'chrysler_pacifica_2017_hybrid_private_fusion'), + CAR.JEEP_CHEROKEE: dbc_dict('chrysler_pacifica_2017_hybrid_generated', 'chrysler_pacifica_2017_hybrid_private_fusion'), + CAR.JEEP_CHEROKEE_2019: dbc_dict('chrysler_pacifica_2017_hybrid_generated', 'chrysler_pacifica_2017_hybrid_private_fusion'), + CAR.RAM_1500: dbc_dict('chrysler_ram_dt_generated', None), + CAR.RAM_HD: dbc_dict('chrysler_ram_hd_generated', None), +} diff --git a/selfdrive/car/disable_ecu.py b/selfdrive/car/disable_ecu.py old mode 100644 new mode 100755 index 3a06cc06f1..cd3e93fa80 --- a/selfdrive/car/disable_ecu.py +++ b/selfdrive/car/disable_ecu.py @@ -1,11 +1,12 @@ from selfdrive.car.isotp_parallel_query import IsoTpParallelQuery -from selfdrive.swaglog import cloudlog +from system.swaglog import cloudlog EXT_DIAG_REQUEST = b'\x10\x03' EXT_DIAG_RESPONSE = b'\x50\x03' COM_CONT_RESPONSE = b'' + def disable_ecu(logcan, sendcan, bus=0, addr=0x7d0, com_cont_req=b'\x28\x83\x01', timeout=0.1, retry=10, debug=False): """Silence an ECU by disabling sending and receiving messages using UDS 0x28. The ECU will stay silent as long as openpilot keeps sending Tester Present. @@ -26,9 +27,22 @@ def disable_ecu(logcan, sendcan, bus=0, addr=0x7d0, com_cont_req=b'\x28\x83\x01' cloudlog.warning("ecu disabled") return True + except Exception: cloudlog.exception("ecu disable exception") print(f"ecu disable retry ({i+1}) ...") cloudlog.warning("ecu disable failed") return False + + +if __name__ == "__main__": + import time + import cereal.messaging as messaging + sendcan = messaging.pub_sock('sendcan') + logcan = messaging.sub_sock('can') + time.sleep(1) + + # honda bosch radar disable + disabled = disable_ecu(logcan, sendcan, bus=1, addr=0x18DAB0F1, com_cont_req=b'\x28\x83\x03', timeout=0.5, debug=False) + print(f"disabled: {disabled}") diff --git a/selfdrive/car/docs.py b/selfdrive/car/docs.py new file mode 100755 index 0000000000..03313e2ff6 --- /dev/null +++ b/selfdrive/car/docs.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +import argparse +from collections import defaultdict +import jinja2 +import os +from enum import Enum +from natsort import natsorted +from typing import Dict, List + +from cereal import car +from common.basedir import BASEDIR +from selfdrive.car import gen_empty_fingerprint +from selfdrive.car.docs_definitions import CarInfo, Column, CommonFootnote +from selfdrive.car.car_helpers import interfaces, get_interface_attr + + +def get_all_footnotes() -> Dict[Enum, int]: + all_footnotes = list(CommonFootnote) + for footnotes in get_interface_attr("Footnote", ignore_none=True).values(): + all_footnotes.extend(footnotes) + return {fn: idx + 1 for idx, fn in enumerate(all_footnotes)} + + +CARS_MD_OUT = os.path.join(BASEDIR, "docs", "CARS.md") +CARS_MD_TEMPLATE = os.path.join(BASEDIR, "selfdrive", "car", "CARS_template.md") + + +def get_all_car_info() -> List[CarInfo]: + all_car_info: List[CarInfo] = [] + footnotes = get_all_footnotes() + for model, car_info in get_interface_attr("CAR_INFO", combine_brands=True).items(): + CP = interfaces[model][0].get_params(model, fingerprint=gen_empty_fingerprint(), car_fw=[car.CarParams.CarFw(ecu="unknown")]) + + if CP.dashcamOnly or car_info is None: + continue + + # A platform can include multiple car models + if not isinstance(car_info, list): + car_info = (car_info,) + + for _car_info in car_info: + if not hasattr(_car_info, "row"): + _car_info.init_make(CP) + _car_info.init(CP, footnotes) + all_car_info.append(_car_info) + + # Sort cars by make and model + year + sorted_cars: List[CarInfo] = natsorted(all_car_info, key=lambda car: car.name.lower()) + return sorted_cars + + +def group_by_make(all_car_info: List[CarInfo]) -> Dict[str, List[CarInfo]]: + sorted_car_info = defaultdict(list) + for car_info in all_car_info: + sorted_car_info[car_info.make].append(car_info) + return dict(sorted_car_info) + + +def generate_cars_md(all_car_info: List[CarInfo], template_fn: str) -> str: + with open(template_fn, "r") as f: + template = jinja2.Template(f.read(), trim_blocks=True, lstrip_blocks=True) + + footnotes = [fn.value.text for fn in get_all_footnotes()] + cars_md: str = template.render(all_car_info=all_car_info, group_by_make=group_by_make, + footnotes=footnotes, Column=Column) + return cars_md + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Auto generates supported cars documentation", + formatter_class=argparse.ArgumentDefaultsHelpFormatter) + + parser.add_argument("--template", default=CARS_MD_TEMPLATE, help="Override default template filename") + parser.add_argument("--out", default=CARS_MD_OUT, help="Override default generated filename") + args = parser.parse_args() + + with open(args.out, 'w') as f: + f.write(generate_cars_md(get_all_car_info(), args.template)) + print(f"Generated and written to {args.out}") diff --git a/selfdrive/car/docs_definitions.py b/selfdrive/car/docs_definitions.py new file mode 100644 index 0000000000..03e9e721b5 --- /dev/null +++ b/selfdrive/car/docs_definitions.py @@ -0,0 +1,217 @@ +import re +from collections import namedtuple +from dataclasses import dataclass, field +from enum import Enum +from typing import Dict, List, Optional, Tuple, Union + +from cereal import car +from common.conversions import Conversions as CV + +GOOD_TORQUE_THRESHOLD = 1.0 # m/s^2 +MODEL_YEARS_RE = r"(?<= )((\d{4}-\d{2})|(\d{4}))(,|$)" + + +class Column(Enum): + MAKE = "Make" + MODEL = "Model" + PACKAGE = "Supported Package" + LONGITUDINAL = "ACC" + FSR_LONGITUDINAL = "No ACC accel below" + FSR_STEERING = "No ALC below" + STEERING_TORQUE = "Steering Torque" + AUTO_RESUME = "Resume from stop" + HARNESS = "Harness" + + +class Star(Enum): + FULL = "full" + HALF = "half" + EMPTY = "empty" + + +class Harness(Enum): + nidec = "Honda Nidec" + bosch_a = "Honda Bosch A" + bosch_b = "Honda Bosch B" + toyota = "Toyota" + subaru_a = "Subaru A" + subaru_b = "Subaru B" + fca = "FCA" + ram = "Ram" + vw = "VW" + j533 = "J533" + hyundai_a = "Hyundai A" + hyundai_b = "Hyundai B" + hyundai_c = "Hyundai C" + hyundai_d = "Hyundai D" + hyundai_e = "Hyundai E" + hyundai_f = "Hyundai F" + hyundai_g = "Hyundai G" + hyundai_h = "Hyundai H" + hyundai_i = "Hyundai I" + hyundai_j = "Hyundai J" + hyundai_k = "Hyundai K" + hyundai_l = "Hyundai L" + hyundai_m = "Hyundai M" + hyundai_n = "Hyundai N" + hyundai_o = "Hyundai O" + hyundai_p = "Hyundai P" + hyundai_q = "Hyundai Q" + custom = "Developer" + obd_ii = "OBD-II" + gm = "GM" + nissan_a = "Nissan A" + nissan_b = "Nissan B" + mazda = "Mazda" + ford_q3 = "Ford Q3" + ford_q4 = "Ford Q4" + none = "None" + + +CarFootnote = namedtuple("CarFootnote", ["text", "column", "docs_only", "shop_footnote"], defaults=(False, False)) + + +class CommonFootnote(Enum): + EXP_LONG_AVAIL = CarFootnote( + "Experimental openpilot longitudinal control is available behind a toggle; the toggle is only available in non-release branches such as `devel` or `master-ci`. ", + Column.LONGITUDINAL, docs_only=True) + EXP_LONG_DSU = CarFootnote( + "By default, this car will use the stock Adaptive Cruise Control (ACC) for longitudinal control. If the Driver Support Unit (DSU) is disconnected, openpilot ACC will replace " + + "stock ACC. NOTE: disconnecting the DSU disables Automatic Emergency Braking (AEB).", + Column.LONGITUDINAL) + + +def get_footnotes(footnotes: List[Enum], column: Column) -> List[Enum]: + # Returns applicable footnotes given current column + return [fn for fn in footnotes if fn.value.column == column] + + +# TODO: store years as a list +def get_year_list(years): + years_list = [] + if len(years) == 0: + return years_list + + for year in years.split(','): + year = year.strip() + if len(year) == 4: + years_list.append(str(year)) + elif "-" in year and len(year) == 7: + start, end = year.split("-") + years_list.extend(map(str, range(int(start), int(f"20{end}") + 1))) + else: + raise Exception(f"Malformed year string: {years}") + return years_list + + +def split_name(name: str) -> Tuple[str, str, str]: + make, model = name.split(" ", 1) + years = "" + match = re.search(MODEL_YEARS_RE, model) + if match is not None: + years = model[match.start():] + model = model[:match.start() - 1] + return make, model, years + + +@dataclass +class CarInfo: + name: str + package: str + video_link: Optional[str] = None + footnotes: List[Enum] = field(default_factory=list) + min_steer_speed: Optional[float] = None + min_enable_speed: Optional[float] = None + harness: Enum = Harness.none + + def init(self, CP: car.CarParams, all_footnotes: Dict[Enum, int]): + # TODO: set all the min steer speeds in carParams and remove this + if self.min_steer_speed is not None: + assert CP.minSteerSpeed == 0, f"{CP.carFingerprint}: Minimum steer speed set in both CarInfo and CarParams" + else: + self.min_steer_speed = CP.minSteerSpeed + + # TODO: set all the min enable speeds in carParams correctly and remove this + if self.min_enable_speed is None: + self.min_enable_speed = CP.minEnableSpeed + + self.car_name = CP.carName + self.car_fingerprint = CP.carFingerprint + self.make, self.model, self.years = split_name(self.name) + + op_long = "Stock" + if CP.openpilotLongitudinalControl and not CP.enableDsu: + op_long = "openpilot" + elif CP.experimentalLongitudinalAvailable or CP.enableDsu: + op_long = "openpilot available" + if CP.enableDsu: + self.footnotes.append(CommonFootnote.EXP_LONG_DSU) + else: + self.footnotes.append(CommonFootnote.EXP_LONG_AVAIL) + + self.row = { + Column.MAKE: self.make, + Column.MODEL: self.model, + Column.PACKAGE: self.package, + Column.LONGITUDINAL: op_long, + Column.FSR_LONGITUDINAL: f"{max(self.min_enable_speed * CV.MS_TO_MPH, 0):.0f} mph", + Column.FSR_STEERING: f"{max(self.min_steer_speed * CV.MS_TO_MPH, 0):.0f} mph", + Column.STEERING_TORQUE: Star.EMPTY, + Column.AUTO_RESUME: Star.FULL if CP.autoResumeSng else Star.EMPTY, + Column.HARNESS: self.harness.value, + } + + # Set steering torque star from max lateral acceleration + assert CP.maxLateralAccel > 0.1 + if CP.maxLateralAccel >= GOOD_TORQUE_THRESHOLD: + self.row[Column.STEERING_TORQUE] = Star.FULL + + self.all_footnotes = all_footnotes + self.year_list = get_year_list(self.years) + self.detail_sentence = self.get_detail_sentence(CP) + + return self + + def init_make(self, CP: car.CarParams): + """CarInfo subclasses can add make-specific logic for harness selection, footnotes, etc.""" + + def get_detail_sentence(self, CP): + if not CP.notCar: + sentence_builder = "openpilot upgrades your {car_model} with automated lane centering{alc} and adaptive cruise control{acc}." + + if self.min_steer_speed > self.min_enable_speed: + alc = f" above {self.min_steer_speed * CV.MS_TO_MPH:.0f} mph," if self.min_steer_speed > 0 else " at all speeds," + else: + alc = "" + + # Exception for cars which do not auto-resume yet + acc = "" + if self.min_enable_speed > 0: + acc = f" while driving above {self.min_enable_speed * CV.MS_TO_MPH:.0f} mph" + elif CP.autoResumeSng: + acc = " that automatically resumes from a stop" + + if self.row[Column.STEERING_TORQUE] != Star.FULL: + sentence_builder += " This car may not be able to take tight turns on its own." + + return sentence_builder.format(car_model=f"{self.make} {self.model}", alc=alc, acc=acc) + + else: + if CP.carFingerprint == "COMMA BODY": + return "The body is a robotics dev kit that can run openpilot. Learn more." + else: + raise Exception(f"This notCar does not have a detail sentence: {CP.carFingerprint}") + + def get_column(self, column: Column, star_icon: str, footnote_tag: str) -> str: + item: Union[str, Star] = self.row[column] + if isinstance(item, Star): + item = star_icon.format(item.value) + elif column == Column.MODEL and len(self.years): + item += f" {self.years}" + + footnotes = get_footnotes(self.footnotes, column) + if len(footnotes): + sups = sorted([self.all_footnotes[fn] for fn in footnotes]) + item += footnote_tag.format(f'{",".join(map(str, sups))}') + + return item diff --git a/selfdrive/car/ecu_addrs.py b/selfdrive/car/ecu_addrs.py new file mode 100755 index 0000000000..9f6ace2b5f --- /dev/null +++ b/selfdrive/car/ecu_addrs.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +import capnp +import time +from typing import Optional, Set, Tuple + +import cereal.messaging as messaging +from panda.python.uds import SERVICE_TYPE +from selfdrive.car import make_can_msg +from selfdrive.boardd.boardd import can_list_to_can_capnp +from system.swaglog import cloudlog + + +def make_tester_present_msg(addr, bus, subaddr=None): + dat = [0x02, SERVICE_TYPE.TESTER_PRESENT, 0x0] + if subaddr is not None: + dat.insert(0, subaddr) + + dat.extend([0x0] * (8 - len(dat))) + return make_can_msg(addr, bytes(dat), bus) + + +def is_tester_present_response(msg: capnp.lib.capnp._DynamicStructReader, subaddr: Optional[int] = None) -> bool: + # ISO-TP messages are always padded to 8 bytes + # tester present response is always a single frame + dat_offset = 1 if subaddr is not None else 0 + if len(msg.dat) == 8 and 1 <= msg.dat[dat_offset] <= 7: + # success response + if msg.dat[dat_offset + 1] == (SERVICE_TYPE.TESTER_PRESENT + 0x40): + return True + # error response + if msg.dat[dat_offset + 1] == 0x7F and msg.dat[dat_offset + 2] == SERVICE_TYPE.TESTER_PRESENT: + return True + return False + + +def get_all_ecu_addrs(logcan: messaging.SubSocket, sendcan: messaging.PubSocket, bus: int, timeout: float = 1, debug: bool = True) -> Set[Tuple[int, Optional[int], int]]: + addr_list = [0x700 + i for i in range(256)] + [0x18da00f1 + (i << 8) for i in range(256)] + queries: Set[Tuple[int, Optional[int], int]] = {(addr, None, bus) for addr in addr_list} + responses = queries + return get_ecu_addrs(logcan, sendcan, queries, responses, timeout=timeout, debug=debug) + + +def get_ecu_addrs(logcan: messaging.SubSocket, sendcan: messaging.PubSocket, queries: Set[Tuple[int, Optional[int], int]], + responses: Set[Tuple[int, Optional[int], int]], timeout: float = 1, debug: bool = False) -> Set[Tuple[int, Optional[int], int]]: + ecu_responses: Set[Tuple[int, Optional[int], int]] = set() # set((addr, subaddr, bus),) + try: + msgs = [make_tester_present_msg(addr, bus, subaddr) for addr, subaddr, bus in queries] + + messaging.drain_sock_raw(logcan) + sendcan.send(can_list_to_can_capnp(msgs, msgtype='sendcan')) + start_time = time.monotonic() + while time.monotonic() - start_time < timeout: + can_packets = messaging.drain_sock(logcan, wait_for_one=True) + for packet in can_packets: + for msg in packet.can: + subaddr = None if (msg.address, None, msg.src) in responses else msg.dat[0] + if (msg.address, subaddr, msg.src) in responses and is_tester_present_response(msg, subaddr): + if debug: + print(f"CAN-RX: {hex(msg.address)} - 0x{bytes.hex(msg.dat)}") + if (msg.address, subaddr, msg.src) in ecu_responses: + print(f"Duplicate ECU address: {hex(msg.address)}") + ecu_responses.add((msg.address, subaddr, msg.src)) + except Exception: + cloudlog.exception("ECU addr scan exception") + return ecu_responses + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description='Get addresses of all ECUs') + parser.add_argument('--debug', action='store_true') + parser.add_argument('--bus', type=int, default=1) + parser.add_argument('--timeout', type=float, default=1.0) + args = parser.parse_args() + + logcan = messaging.sub_sock('can') + sendcan = messaging.pub_sock('sendcan') + + time.sleep(1.0) + + print("Getting ECU addresses ...") + ecu_addrs = get_all_ecu_addrs(logcan, sendcan, args.bus, args.timeout, debug=args.debug) + + print() + print("Found ECUs on addresses:") + for addr, subaddr, bus in ecu_addrs: + msg = f" 0x{hex(addr)}" + if subaddr is not None: + msg += f" (sub-address: 0x{hex(subaddr)})" + print(msg) diff --git a/selfdrive/car/fingerprints.py b/selfdrive/car/fingerprints.py index 9b280f3b45..1a9bb8c4e7 100644 --- a/selfdrive/car/fingerprints.py +++ b/selfdrive/car/fingerprints.py @@ -1,44 +1,12 @@ -import os -from common.basedir import BASEDIR +from selfdrive.car.interfaces import get_interface_attr -def get_attr_from_cars(attr, result=dict, combine_brands=True): - # read all the folders in selfdrive/car and return a dict where: - # - keys are all the car models - # - values are attr values from all car folders - result = result() - - for car_folder in [x[0] for x in os.walk(BASEDIR + '/selfdrive/car')]: - try: - car_name = car_folder.split('/')[-1] - values = __import__(f'selfdrive.car.{car_name}.values', fromlist=[attr]) - if hasattr(values, attr): - attr_values = getattr(values, attr) - else: - continue - - if isinstance(attr_values, dict): - for f, v in attr_values.items(): - if combine_brands: - result[f] = v - else: - if car_name not in result: - result[car_name] = {} - result[car_name][f] = v - elif isinstance(attr_values, list): - result += attr_values - - except (ImportError, OSError): - pass - - return result - - -FW_VERSIONS = get_attr_from_cars('FW_VERSIONS') -_FINGERPRINTS = get_attr_from_cars('FINGERPRINTS') +FW_VERSIONS = get_interface_attr('FW_VERSIONS', combine_brands=True, ignore_none=True) +_FINGERPRINTS = get_interface_attr('FINGERPRINTS', combine_brands=True, ignore_none=True) _DEBUG_ADDRESS = {1880: 8} # reserved for debug purposes + def is_valid_for_fingerprint(msg, car_fingerprint): adr = msg.address # ignore addresses that are more than 11 bits diff --git a/selfdrive/car/ford/carcontroller.py b/selfdrive/car/ford/carcontroller.py index 389d3d8d8b..f18014601c 100644 --- a/selfdrive/car/ford/carcontroller.py +++ b/selfdrive/car/ford/carcontroller.py @@ -1,86 +1,111 @@ import math from cereal import car -from selfdrive.car import make_can_msg -from selfdrive.car.ford.fordcan import create_steer_command, create_lkas_ui, spam_cancel_button +from common.numpy_fast import clip, interp from opendbc.can.packer import CANPacker +from selfdrive.car.ford import fordcan +from selfdrive.car.ford.values import CANBUS, CarControllerParams VisualAlert = car.CarControl.HUDControl.VisualAlert -MAX_STEER_DELTA = 1 -TOGGLE_DEBUG = False -class CarController(): - def __init__(self, dbc_name, CP, VM): - self.packer = CANPacker(dbc_name) - self.enabled_last = False - self.main_on_last = False - self.vehicle_model = VM - self.generic_toggle_last = 0 - self.steer_alert_last = False - self.lkas_action = 0 +def apply_ford_steer_angle_limits(apply_angle, apply_angle_last, vEgo): + # rate limit + steer_up = apply_angle_last * apply_angle > 0. and abs(apply_angle) > abs(apply_angle_last) + rate_limit = CarControllerParams.RATE_LIMIT_UP if steer_up else CarControllerParams.RATE_LIMIT_DOWN + max_angle_diff = interp(vEgo, rate_limit.speed_points, rate_limit.max_angle_diff_points) + apply_angle = clip(apply_angle, (apply_angle_last - max_angle_diff), (apply_angle_last + max_angle_diff)) - def update(self, enabled, CS, frame, actuators, visual_alert, pcm_cancel): + # absolute limit (LatCtlPath_An_Actl) + apply_path_angle = math.radians(apply_angle) / CarControllerParams.LKAS_STEER_RATIO + apply_path_angle = clip(apply_path_angle, -0.5, 0.5235) + apply_angle = math.degrees(apply_path_angle) * CarControllerParams.LKAS_STEER_RATIO - can_sends = [] - steer_alert = visual_alert in (VisualAlert.steerRequired, VisualAlert.ldw) + return apply_angle - apply_steer = actuators.steer - if pcm_cancel: - #print "CANCELING!!!!" - can_sends.append(spam_cancel_button(self.packer)) +class CarController: + def __init__(self, dbc_name, CP, VM): + self.CP = CP + self.VM = VM + self.packer = CANPacker(dbc_name) + self.frame = 0 - if (frame % 3) == 0: + self.apply_angle_last = 0 + self.main_on_last = False + self.lkas_enabled_last = False + self.steer_alert_last = False - curvature = self.vehicle_model.calc_curvature(math.radians(actuators.steeringAngleDeg), CS.out.vEgo, 0.0) + def update(self, CC, CS): + can_sends = [] - # The use of the toggle below is handy for trying out the various LKAS modes - if TOGGLE_DEBUG: - self.lkas_action += int(CS.out.genericToggle and not self.generic_toggle_last) - self.lkas_action &= 0xf + actuators = CC.actuators + hud_control = CC.hudControl + + main_on = CS.out.cruiseState.available + steer_alert = hud_control.visualAlert in (VisualAlert.steerRequired, VisualAlert.ldw) + + ### acc buttons ### + if CC.cruiseControl.cancel: + can_sends.append(fordcan.create_button_command(self.packer, CS.buttons_stock_values, cancel=True)) + can_sends.append(fordcan.create_button_command(self.packer, CS.buttons_stock_values, cancel=True, bus=CANBUS.main)) + elif CC.cruiseControl.resume and (self.frame % CarControllerParams.BUTTONS_STEP) == 0: + can_sends.append(fordcan.create_button_command(self.packer, CS.buttons_stock_values, resume=True)) + can_sends.append(fordcan.create_button_command(self.packer, CS.buttons_stock_values, resume=True, bus=CANBUS.main)) + # if stock lane centering isn't off, send a button press to toggle it off + # the stock system checks for steering pressed, and eventually disengages cruise control + elif CS.acc_tja_status_stock_values["Tja_D_Stat"] != 0 and (self.frame % CarControllerParams.ACC_UI_STEP) == 0: + can_sends.append(fordcan.create_button_command(self.packer, CS.buttons_stock_values, tja_toggle=True)) + + + ### lateral control ### + if CC.latActive: + lca_rq = 1 + apply_angle = apply_ford_steer_angle_limits(actuators.steeringAngleDeg, self.apply_angle_last, CS.out.vEgo) + else: + lca_rq = 0 + apply_angle = 0. + + # send steering commands at 20Hz + if (self.frame % CarControllerParams.LKAS_STEER_STEP) == 0: + # use LatCtlPath_An_Actl to actuate steering + path_angle = math.radians(apply_angle) / CarControllerParams.LKAS_STEER_RATIO + + # set slower ramp type when small steering angle change + # 0=Slow, 1=Medium, 2=Fast, 3=Immediately + steer_change = abs(CS.out.steeringAngleDeg - actuators.steeringAngleDeg) + if steer_change < 2.0: + ramp_type = 0 + elif steer_change < 4.0: + ramp_type = 1 + elif steer_change < 6.0: + ramp_type = 2 else: - self.lkas_action = 5 # 4 and 5 seem the best. 8 and 9 seem to aggressive and laggy - - can_sends.append(create_steer_command(self.packer, apply_steer, enabled, - CS.lkas_state, CS.out.steeringAngleDeg, curvature, self.lkas_action)) - self.generic_toggle_last = CS.out.genericToggle - - if (frame % 100) == 0: + ramp_type = 3 + precision = 1 # 0=Comfortable, 1=Precise (the stock system always uses comfortable) - can_sends.append(make_can_msg(973, b'\x00\x00\x00\x00\x00\x00\x00\x00', 0)) - #can_sends.append(make_can_msg(984, b'\x00\x00\x00\x00\x80\x45\x60\x30', 0)) + self.apply_angle_last = apply_angle + can_sends.append(fordcan.create_lka_command(self.packer, 0, 0)) + can_sends.append(fordcan.create_tja_command(self.packer, lca_rq, ramp_type, precision, + 0, path_angle, 0, 0)) - if (frame % 100) == 0 or (self.enabled_last != enabled) or (self.main_on_last != CS.out.cruiseState.available) or \ - (self.steer_alert_last != steer_alert): - can_sends.append(create_lkas_ui(self.packer, CS.out.cruiseState.available, enabled, steer_alert)) - if (frame % 200) == 0: - can_sends.append(make_can_msg(1875, b'\x80\xb0\x55\x55\x78\x90\x00\x00', 1)) + ### ui ### + send_ui = (self.main_on_last != main_on) or (self.lkas_enabled_last != CC.latActive) or (self.steer_alert_last != steer_alert) - if (frame % 10) == 0: + # send lkas ui command at 1Hz or if ui state changes + if (self.frame % CarControllerParams.LKAS_UI_STEP) == 0 or send_ui: + can_sends.append(fordcan.create_lkas_ui_command(self.packer, main_on, CC.latActive, steer_alert, hud_control, CS.lkas_status_stock_values)) - can_sends.append(make_can_msg(1648, b'\x00\x00\x00\x40\x00\x00\x50\x00', 1)) - can_sends.append(make_can_msg(1649, b'\x10\x10\xf1\x70\x04\x00\x00\x00', 1)) + # send acc ui command at 20Hz or if ui state changes + if (self.frame % CarControllerParams.ACC_UI_STEP) == 0 or send_ui: + can_sends.append(fordcan.create_acc_ui_command(self.packer, main_on, CC.latActive, hud_control, CS.acc_tja_status_stock_values)) - can_sends.append(make_can_msg(1664, b'\x00\x00\x03\xe8\x00\x01\xa9\xb2', 1)) - can_sends.append(make_can_msg(1674, b'\x08\x00\x00\xff\x0c\xfb\x6a\x08', 1)) - can_sends.append(make_can_msg(1675, b'\x00\x00\x3b\x60\x37\x00\x00\x00', 1)) - can_sends.append(make_can_msg(1690, b'\x70\x00\x00\x55\x86\x1c\xe0\x00', 1)) - - can_sends.append(make_can_msg(1910, b'\x06\x4b\x06\x4b\x42\xd3\x11\x30', 1)) - can_sends.append(make_can_msg(1911, b'\x48\x53\x37\x54\x48\x53\x37\x54', 1)) - can_sends.append(make_can_msg(1912, b'\x31\x34\x47\x30\x38\x31\x43\x42', 1)) - can_sends.append(make_can_msg(1913, b'\x31\x34\x47\x30\x38\x32\x43\x42', 1)) - can_sends.append(make_can_msg(1969, b'\xf4\x40\x00\x00\x00\x00\x00\x00', 1)) - can_sends.append(make_can_msg(1971, b'\x0b\xc0\x00\x00\x00\x00\x00\x00', 1)) - - static_msgs = range(1653, 1658) - for addr in static_msgs: - cnt = (frame % 10) + 1 - can_sends.append(make_can_msg(addr, (cnt << 4).to_bytes(1, 'little') + b'\x00\x00\x00\x00\x00\x00\x00', 1)) - - self.enabled_last = enabled - self.main_on_last = CS.out.cruiseState.available + self.main_on_last = main_on + self.lkas_enabled_last = CC.latActive self.steer_alert_last = steer_alert - return actuators, can_sends + new_actuators = actuators.copy() + new_actuators.steeringAngleDeg = self.apply_angle_last + + self.frame += 1 + return new_actuators, can_sends diff --git a/selfdrive/car/ford/carstate.py b/selfdrive/car/ford/carstate.py index eba623f5ce..2276b1208a 100644 --- a/selfdrive/car/ford/carstate.py +++ b/selfdrive/car/ford/carstate.py @@ -1,38 +1,90 @@ from cereal import car +from common.conversions import Conversions as CV +from opendbc.can.can_define import CANDefine from opendbc.can.parser import CANParser -from common.numpy_fast import mean -from selfdrive.config import Conversions as CV from selfdrive.car.interfaces import CarStateBase -from selfdrive.car.ford.values import DBC +from selfdrive.car.ford.values import CANBUS, DBC, CarControllerParams + +GearShifter = car.CarState.GearShifter +TransmissionType = car.CarParams.TransmissionType -WHEEL_RADIUS = 0.33 class CarState(CarStateBase): - def update(self, cp): + def __init__(self, CP): + super().__init__(CP) + can_define = CANDefine(DBC[CP.carFingerprint]["pt"]) + if CP.transmissionType == TransmissionType.automatic: + self.shifter_values = can_define.dv["Gear_Shift_by_Wire_FD1"]["TrnGear_D_RqDrv"] + + def update(self, cp, cp_cam): ret = car.CarState.new_message() - ret.wheelSpeeds = self.get_wheel_speeds( - cp.vl["WheelSpeed_CG1"]["WhlFl_W_Meas"], - cp.vl["WheelSpeed_CG1"]["WhlFr_W_Meas"], - cp.vl["WheelSpeed_CG1"]["WhlRl_W_Meas"], - cp.vl["WheelSpeed_CG1"]["WhlRr_W_Meas"], - unit=WHEEL_RADIUS, - ) - ret.vEgoRaw = mean([ret.wheelSpeeds.rr, ret.wheelSpeeds.rl, ret.wheelSpeeds.fr, ret.wheelSpeeds.fl]) + # car speed + ret.vEgoRaw = cp.vl["BrakeSysFeatures"]["Veh_V_ActlBrk"] * CV.KPH_TO_MS ret.vEgo, ret.aEgo = self.update_speed_kf(ret.vEgoRaw) - ret.standstill = not ret.vEgoRaw > 0.001 - ret.steeringAngleDeg = cp.vl["Steering_Wheel_Data_CG1"]["SteWhlRelInit_An_Sns"] - ret.steeringPressed = not cp.vl["Lane_Keep_Assist_Status"]["LaHandsOff_B_Actl"] - ret.steerError = cp.vl["Lane_Keep_Assist_Status"]["LaActDeny_B_Actl"] == 1 - ret.cruiseState.speed = cp.vl["Cruise_Status"]["Set_Speed"] * CV.MPH_TO_MS - ret.cruiseState.enabled = not (cp.vl["Cruise_Status"]["Cruise_State"] in (0, 3)) - ret.cruiseState.available = cp.vl["Cruise_Status"]["Cruise_State"] != 0 - ret.gas = cp.vl["EngineData_14"]["ApedPosScal_Pc_Actl"] / 100. + ret.yawRate = cp.vl["Yaw_Data_FD1"]["VehYaw_W_Actl"] + ret.standstill = cp.vl["DesiredTorqBrk"]["VehStop_D_Stat"] == 1 + + # gas pedal + ret.gas = cp.vl["EngVehicleSpThrottle"]["ApedPos_Pc_ActlArb"] / 100. ret.gasPressed = ret.gas > 1e-6 - ret.brakePressed = bool(cp.vl["Cruise_Status"]["Brake_Drv_Appl"]) - ret.genericToggle = bool(cp.vl["Steering_Buttons"]["Dist_Incr"]) - # TODO: we also need raw driver torque, needed for Assisted Lane Change - self.lkas_state = cp.vl["Lane_Keep_Assist_Status"]["LaActAvail_D_Actl"] + + # brake pedal + ret.brake = cp.vl["BrakeSnData_4"]["BrkTot_Tq_Actl"] / 32756. # torque in Nm + ret.brakePressed = cp.vl["EngBrakeData"]["BpedDrvAppl_D_Actl"] == 2 + ret.parkingBrake = cp.vl["DesiredTorqBrk"]["PrkBrkStatus"] in (1, 2) + + # steering wheel + ret.steeringAngleDeg = cp.vl["SteeringPinion_Data"]["StePinComp_An_Est"] + ret.steeringTorque = cp.vl["EPAS_INFO"]["SteeringColumnTorque"] + ret.steeringPressed = abs(ret.steeringTorque) > CarControllerParams.STEER_DRIVER_ALLOWANCE + ret.steerFaultTemporary = cp.vl["EPAS_INFO"]["EPAS_Failure"] == 1 + ret.steerFaultPermanent = cp.vl["EPAS_INFO"]["EPAS_Failure"] in (2, 3) + # ret.espDisabled = False # TODO: find traction control signal + + # cruise state + ret.cruiseState.speed = cp.vl["EngBrakeData"]["Veh_V_DsplyCcSet"] * CV.MPH_TO_MS + ret.cruiseState.enabled = cp.vl["EngBrakeData"]["CcStat_D_Actl"] in (4, 5) + ret.cruiseState.available = cp.vl["EngBrakeData"]["CcStat_D_Actl"] in (3, 4, 5) + ret.cruiseState.nonAdaptive = cp.vl["Cluster_Info1_FD1"]["AccEnbl_B_RqDrv"] == 0 + ret.cruiseState.standstill = cp.vl["EngBrakeData"]["AccStopMde_D_Rq"] == 3 + + # gear + if self.CP.transmissionType == TransmissionType.automatic: + gear = self.shifter_values.get(cp.vl["Gear_Shift_by_Wire_FD1"]["TrnGear_D_RqDrv"], None) + ret.gearShifter = self.parse_gear_shifter(gear) + elif self.CP.transmissionType == TransmissionType.manual: + ret.clutchPressed = cp.vl["Engine_Clutch_Data"]["CluPdlPos_Pc_Meas"] > 0 + if bool(cp.vl["BCM_Lamp_Stat_FD1"]["RvrseLghtOn_B_Stat"]): + ret.gearShifter = GearShifter.reverse + else: + ret.gearShifter = GearShifter.drive + + # safety + ret.stockFcw = bool(cp_cam.vl["ACCDATA_3"]["FcwVisblWarn_B_Rq"]) + ret.stockAeb = ret.stockFcw and ret.cruiseState.enabled + + # button presses + ret.leftBlinker = cp.vl["Steering_Data_FD1"]["TurnLghtSwtch_D_Stat"] == 1 + ret.rightBlinker = cp.vl["Steering_Data_FD1"]["TurnLghtSwtch_D_Stat"] == 2 + # TODO: block this going to the camera otherwise it will enable stock TJA + ret.genericToggle = bool(cp.vl["Steering_Data_FD1"]["TjaButtnOnOffPress"]) + + # lock info + ret.doorOpen = any([cp.vl["BodyInfo_3_FD1"]["DrStatDrv_B_Actl"], cp.vl["BodyInfo_3_FD1"]["DrStatPsngr_B_Actl"], + cp.vl["BodyInfo_3_FD1"]["DrStatRl_B_Actl"], cp.vl["BodyInfo_3_FD1"]["DrStatRr_B_Actl"]]) + ret.seatbeltUnlatched = cp.vl["RCMStatusMessage2_FD1"]["FirstRowBuckleDriver"] == 2 + + # blindspot sensors + if self.CP.enableBsm: + ret.leftBlindspot = cp.vl["Side_Detect_L_Stat"]["SodDetctLeft_D_Stat"] != 0 + ret.rightBlindspot = cp.vl["Side_Detect_R_Stat"]["SodDetctRight_D_Stat"] != 0 + + # Stock steering buttons so that we can passthru blinkers etc. + self.buttons_stock_values = cp.vl["Steering_Data_FD1"] + # Stock values from IPMA so that we can retain some stock functionality + self.acc_tja_status_stock_values = cp_cam.vl["ACCDATA_3"] + self.lkas_status_stock_values = cp_cam.vl["IPMA_Data"] return ret @@ -40,19 +92,164 @@ class CarState(CarStateBase): def get_can_parser(CP): signals = [ # sig_name, sig_address - ("WhlRr_W_Meas", "WheelSpeed_CG1"), - ("WhlRl_W_Meas", "WheelSpeed_CG1"), - ("WhlFr_W_Meas", "WheelSpeed_CG1"), - ("WhlFl_W_Meas", "WheelSpeed_CG1"), - ("SteWhlRelInit_An_Sns", "Steering_Wheel_Data_CG1"), - ("Cruise_State", "Cruise_Status"), - ("Set_Speed", "Cruise_Status"), - ("LaActAvail_D_Actl", "Lane_Keep_Assist_Status"), - ("LaHandsOff_B_Actl", "Lane_Keep_Assist_Status"), - ("LaActDeny_B_Actl", "Lane_Keep_Assist_Status"), - ("ApedPosScal_Pc_Actl", "EngineData_14"), - ("Dist_Incr", "Steering_Buttons"), - ("Brake_Drv_Appl", "Cruise_Status"), + ("Veh_V_ActlBrk", "BrakeSysFeatures"), # ABS vehicle speed (kph) + ("VehYaw_W_Actl", "Yaw_Data_FD1"), # ABS vehicle yaw rate (rad/s) + ("VehStop_D_Stat", "DesiredTorqBrk"), # ABS vehicle stopped + ("PrkBrkStatus", "DesiredTorqBrk"), # ABS park brake status + ("ApedPos_Pc_ActlArb", "EngVehicleSpThrottle"), # PCM throttle (pct) + ("BrkTot_Tq_Actl", "BrakeSnData_4"), # ABS brake torque (Nm) + ("BpedDrvAppl_D_Actl", "EngBrakeData"), # PCM driver brake pedal pressed + ("Veh_V_DsplyCcSet", "EngBrakeData"), # PCM ACC set speed (mph) + # The units might change with IPC settings? + ("CcStat_D_Actl", "EngBrakeData"), # PCM ACC status + ("AccStopMde_D_Rq", "EngBrakeData"), # PCM ACC standstill + ("AccEnbl_B_RqDrv", "Cluster_Info1_FD1"), # PCM ACC enable + ("StePinComp_An_Est", "SteeringPinion_Data"), # PSCM estimated steering angle (deg) + # Calculates steering angle (and offset) from pinion + # angle and driving measurements. + # StePinRelInit_An_Sns is the pinion angle, initialised + # to zero at the beginning of the drive. + ("SteeringColumnTorque", "EPAS_INFO"), # PSCM steering column torque (Nm) + ("EPAS_Failure", "EPAS_INFO"), # PSCM EPAS status + ("TurnLghtSwtch_D_Stat", "Steering_Data_FD1"), # SCCM Turn signal switch + ("TjaButtnOnOffPress", "Steering_Data_FD1"), # SCCM ACC button, lane-centering/traffic jam assist toggle + ("DrStatDrv_B_Actl", "BodyInfo_3_FD1"), # BCM Door open, driver + ("DrStatPsngr_B_Actl", "BodyInfo_3_FD1"), # BCM Door open, passenger + ("DrStatRl_B_Actl", "BodyInfo_3_FD1"), # BCM Door open, rear left + ("DrStatRr_B_Actl", "BodyInfo_3_FD1"), # BCM Door open, rear right + ("FirstRowBuckleDriver", "RCMStatusMessage2_FD1"), # RCM Seatbelt status, driver + ("HeadLghtHiFlash_D_Stat", "Steering_Data_FD1"), # SCCM Passthru the remaining buttons + ("WiprFront_D_Stat", "Steering_Data_FD1"), + ("LghtAmb_D_Sns", "Steering_Data_FD1"), + ("AccButtnGapDecPress", "Steering_Data_FD1"), + ("AccButtnGapIncPress", "Steering_Data_FD1"), + ("AslButtnOnOffCnclPress", "Steering_Data_FD1"), + ("AslButtnOnOffPress", "Steering_Data_FD1"), + ("CcAslButtnCnclPress", "Steering_Data_FD1"), + ("LaSwtchPos_D_Stat", "Steering_Data_FD1"), + ("CcAslButtnCnclResPress", "Steering_Data_FD1"), + ("CcAslButtnDeny_B_Actl", "Steering_Data_FD1"), + ("CcAslButtnIndxDecPress", "Steering_Data_FD1"), + ("CcAslButtnIndxIncPress", "Steering_Data_FD1"), + ("CcAslButtnOffCnclPress", "Steering_Data_FD1"), + ("CcAslButtnOnOffCncl", "Steering_Data_FD1"), + ("CcAslButtnOnPress", "Steering_Data_FD1"), + ("CcAslButtnResDecPress", "Steering_Data_FD1"), + ("CcAslButtnResIncPress", "Steering_Data_FD1"), + ("CcAslButtnSetDecPress", "Steering_Data_FD1"), + ("CcAslButtnSetIncPress", "Steering_Data_FD1"), + ("CcAslButtnSetPress", "Steering_Data_FD1"), + ("CcAsllButtnResPress", "Steering_Data_FD1"), + ("CcButtnOffPress", "Steering_Data_FD1"), + ("CcButtnOnOffCnclPress", "Steering_Data_FD1"), + ("CcButtnOnOffPress", "Steering_Data_FD1"), + ("CcButtnOnPress", "Steering_Data_FD1"), + ("HeadLghtHiFlash_D_Actl", "Steering_Data_FD1"), + ("HeadLghtHiOn_B_StatAhb", "Steering_Data_FD1"), + ("AhbStat_B_Dsply", "Steering_Data_FD1"), + ("AccButtnGapTogglePress", "Steering_Data_FD1"), + ("WiprFrontSwtch_D_Stat", "Steering_Data_FD1"), + ("HeadLghtHiCtrl_D_RqAhb", "Steering_Data_FD1"), + ] + + checks = [ + # sig_address, frequency + ("BrakeSysFeatures", 50), + ("Yaw_Data_FD1", 100), + ("DesiredTorqBrk", 50), + ("EngVehicleSpThrottle", 100), + ("BrakeSnData_4", 50), + ("EngBrakeData", 10), + ("Cluster_Info1_FD1", 10), + ("SteeringPinion_Data", 100), + ("EPAS_INFO", 50), + ("Lane_Assist_Data3_FD1", 33), + ("Steering_Data_FD1", 10), + ("BodyInfo_3_FD1", 2), + ("RCMStatusMessage2_FD1", 10), + ] + + if CP.transmissionType == TransmissionType.automatic: + signals += [ + ("TrnGear_D_RqDrv", "Gear_Shift_by_Wire_FD1"), # GWM transmission gear position + ] + checks += [ + ("Gear_Shift_by_Wire_FD1", 10), + ] + elif CP.transmissionType == TransmissionType.manual: + signals += [ + ("CluPdlPos_Pc_Meas", "Engine_Clutch_Data"), # PCM clutch (pct) + ("RvrseLghtOn_B_Stat", "BCM_Lamp_Stat_FD1"), # BCM reverse light + ] + checks += [ + ("Engine_Clutch_Data", 33), + ("BCM_Lamp_Stat_FD1", 1), + ] + + if CP.enableBsm: + signals += [ + ("SodDetctLeft_D_Stat", "Side_Detect_L_Stat"), # Blindspot sensor, left + ("SodDetctRight_D_Stat", "Side_Detect_R_Stat"), # Blindspot sensor, right + ] + checks += [ + ("Side_Detect_L_Stat", 5), + ("Side_Detect_R_Stat", 5), + ] + + return CANParser(DBC[CP.carFingerprint]["pt"], signals, checks, CANBUS.main) + + @staticmethod + def get_cam_can_parser(CP): + signals = [ + # sig_name, sig_address + ("HaDsply_No_Cs", "ACCDATA_3"), + ("HaDsply_No_Cnt", "ACCDATA_3"), + ("AccStopStat_D_Dsply", "ACCDATA_3"), # ACC stopped status message + ("AccTrgDist2_D_Dsply", "ACCDATA_3"), # ACC target distance + ("AccStopRes_B_Dsply", "ACCDATA_3"), + ("TjaWarn_D_Rq", "ACCDATA_3"), # TJA warning + ("Tja_D_Stat", "ACCDATA_3"), # TJA status + ("TjaMsgTxt_D_Dsply", "ACCDATA_3"), # TJA text + ("IaccLamp_D_Rq", "ACCDATA_3"), # iACC status icon + ("AccMsgTxt_D2_Rq", "ACCDATA_3"), # ACC text + ("FcwDeny_B_Dsply", "ACCDATA_3"), # FCW disabled + ("FcwMemStat_B_Actl", "ACCDATA_3"), # FCW enabled setting + ("AccTGap_B_Dsply", "ACCDATA_3"), # ACC time gap display setting + ("CadsAlignIncplt_B_Actl", "ACCDATA_3"), + ("AccFllwMde_B_Dsply", "ACCDATA_3"), # ACC follow mode display setting + ("CadsRadrBlck_B_Actl", "ACCDATA_3"), + ("CmbbPostEvnt_B_Dsply", "ACCDATA_3"), # AEB event status + ("AccStopMde_B_Dsply", "ACCDATA_3"), # ACC stop mode display setting + ("FcwMemSens_D_Actl", "ACCDATA_3"), # FCW sensitivity setting + ("FcwMsgTxt_D_Rq", "ACCDATA_3"), # FCW text + ("AccWarn_D_Dsply", "ACCDATA_3"), # ACC warning + ("FcwVisblWarn_B_Rq", "ACCDATA_3"), # FCW visible alert + ("FcwAudioWarn_B_Rq", "ACCDATA_3"), # FCW audio alert + ("AccTGap_D_Dsply", "ACCDATA_3"), # ACC time gap + ("AccMemEnbl_B_RqDrv", "ACCDATA_3"), # ACC adaptive/normal setting + ("FdaMem_B_Stat", "ACCDATA_3"), # FDA enabled setting + + ("FeatConfigIpmaActl", "IPMA_Data"), + ("FeatNoIpmaActl", "IPMA_Data"), + ("PersIndexIpma_D_Actl", "IPMA_Data"), + ("AhbcRampingV_D_Rq", "IPMA_Data"), # AHB ramping + ("LaActvStats_D_Dsply", "IPMA_Data"), # LKAS status (lines) + ("LaDenyStats_B_Dsply", "IPMA_Data"), # LKAS error + ("LaHandsOff_D_Dsply", "IPMA_Data"), # LKAS hands on chime + ("CamraDefog_B_Req", "IPMA_Data"), # Windshield heater? + ("CamraStats_D_Dsply", "IPMA_Data"), # Camera status + ("DasAlrtLvl_D_Dsply", "IPMA_Data"), # DAS alert level + ("DasStats_D_Dsply", "IPMA_Data"), # DAS status + ("DasWarn_D_Dsply", "IPMA_Data"), # DAS warning + ("AhbHiBeam_D_Rq", "IPMA_Data"), # AHB status + ("Passthru_63", "IPMA_Data"), + ("Passthru_48", "IPMA_Data"), ] - checks = [] - return CANParser(DBC[CP.carFingerprint]["pt"], signals, checks, 0, enforce_checks=False) + + checks = [ + # sig_address, frequency + ("ACCDATA_3", 5), + ("IPMA_Data", 1), + ] + + return CANParser(DBC[CP.carFingerprint]["pt"], signals, checks, CANBUS.camera) diff --git a/selfdrive/car/ford/fordcan.py b/selfdrive/car/ford/fordcan.py index 5a8b0b2dec..373ce096c6 100644 --- a/selfdrive/car/ford/fordcan.py +++ b/selfdrive/car/ford/fordcan.py @@ -1,50 +1,164 @@ -from common.numpy_fast import clip -from selfdrive.car.ford.values import MAX_ANGLE +from cereal import car +from selfdrive.car.ford.values import CANBUS +HUDControl = car.CarControl.HUDControl -def create_steer_command(packer, angle_cmd, enabled, lkas_state, angle_steers, curvature, lkas_action): - """Creates a CAN message for the Ford Steer Command.""" - #if enabled and lkas available: - if enabled and lkas_state in (2, 3): # and (frame % 500) >= 3: - action = lkas_action +def create_lka_command(packer, angle_deg: float, curvature: float): + """ + Creates a CAN message for the Ford LKAS Command. + + This command can apply "Lane Keeping Aid" manoeuvres, which are subject to the PSCM lockout. + + Frequency is 20Hz. + """ + + values = { + "LkaDrvOvrrd_D_Rq": 0, # driver override level? [0|3] + "LkaActvStats_D2_Req": 0, # action [0|7] + "LaRefAng_No_Req": angle_deg, # angle [-102.4|102.3] degrees + "LaRampType_B_Req": 0, # Ramp speed: 0=Smooth, 1=Quick + "LaCurvature_No_Calc": curvature, # curvature [-0.01024|0.01023] 1/meter + "LdwActvStats_D_Req": 0, # LDW status [0|7] + "LdwActvIntns_D_Req": 0, # LDW intensity [0|3], shake alert strength + } + return packer.make_can_msg("Lane_Assist_Data1", CANBUS.main, values) + + +def create_tja_command(packer, lca_rq: int, ramp_type: int, precision: int, path_offset: float, path_angle: float, curvature_rate: float, curvature: float): + """ + Creates a CAN message for the Ford TJA/LCA Command. + + This command can apply "Lane Centering" manoeuvres: continuous lane centering for traffic jam + assist and highway driving. It is not subject to the PSCM lockout. + + Ford lane centering command uses a third order polynomial to describe the road centerline. The + polynomial is defined by the following coefficients: + c0: lateral offset between the vehicle and the centerline + c1: heading angle between the vehicle and the centerline + c2: curvature of the centerline + c3: rate of change of curvature of the centerline + As the PSCM combines this information with other sensor data, such as the vehicle's yaw rate and + speed, the steering angle cannot be easily controlled. + + The PSCM should be configured to accept TJA/LCA commands before these commands will be processed. + This can be done using tools such as Forscan. + + Frequency is 20Hz. + """ + + values = { + "LatCtlRng_L_Max": 0, # Unknown [0|126] meter + "HandsOffCnfm_B_Rq": 0, # Unknown: 0=Inactive, 1=Active [0|1] + "LatCtl_D_Rq": lca_rq, # Mode: 0=None, 1=ContinuousPathFollowing, 2=InterventionLeft, 3=InterventionRight, 4-7=NotUsed [0|7] + "LatCtlRampType_D_Rq": ramp_type, # Ramp speed: 0=Slow, 1=Medium, 2=Fast, 3=Immediate [0|3] + "LatCtlPrecision_D_Rq": precision, # Precision: 0=Comfortable, 1=Precise, 2/3=NotUsed [0|3] + "LatCtlPathOffst_L_Actl": path_offset, # Path offset [-5.12|5.11] meter + "LatCtlPath_An_Actl": path_angle, # Path angle [-0.5|0.5235] radians + "LatCtlCurv_NoRate_Actl": curvature_rate, # Curvature rate [-0.001024|0.00102375] 1/meter^2 + "LatCtlCurv_No_Actl": curvature, # Curvature [-0.02|0.02094] 1/meter + } + return packer.make_can_msg("LateralMotionControl", CANBUS.main, values) + + +def create_lkas_ui_command(packer, main_on: bool, enabled: bool, steer_alert: bool, hud_control, stock_values: dict): + """ + Creates a CAN message for the Ford IPC IPMA/LKAS status. + + Show the LKAS status with the "driver assist" lines in the IPC. + + Stock functionality is maintained by passing through unmodified signals. + + Frequency is 1Hz. + """ + + # LaActvStats_D_Dsply + # R Intvn Warn Supprs Avail No + # L + # Intvn 24 19 14 9 4 + # Warn 23 18 13 8 3 + # Supprs 22 17 12 7 2 + # Avail 21 16 11 6 1 + # No 20 15 10 5 0 + # + # TODO: test suppress state + if enabled: + lines = 0 # NoLeft_NoRight + if hud_control.leftLaneDepart: + lines += 4 + elif hud_control.leftLaneVisible: + lines += 1 + if hud_control.rightLaneDepart: + lines += 20 + elif hud_control.rightLaneVisible: + lines += 5 + elif main_on: + lines = 0 else: - action = 0xf - angle_cmd = angle_steers/MAX_ANGLE + if hud_control.leftLaneDepart: + lines = 3 # WarnLeft_NoRight + elif hud_control.rightLaneDepart: + lines = 15 # NoLeft_WarnRight + else: + lines = 30 # LA_Off - angle_cmd = clip(angle_cmd * MAX_ANGLE, - MAX_ANGLE, MAX_ANGLE) + # TODO: use level 1 for no sound when less severe? + hands_on_wheel_dsply = 2 if steer_alert else 0 values = { - "Lkas_Action": action, - "Lkas_Alert": 0xf, # no alerts - "Lane_Curvature": clip(curvature, -0.01, 0.01), # is it just for debug? - #"Lane_Curvature": 0, # is it just for debug? - "Steer_Angle_Req": angle_cmd + **stock_values, + "LaActvStats_D_Dsply": lines, # LKAS status (lines) [0|31] + "LaHandsOff_D_Dsply": hands_on_wheel_dsply, # 0=HandsOn, 1=Level1 (w/o chime), 2=Level2 (w/ chime), 3=Suppressed } - return packer.make_can_msg("Lane_Keep_Assist_Control", 0, values) + return packer.make_can_msg("IPMA_Data", CANBUS.main, values) + + +def create_acc_ui_command(packer, main_on: bool, enabled: bool, hud_control, stock_values: dict): + """ + Creates a CAN message for the Ford IPC adaptive cruise, forward collision warning and traffic jam + assist status. + Stock functionality is maintained by passing through unmodified signals. -def create_lkas_ui(packer, main_on, enabled, steer_alert): - """Creates a CAN message for the Ford Steer Ui.""" + Frequency is 20Hz. + """ - if not main_on: - lines = 0xf - elif enabled: - lines = 0x3 + # Tja_D_Stat + if enabled: + if hud_control.leftLaneDepart: + status = 3 # ActiveInterventionLeft + elif hud_control.rightLaneDepart: + status = 4 # ActiveInterventionRight + else: + status = 2 # Active + elif main_on: + if hud_control.leftLaneDepart: + status = 5 # ActiveWarningLeft + elif hud_control.rightLaneDepart: + status = 6 # ActiveWarningRight + else: + status = 1 # Standby else: - lines = 0x6 + status = 0 # Off values = { - "Set_Me_X80": 0x80, - "Set_Me_X45": 0x45, - "Set_Me_X30": 0x30, - "Lines_Hud": lines, - "Hands_Warning_W_Chime": steer_alert, + **stock_values, + "Tja_D_Stat": status, } - return packer.make_can_msg("Lane_Keep_Assist_Ui", 0, values) + return packer.make_can_msg("ACCDATA_3", CANBUS.main, values) + + +def create_button_command(packer, stock_values: dict, cancel = False, resume = False, tja_toggle = False, bus: int = CANBUS.camera): + """ + Creates a CAN message for the Ford SCCM buttons/switches. + + Includes cruise control buttons, turn lights and more. + """ -def spam_cancel_button(packer): values = { - "Cancel": 1 + **stock_values, + "CcAslButtnCnclPress": 1 if cancel else 0, # CC cancel button + "CcAsllButtnResPress": 1 if resume else 0, # CC resume button + "TjaButtnOnOffPress": 1 if tja_toggle else 0, # TJA toggle button } - return packer.make_can_msg("Steering_Buttons", 0, values) + return packer.make_can_msg("Steering_Data_FD1", bus, values) diff --git a/selfdrive/car/ford/interface.py b/selfdrive/car/ford/interface.py old mode 100755 new mode 100644 index 0faaa3f669..f3d77bc05a --- a/selfdrive/car/ford/interface.py +++ b/selfdrive/car/ford/interface.py @@ -1,70 +1,69 @@ #!/usr/bin/env python3 from cereal import car -from selfdrive.config import Conversions as CV -from selfdrive.car.ford.values import MAX_ANGLE -from selfdrive.car import STD_CARGO_KG, scale_rot_inertia, scale_tire_stiffness, gen_empty_fingerprint, get_safety_config +from common.conversions import Conversions as CV +from selfdrive.car import STD_CARGO_KG, get_safety_config +from selfdrive.car.ford.values import CAR, Ecu, TransmissionType, GearShifter from selfdrive.car.interfaces import CarInterfaceBase +CarParams = car.CarParams + class CarInterface(CarInterfaceBase): @staticmethod - def get_params(candidate, fingerprint=gen_empty_fingerprint(), car_fw=None): - ret = CarInterfaceBase.get_std_params(candidate, fingerprint) + def _get_params(ret, candidate, fingerprint, car_fw, experimental_long): ret.carName = "ford" - ret.safetyConfigs = [get_safety_config(car.CarParams.SafetyModel.ford)] ret.dashcamOnly = True + ret.safetyConfigs = [get_safety_config(CarParams.SafetyModel.ford)] - ret.wheelbase = 2.85 - ret.steerRatio = 14.8 - 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 - ret.steerActuatorDelay = 0.1 # Default delay, not measured yet + # Angle-based steering + ret.steerControlType = CarParams.SteerControlType.angle + ret.steerActuatorDelay = 0.4 ret.steerLimitTimer = 1.0 - ret.steerRateCost = 1.0 - ret.centerToFront = ret.wheelbase * 0.44 - tire_stiffness_factor = 0.5328 - # TODO: get actual value, for now starting with reasonable value for - # civic and scaling by mass and wheelbase - ret.rotationalInertia = scale_rot_inertia(ret.mass, ret.wheelbase) + if candidate == CAR.ESCAPE_MK4: + ret.wheelbase = 2.71 + ret.steerRatio = 14.3 # Copied from Focus + ret.mass = 1750 + STD_CARGO_KG - # TODO: start from empirically derived lateral slip stiffness for the civic and scale by - # mass and CG position, so all cars will have approximately similar dyn behaviors - ret.tireStiffnessFront, ret.tireStiffnessRear = scale_tire_stiffness(ret.mass, ret.wheelbase, ret.centerToFront, - tire_stiffness_factor=tire_stiffness_factor) + elif candidate == CAR.EXPLORER_MK6: + ret.wheelbase = 3.025 + ret.steerRatio = 16.8 # learned + ret.mass = 2050 + STD_CARGO_KG - ret.steerControlType = car.CarParams.SteerControlType.angle + elif candidate == CAR.FOCUS_MK4: + ret.wheelbase = 2.7 + ret.steerRatio = 13.8 # learned + ret.mass = 1350 + STD_CARGO_KG - return ret + else: + raise ValueError(f"Unsupported car: {candidate}") - # returns a car.CarState - def update(self, c, can_strings): - # ******************* do can recv ******************* - self.cp.update_strings(can_strings) + # Auto Transmission: 0x732 ECU or Gear_Shift_by_Wire_FD1 + found_ecus = [fw.ecu for fw in car_fw] + if Ecu.shiftByWire in found_ecus or 0x5A in fingerprint[0]: + ret.transmissionType = TransmissionType.automatic + else: + ret.transmissionType = TransmissionType.manual + ret.minEnableSpeed = 20.0 * CV.MPH_TO_MS - ret = self.CS.update(self.cp) + # BSM: Side_Detect_L_Stat, Side_Detect_R_Stat + # TODO: detect bsm in car_fw? + ret.enableBsm = 0x3A6 in fingerprint[0] and 0x3A7 in fingerprint[0] - ret.canValid = self.cp.can_valid + # LCA can steer down to zero + ret.minSteerSpeed = 0. - # events - events = self.create_common_events(ret) + ret.autoResumeSng = ret.minEnableSpeed == -1. + ret.centerToFront = ret.wheelbase * 0.44 + return ret - if self.CS.lkas_state not in (2, 3) and ret.vEgo > 13. * CV.MPH_TO_MS and ret.cruiseState.enabled: - events.add(car.CarEvent.EventName.steerTempUnavailable) + def _update(self, c): + ret = self.CS.update(self.cp, self.cp_cam) + events = self.create_common_events(ret, extra_gears=[GearShifter.manumatic]) ret.events = events.to_msg() - self.CS.out = ret.as_reader() - return self.CS.out + return ret - # pass in a car.CarControl - # to be called @ 100hz def apply(self, c): - - ret = self.CC.update(c.enabled, self.CS, self.frame, c.actuators, - c.hudControl.visualAlert, c.cruiseControl.cancel) - - self.frame += 1 - return ret + return self.CC.update(c, self.CS) diff --git a/selfdrive/car/ford/radar_interface.py b/selfdrive/car/ford/radar_interface.py old mode 100755 new mode 100644 index 94eb8bb0cc..c942703002 --- a/selfdrive/car/ford/radar_interface.py +++ b/selfdrive/car/ford/radar_interface.py @@ -1,32 +1,68 @@ #!/usr/bin/env python3 +from math import cos, sin from cereal import car from opendbc.can.parser import CANParser -from selfdrive.car.ford.values import DBC -from selfdrive.config import Conversions as CV +from common.conversions import Conversions as CV +from selfdrive.car.ford.values import CANBUS, DBC, RADAR from selfdrive.car.interfaces import RadarInterfaceBase -RADAR_MSGS = list(range(0x500, 0x540)) +DELPHI_ESR_RADAR_MSGS = list(range(0x500, 0x540)) +DELPHI_MRR_RADAR_START_ADDR = 0x120 +DELPHI_MRR_RADAR_MSG_COUNT = 64 -def _create_radar_can_parser(car_fingerprint): - msg_n = len(RADAR_MSGS) + +def _create_delphi_esr_radar_can_parser(): + msg_n = len(DELPHI_ESR_RADAR_MSGS) signals = list(zip(['X_Rel'] * msg_n + ['Angle'] * msg_n + ['V_Rel'] * msg_n, - RADAR_MSGS * 3)) - checks = list(zip(RADAR_MSGS, [20] * msg_n)) + DELPHI_ESR_RADAR_MSGS * 3)) + checks = list(zip(DELPHI_ESR_RADAR_MSGS, [20] * msg_n)) + + return CANParser(RADAR.DELPHI_ESR, signals, checks, CANBUS.radar) + + +def _create_delphi_mrr_radar_can_parser(): + signals = [] + checks = [] + + for i in range(1, DELPHI_MRR_RADAR_MSG_COUNT + 1): + msg = f"MRR_Detection_{i:03d}" + signals += [ + (f"CAN_DET_VALID_LEVEL_{i:02d}", msg), + (f"CAN_DET_AZIMUTH_{i:02d}", msg), + (f"CAN_DET_RANGE_{i:02d}", msg), + (f"CAN_DET_RANGE_RATE_{i:02d}", msg), + (f"CAN_DET_AMPLITUDE_{i:02d}", msg), + (f"CAN_SCAN_INDEX_2LSB_{i:02d}", msg), + ] + checks += [(msg, 20)] + + return CANParser(RADAR.DELPHI_MRR, signals, checks, CANBUS.radar) - return CANParser(DBC[car_fingerprint]['radar'], signals, checks, 1) class RadarInterface(RadarInterfaceBase): def __init__(self, CP): super().__init__(CP) - self.validCnt = {key: 0 for key in RADAR_MSGS} - self.track_id = 0 - self.rcp = _create_radar_can_parser(CP.carFingerprint) - self.trigger_msg = 0x53f self.updated_messages = set() + self.track_id = 0 + self.radar = DBC[CP.carFingerprint]['radar'] + if self.radar is None: + self.rcp = None + elif self.radar == RADAR.DELPHI_ESR: + self.rcp = _create_delphi_esr_radar_can_parser() + self.trigger_msg = DELPHI_ESR_RADAR_MSGS[-1] + self.valid_cnt = {key: 0 for key in DELPHI_ESR_RADAR_MSGS} + elif self.radar == RADAR.DELPHI_MRR: + self.rcp = _create_delphi_mrr_radar_can_parser() + self.trigger_msg = DELPHI_MRR_RADAR_START_ADDR + DELPHI_MRR_RADAR_MSG_COUNT - 1 + else: + raise ValueError(f"Unsupported radar: {self.radar}") def update(self, can_strings): + if self.rcp is None: + return super().update(None) + vls = self.rcp.update_strings(can_strings) self.updated_messages.update(vls) @@ -39,20 +75,30 @@ class RadarInterface(RadarInterfaceBase): errors.append("canError") ret.errors = errors + if self.radar == RADAR.DELPHI_ESR: + self._update_delphi_esr() + elif self.radar == RADAR.DELPHI_MRR: + self._update_delphi_mrr() + + ret.points = list(self.pts.values()) + self.updated_messages.clear() + return ret + + def _update_delphi_esr(self): for ii in sorted(self.updated_messages): cpt = self.rcp.vl[ii] if cpt['X_Rel'] > 0.00001: - self.validCnt[ii] = 0 # reset counter + self.valid_cnt[ii] = 0 # reset counter if cpt['X_Rel'] > 0.00001: - self.validCnt[ii] += 1 + self.valid_cnt[ii] += 1 else: - self.validCnt[ii] = max(self.validCnt[ii] - 1, 0) - #print ii, self.validCnt[ii], cpt['VALID'], cpt['X_Rel'], cpt['Angle'] + self.valid_cnt[ii] = max(self.valid_cnt[ii] - 1, 0) + #print ii, self.valid_cnt[ii], cpt['VALID'], cpt['X_Rel'], cpt['Angle'] # radar point only valid if there have been enough valid measurements - if self.validCnt[ii] > 0: + if self.valid_cnt[ii] > 0: if ii not in self.pts: self.pts[ii] = car.RadarData.RadarPoint.new_message() self.pts[ii].trackId = self.track_id @@ -67,6 +113,36 @@ class RadarInterface(RadarInterfaceBase): if ii in self.pts: del self.pts[ii] - ret.points = list(self.pts.values()) - self.updated_messages.clear() - return ret + def _update_delphi_mrr(self): + for ii in range(1, DELPHI_MRR_RADAR_MSG_COUNT + 1): + msg = self.rcp.vl[f"MRR_Detection_{ii:03d}"] + + # SCAN_INDEX rotates through 0..3 on each message + # treat these as separate points + scanIndex = msg[f"CAN_SCAN_INDEX_2LSB_{ii:02d}"] + i = (ii - 1) * 4 + scanIndex + + if i not in self.pts: + self.pts[i] = car.RadarData.RadarPoint.new_message() + self.pts[i].trackId = self.track_id + self.pts[i].aRel = float('nan') + self.pts[i].yvRel = float('nan') + self.track_id += 1 + + valid = bool(msg[f"CAN_DET_VALID_LEVEL_{ii:02d}"]) + amplitude = msg[f"CAN_DET_AMPLITUDE_{ii:02d}"] # dBsm [-64|63] + + if valid and 0 < amplitude <= 15: + azimuth = msg[f"CAN_DET_AZIMUTH_{ii:02d}"] # rad [-3.1416|3.13964] + dist = msg[f"CAN_DET_RANGE_{ii:02d}"] # m [0|255.984] + distRate = msg[f"CAN_DET_RANGE_RATE_{ii:02d}"] # m/s [-128|127.984] + + # *** openpilot radar point *** + self.pts[i].dRel = cos(azimuth) * dist # m from front of car + self.pts[i].yRel = -sin(azimuth) * dist # in car frame's y axis, left is positive + self.pts[i].vRel = distRate # m/s + + self.pts[i].measured = True + + else: + del self.pts[i] diff --git a/selfdrive/car/ford/values.py b/selfdrive/car/ford/values.py index e1e2206472..5114f8d065 100644 --- a/selfdrive/car/ford/values.py +++ b/selfdrive/car/ford/values.py @@ -1,12 +1,163 @@ -from selfdrive.car import dbc_dict +from collections import defaultdict, namedtuple +from dataclasses import dataclass +from enum import Enum +from typing import Dict, List, Union + from cereal import car +from selfdrive.car import dbc_dict +from selfdrive.car.docs_definitions import CarInfo, Harness +from selfdrive.car.fw_query_definitions import FwQueryConfig, Request, StdQueries + Ecu = car.CarParams.Ecu +TransmissionType = car.CarParams.TransmissionType +GearShifter = car.CarState.GearShifter + +AngleRateLimit = namedtuple('AngleRateLimit', ['speed_points', 'max_angle_diff_points']) + + +class CarControllerParams: + # Messages: Lane_Assist_Data1, LateralMotionControl + LKAS_STEER_STEP = 5 + # Message: IPMA_Data + LKAS_UI_STEP = 100 + # Message: ACCDATA_3 + ACC_UI_STEP = 5 + # Message: Steering_Data_FD1, but send twice as fast + BUTTONS_STEP = 10 / 2 + + LKAS_STEER_RATIO = 2.75 # Approximate ratio between LatCtlPath_An_Actl and steering angle in radians + # TODO: remove this once we understand how the EPS calculates the steering angle better + STEER_DRIVER_ALLOWANCE = 0.8 # Driver intervention threshold in Nm + + RATE_LIMIT_UP = AngleRateLimit(speed_points=[0., 5., 15.], max_angle_diff_points=[5., .8, .15]) + RATE_LIMIT_DOWN = AngleRateLimit(speed_points=[0., 5., 15.], max_angle_diff_points=[5., 3.5, 0.4]) + + +class CANBUS: + main = 0 + radar = 1 + camera = 2 -MAX_ANGLE = 87. # make sure we never command the extremes (0xfff) which cause latching fault class CAR: - FUSION = "FORD FUSION 2018" + ESCAPE_MK4 = "FORD ESCAPE 4TH GEN" + EXPLORER_MK6 = "FORD EXPLORER 6TH GEN" + FOCUS_MK4 = "FORD FOCUS 4TH GEN" + + +class RADAR: + DELPHI_ESR = 'ford_fusion_2018_adas' + DELPHI_MRR = 'FORD_CADS' + + +DBC: Dict[str, Dict[str, str]] = defaultdict(lambda: dbc_dict("ford_lincoln_base_pt", RADAR.DELPHI_MRR)) + + +@dataclass +class FordCarInfo(CarInfo): + package: str = "Co-Pilot360 Assist+" + harness: Enum = Harness.ford_q3 + + +CAR_INFO: Dict[str, Union[CarInfo, List[CarInfo]]] = { + CAR.ESCAPE_MK4: [ + FordCarInfo("Ford Escape 2020-21"), + FordCarInfo("Ford Kuga 2020-21", "Driver Assistance Pack"), + ], + CAR.EXPLORER_MK6: FordCarInfo("Ford Explorer 2020-22"), + CAR.FOCUS_MK4: FordCarInfo("Ford Focus EU 2019", "Driver Assistance Pack"), +} + +FW_QUERY_CONFIG = FwQueryConfig( + requests=[ + Request( + [StdQueries.TESTER_PRESENT_REQUEST, StdQueries.MANUFACTURER_SOFTWARE_VERSION_REQUEST], + [StdQueries.TESTER_PRESENT_RESPONSE, StdQueries.MANUFACTURER_SOFTWARE_VERSION_RESPONSE], + whitelist_ecus=[Ecu.engine], + ), + Request( + [StdQueries.TESTER_PRESENT_REQUEST, StdQueries.MANUFACTURER_SOFTWARE_VERSION_REQUEST], + [StdQueries.TESTER_PRESENT_RESPONSE, StdQueries.MANUFACTURER_SOFTWARE_VERSION_RESPONSE], + bus=0, + whitelist_ecus=[Ecu.eps, Ecu.abs, Ecu.fwdRadar, Ecu.fwdCamera, Ecu.shiftByWire], + ), + ], +) -DBC = { - CAR.FUSION: dbc_dict('ford_fusion_2018_pt', 'ford_fusion_2018_adas'), +FW_VERSIONS = { + CAR.ESCAPE_MK4: { + (Ecu.eps, 0x730, None): [ + b'LX6C-14D003-AF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'LX6C-14D003-AH\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + ], + (Ecu.abs, 0x760, None): [ + b'LX6C-2D053-NS\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'LX6C-2D053-NY\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'LX6C-2D053-SA\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + ], + (Ecu.fwdRadar, 0x764, None): [ + b'LB5T-14D049-AB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + ], + (Ecu.fwdCamera, 0x706, None): [ + b'LJ6T-14F397-AD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'LJ6T-14F397-AE\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + ], + (Ecu.engine, 0x7E0, None): [ + b'LX6A-14C204-BJV\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'LX6A-14C204-ESG\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'MX6A-14C204-BEF\x00\x00\x00\x00\x00\x00\x00\x00\x00', + ], + (Ecu.shiftByWire, 0x732, None): [ + b'LX6P-14G395-AB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'LX6P-14G395-AD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + ], + }, + CAR.EXPLORER_MK6: { + (Ecu.eps, 0x730, None): [ + b'L1MC-14D003-AK\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'L1MC-14D003-AL\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'M1MC-14D003-AB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + ], + (Ecu.abs, 0x760, None): [ + b'L1MC-2D053-BB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'L1MC-2D053-BF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'L1MC-2D053-KB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + ], + (Ecu.fwdRadar, 0x764, None): [ + b'LB5T-14D049-AB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + ], + (Ecu.fwdCamera, 0x706, None): [ + b'LB5T-14F397-AE\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'LB5T-14F397-AF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + ], + (Ecu.engine, 0x7E0, None): [ + b'LB5A-14C204-EAC\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'MB5A-14C204-MD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'NB5A-14C204-HB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + ], + (Ecu.shiftByWire, 0x732, None): [ + b'L1MP-14G395-AD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'L1MP-14G395-AE\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'L1MP-14G395-JB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + ], + }, + CAR.FOCUS_MK4: { + (Ecu.eps, 0x730, None): [ + b'JX6C-14D003-AH\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + ], + (Ecu.abs, 0x760, None): [ + b'JX61-2D053-CJ\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + ], + (Ecu.fwdRadar, 0x764, None): [ + b'JX7T-14D049-AC\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + ], + (Ecu.fwdCamera, 0x706, None): [ + b'JX7T-14F397-AH\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + ], + (Ecu.engine, 0x7E0, None): [ + b'JX6A-14C204-BPL\x00\x00\x00\x00\x00\x00\x00\x00\x00', + ], + (Ecu.shiftByWire, 0x732, None): [ + ], + }, } diff --git a/selfdrive/car/fw_query_definitions.py b/selfdrive/car/fw_query_definitions.py new file mode 100755 index 0000000000..c7e4d4eb30 --- /dev/null +++ b/selfdrive/car/fw_query_definitions.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 +import capnp +from dataclasses import dataclass, field +import struct +from typing import Dict, List, Optional, Tuple + +import panda.python.uds as uds + + +def p16(val): + return struct.pack("!H", val) + + +class StdQueries: + # FW queries + TESTER_PRESENT_REQUEST = bytes([uds.SERVICE_TYPE.TESTER_PRESENT, 0x0]) + TESTER_PRESENT_RESPONSE = bytes([uds.SERVICE_TYPE.TESTER_PRESENT + 0x40, 0x0]) + + SHORT_TESTER_PRESENT_REQUEST = bytes([uds.SERVICE_TYPE.TESTER_PRESENT]) + SHORT_TESTER_PRESENT_RESPONSE = bytes([uds.SERVICE_TYPE.TESTER_PRESENT + 0x40]) + + DEFAULT_DIAGNOSTIC_REQUEST = bytes([uds.SERVICE_TYPE.DIAGNOSTIC_SESSION_CONTROL, + uds.SESSION_TYPE.DEFAULT]) + DEFAULT_DIAGNOSTIC_RESPONSE = bytes([uds.SERVICE_TYPE.DIAGNOSTIC_SESSION_CONTROL + 0x40, + uds.SESSION_TYPE.DEFAULT, 0x0, 0x32, 0x1, 0xf4]) + + EXTENDED_DIAGNOSTIC_REQUEST = bytes([uds.SERVICE_TYPE.DIAGNOSTIC_SESSION_CONTROL, + uds.SESSION_TYPE.EXTENDED_DIAGNOSTIC]) + EXTENDED_DIAGNOSTIC_RESPONSE = bytes([uds.SERVICE_TYPE.DIAGNOSTIC_SESSION_CONTROL + 0x40, + uds.SESSION_TYPE.EXTENDED_DIAGNOSTIC, 0x0, 0x32, 0x1, 0xf4]) + + MANUFACTURER_SOFTWARE_VERSION_REQUEST = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER]) + \ + p16(uds.DATA_IDENTIFIER_TYPE.VEHICLE_MANUFACTURER_ECU_SOFTWARE_NUMBER) + MANUFACTURER_SOFTWARE_VERSION_RESPONSE = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER + 0x40]) + \ + p16(uds.DATA_IDENTIFIER_TYPE.VEHICLE_MANUFACTURER_ECU_SOFTWARE_NUMBER) + + UDS_VERSION_REQUEST = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER]) + \ + p16(uds.DATA_IDENTIFIER_TYPE.APPLICATION_SOFTWARE_IDENTIFICATION) + UDS_VERSION_RESPONSE = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER + 0x40]) + \ + p16(uds.DATA_IDENTIFIER_TYPE.APPLICATION_SOFTWARE_IDENTIFICATION) + + OBD_VERSION_REQUEST = b'\x09\x04' + OBD_VERSION_RESPONSE = b'\x49\x04' + + # VIN queries + OBD_VIN_REQUEST = b'\x09\x02' + OBD_VIN_RESPONSE = b'\x49\x02\x01' + + UDS_VIN_REQUEST = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER]) + p16(uds.DATA_IDENTIFIER_TYPE.VIN) + UDS_VIN_RESPONSE = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER + 0x40]) + p16(uds.DATA_IDENTIFIER_TYPE.VIN) + + +@dataclass +class Request: + request: List[bytes] + response: List[bytes] + whitelist_ecus: List[int] = field(default_factory=list) + rx_offset: int = 0x8 + bus: int = 1 + + +@dataclass +class FwQueryConfig: + requests: List[Request] + # Overrides and removes from essential ecus for specific models and ecus (exact matching) + non_essential_ecus: Dict[capnp.lib.capnp._EnumModule, List[str]] = field(default_factory=dict) + # Ecus added for data collection, not to be fingerprinted on + extra_ecus: List[Tuple[capnp.lib.capnp._EnumModule, int, Optional[int]]] = field(default_factory=list) diff --git a/selfdrive/car/fw_versions.py b/selfdrive/car/fw_versions.py index 59fd4fe8a5..f4d92ab960 100755 --- a/selfdrive/car/fw_versions.py +++ b/selfdrive/car/fw_versions.py @@ -1,183 +1,24 @@ #!/usr/bin/env python3 -import struct -import traceback -from typing import Any from collections import defaultdict - +from typing import Any, Optional, Set, Tuple from tqdm import tqdm import panda.python.uds as uds from cereal import car -from selfdrive.car.fingerprints import FW_VERSIONS, get_attr_from_cars +from selfdrive.car.ecu_addrs import get_ecu_addrs +from selfdrive.car.interfaces import get_interface_attr +from selfdrive.car.fingerprints import FW_VERSIONS from selfdrive.car.isotp_parallel_query import IsoTpParallelQuery -from selfdrive.car.toyota.values import CAR as TOYOTA -from selfdrive.swaglog import cloudlog +from system.swaglog import cloudlog Ecu = car.CarParams.Ecu +ESSENTIAL_ECUS = [Ecu.engine, Ecu.eps, Ecu.abs, Ecu.fwdRadar, Ecu.fwdCamera, Ecu.vsa] +FW_QUERY_CONFIGS = get_interface_attr('FW_QUERY_CONFIG', ignore_none=True) +VERSIONS = get_interface_attr('FW_VERSIONS', ignore_none=True) -def p16(val): - return struct.pack("!H", val) - - -TESTER_PRESENT_REQUEST = bytes([uds.SERVICE_TYPE.TESTER_PRESENT, 0x0]) -TESTER_PRESENT_RESPONSE = bytes([uds.SERVICE_TYPE.TESTER_PRESENT + 0x40, 0x0]) - -SHORT_TESTER_PRESENT_REQUEST = bytes([uds.SERVICE_TYPE.TESTER_PRESENT]) -SHORT_TESTER_PRESENT_RESPONSE = bytes([uds.SERVICE_TYPE.TESTER_PRESENT + 0x40]) - -DEFAULT_DIAGNOSTIC_REQUEST = bytes([uds.SERVICE_TYPE.DIAGNOSTIC_SESSION_CONTROL, - uds.SESSION_TYPE.DEFAULT]) -DEFAULT_DIAGNOSTIC_RESPONSE = bytes([uds.SERVICE_TYPE.DIAGNOSTIC_SESSION_CONTROL + 0x40, - uds.SESSION_TYPE.DEFAULT, 0x0, 0x32, 0x1, 0xf4]) - -EXTENDED_DIAGNOSTIC_REQUEST = bytes([uds.SERVICE_TYPE.DIAGNOSTIC_SESSION_CONTROL, - uds.SESSION_TYPE.EXTENDED_DIAGNOSTIC]) -EXTENDED_DIAGNOSTIC_RESPONSE = bytes([uds.SERVICE_TYPE.DIAGNOSTIC_SESSION_CONTROL + 0x40, - uds.SESSION_TYPE.EXTENDED_DIAGNOSTIC, 0x0, 0x32, 0x1, 0xf4]) - -UDS_VERSION_REQUEST = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER]) + \ - p16(uds.DATA_IDENTIFIER_TYPE.APPLICATION_SOFTWARE_IDENTIFICATION) -UDS_VERSION_RESPONSE = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER + 0x40]) + \ - p16(uds.DATA_IDENTIFIER_TYPE.APPLICATION_SOFTWARE_IDENTIFICATION) - - -HYUNDAI_VERSION_REQUEST_LONG = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER]) + \ - p16(0xf100) # Long description -HYUNDAI_VERSION_REQUEST_MULTI = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER]) + \ - p16(uds.DATA_IDENTIFIER_TYPE.VEHICLE_MANUFACTURER_SPARE_PART_NUMBER) + \ - p16(uds.DATA_IDENTIFIER_TYPE.APPLICATION_SOFTWARE_IDENTIFICATION) + \ - p16(0xf100) -HYUNDAI_VERSION_RESPONSE = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER + 0x40]) - - -TOYOTA_VERSION_REQUEST = b'\x1a\x88\x01' -TOYOTA_VERSION_RESPONSE = b'\x5a\x88\x01' - -VOLKSWAGEN_VERSION_REQUEST_MULTI = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER]) + \ - p16(uds.DATA_IDENTIFIER_TYPE.VEHICLE_MANUFACTURER_SPARE_PART_NUMBER) + \ - p16(uds.DATA_IDENTIFIER_TYPE.VEHICLE_MANUFACTURER_ECU_SOFTWARE_VERSION_NUMBER) + \ - p16(uds.DATA_IDENTIFIER_TYPE.APPLICATION_DATA_IDENTIFICATION) -VOLKSWAGEN_VERSION_RESPONSE = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER + 0x40]) - -OBD_VERSION_REQUEST = b'\x09\x04' -OBD_VERSION_RESPONSE = b'\x49\x04' - -DEFAULT_RX_OFFSET = 0x8 -VOLKSWAGEN_RX_OFFSET = 0x6a - -MAZDA_VERSION_REQUEST = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER]) + \ - p16(uds.DATA_IDENTIFIER_TYPE.VEHICLE_MANUFACTURER_ECU_SOFTWARE_NUMBER) -MAZDA_VERSION_RESPONSE = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER + 0x40]) + \ - p16(uds.DATA_IDENTIFIER_TYPE.VEHICLE_MANUFACTURER_ECU_SOFTWARE_NUMBER) - -NISSAN_DIAGNOSTIC_REQUEST_KWP = bytes([uds.SERVICE_TYPE.DIAGNOSTIC_SESSION_CONTROL, 0xc0]) -NISSAN_DIAGNOSTIC_RESPONSE_KWP = bytes([uds.SERVICE_TYPE.DIAGNOSTIC_SESSION_CONTROL + 0x40, 0xc0]) - -NISSAN_VERSION_REQUEST_KWP = b'\x21\x83' -NISSAN_VERSION_RESPONSE_KWP = b'\x61\x83' - -NISSAN_VERSION_REQUEST_STANDARD = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER]) + \ - p16(uds.DATA_IDENTIFIER_TYPE.VEHICLE_MANUFACTURER_ECU_SOFTWARE_NUMBER) -NISSAN_VERSION_RESPONSE_STANDARD = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER + 0x40]) + \ - p16(uds.DATA_IDENTIFIER_TYPE.VEHICLE_MANUFACTURER_ECU_SOFTWARE_NUMBER) - -NISSAN_RX_OFFSET = 0x20 - -SUBARU_VERSION_REQUEST = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER]) + \ - p16(uds.DATA_IDENTIFIER_TYPE.APPLICATION_DATA_IDENTIFICATION) -SUBARU_VERSION_RESPONSE = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER + 0x40]) + \ - p16(uds.DATA_IDENTIFIER_TYPE.APPLICATION_DATA_IDENTIFICATION) - - -# brand, request, response, response offset -REQUESTS = [ - # Subaru - ( - "subaru", - [TESTER_PRESENT_REQUEST, SUBARU_VERSION_REQUEST], - [TESTER_PRESENT_RESPONSE, SUBARU_VERSION_RESPONSE], - DEFAULT_RX_OFFSET, - ), - # Hyundai - ( - "hyundai", - [HYUNDAI_VERSION_REQUEST_LONG], - [HYUNDAI_VERSION_RESPONSE], - DEFAULT_RX_OFFSET, - ), - ( - "hyundai", - [HYUNDAI_VERSION_REQUEST_MULTI], - [HYUNDAI_VERSION_RESPONSE], - DEFAULT_RX_OFFSET, - ), - # Honda - ( - "honda", - [UDS_VERSION_REQUEST], - [UDS_VERSION_RESPONSE], - DEFAULT_RX_OFFSET, - ), - # Toyota - ( - "toyota", - [SHORT_TESTER_PRESENT_REQUEST, TOYOTA_VERSION_REQUEST], - [SHORT_TESTER_PRESENT_RESPONSE, TOYOTA_VERSION_RESPONSE], - DEFAULT_RX_OFFSET, - ), - ( - "toyota", - [SHORT_TESTER_PRESENT_REQUEST, OBD_VERSION_REQUEST], - [SHORT_TESTER_PRESENT_RESPONSE, OBD_VERSION_RESPONSE], - DEFAULT_RX_OFFSET, - ), - ( - "toyota", - [TESTER_PRESENT_REQUEST, DEFAULT_DIAGNOSTIC_REQUEST, EXTENDED_DIAGNOSTIC_REQUEST, UDS_VERSION_REQUEST], - [TESTER_PRESENT_RESPONSE, DEFAULT_DIAGNOSTIC_RESPONSE, EXTENDED_DIAGNOSTIC_RESPONSE, UDS_VERSION_RESPONSE], - DEFAULT_RX_OFFSET, - ), - # Volkswagen - ( - "volkswagen", - [VOLKSWAGEN_VERSION_REQUEST_MULTI], - [VOLKSWAGEN_VERSION_RESPONSE], - VOLKSWAGEN_RX_OFFSET, - ), - ( - "volkswagen", - [VOLKSWAGEN_VERSION_REQUEST_MULTI], - [VOLKSWAGEN_VERSION_RESPONSE], - DEFAULT_RX_OFFSET, - ), - # Mazda - ( - "mazda", - [MAZDA_VERSION_REQUEST], - [MAZDA_VERSION_RESPONSE], - DEFAULT_RX_OFFSET, - ), - # Nissan - ( - "nissan", - [NISSAN_DIAGNOSTIC_REQUEST_KWP, NISSAN_VERSION_REQUEST_KWP], - [NISSAN_DIAGNOSTIC_RESPONSE_KWP, NISSAN_VERSION_RESPONSE_KWP], - DEFAULT_RX_OFFSET, - ), - ( - "nissan", - [NISSAN_DIAGNOSTIC_REQUEST_KWP, NISSAN_VERSION_REQUEST_KWP], - [NISSAN_DIAGNOSTIC_RESPONSE_KWP, NISSAN_VERSION_RESPONSE_KWP], - NISSAN_RX_OFFSET, - ), - ( - "nissan", - [NISSAN_VERSION_REQUEST_STANDARD], - [NISSAN_VERSION_RESPONSE_STANDARD], - NISSAN_RX_OFFSET, - ), -] +MODEL_TO_BRAND = {c: b for b, e in VERSIONS.items() for c in e} +REQUESTS = [(brand, r) for brand, config in FW_QUERY_CONFIGS.items() for r in config.requests] def chunks(l, n=128): @@ -185,13 +26,22 @@ def chunks(l, n=128): yield l[i:i + n] -def build_fw_dict(fw_versions): - fw_versions_dict = {} +def build_fw_dict(fw_versions, filter_brand=None): + fw_versions_dict = defaultdict(set) for fw in fw_versions: - addr = fw.address - sub_addr = fw.subAddress if fw.subAddress != 0 else None - fw_versions_dict[(addr, sub_addr)] = fw.fwVersion - return fw_versions_dict + if filter_brand is None or fw.brand == filter_brand: + addr = fw.address + sub_addr = fw.subAddress if fw.subAddress != 0 else None + fw_versions_dict[(addr, sub_addr)].add(fw.fwVersion) + return dict(fw_versions_dict) + + +def get_brand_addrs(): + brand_addrs = defaultdict(set) + for brand, cars in VERSIONS.items(): + for fw in cars.values(): + brand_addrs[brand] |= {(addr, sub_addr) for _, addr, sub_addr in fw.keys()} + return brand_addrs def match_fw_to_car_fuzzy(fw_versions_dict, log=True, exclude=None): @@ -203,9 +53,9 @@ def match_fw_to_car_fuzzy(fw_versions_dict, log=True, exclude=None): # Getting this exactly right isn't crucial, but excluding camera and radar makes it almost # impossible to get 3 matching versions, even if two models with shared parts are released at the same # time and only one is in our database. - exclude_types = [Ecu.fwdCamera, Ecu.fwdRadar, Ecu.eps] + exclude_types = [Ecu.fwdCamera, Ecu.fwdRadar, Ecu.eps, Ecu.debug] - # Build lookup table from (addr, subaddr, fw) to list of candidate cars + # Build lookup table from (addr, sub_addr, fw) to list of candidate cars all_fw_versions = defaultdict(list) for candidate, fw_by_addr in FW_VERSIONS.items(): if candidate == exclude: @@ -219,17 +69,18 @@ def match_fw_to_car_fuzzy(fw_versions_dict, log=True, exclude=None): match_count = 0 candidate = None - for addr, version in fw_versions_dict.items(): - # All cars that have this FW response on the specified address - candidates = all_fw_versions[(addr[0], addr[1], version)] - - if len(candidates) == 1: - match_count += 1 - if candidate is None: - candidate = candidates[0] - # We uniquely matched two different cars. No fuzzy match possible - elif candidate != candidates[0]: - return set() + for addr, versions in fw_versions_dict.items(): + for version in versions: + # All cars that have this FW response on the specified address + candidates = all_fw_versions[(addr[0], addr[1], version)] + + if len(candidates) == 1: + match_count += 1 + if candidate is None: + candidate = candidates[0] + # We uniquely matched two different cars. No fuzzy match possible + elif candidate != candidates[0]: + return set() if match_count >= 2: if log: @@ -249,61 +100,142 @@ def match_fw_to_car_exact(fw_versions_dict): for candidate, fws in candidates.items(): for ecu, expected_versions in fws.items(): + config = FW_QUERY_CONFIGS[MODEL_TO_BRAND[candidate]] ecu_type = ecu[0] addr = ecu[1:] - found_version = fw_versions_dict.get(addr, None) - ESSENTIAL_ECUS = [Ecu.engine, Ecu.eps, Ecu.esp, Ecu.fwdRadar, Ecu.fwdCamera, Ecu.vsa] - if ecu_type == Ecu.esp and candidate in (TOYOTA.RAV4, TOYOTA.COROLLA, TOYOTA.HIGHLANDER, TOYOTA.SIENNA, TOYOTA.LEXUS_IS) and found_version is None: - continue - # On some Toyota models, the engine can show on two different addresses - if ecu_type == Ecu.engine and candidate in (TOYOTA.CAMRY, TOYOTA.COROLLA_TSS2, TOYOTA.CHR, TOYOTA.LEXUS_IS) and found_version is None: - continue + found_versions = fw_versions_dict.get(addr, set()) + if not len(found_versions): + # Some models can sometimes miss an ecu, or show on two different addresses + if candidate in config.non_essential_ecus.get(ecu_type, []): + continue - # Ignore non essential ecus - if ecu_type not in ESSENTIAL_ECUS and found_version is None: + # Ignore non essential ecus + if ecu_type not in ESSENTIAL_ECUS: + continue + + # Virtual debug ecu doesn't need to match the database + if ecu_type == Ecu.debug: continue - if found_version not in expected_versions: + if not any([found_version in expected_versions for found_version in found_versions]): invalid.append(candidate) break return set(candidates.keys()) - set(invalid) -def match_fw_to_car(fw_versions, allow_fuzzy=True): - fw_versions_dict = build_fw_dict(fw_versions) - matches = match_fw_to_car_exact(fw_versions_dict) +def match_fw_to_car(fw_versions, allow_exact=True, allow_fuzzy=True): + # Try exact matching first + exact_matches = [] + if allow_exact: + exact_matches = [(True, match_fw_to_car_exact)] + if allow_fuzzy: + exact_matches.append((False, match_fw_to_car_fuzzy)) + + for exact_match, match_func in exact_matches: + # For each brand, attempt to fingerprint using all FW returned from its queries + matches = set() + for brand in VERSIONS.keys(): + fw_versions_dict = build_fw_dict(fw_versions, filter_brand=brand) + matches |= match_func(fw_versions_dict) + + if len(matches): + return exact_match, matches + + return True, set() + + +def get_present_ecus(logcan, sendcan): + queries = list() + parallel_queries = list() + responses = set() + + for brand, r in REQUESTS: + for brand_versions in VERSIONS[brand].values(): + for ecu_type, addr, sub_addr in brand_versions: + # Only query ecus in whitelist if whitelist is not empty + if len(r.whitelist_ecus) == 0 or ecu_type in r.whitelist_ecus: + a = (addr, sub_addr, r.bus) + # Build set of queries + if sub_addr is None: + if a not in parallel_queries: + parallel_queries.append(a) + else: # subaddresses must be queried one by one + if [a] not in queries: + queries.append([a]) + + # Build set of expected responses to filter + response_addr = uds.get_rx_addr_for_tx_addr(addr, r.rx_offset) + responses.add((response_addr, sub_addr, r.bus)) + + queries.insert(0, parallel_queries) + + ecu_responses: Set[Tuple[int, Optional[int], int]] = set() + for query in queries: + ecu_responses.update(get_ecu_addrs(logcan, sendcan, set(query), responses, timeout=0.1)) + return ecu_responses + + +def get_brand_ecu_matches(ecu_rx_addrs): + """Returns dictionary of brands and matches with ECUs in their FW versions""" + + brand_addrs = get_brand_addrs() + brand_matches = {brand: set() for brand, _ in REQUESTS} + + brand_rx_offsets = set((brand, r.rx_offset) for brand, r in REQUESTS) + for addr, sub_addr, _ in ecu_rx_addrs: + # Since we can't know what request an ecu responded to, add matches for all possible rx offsets + for brand, rx_offset in brand_rx_offsets: + a = (uds.get_rx_addr_for_tx_addr(addr, -rx_offset), sub_addr) + if a in brand_addrs[brand]: + brand_matches[brand].add(a) + + return brand_matches - exact_match = True - if allow_fuzzy and len(matches) == 0: - matches = match_fw_to_car_fuzzy(fw_versions_dict) - # Fuzzy match found +def get_fw_versions_ordered(logcan, sendcan, ecu_rx_addrs, timeout=0.1, num_pandas=1, debug=False, progress=False): + """Queries for FW versions ordering brands by likelihood, breaks when exact match is found""" + + all_car_fw = [] + brand_matches = get_brand_ecu_matches(ecu_rx_addrs) + + for brand in sorted(brand_matches, key=lambda b: len(brand_matches[b]), reverse=True): + car_fw = get_fw_versions(logcan, sendcan, query_brand=brand, timeout=timeout, num_pandas=num_pandas, debug=debug, progress=progress) + all_car_fw.extend(car_fw) + # Try to match using FW returned from this brand only + matches = match_fw_to_car_exact(build_fw_dict(car_fw)) if len(matches) == 1: - exact_match = False + break - return exact_match, matches + return all_car_fw -def get_fw_versions(logcan, sendcan, bus, extra=None, timeout=0.1, debug=False, progress=False): - ecu_types = {} +def get_fw_versions(logcan, sendcan, query_brand=None, extra=None, timeout=0.1, num_pandas=1, debug=False, progress=False): + versions = VERSIONS.copy() - # Extract ECU addresses to query from fingerprints - # ECUs using a subadress need be queried one by one, the rest can be done in parallel - addrs = [] - parallel_addrs = [] + # Each brand can define extra ECUs to query for data collection + for brand, config in FW_QUERY_CONFIGS.items(): + versions[brand]["debug"] = {ecu: [] for ecu in config.extra_ecus} + + if query_brand is not None: + versions = {query_brand: versions[query_brand]} - versions = get_attr_from_cars('FW_VERSIONS', combine_brands=False) if extra is not None: versions.update(extra) + # Extract ECU addresses to query from fingerprints + # ECUs using a subaddress need be queried one by one, the rest can be done in parallel + addrs = [] + parallel_addrs = [] + ecu_types = {} + for brand, brand_versions in versions.items(): for c in brand_versions.values(): for ecu_type, addr, sub_addr in c.keys(): a = (brand, addr, sub_addr) if a not in ecu_types: - ecu_types[(addr, sub_addr)] = ecu_type + ecu_types[a] = ecu_type if sub_addr is None: if a not in parallel_addrs: @@ -314,33 +246,39 @@ def get_fw_versions(logcan, sendcan, bus, extra=None, timeout=0.1, debug=False, addrs.insert(0, parallel_addrs) - fw_versions = {} - for i, addr in enumerate(tqdm(addrs, disable=not progress)): + # Get versions and build capnp list to put into CarParams + car_fw = [] + requests = [(brand, r) for brand, r in REQUESTS if query_brand is None or brand == query_brand] + for addr in tqdm(addrs, disable=not progress): for addr_chunk in chunks(addr): - for brand, request, response, response_offset in REQUESTS: + for brand, r in requests: + # Skip query if no panda available + if r.bus > num_pandas * 4 - 1: + continue + try: - addrs = [(a, s) for (b, a, s) in addr_chunk if b in (brand, 'any')] + addrs = [(a, s) for (b, a, s) in addr_chunk if b in (brand, 'any') and + (len(r.whitelist_ecus) == 0 or ecu_types[(b, a, s)] in r.whitelist_ecus)] if addrs: - query = IsoTpParallelQuery(sendcan, logcan, bus, addrs, request, response, response_offset, debug=debug) - t = 2 * timeout if i == 0 else timeout - fw_versions.update(query.get_data(t)) + query = IsoTpParallelQuery(sendcan, logcan, r.bus, addrs, r.request, r.response, r.rx_offset, debug=debug) + for (tx_addr, sub_addr), version in query.get_data(timeout).items(): + f = car.CarParams.CarFw.new_message() + + f.ecu = ecu_types.get((brand, tx_addr, sub_addr), Ecu.unknown) + f.fwVersion = version + f.address = tx_addr + f.responseAddress = uds.get_rx_addr_for_tx_addr(tx_addr, r.rx_offset) + f.request = r.request + f.brand = brand + f.bus = r.bus + + if sub_addr is not None: + f.subAddress = sub_addr + + car_fw.append(f) except Exception: - cloudlog.warning(f"FW query exception: {traceback.format_exc()}") - - # Build capnp list to put into CarParams - car_fw = [] - for addr, version in fw_versions.items(): - f = car.CarParams.CarFw.new_message() - - f.ecu = ecu_types[addr] - f.fwVersion = version - f.address = addr[0] - - if addr[1] is not None: - f.subAddress = addr[1] - - car_fw.append(f) + cloudlog.exception("FW query exception") return car_fw @@ -354,9 +292,11 @@ if __name__ == "__main__": parser = argparse.ArgumentParser(description='Get firmware version of ECUs') parser.add_argument('--scan', action='store_true') parser.add_argument('--debug', action='store_true') + parser.add_argument('--brand', help='Only query addresses/with requests for this brand') args = parser.parse_args() logcan = messaging.sub_sock('can') + pandaStates_sock = messaging.sub_sock('pandaStates') sendcan = messaging.pub_sock('sendcan') extra: Any = None @@ -370,24 +310,26 @@ if __name__ == "__main__": extra = {"any": {"debug": extra}} time.sleep(1.) + num_pandas = len(messaging.recv_one_retry(pandaStates_sock).pandaStates) t = time.time() print("Getting vin...") - addr, vin = get_vin(logcan, sendcan, 1, retry=10, debug=args.debug) - print(f"VIN: {vin}") + vin_rx_addr, vin = get_vin(logcan, sendcan, 1, retry=10, debug=args.debug) + print(f'RX: {hex(vin_rx_addr)}, VIN: {vin}') print(f"Getting VIN took {time.time() - t:.3f} s") print() t = time.time() - fw_vers = get_fw_versions(logcan, sendcan, 1, extra=extra, debug=args.debug, progress=True) + fw_vers = get_fw_versions(logcan, sendcan, query_brand=args.brand, extra=extra, num_pandas=num_pandas, debug=args.debug, progress=True) _, candidates = match_fw_to_car(fw_vers) print() print("Found FW versions") print("{") + padding = max([len(fw.brand) for fw in fw_vers] or [0]) for version in fw_vers: subaddr = None if version.subAddress == 0 else hex(version.subAddress) - print(f" (Ecu.{version.ecu}, {hex(version.address)}, {subaddr}): [{version.fwVersion}]") + print(f" Brand: {version.brand:{padding}}, bus: {version.bus} - (Ecu.{version.ecu}, {hex(version.address)}, {subaddr}): [{version.fwVersion}]") print("}") print() diff --git a/selfdrive/car/gm/carcontroller.py b/selfdrive/car/gm/carcontroller.py index 7ad1e7cf88..a6cd2f19b9 100644 --- a/selfdrive/car/gm/carcontroller.py +++ b/selfdrive/car/gm/carcontroller.py @@ -1,101 +1,146 @@ from cereal import car -from common.realtime import DT_CTRL +from common.conversions import Conversions as CV from common.numpy_fast import interp -from selfdrive.config import Conversions as CV +from common.realtime import DT_CTRL +from opendbc.can.packer import CANPacker from selfdrive.car import apply_std_steer_torque_limits from selfdrive.car.gm import gmcan -from selfdrive.car.gm.values import DBC, CanBus, CarControllerParams -from opendbc.can.packer import CANPacker +from selfdrive.car.gm.values import DBC, CanBus, CarControllerParams, CruiseButtons VisualAlert = car.CarControl.HUDControl.VisualAlert +NetworkLocation = car.CarParams.NetworkLocation +LongCtrlState = car.CarControl.Actuators.LongControlState +# Camera cancels up to 0.1s after brake is pressed, ECM allows 0.5s +CAMERA_CANCEL_DELAY_FRAMES = 10 -class CarController(): + +class CarController: def __init__(self, dbc_name, CP, VM): + self.CP = CP self.start_time = 0. self.apply_steer_last = 0 self.apply_gas = 0 self.apply_brake = 0 + self.frame = 0 + self.last_steer_frame = 0 + self.last_button_frame = 0 + self.cancel_counter = 0 - self.lka_steering_cmd_counter_last = -1 + self.lka_steering_cmd_counter = 0 + self.sent_lka_steering_cmd = False self.lka_icon_status_last = (False, False) - self.steer_rate_limited = False - - self.params = CarControllerParams() - self.packer_pt = CANPacker(DBC[CP.carFingerprint]['pt']) - self.packer_obj = CANPacker(DBC[CP.carFingerprint]['radar']) - self.packer_ch = CANPacker(DBC[CP.carFingerprint]['chassis']) + self.params = CarControllerParams(self.CP) - def update(self, c, enabled, CS, frame, actuators, - hud_v_cruise, hud_show_lanes, hud_show_car, hud_alert): + self.packer_pt = CANPacker(DBC[self.CP.carFingerprint]['pt']) + self.packer_obj = CANPacker(DBC[self.CP.carFingerprint]['radar']) + self.packer_ch = CANPacker(DBC[self.CP.carFingerprint]['chassis']) - P = self.params + def update(self, CC, CS): + actuators = CC.actuators + hud_control = CC.hudControl + hud_alert = hud_control.visualAlert + hud_v_cruise = hud_control.setSpeed + if hud_v_cruise > 70: + hud_v_cruise = 0 # Send CAN commands. can_sends = [] - # Steering (50Hz) + # Steering (Active: 50Hz, inactive: 10Hz) + # Attempt to sync with camera on startup at 50Hz, first few msgs are blocked + init_lka_counter = not self.sent_lka_steering_cmd and self.CP.networkLocation == NetworkLocation.fwdCamera + steer_step = self.params.INACTIVE_STEER_STEP + if CC.latActive or init_lka_counter: + steer_step = self.params.ACTIVE_STEER_STEP + # Avoid GM EPS faults when transmitting messages too close together: skip this transmit if we just received the # next Panda loopback confirmation in the current CS frame. - if CS.lka_steering_cmd_counter != self.lka_steering_cmd_counter_last: - self.lka_steering_cmd_counter_last = CS.lka_steering_cmd_counter - elif (frame % P.STEER_STEP) == 0: - lkas_enabled = c.active and not (CS.out.steerWarning or CS.out.steerError) and CS.out.vEgo > P.MIN_STEER_SPEED - if lkas_enabled: - new_steer = int(round(actuators.steer * P.STEER_MAX)) - apply_steer = apply_std_steer_torque_limits(new_steer, self.apply_steer_last, CS.out.steeringTorque, P) - self.steer_rate_limited = new_steer != apply_steer + if CS.loopback_lka_steering_cmd_updated: + self.lka_steering_cmd_counter += 1 + self.sent_lka_steering_cmd = True + elif (self.frame - self.last_steer_frame) >= steer_step: + # Initialize ASCMLKASteeringCmd counter using the camera until we get a msg on the bus + if init_lka_counter: + self.lka_steering_cmd_counter = CS.camera_lka_steering_cmd_counter + 1 + + if CC.latActive: + new_steer = int(round(actuators.steer * self.params.STEER_MAX)) + apply_steer = apply_std_steer_torque_limits(new_steer, self.apply_steer_last, CS.out.steeringTorque, self.params) else: apply_steer = 0 + self.last_steer_frame = self.frame self.apply_steer_last = apply_steer - # GM EPS faults on any gap in received message counters. To handle transient OP/Panda safety sync issues at the - # moment of disengaging, increment the counter based on the last message known to pass Panda safety checks. - idx = (CS.lka_steering_cmd_counter + 1) % 4 - - can_sends.append(gmcan.create_steering_control(self.packer_pt, CanBus.POWERTRAIN, apply_steer, idx, lkas_enabled)) - - # Gas/regen and brakes - all at 25Hz - if (frame % 4) == 0: - if not c.active: - # Stock ECU sends max regen when not enabled. - self.apply_gas = P.MAX_ACC_REGEN - self.apply_brake = 0 - else: - self.apply_gas = int(round(interp(actuators.accel, P.GAS_LOOKUP_BP, P.GAS_LOOKUP_V))) - self.apply_brake = int(round(interp(actuators.accel, P.BRAKE_LOOKUP_BP, P.BRAKE_LOOKUP_V))) - - idx = (frame // 4) % 4 - - at_full_stop = enabled and CS.out.standstill - near_stop = enabled and (CS.out.vEgo < P.NEAR_STOP_BRAKE_PHASE) - can_sends.append(gmcan.create_friction_brake_command(self.packer_ch, CanBus.CHASSIS, self.apply_brake, idx, near_stop, at_full_stop)) - can_sends.append(gmcan.create_gas_regen_command(self.packer_pt, CanBus.POWERTRAIN, self.apply_gas, idx, enabled, at_full_stop)) - - # Send dashboard UI commands (ACC status), 25hz - if (frame % 4) == 0: - send_fcw = hud_alert == VisualAlert.fcw - can_sends.append(gmcan.create_acc_dashboard_command(self.packer_pt, CanBus.POWERTRAIN, enabled, hud_v_cruise * CV.MS_TO_KPH, hud_show_car, send_fcw)) - - # Radar needs to know current speed and yaw rate (50hz), - # and that ADAS is alive (10hz) - time_and_headlights_step = 10 - tt = frame * DT_CTRL - - if frame % time_and_headlights_step == 0: - idx = (frame // time_and_headlights_step) % 4 - can_sends.append(gmcan.create_adas_time_status(CanBus.OBSTACLE, int((tt - self.start_time) * 60), idx)) - can_sends.append(gmcan.create_adas_headlights_status(self.packer_obj, CanBus.OBSTACLE)) - - speed_and_accelerometer_step = 2 - if frame % speed_and_accelerometer_step == 0: - idx = (frame // speed_and_accelerometer_step) % 4 - can_sends.append(gmcan.create_adas_steering_status(CanBus.OBSTACLE, idx)) - can_sends.append(gmcan.create_adas_accelerometer_speed_status(CanBus.OBSTACLE, CS.out.vEgo, idx)) - - if frame % P.ADAS_KEEPALIVE_STEP == 0: - can_sends += gmcan.create_adas_keepalive(CanBus.POWERTRAIN) + idx = self.lka_steering_cmd_counter % 4 + can_sends.append(gmcan.create_steering_control(self.packer_pt, CanBus.POWERTRAIN, apply_steer, idx, CC.latActive)) + + if self.CP.openpilotLongitudinalControl: + # Gas/regen, brakes, and UI commands - all at 25Hz + if self.frame % 4 == 0: + if not CC.longActive: + # ASCM sends max regen when not enabled + self.apply_gas = self.params.INACTIVE_REGEN + self.apply_brake = 0 + else: + self.apply_gas = int(round(interp(actuators.accel, self.params.GAS_LOOKUP_BP, self.params.GAS_LOOKUP_V))) + self.apply_brake = int(round(interp(actuators.accel, self.params.BRAKE_LOOKUP_BP, self.params.BRAKE_LOOKUP_V))) + + idx = (self.frame // 4) % 4 + + at_full_stop = CC.longActive and CS.out.standstill + near_stop = CC.longActive and (CS.out.vEgo < self.params.NEAR_STOP_BRAKE_PHASE) + friction_brake_bus = CanBus.CHASSIS + # GM Camera exceptions + # TODO: can we always check the longControlState? + if self.CP.networkLocation == NetworkLocation.fwdCamera: + at_full_stop = at_full_stop and actuators.longControlState == LongCtrlState.stopping + friction_brake_bus = CanBus.POWERTRAIN + + # GasRegenCmdActive needs to be 1 to avoid cruise faults. It describes the ACC state, not actuation + can_sends.append(gmcan.create_gas_regen_command(self.packer_pt, CanBus.POWERTRAIN, self.apply_gas, idx, CC.enabled, at_full_stop)) + can_sends.append(gmcan.create_friction_brake_command(self.packer_ch, friction_brake_bus, self.apply_brake, idx, CC.enabled, near_stop, at_full_stop, self.CP)) + + # Send dashboard UI commands (ACC status) + send_fcw = hud_alert == VisualAlert.fcw + can_sends.append(gmcan.create_acc_dashboard_command(self.packer_pt, CanBus.POWERTRAIN, CC.enabled, + hud_v_cruise * CV.MS_TO_KPH, hud_control.leadVisible, send_fcw)) + + # Radar needs to know current speed and yaw rate (50hz), + # and that ADAS is alive (10hz) + if not self.CP.radarOffCan: + tt = self.frame * DT_CTRL + time_and_headlights_step = 10 + if self.frame % time_and_headlights_step == 0: + idx = (self.frame // time_and_headlights_step) % 4 + can_sends.append(gmcan.create_adas_time_status(CanBus.OBSTACLE, int((tt - self.start_time) * 60), idx)) + can_sends.append(gmcan.create_adas_headlights_status(self.packer_obj, CanBus.OBSTACLE)) + + speed_and_accelerometer_step = 2 + if self.frame % speed_and_accelerometer_step == 0: + idx = (self.frame // speed_and_accelerometer_step) % 4 + can_sends.append(gmcan.create_adas_steering_status(CanBus.OBSTACLE, idx)) + can_sends.append(gmcan.create_adas_accelerometer_speed_status(CanBus.OBSTACLE, CS.out.vEgo, idx)) + + if self.CP.networkLocation == NetworkLocation.gateway and self.frame % self.params.ADAS_KEEPALIVE_STEP == 0: + can_sends += gmcan.create_adas_keepalive(CanBus.POWERTRAIN) + + else: + # While car is braking, cancel button causes ECM to enter a soft disable state with a fault status. + # A delayed cancellation allows camera to cancel and avoids a fault when user depresses brake quickly + self.cancel_counter = self.cancel_counter + 1 if CC.cruiseControl.cancel else 0 + + # Stock longitudinal, integrated at camera + if (self.frame - self.last_button_frame) * DT_CTRL > 0.04: + if self.cancel_counter > CAMERA_CANCEL_DELAY_FRAMES: + self.last_button_frame = self.frame + can_sends.append(gmcan.create_buttons(self.packer_pt, CanBus.CAMERA, CS.buttons_counter, CruiseButtons.CANCEL)) + + if self.CP.networkLocation == NetworkLocation.fwdCamera: + # Silence "Take Steering" alert sent by camera, forward PSCMStatus with HandsOffSWlDetectionStatus=1 + if self.frame % 10 == 0: + can_sends.append(gmcan.create_pscm_status(self.packer_pt, CanBus.CAMERA, CS.pscm_status)) # Show green icon when LKA torque is applied, and # alarming orange icon when approaching torque limit. @@ -104,14 +149,17 @@ class CarController(): lka_active = CS.lkas_status == 1 lka_critical = lka_active and abs(actuators.steer) > 0.9 lka_icon_status = (lka_active, lka_critical) - if frame % P.CAMERA_KEEPALIVE_STEP == 0 or lka_icon_status != self.lka_icon_status_last: + + # SW_GMLAN not yet on cam harness, no HUD alerts + if self.CP.networkLocation != NetworkLocation.fwdCamera and (self.frame % self.params.CAMERA_KEEPALIVE_STEP == 0 or lka_icon_status != self.lka_icon_status_last): steer_alert = hud_alert in (VisualAlert.steerRequired, VisualAlert.ldw) can_sends.append(gmcan.create_lka_icon_command(CanBus.SW_GMLAN, lka_active, lka_critical, steer_alert)) self.lka_icon_status_last = lka_icon_status new_actuators = actuators.copy() - new_actuators.steer = self.apply_steer_last / P.STEER_MAX + new_actuators.steer = self.apply_steer_last / self.params.STEER_MAX new_actuators.gas = self.apply_gas new_actuators.brake = self.apply_brake + self.frame += 1 return new_actuators, can_sends diff --git a/selfdrive/car/gm/carstate.py b/selfdrive/car/gm/carstate.py index 4a6b75fa3f..de0fd2eed6 100644 --- a/selfdrive/car/gm/carstate.py +++ b/selfdrive/car/gm/carstate.py @@ -1,23 +1,39 @@ +import copy from cereal import car +from common.conversions import Conversions as CV from common.numpy_fast import mean from opendbc.can.can_define import CANDefine from opendbc.can.parser import CANParser from selfdrive.car.interfaces import CarStateBase -from selfdrive.car.gm.values import DBC, CAR, AccState, CanBus, STEER_THRESHOLD +from selfdrive.car.gm.values import DBC, AccState, CanBus, STEER_THRESHOLD + +TransmissionType = car.CarParams.TransmissionType +NetworkLocation = car.CarParams.NetworkLocation +STANDSTILL_THRESHOLD = 10 * 0.0311 * CV.KPH_TO_MS class CarState(CarStateBase): def __init__(self, CP): super().__init__(CP) can_define = CANDefine(DBC[CP.carFingerprint]["pt"]) - self.shifter_values = can_define.dv["ECMPRDNL"]["PRNDL"] - self.lka_steering_cmd_counter = 0 + self.shifter_values = can_define.dv["ECMPRDNL2"]["PRNDL2"] + self.loopback_lka_steering_cmd_updated = False + self.camera_lka_steering_cmd_counter = 0 + self.buttons_counter = 0 - def update(self, pt_cp, loopback_cp): + def update(self, pt_cp, cam_cp, loopback_cp): ret = car.CarState.new_message() self.prev_cruise_buttons = self.cruise_buttons self.cruise_buttons = pt_cp.vl["ASCMSteeringButton"]["ACCButtons"] + self.buttons_counter = pt_cp.vl["ASCMSteeringButton"]["RollingCounter"] + self.pscm_status = copy.copy(pt_cp.vl["PSCMStatus"]) + self.moving_backward = pt_cp.vl["EBCMWheelSpdRear"]["MovingBackward"] != 0 + + # Variables used for avoiding LKAS faults + self.loopback_lka_steering_cmd_updated = len(loopback_cp.vl_all["ASCMLKASteeringCmd"]["RollingCounter"]) > 0 + if self.CP.networkLocation == NetworkLocation.fwdCamera: + self.camera_lka_steering_cmd_counter = cam_cp.vl["ASCMLKASteeringCmd"]["RollingCounter"] ret.wheelSpeeds = self.get_wheel_speeds( pt_cp.vl["EBCMWheelSpdFront"]["FLWheelSpd"], @@ -27,11 +43,27 @@ class CarState(CarStateBase): ) ret.vEgoRaw = mean([ret.wheelSpeeds.fl, ret.wheelSpeeds.fr, ret.wheelSpeeds.rl, ret.wheelSpeeds.rr]) ret.vEgo, ret.aEgo = self.update_speed_kf(ret.vEgoRaw) - ret.standstill = ret.vEgoRaw < 0.01 + # sample rear wheel speeds, standstill=True if ECM allows engagement with brake + ret.standstill = ret.wheelSpeeds.rl <= STANDSTILL_THRESHOLD and ret.wheelSpeeds.rr <= STANDSTILL_THRESHOLD + + if pt_cp.vl["ECMPRDNL2"]["ManualMode"] == 1: + ret.gearShifter = self.parse_gear_shifter("T") + else: + ret.gearShifter = self.parse_gear_shifter(self.shifter_values.get(pt_cp.vl["ECMPRDNL2"]["PRNDL2"], None)) + + ret.brake = pt_cp.vl["ECMAcceleratorPos"]["BrakePedalPos"] + if self.CP.networkLocation == NetworkLocation.fwdCamera: + ret.brakePressed = pt_cp.vl["ECMEngineStatus"]["BrakePressed"] != 0 + else: + # Some Volt 2016-17 have loose brake pedal push rod retainers which causes the ECM to believe + # that the brake is being intermittently pressed without user interaction. + # To avoid a cruise fault we need to use a conservative brake position threshold + # https://static.nhtsa.gov/odi/tsbs/2017/MC-10137629-9999.pdf + ret.brakePressed = ret.brake >= 8 - ret.gearShifter = self.parse_gear_shifter(self.shifter_values.get(pt_cp.vl["ECMPRDNL"]["PRNDL"], None)) - ret.brakePressed = pt_cp.vl["ECMEngineStatus"]["Brake_Pressed"] != 0 - ret.brake = pt_cp.vl["EBCMBrakePedalPosition"]["BrakePedalPosition"] / 0xd0 + # Regen braking is braking + if self.CP.transmissionType == TransmissionType.direct: + ret.regenBraking = pt_cp.vl["EBCMRegenPaddle"]["RegenPaddle"] != 0 ret.gas = pt_cp.vl["AcceleratorPedal2"]["AcceleratorPedal2"] / 254. ret.gasPressed = ret.gas > 1e-5 @@ -41,12 +73,11 @@ class CarState(CarStateBase): ret.steeringTorque = pt_cp.vl["PSCMStatus"]["LKADriverAppldTrq"] ret.steeringTorqueEps = pt_cp.vl["PSCMStatus"]["LKATorqueDelivered"] ret.steeringPressed = abs(ret.steeringTorque) > STEER_THRESHOLD - self.lka_steering_cmd_counter = loopback_cp.vl["ASCMLKASteeringCmd"]["RollingCounter"] # 0 inactive, 1 active, 2 temporarily limited, 3 failed self.lkas_status = pt_cp.vl["PSCMStatus"]["LKATorqueDeliveredStatus"] - ret.steerWarning = self.lkas_status == 2 - ret.steerError = self.lkas_status == 3 + ret.steerFaultTemporary = self.lkas_status == 2 + ret.steerFaultPermanent = self.lkas_status == 3 # 1 - open, 0 - closed ret.doorOpen = (pt_cp.vl["BCMDoorBeltStatus"]["FrontLeftDoor"] == 1 or @@ -59,25 +90,46 @@ class CarState(CarStateBase): ret.leftBlinker = pt_cp.vl["BCMTurnSignals"]["TurnSignals"] == 1 ret.rightBlinker = pt_cp.vl["BCMTurnSignals"]["TurnSignals"] == 2 - self.park_brake = pt_cp.vl["EPBStatus"]["EPBClosed"] + ret.parkingBrake = pt_cp.vl["VehicleIgnitionAlt"]["ParkBrake"] == 1 ret.cruiseState.available = pt_cp.vl["ECMEngineStatus"]["CruiseMainOn"] != 0 ret.espDisabled = pt_cp.vl["ESPStatus"]["TractionControlOn"] != 1 - self.pcm_acc_status = pt_cp.vl["AcceleratorPedal2"]["CruiseState"] + ret.accFaulted = pt_cp.vl["AcceleratorPedal2"]["CruiseState"] == AccState.FAULTED - # Regen braking is braking - if self.car_fingerprint == CAR.VOLT: - ret.brakePressed = ret.brakePressed or pt_cp.vl["EBCMRegenPaddle"]["RegenPaddle"] != 0 - - ret.cruiseState.enabled = self.pcm_acc_status != AccState.OFF - ret.cruiseState.standstill = self.pcm_acc_status == AccState.STANDSTILL + ret.cruiseState.enabled = pt_cp.vl["AcceleratorPedal2"]["CruiseState"] != AccState.OFF + ret.cruiseState.standstill = pt_cp.vl["AcceleratorPedal2"]["CruiseState"] == AccState.STANDSTILL + if self.CP.networkLocation == NetworkLocation.fwdCamera: + ret.cruiseState.speed = cam_cp.vl["ASCMActiveCruiseControlStatus"]["ACCSpeedSetpoint"] * CV.KPH_TO_MS + ret.stockAeb = cam_cp.vl["AEBCmd"]["AEBCmdActive"] != 0 + # openpilot controls nonAdaptive when not pcmCruise + if self.CP.pcmCruise: + ret.cruiseState.nonAdaptive = cam_cp.vl["ASCMActiveCruiseControlStatus"]["ACCCruiseState"] not in (2, 3) return ret + @staticmethod + def get_cam_can_parser(CP): + signals = [] + checks = [] + if CP.networkLocation == NetworkLocation.fwdCamera: + signals += [ + ("AEBCmdActive", "AEBCmd"), + ("RollingCounter", "ASCMLKASteeringCmd"), + ("ACCSpeedSetpoint", "ASCMActiveCruiseControlStatus"), + ("ACCCruiseState", "ASCMActiveCruiseControlStatus"), + ] + checks += [ + ("AEBCmd", 10), + ("ASCMLKASteeringCmd", 10), + ("ASCMActiveCruiseControlStatus", 25), + ] + + return CANParser(DBC[CP.carFingerprint]["pt"], signals, checks, CanBus.CAMERA) + @staticmethod def get_can_parser(CP): signals = [ # sig_name, sig_address - ("BrakePedalPosition", "EBCMBrakePedalPosition"), + ("BrakePedalPos", "ECMAcceleratorPos"), ("FrontLeftDoor", "BCMDoorBeltStatus"), ("FrontRightDoor", "BCMDoorBeltStatus"), ("RearLeftDoor", "BCMDoorBeltStatus"), @@ -88,39 +140,47 @@ class CarState(CarStateBase): ("AcceleratorPedal2", "AcceleratorPedal2"), ("CruiseState", "AcceleratorPedal2"), ("ACCButtons", "ASCMSteeringButton"), + ("RollingCounter", "ASCMSteeringButton"), ("SteeringWheelAngle", "PSCMSteeringAngle"), ("SteeringWheelRate", "PSCMSteeringAngle"), ("FLWheelSpd", "EBCMWheelSpdFront"), ("FRWheelSpd", "EBCMWheelSpdFront"), ("RLWheelSpd", "EBCMWheelSpdRear"), ("RRWheelSpd", "EBCMWheelSpdRear"), - ("PRNDL", "ECMPRDNL"), + ("MovingBackward", "EBCMWheelSpdRear"), + ("PRNDL2", "ECMPRDNL2"), + ("ManualMode", "ECMPRDNL2"), ("LKADriverAppldTrq", "PSCMStatus"), ("LKATorqueDelivered", "PSCMStatus"), ("LKATorqueDeliveredStatus", "PSCMStatus"), + ("HandsOffSWlDetectionStatus", "PSCMStatus"), + ("HandsOffSWDetectionMode", "PSCMStatus"), + ("LKATotalTorqueDelivered", "PSCMStatus"), + ("PSCMStatusChecksum", "PSCMStatus"), + ("RollingCounter", "PSCMStatus"), ("TractionControlOn", "ESPStatus"), - ("EPBClosed", "EPBStatus"), + ("ParkBrake", "VehicleIgnitionAlt"), ("CruiseMainOn", "ECMEngineStatus"), - ("Brake_Pressed", "ECMEngineStatus"), + ("BrakePressed", "ECMEngineStatus"), ] checks = [ ("BCMTurnSignals", 1), - ("ECMPRDNL", 10), + ("ECMPRDNL2", 10), ("PSCMStatus", 10), ("ESPStatus", 10), ("BCMDoorBeltStatus", 10), - ("EPBStatus", 20), + ("VehicleIgnitionAlt", 10), ("EBCMWheelSpdFront", 20), ("EBCMWheelSpdRear", 20), ("AcceleratorPedal2", 33), ("ASCMSteeringButton", 33), ("ECMEngineStatus", 100), ("PSCMSteeringAngle", 100), - ("EBCMBrakePedalPosition", 100), + ("ECMAcceleratorPos", 80), ] - if CP.carFingerprint == CAR.VOLT: + if CP.transmissionType == TransmissionType.direct: signals.append(("RegenPaddle", "EBCMRegenPaddle")) checks.append(("EBCMRegenPaddle", 50)) @@ -133,7 +193,7 @@ class CarState(CarStateBase): ] checks = [ - ("ASCMLKASteeringCmd", 50), + ("ASCMLKASteeringCmd", 0), ] - return CANParser(DBC[CP.carFingerprint]["pt"], signals, checks, CanBus.LOOPBACK) + return CANParser(DBC[CP.carFingerprint]["pt"], signals, checks, CanBus.LOOPBACK, enforce_checks=False) diff --git a/selfdrive/car/gm/gmcan.py b/selfdrive/car/gm/gmcan.py index 47e6090a03..56c981326f 100644 --- a/selfdrive/car/gm/gmcan.py +++ b/selfdrive/car/gm/gmcan.py @@ -1,7 +1,23 @@ from selfdrive.car import make_can_msg +from selfdrive.car.gm.values import CAR -def create_steering_control(packer, bus, apply_steer, idx, lkas_active): +def create_buttons(packer, bus, idx, button): + values = { + "ACCButtons": button, + "RollingCounter": idx, + } + return packer.make_can_msg("ASCMSteeringButton", bus, values) + + +def create_pscm_status(packer, bus, pscm_status): + checksum_mod = int(1 - pscm_status["HandsOffSWlDetectionStatus"]) << 5 + pscm_status["HandsOffSWlDetectionStatus"] = 1 + pscm_status["PSCMStatusChecksum"] += checksum_mod + return packer.make_can_msg("PSCMStatus", bus, pscm_status) + + +def create_steering_control(packer, bus, apply_steer, idx, lkas_active): values = { "LKASteeringCmdActive": lkas_active, "LKASteeringCmd": apply_steer, @@ -11,15 +27,17 @@ def create_steering_control(packer, bus, apply_steer, idx, lkas_active): return packer.make_can_msg("ASCMLKASteeringCmd", bus, values) + def create_adas_keepalive(bus): dat = b"\x00\x00\x00\x00\x00\x00\x00" return [make_can_msg(0x409, dat, bus), make_can_msg(0x40a, dat, bus)] -def create_gas_regen_command(packer, bus, throttle, idx, acc_engaged, at_full_stop): + +def create_gas_regen_command(packer, bus, throttle, idx, enabled, at_full_stop): values = { - "GasRegenCmdActive": acc_engaged, + "GasRegenCmdActive": enabled, "RollingCounter": idx, - "GasRegenCmdActiveInv": 1 - acc_engaged, + "GasRegenCmdActiveInv": 1 - enabled, "GasRegenCmd": throttle, "GasRegenFullStopActive": at_full_stop, "GasRegenAlwaysOne": 1, @@ -34,15 +52,21 @@ def create_gas_regen_command(packer, bus, throttle, idx, acc_engaged, at_full_st return packer.make_can_msg("ASCMGasRegenCmd", bus, values) -def create_friction_brake_command(packer, bus, apply_brake, idx, near_stop, at_full_stop): + +def create_friction_brake_command(packer, bus, apply_brake, idx, enabled, near_stop, at_full_stop, CP): mode = 0x1 + + # TODO: Understand this better. Volts and ICE Camera ACC cars are 0x1 when enabled with no brake + if enabled and CP.carFingerprint in (CAR.BOLT_EUV,): + mode = 0x9 + if apply_brake > 0: mode = 0xa if at_full_stop: mode = 0xd # TODO: this is to have GM bringing the car to complete stop, - # but currently it conflicts with OP controls, so turned off. + # but currently it conflicts with OP controls, so turned off. Not set by all cars #elif near_stop: # mode = 0xb @@ -50,45 +74,48 @@ def create_friction_brake_command(packer, bus, apply_brake, idx, near_stop, at_f checksum = (0x10000 - (mode << 12) - brake - idx) & 0xffff values = { - "RollingCounter" : idx, - "FrictionBrakeMode" : mode, + "RollingCounter": idx, + "FrictionBrakeMode": mode, "FrictionBrakeChecksum": checksum, - "FrictionBrakeCmd" : -apply_brake + "FrictionBrakeCmd": -apply_brake } return packer.make_can_msg("EBCMFrictionBrakeCmd", bus, values) -def create_acc_dashboard_command(packer, bus, acc_engaged, target_speed_kph, lead_car_in_sight, fcw): - # Not a bit shift, dash can round up based on low 4 bits. - target_speed = int(target_speed_kph * 16) & 0xfff + +def create_acc_dashboard_command(packer, bus, enabled, target_speed_kph, lead_car_in_sight, fcw): + target_speed = min(target_speed_kph, 255) values = { - "ACCAlwaysOne" : 1, - "ACCResumeButton" : 0, - "ACCSpeedSetpoint" : target_speed, - "ACCGapLevel" : 3 * acc_engaged, # 3 "far", 0 "inactive" - "ACCCmdActive" : acc_engaged, - "ACCAlwaysOne2" : 1, - "ACCLeadCar" : lead_car_in_sight, + "ACCAlwaysOne": 1, + "ACCResumeButton": 0, + "ACCSpeedSetpoint": target_speed, + "ACCGapLevel": 3 * enabled, # 3 "far", 0 "inactive" + "ACCCmdActive": enabled, + "ACCAlwaysOne2": 1, + "ACCLeadCar": lead_car_in_sight, "FCWAlert": 0x3 if fcw else 0 } return packer.make_can_msg("ASCMActiveCruiseControlStatus", bus, values) + def create_adas_time_status(bus, tt, idx): dat = [(tt >> 20) & 0xff, (tt >> 12) & 0xff, (tt >> 4) & 0xff, - ((tt & 0xf) << 4) + (idx << 2)] + ((tt & 0xf) << 4) + (idx << 2)] chksum = 0x1000 - dat[0] - dat[1] - dat[2] - dat[3] chksum = chksum & 0xfff dat += [0x40 + (chksum >> 8), chksum & 0xff, 0x12] return make_can_msg(0xa1, bytes(dat), bus) + def create_adas_steering_status(bus, idx): dat = [idx << 6, 0xf0, 0x20, 0, 0, 0] chksum = 0x60 + sum(dat) dat += [chksum >> 8, chksum & 0xff] return make_can_msg(0x306, bytes(dat), bus) + def create_adas_accelerometer_speed_status(bus, speed_ms, idx): spd = int(speed_ms * 16) & 0xfff accel = 0 & 0xfff @@ -102,6 +129,7 @@ def create_adas_accelerometer_speed_status(bus, speed_ms, idx): dat += [(idx << 5) + (far_range_mode << 4) + (near_range_mode << 3) + (chksum >> 8), chksum & 0xff] return make_can_msg(0x308, bytes(dat), bus) + def create_adas_headlights_status(packer, bus): values = { "Always42": 0x42, @@ -109,6 +137,7 @@ def create_adas_headlights_status(packer, bus): } return packer.make_can_msg("ASCMHeadlight", bus, values) + def create_lka_icon_command(bus, active, critical, steer): if active and steer == 1: if critical: diff --git a/selfdrive/car/gm/interface.py b/selfdrive/car/gm/interface.py index d6a2d3cfee..195df36a7f 100755 --- a/selfdrive/car/gm/interface.py +++ b/selfdrive/car/gm/interface.py @@ -1,20 +1,26 @@ #!/usr/bin/env python3 from cereal import car from math import fabs -from selfdrive.config import Conversions as CV -from selfdrive.car.gm.values import CAR, CruiseButtons, \ - AccState, CarControllerParams -from selfdrive.car import STD_CARGO_KG, scale_rot_inertia, scale_tire_stiffness, gen_empty_fingerprint, get_safety_config +from panda import Panda + +from common.conversions import Conversions as CV +from selfdrive.car import STD_CARGO_KG, create_button_event, scale_tire_stiffness, get_safety_config +from selfdrive.car.gm.values import CAR, CruiseButtons, CarControllerParams, EV_CAR, CAMERA_ACC_CAR from selfdrive.car.interfaces import CarInterfaceBase ButtonType = car.CarState.ButtonEvent.Type EventName = car.CarEvent.EventName +GearShifter = car.CarState.GearShifter +TransmissionType = car.CarParams.TransmissionType +NetworkLocation = car.CarParams.NetworkLocation +BUTTONS_DICT = {CruiseButtons.RES_ACCEL: ButtonType.accelCruise, CruiseButtons.DECEL_SET: ButtonType.decelCruise, + CruiseButtons.MAIN: ButtonType.altButton3, CruiseButtons.CANCEL: ButtonType.cancel} + class CarInterface(CarInterfaceBase): @staticmethod def get_pid_accel_limits(CP, current_speed, cruise_speed): - params = CarControllerParams() - return params.ACCEL_MIN, params.ACCEL_MAX + return CarControllerParams.ACCEL_MIN, CarControllerParams.ACCEL_MAX # Determined by iteratively plotting and minimizing error for f(angle, speed) = steer. @staticmethod @@ -38,55 +44,91 @@ class CarInterface(CarInterfaceBase): return CarInterfaceBase.get_steer_feedforward_default @staticmethod - def get_params(candidate, fingerprint=gen_empty_fingerprint(), car_fw=None): - ret = CarInterfaceBase.get_std_params(candidate, fingerprint) + def _get_params(ret, candidate, fingerprint, car_fw, experimental_long): ret.carName = "gm" ret.safetyConfigs = [get_safety_config(car.CarParams.SafetyModel.gm)] - ret.pcmCruise = False # stock cruise control is kept off + ret.autoResumeSng = False + + if candidate in EV_CAR: + ret.transmissionType = TransmissionType.direct + else: + ret.transmissionType = TransmissionType.automatic + + ret.longitudinalTuning.deadzoneBP = [0.] + ret.longitudinalTuning.deadzoneV = [0.15] + + ret.longitudinalTuning.kpBP = [5., 35.] + ret.longitudinalTuning.kiBP = [0.] + + if candidate in CAMERA_ACC_CAR: + ret.experimentalLongitudinalAvailable = True + ret.networkLocation = NetworkLocation.fwdCamera + ret.radarOffCan = True # no radar + ret.pcmCruise = True + ret.safetyConfigs[0].safetyParam |= Panda.FLAG_GM_HW_CAM + ret.minEnableSpeed = 5 * CV.KPH_TO_MS + + if experimental_long: + ret.pcmCruise = False + ret.openpilotLongitudinalControl = True + ret.safetyConfigs[0].safetyParam |= Panda.FLAG_GM_HW_CAM_LONG + + # Tuning + ret.longitudinalTuning.kpV = [2.0, 1.5] + ret.longitudinalTuning.kiV = [0.72] + ret.stopAccel = -2.0 + ret.stoppingDecelRate = 2.0 # reach brake quickly after enabling + ret.vEgoStopping = 0.25 + ret.vEgoStarting = 0.25 + ret.longitudinalActuatorDelayUpperBound = 0.5 + + else: # ASCM, OBD-II harness + ret.openpilotLongitudinalControl = True + ret.networkLocation = NetworkLocation.gateway + ret.radarOffCan = False + ret.pcmCruise = False # stock non-adaptive cruise control is kept off + # supports stop and go, but initial engage must (conservatively) be above 18mph + ret.minEnableSpeed = 18 * CV.MPH_TO_MS + + # Tuning + ret.longitudinalTuning.kpV = [2.4, 1.5] + ret.longitudinalTuning.kiV = [0.36] # These cars have been put into dashcam only due to both a lack of users and test coverage. # These cars likely still work fine. Once a user confirms each car works and a test route is - # added to selfdrive/test/test_routes, we can remove it from this list. - ret.dashcamOnly = candidate in {CAR.CADILLAC_ATS, CAR.HOLDEN_ASTRA, CAR.MALIBU, CAR.BUICK_REGAL} - - # Presence of a camera on the object bus is ok. - # Have to go to read_only if ASCM is online (ACC-enabled cars), - # or camera is on powertrain bus (LKA cars without ACC). - ret.openpilotLongitudinalControl = True - tire_stiffness_factor = 0.444 # not optimized yet + # added to selfdrive/car/tests/routes.py, we can remove it from this list. + ret.dashcamOnly = candidate in {CAR.CADILLAC_ATS, CAR.HOLDEN_ASTRA, CAR.MALIBU, CAR.BUICK_REGAL, CAR.EQUINOX} - # Start with a baseline lateral tuning for all GM vehicles. Override tuning as needed in each model section below. - ret.minSteerSpeed = 7 * CV.MPH_TO_MS + # Start with a baseline tuning for all GM vehicles. Override tuning as needed in each model section below. + # Some GMs need some tolerance above 10 kph to avoid a fault + ret.minSteerSpeed = 10.1 * CV.KPH_TO_MS ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]] ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.2], [0.00]] ret.lateralTuning.pid.kf = 0.00004 # full torque for 20 deg at 80mph means 0.00007818594 - ret.steerRateCost = 1.0 ret.steerActuatorDelay = 0.1 # Default delay, not measured yet + tire_stiffness_factor = 0.444 # not optimized yet + + ret.steerLimitTimer = 0.4 + ret.radarTimeStep = 0.0667 # GM radar runs at 15Hz instead of standard 20Hz 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 ret.mass = 1607. + STD_CARGO_KG ret.wheelbase = 2.69 ret.steerRatio = 17.7 # Stock 15.7, LiveParameters - tire_stiffness_factor = 0.469 # Stock Michelin Energy Saver A/S, LiveParameters - ret.steerRatioRear = 0. - ret.centerToFront = ret.wheelbase * 0.45 # Volt Gen 1, TODO corner weigh + tire_stiffness_factor = 0.469 # Stock Michelin Energy Saver A/S, LiveParameters + ret.centerToFront = ret.wheelbase * 0.45 # Volt Gen 1, TODO corner weigh ret.lateralTuning.pid.kpBP = [0., 40.] ret.lateralTuning.pid.kpV = [0., 0.17] ret.lateralTuning.pid.kiBP = [0.] ret.lateralTuning.pid.kiV = [0.] - ret.lateralTuning.pid.kf = 1. # get_steer_feedforward_volt() + ret.lateralTuning.pid.kf = 1. # get_steer_feedforward_volt() ret.steerActuatorDelay = 0.2 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_KG ret.wheelbase = 2.83 ret.steerRatio = 15.8 - ret.steerRatioRear = 0. ret.centerToFront = ret.wheelbase * 0.4 # wild guess elif candidate == CAR.HOLDEN_ASTRA: @@ -94,142 +136,105 @@ class CarInterface(CarInterfaceBase): 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.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_KG ret.wheelbase = 2.86 ret.steerRatio = 14.4 # end to end is 13.46 - ret.steerRatioRear = 0. ret.centerToFront = ret.wheelbase * 0.4 - ret.lateralTuning.pid.kf = 1. # get_steer_feedforward_acadia() + ret.lateralTuning.pid.kf = 1. # get_steer_feedforward_acadia() + ret.longitudinalActuatorDelayUpperBound = 0.5 # large delay to initially start braking elif candidate == CAR.BUICK_REGAL: - ret.minEnableSpeed = 18 * CV.MPH_TO_MS ret.mass = 3779. * CV.LB_TO_KG + STD_CARGO_KG # (3849+3708)/2 ret.wheelbase = 2.83 # 111.4 inches in meters ret.steerRatio = 14.4 # guess for tourx - ret.steerRatioRear = 0. ret.centerToFront = ret.wheelbase * 0.4 # guess for tourx elif candidate == CAR.CADILLAC_ATS: - ret.minEnableSpeed = 18 * CV.MPH_TO_MS ret.mass = 1601. + STD_CARGO_KG ret.wheelbase = 2.78 ret.steerRatio = 15.3 - ret.steerRatioRear = 0. - ret.centerToFront = ret.wheelbase * 0.49 + ret.centerToFront = ret.wheelbase * 0.5 elif candidate == CAR.ESCALADE_ESV: ret.minEnableSpeed = -1. # engage speed is decided by pcm ret.mass = 2739. + STD_CARGO_KG ret.wheelbase = 3.302 ret.steerRatio = 17.3 - ret.centerToFront = ret.wheelbase * 0.49 + ret.centerToFront = ret.wheelbase * 0.5 ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[10., 41.0], [10., 41.0]] ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.13, 0.24], [0.01, 0.02]] ret.lateralTuning.pid.kf = 0.000045 tire_stiffness_factor = 1.0 - # TODO: get actual value, for now starting with reasonable value for - # civic and scaling by mass and wheelbase - ret.rotationalInertia = scale_rot_inertia(ret.mass, ret.wheelbase) + elif candidate == CAR.BOLT_EUV: + ret.mass = 1669. + STD_CARGO_KG + ret.wheelbase = 2.63779 + ret.steerRatio = 16.8 + ret.centerToFront = 2.15 # measured + tire_stiffness_factor = 1.0 + ret.steerActuatorDelay = 0.2 + CarInterfaceBase.configure_torque_tune(candidate, ret.lateralTuning) + + elif candidate == CAR.SILVERADO: + ret.mass = 2200. + STD_CARGO_KG + ret.wheelbase = 3.75 + ret.steerRatio = 16.3 + ret.centerToFront = ret.wheelbase * 0.5 + tire_stiffness_factor = 1.0 + CarInterfaceBase.configure_torque_tune(candidate, ret.lateralTuning) + + elif candidate == CAR.EQUINOX: + ret.mass = 3500. * CV.LB_TO_KG + STD_CARGO_KG + ret.wheelbase = 2.72 + ret.steerRatio = 14.4 + ret.centerToFront = ret.wheelbase * 0.4 + CarInterfaceBase.configure_torque_tune(candidate, ret.lateralTuning) # TODO: start from empirically derived lateral slip stiffness for the civic and scale by # mass and CG position, so all cars will have approximately similar dyn behaviors ret.tireStiffnessFront, ret.tireStiffnessRear = scale_tire_stiffness(ret.mass, ret.wheelbase, ret.centerToFront, tire_stiffness_factor=tire_stiffness_factor) - ret.longitudinalTuning.kpBP = [5., 35.] - ret.longitudinalTuning.kpV = [2.4, 1.5] - ret.longitudinalTuning.kiBP = [0.] - ret.longitudinalTuning.kiV = [0.36] - - ret.steerLimitTimer = 0.4 - ret.radarTimeStep = 0.0667 # GM radar runs at 15Hz instead of standard 20Hz - return ret # returns a car.CarState - def update(self, c, can_strings): - self.cp.update_strings(can_strings) - self.cp_loopback.update_strings(can_strings) - - ret = self.CS.update(self.cp, self.cp_loopback) - - ret.canValid = self.cp.can_valid and self.cp_loopback.can_valid - ret.steeringRateLimited = self.CC.steer_rate_limited if self.CC is not None else False - - buttonEvents = [] + def _update(self, c): + ret = self.CS.update(self.cp, self.cp_cam, self.cp_loopback) if self.CS.cruise_buttons != self.CS.prev_cruise_buttons and self.CS.prev_cruise_buttons != CruiseButtons.INIT: - be = car.CarState.ButtonEvent.new_message() - be.type = ButtonType.unknown - if self.CS.cruise_buttons != CruiseButtons.UNPRESS: - be.pressed = True - but = self.CS.cruise_buttons - else: - be.pressed = False - but = self.CS.prev_cruise_buttons - if but == CruiseButtons.RES_ACCEL: - if not (ret.cruiseState.enabled and ret.standstill): - be.type = ButtonType.accelCruise # Suppress resume button if we're resuming from stop so we don't adjust speed. - elif but == CruiseButtons.DECEL_SET: - be.type = ButtonType.decelCruise - elif but == CruiseButtons.CANCEL: - be.type = ButtonType.cancel - elif but == CruiseButtons.MAIN: - be.type = ButtonType.altButton3 - buttonEvents.append(be) - - ret.buttonEvents = buttonEvents - - events = self.create_common_events(ret, pcm_enable=False) - - if ret.vEgo < self.CP.minEnableSpeed: + buttonEvents = [create_button_event(self.CS.cruise_buttons, self.CS.prev_cruise_buttons, BUTTONS_DICT, CruiseButtons.UNPRESS)] + # Handle ACCButtons changing buttons mid-press + if self.CS.cruise_buttons != CruiseButtons.UNPRESS and self.CS.prev_cruise_buttons != CruiseButtons.UNPRESS: + buttonEvents.append(create_button_event(CruiseButtons.UNPRESS, self.CS.prev_cruise_buttons, BUTTONS_DICT, CruiseButtons.UNPRESS)) + + ret.buttonEvents = buttonEvents + + # The ECM allows enabling on falling edge of set, but only rising edge of resume + events = self.create_common_events(ret, extra_gears=[GearShifter.sport, GearShifter.low, + GearShifter.eco, GearShifter.manumatic], + pcm_enable=self.CP.pcmCruise, enable_buttons=(ButtonType.decelCruise,)) + if not self.CP.pcmCruise: + if any(b.type == ButtonType.accelCruise and b.pressed for b in ret.buttonEvents): + events.add(EventName.buttonEnable) + + # Enabling at a standstill with brake is allowed + # TODO: verify 17 Volt can enable for the first time at a stop and allow for all GMs + below_min_enable_speed = ret.vEgo < self.CP.minEnableSpeed or self.CS.moving_backward + if below_min_enable_speed and not (ret.standstill and ret.brake >= 20 and + self.CP.networkLocation == NetworkLocation.fwdCamera): events.add(EventName.belowEngageSpeed) - if self.CS.park_brake: - events.add(EventName.parkBrake) if ret.cruiseState.standstill: events.add(EventName.resumeRequired) - if self.CS.pcm_acc_status == AccState.FAULTED: - events.add(EventName.accFaulted) if ret.vEgo < self.CP.minSteerSpeed: - events.add(car.CarEvent.EventName.belowSteerSpeed) - - # handle button presses - for b in ret.buttonEvents: - # do enable on both accel and decel buttons - if b.type in (ButtonType.accelCruise, ButtonType.decelCruise) and not b.pressed: - events.add(EventName.buttonEnable) - # do disable on button down - if b.type == ButtonType.cancel and b.pressed: - events.add(EventName.buttonCancel) + events.add(EventName.belowSteerSpeed) ret.events = events.to_msg() - # copy back carState packet to CS - self.CS.out = ret.as_reader() - - return self.CS.out + return ret def apply(self, c): - hud_control = c.hudControl - hud_v_cruise = hud_control.setSpeed - if hud_v_cruise > 70: - hud_v_cruise = 0 - - # For Openpilot, "enabled" includes pre-enable. - # In GM, PCM faults out if ACC command overlaps user gas. - enabled = c.enabled and not self.CS.out.gasPressed - - ret = self.CC.update(c, enabled, self.CS, self.frame, - c.actuators, - hud_v_cruise, hud_control.lanesVisible, - hud_control.leadVisible, hud_control.visualAlert) - - self.frame += 1 - return ret + return self.CC.update(c, self.CS) diff --git a/selfdrive/car/gm/radar_interface.py b/selfdrive/car/gm/radar_interface.py index 66fac54748..6904e6f899 100755 --- a/selfdrive/car/gm/radar_interface.py +++ b/selfdrive/car/gm/radar_interface.py @@ -1,9 +1,9 @@ #!/usr/bin/env python3 import math from cereal import car +from common.conversions import Conversions as CV from opendbc.can.parser import CANParser from selfdrive.car.gm.values import DBC, CAR, CanBus -from selfdrive.config import Conversions as CV from selfdrive.car.interfaces import RadarInterfaceBase RADAR_HEADER_MSG = 1120 diff --git a/selfdrive/car/gm/values.py b/selfdrive/car/gm/values.py index 8e09076713..84fa36a994 100644 --- a/selfdrive/car/gm/values.py +++ b/selfdrive/car/gm/values.py @@ -1,13 +1,20 @@ +from collections import defaultdict +from dataclasses import dataclass +from enum import Enum +from typing import Dict, List, Union + from cereal import car from selfdrive.car import dbc_dict +from selfdrive.car.docs_definitions import CarFootnote, CarInfo, Column, Harness Ecu = car.CarParams.Ecu -class CarControllerParams(): - STEER_MAX = 300 # Safety limit, not LKA max. Trucks use 600. - STEER_STEP = 2 # control frames per command - STEER_DELTA_UP = 7 + +class CarControllerParams: + STEER_MAX = 300 # GM limit is 3Nm. Used by carcontroller to generate LKA output + ACTIVE_STEER_STEP = 2 # Active control frames per command (50hz) + INACTIVE_STEER_STEP = 10 # Inactive control frames per command (10hz) + STEER_DELTA_UP = 7 # Delta rates require review due to observed EPS weakness STEER_DELTA_DOWN = 17 - MIN_STEER_SPEED = 3. # m/s STEER_DRIVER_ALLOWANCE = 50 STEER_DRIVER_MULTIPLIER = 4 STEER_DRIVER_FACTOR = 100 @@ -17,26 +24,41 @@ class CarControllerParams(): ADAS_KEEPALIVE_STEP = 100 CAMERA_KEEPALIVE_STEP = 100 - # Volt gasbrake lookups - MAX_GAS = 3072 # Safety limit, not ACC max. Stock ACC >4096 from standstill. - ZERO_GAS = 2048 # Coasting - MAX_BRAKE = 350 # ~ -3.5 m/s^2 with regen - # Allow small margin below -3.5 m/s^2 from ISO 15622:2018 since we # perform the closed loop control, and might need some # to apply some more braking if we're on a downhill slope. # Our controller should still keep the 2 second average above # -3.5 m/s^2 as per planner limits - ACCEL_MAX = 2. # m/s^2 - ACCEL_MIN = -4. # m/s^2 + ACCEL_MAX = 2. # m/s^2 + ACCEL_MIN = -4. # m/s^2 - MAX_ACC_REGEN = 1404 # Max ACC regen is slightly less than max paddle regen - GAS_LOOKUP_BP = [-1., 0., ACCEL_MAX] - GAS_LOOKUP_V = [MAX_ACC_REGEN, ZERO_GAS, MAX_GAS] - BRAKE_LOOKUP_BP = [ACCEL_MIN, -1.] - BRAKE_LOOKUP_V = [MAX_BRAKE, 0.] + def __init__(self, CP): + # Gas/brake lookups + self.ZERO_GAS = 2048 # Coasting + self.MAX_BRAKE = 400 # ~ -4.0 m/s^2 with regen + + if CP.carFingerprint in CAMERA_ACC_CAR: + self.MAX_GAS = 3400 + self.MAX_ACC_REGEN = 1514 + self.INACTIVE_REGEN = 1554 + # Camera ACC vehicles have no regen while enabled. + # Camera transitions to MAX_ACC_REGEN from ZERO_GAS and uses friction brakes instantly + max_regen_acceleration = 0. + + else: + self.MAX_GAS = 3072 # Safety limit, not ACC max. Stock ACC >4096 from standstill. + self.MAX_ACC_REGEN = 1404 # Max ACC regen is slightly less than max paddle regen + self.INACTIVE_REGEN = 1404 + # ICE has much less engine braking force compared to regen in EVs, + # lower threshold removes some braking deadzone + max_regen_acceleration = -1. if CP.carFingerprint in EV_CAR else -0.1 + + self.GAS_LOOKUP_BP = [max_regen_acceleration, 0., self.ACCEL_MAX] + self.GAS_LOOKUP_V = [self.MAX_ACC_REGEN, self.ZERO_GAS, self.MAX_GAS] + + self.BRAKE_LOOKUP_BP = [self.ACCEL_MIN, max_regen_acceleration] + self.BRAKE_LOOKUP_V = [self.MAX_BRAKE, 0.] -STEER_THRESHOLD = 1.0 class CAR: HOLDEN_ASTRA = "HOLDEN ASTRA RS-V BK 2017" @@ -46,6 +68,49 @@ class CAR: ACADIA = "GMC ACADIA DENALI 2018" BUICK_REGAL = "BUICK REGAL ESSENCE 2018" ESCALADE_ESV = "CADILLAC ESCALADE ESV 2016" + BOLT_EUV = "CHEVROLET BOLT EUV 2022" + SILVERADO = "CHEVROLET SILVERADO 1500 2020" + EQUINOX = "CHEVROLET EQUINOX 2019" + + +class Footnote(Enum): + OBD_II = CarFootnote( + 'Requires a community built ASCM harness. ' + + 'NOTE: disconnecting the ASCM disables Automatic Emergency Braking (AEB).', + Column.MODEL) + + +@dataclass +class GMCarInfo(CarInfo): + package: str = "Adaptive Cruise Control (ACC)" + + def init_make(self, CP: car.CarParams): + if CP.networkLocation == car.CarParams.NetworkLocation.fwdCamera: + self.harness = Harness.gm + else: + self.harness = Harness.obd_ii + self.footnotes.append(Footnote.OBD_II) + + +CAR_INFO: Dict[str, Union[GMCarInfo, List[GMCarInfo]]] = { + CAR.HOLDEN_ASTRA: GMCarInfo("Holden Astra 2017"), + CAR.VOLT: GMCarInfo("Chevrolet Volt 2017-18", min_enable_speed=0, video_link="https://youtu.be/QeMCN_4TFfQ"), + CAR.CADILLAC_ATS: GMCarInfo("Cadillac ATS Premium Performance 2018"), + CAR.MALIBU: GMCarInfo("Chevrolet Malibu Premier 2017"), + CAR.ACADIA: GMCarInfo("GMC Acadia 2018", video_link="https://www.youtube.com/watch?v=0ZN6DdsBUZo"), + CAR.BUICK_REGAL: GMCarInfo("Buick Regal Essence 2018"), + CAR.ESCALADE_ESV: GMCarInfo("Cadillac Escalade ESV 2016", "Adaptive Cruise Control (ACC) & LKAS"), + CAR.BOLT_EUV: [ + GMCarInfo("Chevrolet Bolt EUV 2022-23", "Premier or Premier Redline Trim without Super Cruise Package", "https://youtu.be/xvwzGMUA210"), + GMCarInfo("Chevrolet Bolt EV 2022-23", "2LT Trim with Adaptive Cruise Control Package"), + ], + CAR.SILVERADO: [ + GMCarInfo("Chevrolet Silverado 1500 2020-21", "Safety Package II"), + GMCarInfo("GMC Sierra 1500 2020-21", "Driver Alert Package II", "https://youtu.be/5HbNoBLzRwE"), + ], + CAR.EQUINOX: GMCarInfo("Chevrolet Equinox 2019-22"), +} + class CruiseButtons: INIT = 0 @@ -64,13 +129,16 @@ class AccState: class CanBus: POWERTRAIN = 0 OBSTACLE = 1 + CAMERA = 2 CHASSIS = 2 SW_GMLAN = 3 LOOPBACK = 128 + DROPPED = 192 FINGERPRINTS = { + CAR.HOLDEN_ASTRA: [ # Astra BK MY17, ASCM unplugged - CAR.HOLDEN_ASTRA: [{ + { 190: 8, 193: 8, 197: 8, 199: 4, 201: 8, 209: 7, 211: 8, 241: 6, 249: 8, 288: 5, 298: 8, 304: 1, 309: 8, 311: 8, 313: 8, 320: 3, 328: 1, 352: 5, 381: 6, 384: 4, 386: 8, 388: 8, 393: 8, 398: 8, 401: 8, 413: 8, 417: 8, 419: 8, 422: 1, 426: 7, 431: 8, 442: 8, 451: 8, 452: 8, 453: 8, 455: 7, 456: 8, 458: 5, 479: 8, 481: 7, 485: 8, 489: 8, 497: 8, 499: 3, 500: 8, 501: 8, 508: 8, 528: 5, 532: 6, 554: 3, 560: 8, 562: 8, 563: 5, 564: 5, 565: 5, 567: 5, 647: 5, 707: 8, 715: 8, 723: 8, 753: 5, 761: 7, 806: 1, 810: 8, 840: 5, 842: 5, 844: 8, 866: 4, 961: 8, 969: 8, 977: 8, 979: 8, 985: 5, 1001: 8, 1009: 8, 1011: 6, 1017: 8, 1019: 3, 1020: 8, 1105: 6, 1217: 8, 1221: 5, 1225: 8, 1233: 8, 1249: 8, 1257: 6, 1259: 8, 1261: 7, 1263: 4, 1265: 8, 1267: 8, 1280: 4, 1300: 8, 1328: 4, 1417: 8, 1906: 7, 1907: 7, 1908: 7, 1912: 7, 1919: 7, }], CAR.VOLT: [ @@ -110,14 +178,25 @@ FINGERPRINTS = { { 309: 1, 848: 8, 849: 8, 850: 8, 851: 8, 852: 8, 853: 8, 854: 3, 1056: 6, 1057: 8, 1058: 8, 1059: 8, 1060: 8, 1061: 8, 1062: 8, 1063: 8, 1064: 8, 1065: 8, 1066: 8, 1067: 8, 1068: 8, 1120: 8, 1121: 8, 1122: 8, 1123: 8, 1124: 8, 1125: 8, 1126: 8, 1127: 8, 1128: 8, 1129: 8, 1130: 8, 1131: 8, 1132: 8, 1133: 8, 1134: 8, 1135: 8, 1136: 8, 1137: 8, 1138: 8, 1139: 8, 1140: 8, 1141: 8, 1142: 8, 1143: 8, 1146: 8, 1147: 8, 1148: 8, 1149: 8, 1150: 8, 1151: 8, 1216: 8, 1217: 8, 1218: 8, 1219: 8, 1220: 8, 1221: 8, 1222: 8, 1223: 8, 1224: 8, 1225: 8, 1226: 8, 1232: 8, 1233: 8, 1234: 8, 1235: 8, 1236: 8, 1237: 8, 1238: 8, 1239: 8, 1240: 8, 1241: 8, 1242: 8, 1787: 8, 1788: 8 }], + CAR.BOLT_EUV: [ + { + 189: 7, 190: 7, 193: 8, 197: 8, 201: 8, 209: 7, 211: 3, 241: 6, 257: 8, 288: 5, 289: 8, 298: 8, 304: 3, 309: 8, 311: 8, 313: 8, 320: 4, 322: 7, 328: 1, 352: 5, 381: 8, 384: 4, 386: 8, 388: 8, 451: 8, 452: 8, 453: 6, 458: 5, 463: 3, 479: 3, 481: 7, 485: 8, 489: 8, 497: 8, 500: 6, 501: 8, 528: 5, 532: 6, 560: 8, 562: 8, 563: 5, 565: 5, 566: 8, 608: 8, 609: 6, 610: 6, 611: 6, 612: 8, 613: 8, 707: 8, 715: 8, 717: 5, 753: 5, 761: 7, 789: 5, 800: 6, 810: 8, 840: 5, 842: 5, 844: 8, 848: 4, 869: 4, 880: 6, 977: 8, 1001: 8, 1017: 8, 1020: 8, 1217: 8, 1221: 5, 1233: 8, 1249: 8, 1265: 8, 1280: 4, 1296: 4, 1300: 8, 1930: 7 + }], + CAR.SILVERADO: [ + { + 190: 6, 193: 8, 197: 8, 201: 8, 208: 8, 209: 7, 211: 2, 241: 6, 249: 8, 257: 8, 288: 5, 289: 8, 298: 8, 304: 3, 309: 8, 311: 8, 313: 8, 320: 4, 322: 7, 328: 1, 352: 5, 381: 8, 384: 4, 386: 8, 388: 8, 413: 8, 451: 8, 452: 8, 453: 6, 455: 7, 460: 5, 463: 3, 479: 3, 481: 7, 485: 8, 489: 8, 497: 8, 500: 6, 501: 8, 528: 5, 532: 6, 534: 2, 560: 8, 562: 8, 563: 5, 565: 5, 608: 8, 609: 6, 610: 6, 611: 6, 612: 8, 613: 8, 707: 8, 715: 8, 717: 5, 761: 7, 789: 5, 800: 6, 801: 8, 810: 8, 840: 5, 842: 5, 844: 8, 848: 4, 869: 4, 880: 6, 977: 8, 1001: 8, 1011: 6, 1017: 8, 1020: 8, 1033: 7, 1034: 7, 1217: 8, 1221: 5, 1233: 8, 1249: 8, 1259: 8, 1261: 7, 1263: 4, 1265: 8, 1267: 1, 1271: 8, 1280: 4, 1296: 4, 1300: 8, 1930: 7 + }], + CAR.EQUINOX: [ + { + 190: 6, 193: 8, 197: 8, 201: 8, 209: 7, 211: 2, 241: 6, 249: 8, 257: 8, 288: 5, 289: 8, 298: 8, 304: 1, 309: 8, 311: 8, 313: 8, 320: 3, 328: 1, 352: 5, 381: 8, 384: 4, 386: 8, 388: 8, 413: 8, 451: 8, 452: 8, 453: 6, 455: 7, 463: 3, 479: 3, 481: 7, 485: 8, 489: 8, 497: 8, 500: 6, 501: 8, 510: 8, 528: 5, 532: 6, 560: 8, 562: 8, 563: 5, 565: 5, 608: 8, 609: 6, 610: 6, 611: 6, 612: 8, 613: 8, 707: 8, 715: 8, 717: 5, 753: 5, 761: 7, 789: 5, 800: 6, 810: 8, 840: 5, 842: 5, 844: 8, 869: 4, 880: 6, 977: 8, 1001: 8, 1011: 6, 1017: 8, 1020: 8, 1033: 7, 1034: 7, 1217: 8, 1221: 5, 1233: 8, 1249: 8, 1259: 8, 1261: 7, 1263: 4, 1265: 8, 1267: 1, 1271: 8, 1280: 4, 1296: 4, 1300: 8, 1930: 7 + }], } -DBC = { - CAR.HOLDEN_ASTRA: dbc_dict('gm_global_a_powertrain_generated', 'gm_global_a_object', chassis_dbc='gm_global_a_chassis'), - CAR.VOLT: dbc_dict('gm_global_a_powertrain_generated', 'gm_global_a_object', chassis_dbc='gm_global_a_chassis'), - CAR.MALIBU: dbc_dict('gm_global_a_powertrain_generated', 'gm_global_a_object', chassis_dbc='gm_global_a_chassis'), - CAR.ACADIA: dbc_dict('gm_global_a_powertrain_generated', 'gm_global_a_object', chassis_dbc='gm_global_a_chassis'), - CAR.CADILLAC_ATS: dbc_dict('gm_global_a_powertrain_generated', 'gm_global_a_object', chassis_dbc='gm_global_a_chassis'), - CAR.BUICK_REGAL: dbc_dict('gm_global_a_powertrain_generated', 'gm_global_a_object', chassis_dbc='gm_global_a_chassis'), - CAR.ESCALADE_ESV: dbc_dict('gm_global_a_powertrain_generated', 'gm_global_a_object', chassis_dbc='gm_global_a_chassis'), -} +DBC: Dict[str, Dict[str, str]] = defaultdict(lambda: dbc_dict('gm_global_a_powertrain_generated', 'gm_global_a_object', chassis_dbc='gm_global_a_chassis')) + +EV_CAR = {CAR.VOLT, CAR.BOLT_EUV} + +# We're integrated at the camera with VOACC on these cars (instead of ASCM w/ OBD-II harness) +CAMERA_ACC_CAR = {CAR.BOLT_EUV, CAR.SILVERADO, CAR.EQUINOX} + +STEER_THRESHOLD = 1.0 diff --git a/selfdrive/car/honda/carcontroller.py b/selfdrive/car/honda/carcontroller.py index 49581799a7..66a1485dc6 100644 --- a/selfdrive/car/honda/carcontroller.py +++ b/selfdrive/car/honda/carcontroller.py @@ -1,18 +1,21 @@ from collections import namedtuple + from cereal import car -from common.realtime import DT_CTRL -from selfdrive.controls.lib.drive_helpers import rate_limit +from common.conversions import Conversions as CV from common.numpy_fast import clip, interp +from common.realtime import DT_CTRL +from opendbc.can.packer import CANPacker from selfdrive.car import create_gas_interceptor_command from selfdrive.car.honda import hondacan -from selfdrive.car.honda.values import CruiseButtons, VISUAL_HUD, HONDA_BOSCH, HONDA_NIDEC_ALT_PCM_ACCEL, CarControllerParams -from opendbc.can.packer import CANPacker +from selfdrive.car.honda.values import CruiseButtons, VISUAL_HUD, HONDA_BOSCH, HONDA_BOSCH_RADARLESS, HONDA_NIDEC_ALT_PCM_ACCEL, CarControllerParams +from selfdrive.controls.lib.drive_helpers import rate_limit VisualAlert = car.CarControl.HUDControl.VisualAlert LongCtrlState = car.CarControl.Actuators.LongControlState + def compute_gb_honda_bosch(accel, speed): - #TODO returns 0s, is unused + # TODO returns 0s, is unused return 0.0, 0.0 @@ -33,14 +36,14 @@ def compute_gas_brake(accel, speed, fingerprint): return compute_gb_honda_nidec(accel, speed) -#TODO not clear this does anything useful -def actuator_hystereses(brake, braking, brake_steady, v_ego, car_fingerprint): +# TODO not clear this does anything useful +def actuator_hysteresis(brake, braking, brake_steady, v_ego, car_fingerprint): # hyst params - brake_hyst_on = 0.02 # to activate brakes exceed this value - brake_hyst_off = 0.005 # to deactivate brakes below this value - brake_hyst_gap = 0.01 # don't change brake command for small oscillations within this value + brake_hyst_on = 0.02 # to activate brakes exceed this value + brake_hyst_off = 0.005 # to deactivate brakes below this value + brake_hyst_gap = 0.01 # don't change brake command for small oscillations within this value - #*** hysteresis logic to avoid brake blinking. go above 0.1 to trigger + # *** hysteresis logic to avoid brake blinking. go above 0.1 to trigger if (brake < brake_hyst_on and not braking) or brake < brake_hyst_off: brake = 0. braking = brake > 0. @@ -92,173 +95,173 @@ def process_hud_alert(hud_alert): HUDData = namedtuple("HUDData", - ["pcm_accel", "v_cruise", "car", - "lanes", "fcw", "acc_alert", "steer_required"]) + ["pcm_accel", "v_cruise", "lead_visible", + "lanes_visible", "fcw", "acc_alert", "steer_required"]) + +def rate_limit_steer(new_steer, last_steer): + # TODO just hardcoded ramp to min/max in 0.33s for all Honda + MAX_DELTA = 3 * DT_CTRL + return clip(new_steer, last_steer - MAX_DELTA, last_steer + MAX_DELTA) -class CarController(): + +class CarController: def __init__(self, dbc_name, CP, VM): + self.CP = CP + self.packer = CANPacker(dbc_name) + self.params = CarControllerParams(CP) + self.frame = 0 + self.braking = False self.brake_steady = 0. self.brake_last = 0. self.apply_brake_last = 0 self.last_pump_ts = 0. - self.packer = CANPacker(dbc_name) - self.accel = 0 - self.speed = 0 - self.gas = 0 - self.brake = 0 + self.accel = 0.0 + self.speed = 0.0 + self.gas = 0.0 + self.brake = 0.0 + self.last_steer = 0.0 - self.params = CarControllerParams(CP) - - def update(self, enabled, active, CS, frame, actuators, pcm_cancel_cmd, - hud_v_cruise, hud_show_lanes, hud_show_car, hud_alert): + def update(self, CC, CS): + actuators = CC.actuators + hud_control = CC.hudControl + hud_v_cruise = hud_control.setSpeed * CV.MS_TO_KPH if hud_control.speedVisible else 255 + pcm_cancel_cmd = CC.cruiseControl.cancel - P = self.params - - if active: + if CC.longActive: accel = actuators.accel - gas, brake = compute_gas_brake(actuators.accel, CS.out.vEgo, CS.CP.carFingerprint) + gas, brake = compute_gas_brake(actuators.accel, CS.out.vEgo, self.CP.carFingerprint) else: accel = 0.0 gas, brake = 0.0, 0.0 + # *** rate limit steer *** + limited_steer = rate_limit_steer(actuators.steer, self.last_steer) + self.last_steer = limited_steer + # *** apply brake hysteresis *** - pre_limit_brake, self.braking, self.brake_steady = actuator_hystereses(brake, self.braking, self.brake_steady, CS.out.vEgo, CS.CP.carFingerprint) + pre_limit_brake, self.braking, self.brake_steady = actuator_hysteresis(brake, self.braking, self.brake_steady, + CS.out.vEgo, self.CP.carFingerprint) # *** rate limit after the enable check *** self.brake_last = rate_limit(pre_limit_brake, self.brake_last, -2., DT_CTRL) # vehicle hud display, wait for one update from 10Hz 0x304 msg - if hud_show_lanes: - hud_lanes = 1 - else: - hud_lanes = 0 - - if enabled: - if hud_show_car: - hud_car = 2 - else: - hud_car = 1 - else: - hud_car = 0 - - fcw_display, steer_required, acc_alert = process_hud_alert(hud_alert) - + fcw_display, steer_required, acc_alert = process_hud_alert(hud_control.visualAlert) # **** process the car messages **** # steer torque is converted back to CAN reference (positive when steering right) - apply_steer = int(interp(-actuators.steer * P.STEER_MAX, P.STEER_LOOKUP_BP, P.STEER_LOOKUP_V)) - - lkas_active = active and not CS.steer_not_allowed + apply_steer = int(interp(-limited_steer * self.params.STEER_MAX, + self.params.STEER_LOOKUP_BP, self.params.STEER_LOOKUP_V)) - # Send CAN commands. + # Send CAN commands can_sends = [] # tester present - w/ no response (keeps radar disabled) - if CS.CP.carFingerprint in HONDA_BOSCH and CS.CP.openpilotLongitudinalControl: - if (frame % 10) == 0: + if self.CP.carFingerprint in HONDA_BOSCH and self.CP.openpilotLongitudinalControl: + if self.frame % 10 == 0: can_sends.append((0x18DAB0F1, 0, b"\x02\x3E\x80\x00\x00\x00\x00\x00", 1)) # Send steering command. - idx = frame % 4 - can_sends.append(hondacan.create_steering_control(self.packer, apply_steer, - lkas_active, CS.CP.carFingerprint, idx, CS.CP.openpilotLongitudinalControl)) - - stopping = actuators.longControlState == LongCtrlState.stopping + can_sends.append(hondacan.create_steering_control(self.packer, apply_steer, CC.latActive, self.CP.carFingerprint, + CS.CP.openpilotLongitudinalControl)) # wind brake from air resistance decel at high speed wind_brake = interp(CS.out.vEgo, [0.0, 2.3, 35.0], [0.001, 0.002, 0.15]) # all of this is only relevant for HONDA NIDEC - max_accel = interp(CS.out.vEgo, P.NIDEC_MAX_ACCEL_BP, P.NIDEC_MAX_ACCEL_V) + max_accel = interp(CS.out.vEgo, self.params.NIDEC_MAX_ACCEL_BP, self.params.NIDEC_MAX_ACCEL_V) # TODO this 1.44 is just to maintain previous behavior pcm_speed_BP = [-wind_brake, - -wind_brake*(3/4), - 0.0, - 0.5] + -wind_brake * (3 / 4), + 0.0, + 0.5] # The Honda ODYSSEY seems to have different PCM_ACCEL # msgs, is it other cars too? - if CS.CP.enableGasInterceptor: + if self.CP.enableGasInterceptor or not CC.longActive: pcm_speed = 0.0 pcm_accel = int(0.0) - elif CS.CP.carFingerprint in HONDA_NIDEC_ALT_PCM_ACCEL: + elif self.CP.carFingerprint in HONDA_NIDEC_ALT_PCM_ACCEL: pcm_speed_V = [0.0, clip(CS.out.vEgo - 3.0, 0.0, 100.0), clip(CS.out.vEgo + 0.0, 0.0, 100.0), clip(CS.out.vEgo + 5.0, 0.0, 100.0)] - pcm_speed = interp(gas-brake, pcm_speed_BP, pcm_speed_V) - pcm_accel = int((1.0) * 0xc6) + pcm_speed = interp(gas - brake, pcm_speed_BP, pcm_speed_V) + pcm_accel = int(1.0 * self.params.NIDEC_GAS_MAX) else: pcm_speed_V = [0.0, clip(CS.out.vEgo - 2.0, 0.0, 100.0), clip(CS.out.vEgo + 2.0, 0.0, 100.0), clip(CS.out.vEgo + 5.0, 0.0, 100.0)] - pcm_speed = interp(gas-brake, pcm_speed_BP, pcm_speed_V) - pcm_accel = int(clip((accel/1.44)/max_accel, 0.0, 1.0) * 0xc6) + pcm_speed = interp(gas - brake, pcm_speed_BP, pcm_speed_V) + pcm_accel = int(clip((accel / 1.44) / max_accel, 0.0, 1.0) * self.params.NIDEC_GAS_MAX) - if not CS.CP.openpilotLongitudinalControl: - if (frame % 2) == 0: - idx = frame // 2 - can_sends.append(hondacan.create_bosch_supplemental_1(self.packer, CS.CP.carFingerprint, idx)) + if not self.CP.openpilotLongitudinalControl: + if self.frame % 2 == 0 and self.CP.carFingerprint not in HONDA_BOSCH_RADARLESS: # radarless cars don't have supplemental message + can_sends.append(hondacan.create_bosch_supplemental_1(self.packer, self.CP.carFingerprint)) # If using stock ACC, spam cancel command to kill gas when OP disengages. if pcm_cancel_cmd: - can_sends.append(hondacan.spam_buttons_command(self.packer, CruiseButtons.CANCEL, idx, CS.CP.carFingerprint)) - elif CS.out.cruiseState.standstill: - can_sends.append(hondacan.spam_buttons_command(self.packer, CruiseButtons.RES_ACCEL, idx, CS.CP.carFingerprint)) + can_sends.append(hondacan.spam_buttons_command(self.packer, CruiseButtons.CANCEL, self.CP.carFingerprint)) + elif CC.cruiseControl.resume: + can_sends.append(hondacan.spam_buttons_command(self.packer, CruiseButtons.RES_ACCEL, self.CP.carFingerprint)) else: # Send gas and brake commands. - if (frame % 2) == 0: - idx = frame // 2 - ts = frame * DT_CTRL - - if CS.CP.carFingerprint in HONDA_BOSCH: - self.accel = clip(accel, P.BOSCH_ACCEL_MIN, P.BOSCH_ACCEL_MAX) - self.gas = interp(accel, P.BOSCH_GAS_LOOKUP_BP, P.BOSCH_GAS_LOOKUP_V) - can_sends.extend(hondacan.create_acc_commands(self.packer, enabled, active, accel, self.gas, idx, stopping, CS.CP.carFingerprint)) + if self.frame % 2 == 0: + ts = self.frame * DT_CTRL + + if self.CP.carFingerprint in HONDA_BOSCH: + self.accel = clip(accel, self.params.BOSCH_ACCEL_MIN, self.params.BOSCH_ACCEL_MAX) + self.gas = interp(accel, self.params.BOSCH_GAS_LOOKUP_BP, self.params.BOSCH_GAS_LOOKUP_V) + + stopping = actuators.longControlState == LongCtrlState.stopping + can_sends.extend(hondacan.create_acc_commands(self.packer, CC.enabled, CC.longActive, self.accel, self.gas, + stopping, self.CP.carFingerprint)) else: apply_brake = clip(self.brake_last - wind_brake, 0.0, 1.0) - apply_brake = int(clip(apply_brake * P.NIDEC_BRAKE_MAX, 0, P.NIDEC_BRAKE_MAX - 1)) + apply_brake = int(clip(apply_brake * self.params.NIDEC_BRAKE_MAX, 0, self.params.NIDEC_BRAKE_MAX - 1)) pump_on, self.last_pump_ts = brake_pump_hysteresis(apply_brake, self.apply_brake_last, self.last_pump_ts, ts) pcm_override = True can_sends.append(hondacan.create_brake_command(self.packer, apply_brake, pump_on, - pcm_override, pcm_cancel_cmd, fcw_display, idx, CS.CP.carFingerprint, CS.stock_brake)) + pcm_override, pcm_cancel_cmd, fcw_display, + self.CP.carFingerprint, CS.stock_brake)) self.apply_brake_last = apply_brake - self.brake = apply_brake / P.NIDEC_BRAKE_MAX + self.brake = apply_brake / self.params.NIDEC_BRAKE_MAX - if CS.CP.enableGasInterceptor: + if self.CP.enableGasInterceptor: # way too aggressive at low speed without this gas_mult = interp(CS.out.vEgo, [0., 10.], [0.4, 1.0]) # send exactly zero if apply_gas is zero. Interceptor will send the max between read value and apply_gas. # This prevents unexpected pedal range rescaling # Sending non-zero gas when OP is not enabled will cause the PCM not to respond to throttle as expected # when you do enable. - if active: - self.gas = clip(gas_mult * (gas - brake + wind_brake*3/4), 0., 1.) + if CC.longActive: + self.gas = clip(gas_mult * (gas - brake + wind_brake * 3 / 4), 0., 1.) else: self.gas = 0.0 - can_sends.append(create_gas_interceptor_command(self.packer, self.gas, idx)) + can_sends.append(create_gas_interceptor_command(self.packer, self.gas, self.frame // 2)) # Send dashboard UI commands. - if (frame % 10) == 0: - idx = (frame//10) % 4 - hud = HUDData(int(pcm_accel), int(round(hud_v_cruise)), hud_car, - hud_lanes, fcw_display, acc_alert, steer_required) - can_sends.extend(hondacan.create_ui_commands(self.packer, CS.CP, pcm_speed, hud, CS.is_metric, idx, CS.stock_hud)) + if self.frame % 10 == 0: + hud = HUDData(int(pcm_accel), int(round(hud_v_cruise)), hud_control.leadVisible, + hud_control.lanesVisible, fcw_display, acc_alert, steer_required) + can_sends.extend(hondacan.create_ui_commands(self.packer, self.CP, CC.enabled, pcm_speed, hud, CS.is_metric, CS.acc_hud, CS.lkas_hud)) - if (CS.CP.openpilotLongitudinalControl) and (CS.CP.carFingerprint not in HONDA_BOSCH): + if self.CP.openpilotLongitudinalControl and self.CP.carFingerprint not in HONDA_BOSCH: self.speed = pcm_speed - if not CS.CP.enableGasInterceptor: - self.gas = pcm_accel / 0xc6 + if not self.CP.enableGasInterceptor: + self.gas = pcm_accel / self.params.NIDEC_GAS_MAX new_actuators = actuators.copy() new_actuators.speed = self.speed new_actuators.accel = self.accel new_actuators.gas = self.gas new_actuators.brake = self.brake + new_actuators.steer = self.last_steer + self.frame += 1 return new_actuators, can_sends diff --git a/selfdrive/car/honda/carstate.py b/selfdrive/car/honda/carstate.py index 0a56a02b94..a37667fd3a 100644 --- a/selfdrive/car/honda/carstate.py +++ b/selfdrive/car/honda/carstate.py @@ -1,11 +1,13 @@ -from cereal import car from collections import defaultdict + +from cereal import car +from common.conversions import Conversions as CV from common.numpy_fast import interp from opendbc.can.can_define import CANDefine from opendbc.can.parser import CANParser -from selfdrive.config import Conversions as CV +from selfdrive.car.honda.hondacan import get_pt_bus +from selfdrive.car.honda.values import CAR, DBC, STEER_THRESHOLD, HONDA_BOSCH, HONDA_NIDEC_ALT_SCM_MESSAGES, HONDA_BOSCH_ALT_BRAKE_SIGNAL, HONDA_BOSCH_RADARLESS from selfdrive.car.interfaces import CarStateBase -from selfdrive.car.honda.values import CAR, DBC, STEER_THRESHOLD, HONDA_BOSCH, HONDA_NIDEC_ALT_SCM_MESSAGES, HONDA_BOSCH_ALT_BRAKE_SIGNAL TransmissionType = car.CarParams.TransmissionType @@ -21,9 +23,10 @@ def get_can_signals(CP, gearbox_msg, main_on_sig_msg): ("STEER_ANGLE_RATE", "STEERING_SENSORS"), ("MOTOR_TORQUE", "STEER_MOTOR_TORQUE"), ("STEER_TORQUE_SENSOR", "STEER_STATUS"), + ("IMPERIAL_UNIT", "CAR_SPEED"), + ("ROUGH_CAR_SPEED_2", "CAR_SPEED"), ("LEFT_BLINKER", "SCM_FEEDBACK"), ("RIGHT_BLINKER", "SCM_FEEDBACK"), - ("GEAR", gearbox_msg), ("SEATBELT_DRIVER_LAMP", "SEATBELT_STATUS"), ("SEATBELT_DRIVER_LATCHED", "SEATBELT_STATUS"), ("BRAKE_PRESSED", "POWERTRAIN_DATA"), @@ -34,6 +37,7 @@ def get_can_signals(CP, gearbox_msg, main_on_sig_msg): ("BRAKE_HOLD_ACTIVE", "VSA_STATUS"), ("STEER_STATUS", "STEER_STATUS"), ("GEAR_SHIFTER", gearbox_msg), + ("GEAR", gearbox_msg), ("PEDAL_GAS", "POWERTRAIN_DATA"), ("CRUISE_SETTING", "SCM_BUTTONS"), ("ACC_STATUS", "POWERTRAIN_DATA"), @@ -47,9 +51,10 @@ def get_can_signals(CP, gearbox_msg, main_on_sig_msg): ("SEATBELT_STATUS", 10), ("CRUISE", 10), ("POWERTRAIN_DATA", 100), + ("CAR_SPEED", 10), ("VSA_STATUS", 50), ("STEER_STATUS", 100), - ("STEER_MOTOR_TORQUE", 0), # TODO: not on every car + ("STEER_MOTOR_TORQUE", 0), # TODO: not on every car ] if CP.carFingerprint == CAR.ODYSSEY_CHN: @@ -72,17 +77,13 @@ def get_can_signals(CP, gearbox_msg, main_on_sig_msg): signals.append(("BRAKE_PRESSED", "BRAKE_MODULE")) checks.append(("BRAKE_MODULE", 50)) - if CP.carFingerprint in HONDA_BOSCH: - signals += [ - ("EPB_STATE", "EPB_STATUS"), - ("IMPERIAL_UNIT", "CAR_SPEED"), - ] - checks += [ - ("EPB_STATUS", 50), - ("CAR_SPEED", 10), - ] + if CP.carFingerprint in (HONDA_BOSCH | {CAR.CIVIC, CAR.ODYSSEY, CAR.ODYSSEY_CHN}): + signals.append(("EPB_STATE", "EPB_STATUS")) + checks.append(("EPB_STATUS", 50)) - if not CP.openpilotLongitudinalControl: + if CP.carFingerprint in HONDA_BOSCH: + # these messages are on camera bus on radarless cars + if not CP.openpilotLongitudinalControl and CP.carFingerprint not in HONDA_BOSCH_RADARLESS: signals += [ ("CRUISE_CONTROL_LABEL", "ACC_HUD"), ("CRUISE_SPEED", "ACC_HUD"), @@ -102,34 +103,16 @@ def get_can_signals(CP, gearbox_msg, main_on_sig_msg): else: checks.append(("CRUISE_PARAMS", 50)) - if CP.carFingerprint in (CAR.ACCORD, CAR.ACCORDH, CAR.CIVIC_BOSCH, CAR.CIVIC_BOSCH_DIESEL, CAR.CRV_HYBRID, CAR.INSIGHT, CAR.ACURA_RDX_3G, CAR.HONDA_E): + if CP.carFingerprint in (CAR.ACCORD, CAR.ACCORDH, CAR.CIVIC_BOSCH, CAR.CIVIC_BOSCH_DIESEL, CAR.CRV_HYBRID, CAR.INSIGHT, CAR.ACURA_RDX_3G, CAR.HONDA_E, CAR.CIVIC_2022): signals.append(("DRIVERS_DOOR_OPEN", "SCM_FEEDBACK")) - elif CP.carFingerprint == CAR.ODYSSEY_CHN: + elif CP.carFingerprint in (CAR.ODYSSEY_CHN, CAR.FREED, CAR.HRV): signals.append(("DRIVERS_DOOR_OPEN", "SCM_BUTTONS")) - elif CP.carFingerprint in (CAR.FREED, CAR.HRV): - signals += [("DRIVERS_DOOR_OPEN", "SCM_BUTTONS"), - ("WHEELS_MOVING", "STANDSTILL")] else: signals += [("DOOR_OPEN_FL", "DOORS_STATUS"), ("DOOR_OPEN_FR", "DOORS_STATUS"), ("DOOR_OPEN_RL", "DOORS_STATUS"), - ("DOOR_OPEN_RR", "DOORS_STATUS"), - ("WHEELS_MOVING", "STANDSTILL")] - checks += [ - ("DOORS_STATUS", 3), - ("STANDSTILL", 50), - ] - - if CP.carFingerprint == CAR.CIVIC: - signals += [("IMPERIAL_UNIT", "HUD_SETTING"), - ("EPB_STATE", "EPB_STATUS")] - checks += [ - ("HUD_SETTING", 50), - ("EPB_STATUS", 50), - ] - elif CP.carFingerprint in (CAR.ODYSSEY, CAR.ODYSSEY_CHN): - signals.append(("EPB_STATE", "EPB_STATUS")) - checks.append(("EPB_STATUS", 50)) + ("DOOR_OPEN_RR", "DOORS_STATUS")] + checks.append(("DOORS_STATUS", 3)) # add gas interceptor reading if we are using it if CP.enableGasInterceptor: @@ -168,6 +151,10 @@ class CarState(CarStateBase): self.cruise_setting = 0 self.v_cruise_pcm_prev = 0 + # When available we use cp.vl["CAR_SPEED"]["ROUGH_CAR_SPEED_2"] to populate vEgoCluster + # However, on cars without a digital speedometer this is not always present (HRV, FIT, CRV 2016, ILX and RDX) + self.dash_speed_seen = False + def update(self, cp, cp_cam, cp_body): ret = car.CarState.new_message() @@ -178,30 +165,31 @@ class CarState(CarStateBase): # update prevs, update must run once per loop self.prev_cruise_buttons = self.cruise_buttons self.prev_cruise_setting = self.cruise_setting + self.cruise_setting = cp.vl["SCM_BUTTONS"]["CRUISE_SETTING"] + self.cruise_buttons = cp.vl["SCM_BUTTONS"]["CRUISE_BUTTONS"] + + # used for car hud message + self.is_metric = not cp.vl["CAR_SPEED"]["IMPERIAL_UNIT"] # ******************* parse out can ******************* - # TODO: find wheels moving bit in dbc - if self.CP.carFingerprint in (CAR.ACCORD, CAR.ACCORDH, CAR.CIVIC_BOSCH, CAR.CIVIC_BOSCH_DIESEL, CAR.CRV_HYBRID, CAR.INSIGHT, CAR.ACURA_RDX_3G, CAR.HONDA_E): - ret.standstill = cp.vl["ENGINE_DATA"]["XMISSION_SPEED"] < 0.1 + # STANDSTILL->WHEELS_MOVING bit can be noisy around zero, so use XMISSION_SPEED + # panda checks if the signal is non-zero + ret.standstill = cp.vl["ENGINE_DATA"]["XMISSION_SPEED"] < 1e-5 + # TODO: find a common signal across all cars + if self.CP.carFingerprint in (CAR.ACCORD, CAR.ACCORDH, CAR.CIVIC_BOSCH, CAR.CIVIC_BOSCH_DIESEL, CAR.CRV_HYBRID, CAR.INSIGHT, CAR.ACURA_RDX_3G, CAR.HONDA_E, CAR.CIVIC_2022): ret.doorOpen = bool(cp.vl["SCM_FEEDBACK"]["DRIVERS_DOOR_OPEN"]) - elif self.CP.carFingerprint == CAR.ODYSSEY_CHN: - ret.standstill = cp.vl["ENGINE_DATA"]["XMISSION_SPEED"] < 0.1 - ret.doorOpen = bool(cp.vl["SCM_BUTTONS"]["DRIVERS_DOOR_OPEN"]) - elif self.CP.carFingerprint in (CAR.FREED, CAR.HRV): - ret.standstill = not cp.vl["STANDSTILL"]["WHEELS_MOVING"] + elif self.CP.carFingerprint in (CAR.ODYSSEY_CHN, CAR.FREED, CAR.HRV): ret.doorOpen = bool(cp.vl["SCM_BUTTONS"]["DRIVERS_DOOR_OPEN"]) else: - ret.standstill = not cp.vl["STANDSTILL"]["WHEELS_MOVING"] ret.doorOpen = any([cp.vl["DOORS_STATUS"]["DOOR_OPEN_FL"], cp.vl["DOORS_STATUS"]["DOOR_OPEN_FR"], cp.vl["DOORS_STATUS"]["DOOR_OPEN_RL"], cp.vl["DOORS_STATUS"]["DOOR_OPEN_RR"]]) ret.seatbeltUnlatched = bool(cp.vl["SEATBELT_STATUS"]["SEATBELT_DRIVER_LAMP"] or not cp.vl["SEATBELT_STATUS"]["SEATBELT_DRIVER_LATCHED"]) steer_status = self.steer_status_values[cp.vl["STEER_STATUS"]["STEER_STATUS"]] - ret.steerError = steer_status not in ("NORMAL", "NO_TORQUE_ALERT_1", "NO_TORQUE_ALERT_2", "LOW_SPEED_LOCKOUT", "TMP_FAULT") - # NO_TORQUE_ALERT_2 can be caused by bump OR steering nudge from driver - self.steer_not_allowed = steer_status not in ("NORMAL", "NO_TORQUE_ALERT_2") + ret.steerFaultPermanent = steer_status not in ("NORMAL", "NO_TORQUE_ALERT_1", "NO_TORQUE_ALERT_2", "LOW_SPEED_LOCKOUT", "TMP_FAULT") # LOW_SPEED_LOCKOUT is not worth a warning - ret.steerWarning = steer_status not in ("NORMAL", "LOW_SPEED_LOCKOUT", "NO_TORQUE_ALERT_2") + # NO_TORQUE_ALERT_2 can be caused by bump or steering nudge from driver + ret.steerFaultTemporary = steer_status not in ("NORMAL", "LOW_SPEED_LOCKOUT", "NO_TORQUE_ALERT_2") if self.CP.openpilotLongitudinalControl: self.brake_error = cp.vl["STANDSTILL"]["BRAKE_ERROR_1"] or cp.vl["STANDSTILL"]["BRAKE_ERROR_2"] @@ -220,30 +208,32 @@ class CarState(CarStateBase): ret.vEgoRaw = (1. - v_weight) * cp.vl["ENGINE_DATA"]["XMISSION_SPEED"] * CV.KPH_TO_MS * self.CP.wheelSpeedFactor + v_weight * v_wheel ret.vEgo, ret.aEgo = self.update_speed_kf(ret.vEgoRaw) + self.dash_speed_seen = self.dash_speed_seen or cp.vl["CAR_SPEED"]["ROUGH_CAR_SPEED_2"] > 1e-3 + if self.dash_speed_seen: + conversion = CV.KPH_TO_MS if self.is_metric else CV.MPH_TO_MS + ret.vEgoCluster = cp.vl["CAR_SPEED"]["ROUGH_CAR_SPEED_2"] * conversion + ret.steeringAngleDeg = cp.vl["STEERING_SENSORS"]["STEER_ANGLE"] ret.steeringRateDeg = cp.vl["STEERING_SENSORS"]["STEER_ANGLE_RATE"] - self.cruise_setting = cp.vl["SCM_BUTTONS"]["CRUISE_SETTING"] - self.cruise_buttons = cp.vl["SCM_BUTTONS"]["CRUISE_BUTTONS"] - ret.leftBlinker, ret.rightBlinker = self.update_blinker_from_stalk( 250, cp.vl["SCM_FEEDBACK"]["LEFT_BLINKER"], cp.vl["SCM_FEEDBACK"]["RIGHT_BLINKER"]) ret.brakeHoldActive = cp.vl["VSA_STATUS"]["BRAKE_HOLD_ACTIVE"] == 1 - if self.CP.carFingerprint in (CAR.CIVIC, CAR.ODYSSEY, CAR.ODYSSEY_CHN, CAR.CRV_5G, CAR.ACCORD, CAR.ACCORDH, CAR.CIVIC_BOSCH, - CAR.CIVIC_BOSCH_DIESEL, CAR.CRV_HYBRID, CAR.INSIGHT, CAR.ACURA_RDX_3G, CAR.HONDA_E): - self.park_brake = cp.vl["EPB_STATUS"]["EPB_STATE"] != 0 - else: - self.park_brake = 0 # TODO + # TODO: set for all cars + if self.CP.carFingerprint in (HONDA_BOSCH | {CAR.CIVIC, CAR.ODYSSEY, CAR.ODYSSEY_CHN}): + ret.parkingBrake = cp.vl["EPB_STATUS"]["EPB_STATE"] != 0 gear = int(cp.vl[self.gearbox_msg]["GEAR_SHIFTER"]) ret.gearShifter = self.parse_gear_shifter(self.shifter_values.get(gear, None)) if self.CP.enableGasInterceptor: - ret.gas = (cp.vl["GAS_SENSOR"]["INTERCEPTOR_GAS"] + cp.vl["GAS_SENSOR"]["INTERCEPTOR_GAS2"]) / 2. + # Same threshold as panda, equivalent to 1e-5 with previous DBC scaling + ret.gas = (cp.vl["GAS_SENSOR"]["INTERCEPTOR_GAS"] + cp.vl["GAS_SENSOR"]["INTERCEPTOR_GAS2"]) // 2 + ret.gasPressed = ret.gas > 492 else: ret.gas = cp.vl["POWERTRAIN_DATA"]["PEDAL_GAS"] - ret.gasPressed = ret.gas > 1e-5 + ret.gasPressed = ret.gas > 1e-5 ret.steeringTorque = cp.vl["STEER_STATUS"]["STEER_TORQUE_SENSOR"] ret.steeringTorqueEps = cp.vl["STEER_MOTOR_TORQUE"]["MOTOR_TORQUE"] @@ -251,11 +241,15 @@ class CarState(CarStateBase): if self.CP.carFingerprint in HONDA_BOSCH: if not self.CP.openpilotLongitudinalControl: - ret.cruiseState.nonAdaptive = cp.vl["ACC_HUD"]["CRUISE_CONTROL_LABEL"] != 0 - ret.cruiseState.standstill = cp.vl["ACC_HUD"]["CRUISE_SPEED"] == 252. + # ACC_HUD is on camera bus on radarless cars + acc_hud = cp_cam.vl["ACC_HUD"] if self.CP.carFingerprint in HONDA_BOSCH_RADARLESS else cp.vl["ACC_HUD"] + ret.cruiseState.nonAdaptive = acc_hud["CRUISE_CONTROL_LABEL"] != 0 + ret.cruiseState.standstill = acc_hud["CRUISE_SPEED"] == 252. + # on certain cars, CRUISE_SPEED changes to imperial with car's unit setting + conversion = CV.MPH_TO_MS if self.CP.carFingerprint in HONDA_BOSCH_RADARLESS and not self.is_metric else CV.KPH_TO_MS # On set, cruise set speed pulses between 254~255 and the set speed prev is set to avoid this. - ret.cruiseState.speed = self.v_cruise_pcm_prev if cp.vl["ACC_HUD"]["CRUISE_SPEED"] > 160.0 else cp.vl["ACC_HUD"]["CRUISE_SPEED"] * CV.KPH_TO_MS + ret.cruiseState.speed = self.v_cruise_pcm_prev if acc_hud["CRUISE_SPEED"] > 160.0 else acc_hud["CRUISE_SPEED"] * conversion self.v_cruise_pcm_prev = ret.cruiseState.speed else: ret.cruiseState.speed = cp.vl["CRUISE"]["CRUISE_SPEED_PCM"] * CV.KPH_TO_MS @@ -284,26 +278,21 @@ class CarState(CarStateBase): if ret.brake > 0.1: ret.brakePressed = True - # TODO: discover the CAN msg that has the imperial unit bit for all other cars - if self.CP.carFingerprint in (CAR.CIVIC, ): - self.is_metric = not cp.vl["HUD_SETTING"]["IMPERIAL_UNIT"] - elif self.CP.carFingerprint in HONDA_BOSCH: - self.is_metric = not cp.vl["CAR_SPEED"]["IMPERIAL_UNIT"] - else: - self.is_metric = False - if self.CP.carFingerprint in HONDA_BOSCH: - ret.stockAeb = (not self.CP.openpilotLongitudinalControl) and bool(cp.vl["ACC_CONTROL"]["AEB_STATUS"] and cp.vl["ACC_CONTROL"]["ACCEL_COMMAND"] < -1e-5) + # TODO: find the radarless AEB_STATUS bit and make sure ACCEL_COMMAND is correct to enable AEB alerts + if self.CP.carFingerprint not in HONDA_BOSCH_RADARLESS: + ret.stockAeb = (not self.CP.openpilotLongitudinalControl) and bool(cp.vl["ACC_CONTROL"]["AEB_STATUS"] and cp.vl["ACC_CONTROL"]["ACCEL_COMMAND"] < -1e-5) else: ret.stockAeb = bool(cp_cam.vl["BRAKE_COMMAND"]["AEB_REQ_1"] and cp_cam.vl["BRAKE_COMMAND"]["COMPUTER_BRAKE"] > 1e-5) - if self.CP.carFingerprint in HONDA_BOSCH: - self.stock_hud = False - ret.stockFcw = False - else: + self.acc_hud = False + self.lkas_hud = False + if self.CP.carFingerprint not in HONDA_BOSCH: ret.stockFcw = cp_cam.vl["BRAKE_COMMAND"]["FCW"] != 0 - self.stock_hud = cp_cam.vl["ACC_HUD"] + self.acc_hud = cp_cam.vl["ACC_HUD"] self.stock_brake = cp_cam.vl["BRAKE_COMMAND"] + if self.CP.carFingerprint in HONDA_BOSCH_RADARLESS: + self.lkas_hud = cp_cam.vl["LKAS_HUD"] if self.CP.enableBsm and self.CP.carFingerprint in (CAR.CRV_5G, ): # BSM messages are on B-CAN, requires a panda forwarding B-CAN messages to CAN 0 @@ -315,8 +304,7 @@ class CarState(CarStateBase): def get_can_parser(self, CP): signals, checks = get_can_signals(CP, self.gearbox_msg, self.main_on_sig_msg) - bus_pt = 1 if CP.carFingerprint in HONDA_BOSCH else 0 - return CANParser(DBC[CP.carFingerprint]["pt"], signals, checks, bus_pt) + return CANParser(DBC[CP.carFingerprint]["pt"], signals, checks, get_pt_bus(CP.carFingerprint)) @staticmethod def get_cam_can_parser(CP): @@ -325,7 +313,17 @@ class CarState(CarStateBase): ("STEERING_CONTROL", 100), ] - if CP.carFingerprint not in HONDA_BOSCH: + if CP.carFingerprint in HONDA_BOSCH_RADARLESS: + signals.append(("LKAS_PROBLEM", "LKAS_HUD")) + checks.append(("LKAS_HUD", 10)) + if not CP.openpilotLongitudinalControl: + signals += [ + ("CRUISE_SPEED", "ACC_HUD"), + ("CRUISE_CONTROL_LABEL", "ACC_HUD"), + ] + checks.append(("ACC_HUD", 10)) + + elif CP.carFingerprint not in HONDA_BOSCH: signals += [("COMPUTER_BRAKE", "BRAKE_COMMAND"), ("AEB_REQ_1", "BRAKE_COMMAND"), ("FCW", "BRAKE_COMMAND"), diff --git a/selfdrive/car/honda/hondacan.py b/selfdrive/car/honda/hondacan.py index db7104cd4f..87f8e6c5de 100644 --- a/selfdrive/car/honda/hondacan.py +++ b/selfdrive/car/honda/hondacan.py @@ -1,5 +1,5 @@ -from selfdrive.car.honda.values import HondaFlags, HONDA_BOSCH, CAR, CarControllerParams -from selfdrive.config import Conversions as CV +from common.conversions import Conversions as CV +from selfdrive.car.honda.values import HondaFlags, HONDA_BOSCH, HONDA_BOSCH_RADARLESS, CAR, CarControllerParams # CAN bus layout with relay # 0 = ACC-CAN - radar side @@ -7,8 +7,9 @@ from selfdrive.config import Conversions as CV # 2 = ACC-CAN - camera side # 3 = F-CAN A - OBDII port + def get_pt_bus(car_fingerprint): - return 1 if car_fingerprint in HONDA_BOSCH else 0 + return 1 if car_fingerprint in (HONDA_BOSCH - HONDA_BOSCH_RADARLESS) else 0 def get_lkas_cmd_bus(car_fingerprint, radar_disabled=False): @@ -18,7 +19,8 @@ def get_lkas_cmd_bus(car_fingerprint, radar_disabled=False): # normally steering commands are sent to radar, which forwards them to powertrain bus return 0 -def create_brake_command(packer, apply_brake, pump_on, pcm_override, pcm_cancel_cmd, fcw, idx, car_fingerprint, stock_brake): + +def create_brake_command(packer, apply_brake, pump_on, pcm_override, pcm_cancel_cmd, fcw, car_fingerprint, stock_brake): # TODO: do we loose pressure if we keep pump off for long? brakelights = apply_brake > 0 brake_rq = apply_brake > 0 @@ -40,10 +42,10 @@ def create_brake_command(packer, apply_brake, pump_on, pcm_override, pcm_cancel_ "AEB_STATUS": 0, } bus = get_pt_bus(car_fingerprint) - return packer.make_can_msg("BRAKE_COMMAND", bus, values, idx) + return packer.make_can_msg("BRAKE_COMMAND", bus, values) -def create_acc_commands(packer, enabled, active, accel, gas, idx, stopping, car_fingerprint): +def create_acc_commands(packer, enabled, active, accel, gas, stopping, car_fingerprint): commands = [] bus = get_pt_bus(car_fingerprint) min_gas_accel = CarControllerParams.BOSCH_GAS_LOOKUP_BP[0] @@ -65,7 +67,7 @@ def create_acc_commands(packer, enabled, active, accel, gas, idx, stopping, car_ "STANDSTILL": standstill, "STANDSTILL_RELEASE": standstill_release, } - commands.append(packer.make_can_msg("ACC_CONTROL", bus, acc_control_values, idx)) + commands.append(packer.make_can_msg("ACC_CONTROL", bus, acc_control_values)) acc_control_on_values = { "SET_TO_3": 0x03, @@ -74,20 +76,21 @@ def create_acc_commands(packer, enabled, active, accel, gas, idx, stopping, car_ "SET_TO_75": 0x75, "SET_TO_30": 0x30, } - commands.append(packer.make_can_msg("ACC_CONTROL_ON", bus, acc_control_on_values, idx)) + commands.append(packer.make_can_msg("ACC_CONTROL_ON", bus, acc_control_on_values)) return commands -def create_steering_control(packer, apply_steer, lkas_active, car_fingerprint, idx, radar_disabled): + +def create_steering_control(packer, apply_steer, lkas_active, car_fingerprint, radar_disabled): values = { "STEER_TORQUE": apply_steer if lkas_active else 0, "STEER_TORQUE_REQUEST": lkas_active, } bus = get_lkas_cmd_bus(car_fingerprint, radar_disabled) - return packer.make_can_msg("STEERING_CONTROL", bus, values, idx) + return packer.make_can_msg("STEERING_CONTROL", bus, values) -def create_bosch_supplemental_1(packer, car_fingerprint, idx): +def create_bosch_supplemental_1(packer, car_fingerprint): # non-active params values = { "SET_ME_X04": 0x04, @@ -95,80 +98,79 @@ def create_bosch_supplemental_1(packer, car_fingerprint, idx): "SET_ME_X10": 0x10, } bus = get_lkas_cmd_bus(car_fingerprint) - return packer.make_can_msg("BOSCH_SUPPLEMENTAL_1", bus, values, idx) + return packer.make_can_msg("BOSCH_SUPPLEMENTAL_1", bus, values) -def create_ui_commands(packer, CP, pcm_speed, hud, is_metric, idx, stock_hud): +def create_ui_commands(packer, CP, enabled, pcm_speed, hud, is_metric, acc_hud, lkas_hud): commands = [] bus_pt = get_pt_bus(CP.carFingerprint) radar_disabled = CP.carFingerprint in HONDA_BOSCH and CP.openpilotLongitudinalControl bus_lkas = get_lkas_cmd_bus(CP.carFingerprint, radar_disabled) if CP.openpilotLongitudinalControl: + acc_hud_values = { + 'CRUISE_SPEED': hud.v_cruise, + 'ENABLE_MINI_CAR': 1, + 'HUD_DISTANCE': 0, # max distance setting on display + 'IMPERIAL_UNIT': int(not is_metric), + 'HUD_LEAD': 2 if enabled and hud.lead_visible else 1 if enabled else 0, + 'SET_ME_X01_2': 1, + } + if CP.carFingerprint in HONDA_BOSCH: - acc_hud_values = { - 'CRUISE_SPEED': hud.v_cruise, - 'ENABLE_MINI_CAR': 1, - 'SET_TO_1': 1, - 'HUD_LEAD': hud.car, - 'HUD_DISTANCE': 3, - 'ACC_ON': hud.car != 0, - 'SET_TO_X1': 1, - 'IMPERIAL_UNIT': int(not is_metric), - 'FCM_OFF': 1, - } + acc_hud_values['ACC_ON'] = int(enabled) + acc_hud_values['FCM_OFF'] = 1 + acc_hud_values['FCM_OFF_2'] = 1 else: - acc_hud_values = { - 'PCM_SPEED': pcm_speed * CV.MS_TO_KPH, - 'PCM_GAS': hud.pcm_accel, - 'CRUISE_SPEED': hud.v_cruise, - 'ENABLE_MINI_CAR': 1, - 'HUD_LEAD': hud.car, - 'HUD_DISTANCE': 3, # max distance setting on display - 'IMPERIAL_UNIT': int(not is_metric), - 'SET_ME_X01_2': 1, - 'SET_ME_X01': 1, - "FCM_OFF": stock_hud["FCM_OFF"], - "FCM_OFF_2": stock_hud["FCM_OFF_2"], - "FCM_PROBLEM": stock_hud["FCM_PROBLEM"], - "ICONS": stock_hud["ICONS"], - } - commands.append(packer.make_can_msg("ACC_HUD", bus_pt, acc_hud_values, idx)) + acc_hud_values['PCM_SPEED'] = pcm_speed * CV.MS_TO_KPH + acc_hud_values['PCM_GAS'] = hud.pcm_accel + acc_hud_values['SET_ME_X01'] = 1 + acc_hud_values['FCM_OFF'] = acc_hud['FCM_OFF'] + acc_hud_values['FCM_OFF_2'] = acc_hud['FCM_OFF_2'] + acc_hud_values['FCM_PROBLEM'] = acc_hud['FCM_PROBLEM'] + acc_hud_values['ICONS'] = acc_hud['ICONS'] + commands.append(packer.make_can_msg("ACC_HUD", bus_pt, acc_hud_values)) lkas_hud_values = { 'SET_ME_X41': 0x41, - 'SET_ME_X48': 0x48, 'STEERING_REQUIRED': hud.steer_required, - 'SOLID_LANES': hud.lanes, + 'SOLID_LANES': hud.lanes_visible, 'BEEP': 0, } + if CP.carFingerprint in HONDA_BOSCH_RADARLESS: + lkas_hud_values['LANE_LINES'] = 3 + lkas_hud_values['DASHED_LANES'] = hud.lanes_visible + # car likely needs to see LKAS_PROBLEM fall within a specific time frame, so forward from camera + lkas_hud_values['LKAS_PROBLEM'] = lkas_hud['LKAS_PROBLEM'] + if not (CP.flags & HondaFlags.BOSCH_EXT_HUD): lkas_hud_values['SET_ME_X48'] = 0x48 if CP.flags & HondaFlags.BOSCH_EXT_HUD and not CP.openpilotLongitudinalControl: - commands.append(packer.make_can_msg('LKAS_HUD_A', bus_lkas, lkas_hud_values, idx)) - commands.append(packer.make_can_msg('LKAS_HUD_B', bus_lkas, lkas_hud_values, idx)) + commands.append(packer.make_can_msg('LKAS_HUD_A', bus_lkas, lkas_hud_values)) + commands.append(packer.make_can_msg('LKAS_HUD_B', bus_lkas, lkas_hud_values)) else: - commands.append(packer.make_can_msg('LKAS_HUD', bus_lkas, lkas_hud_values, idx)) + commands.append(packer.make_can_msg('LKAS_HUD', bus_lkas, lkas_hud_values)) if radar_disabled and CP.carFingerprint in HONDA_BOSCH: radar_hud_values = { 'CMBS_OFF': 0x01, 'SET_TO_1': 0x01, } - commands.append(packer.make_can_msg('RADAR_HUD', bus_pt, radar_hud_values, idx)) + commands.append(packer.make_can_msg('RADAR_HUD', bus_pt, radar_hud_values)) if CP.carFingerprint == CAR.CIVIC_BOSCH: - commands.append(packer.make_can_msg("LEGACY_BRAKE_COMMAND", bus_pt, {}, idx)) + commands.append(packer.make_can_msg("LEGACY_BRAKE_COMMAND", bus_pt, {})) return commands -def spam_buttons_command(packer, button_val, idx, car_fingerprint): +def spam_buttons_command(packer, button_val, car_fingerprint): values = { 'CRUISE_BUTTONS': button_val, 'CRUISE_SETTING': 0, } - bus = get_pt_bus(car_fingerprint) - return packer.make_can_msg("SCM_BUTTONS", bus, values, idx) + # send buttons to camera on radarless cars + bus = 2 if car_fingerprint in HONDA_BOSCH_RADARLESS else get_pt_bus(car_fingerprint) + return packer.make_can_msg("SCM_BUTTONS", bus, values) diff --git a/selfdrive/car/honda/interface.py b/selfdrive/car/honda/interface.py index 94e4305909..990238ae5d 100755 --- a/selfdrive/car/honda/interface.py +++ b/selfdrive/car/honda/interface.py @@ -1,18 +1,19 @@ #!/usr/bin/env python3 from cereal import car from panda import Panda +from common.conversions import Conversions as CV from common.numpy_fast import interp -from common.params import Params -from selfdrive.car.honda.values import CarControllerParams, CruiseButtons, HondaFlags, CAR, HONDA_BOSCH, HONDA_NIDEC_ALT_SCM_MESSAGES, HONDA_BOSCH_ALT_BRAKE_SIGNAL -from selfdrive.car import STD_CARGO_KG, CivicParams, scale_rot_inertia, scale_tire_stiffness, gen_empty_fingerprint, get_safety_config +from selfdrive.car.honda.values import CarControllerParams, CruiseButtons, HondaFlags, CAR, HONDA_BOSCH, HONDA_NIDEC_ALT_SCM_MESSAGES, HONDA_BOSCH_ALT_BRAKE_SIGNAL, HONDA_BOSCH_RADARLESS +from selfdrive.car import STD_CARGO_KG, CivicParams, create_button_event, scale_tire_stiffness, get_safety_config from selfdrive.car.interfaces import CarInterfaceBase from selfdrive.car.disable_ecu import disable_ecu -from selfdrive.config import Conversions as CV ButtonType = car.CarState.ButtonEvent.Type EventName = car.CarEvent.EventName TransmissionType = car.CarParams.TransmissionType +BUTTONS_DICT = {CruiseButtons.RES_ACCEL: ButtonType.accelCruise, CruiseButtons.DECEL_SET: ButtonType.decelCruise, + CruiseButtons.MAIN: ButtonType.altButton3, CruiseButtons.CANCEL: ButtonType.cancel} class CarInterface(CarInterfaceBase): @@ -28,17 +29,18 @@ class CarInterface(CarInterfaceBase): return CarControllerParams.NIDEC_ACCEL_MIN, interp(current_speed, ACCEL_MAX_BP, ACCEL_MAX_VALS) @staticmethod - def get_params(candidate, fingerprint=gen_empty_fingerprint(), car_fw=[]): # pylint: disable=dangerous-default-value - ret = CarInterfaceBase.get_std_params(candidate, fingerprint) + def _get_params(ret, candidate, fingerprint, car_fw, experimental_long): ret.carName = "honda" if candidate in HONDA_BOSCH: ret.safetyConfigs = [get_safety_config(car.CarParams.SafetyModel.hondaBosch)] ret.radarOffCan = True - # Disable the radar and let openpilot control longitudinal - # WARNING: THIS DISABLES AEB! - ret.openpilotLongitudinalControl = Params().get_bool("DisableRadar") + if candidate not in HONDA_BOSCH_RADARLESS: + # Disable the radar and let openpilot control longitudinal + # WARNING: THIS DISABLES AEB! + ret.experimentalLongitudinalAvailable = True + ret.openpilotLongitudinalControl = experimental_long ret.pcmCruise = not ret.openpilotLongitudinalControl else: @@ -84,7 +86,6 @@ class CarInterface(CarInterfaceBase): eps_modified = True if candidate == CAR.CIVIC: - stop_and_go = True ret.mass = CivicParams.MASS ret.wheelbase = CivicParams.WHEELBASE ret.centerToFront = CivicParams.CENTER_TO_FRONT @@ -103,8 +104,7 @@ class CarInterface(CarInterfaceBase): ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[1.1], [0.33]] tire_stiffness_factor = 1. - elif candidate in (CAR.CIVIC_BOSCH, CAR.CIVIC_BOSCH_DIESEL): - stop_and_go = True + elif candidate in (CAR.CIVIC_BOSCH, CAR.CIVIC_BOSCH_DIESEL, CAR.CIVIC_2022): ret.mass = CivicParams.MASS ret.wheelbase = CivicParams.WHEELBASE ret.centerToFront = CivicParams.CENTER_TO_FRONT @@ -114,7 +114,6 @@ class CarInterface(CarInterfaceBase): ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.8], [0.24]] elif candidate in (CAR.ACCORD, CAR.ACCORDH): - stop_and_go = True ret.mass = 3279. * CV.LB_TO_KG + STD_CARGO_KG ret.wheelbase = 2.83 ret.centerToFront = ret.wheelbase * 0.39 @@ -128,7 +127,6 @@ class CarInterface(CarInterfaceBase): ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.6], [0.18]] elif candidate == CAR.ACURA_ILX: - stop_and_go = False ret.mass = 3095. * CV.LB_TO_KG + STD_CARGO_KG ret.wheelbase = 2.67 ret.centerToFront = ret.wheelbase * 0.37 @@ -138,7 +136,6 @@ class CarInterface(CarInterfaceBase): ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.8], [0.24]] elif candidate in (CAR.CRV, CAR.CRV_EU): - stop_and_go = False ret.mass = 3572. * CV.LB_TO_KG + STD_CARGO_KG ret.wheelbase = 2.62 ret.centerToFront = ret.wheelbase * 0.41 @@ -149,7 +146,6 @@ class CarInterface(CarInterfaceBase): ret.wheelSpeedFactor = 1.025 elif candidate == CAR.CRV_5G: - stop_and_go = True ret.mass = 3410. * CV.LB_TO_KG + STD_CARGO_KG ret.wheelbase = 2.66 ret.centerToFront = ret.wheelbase * 0.41 @@ -167,7 +163,6 @@ class CarInterface(CarInterfaceBase): ret.wheelSpeedFactor = 1.025 elif candidate == CAR.CRV_HYBRID: - stop_and_go = True ret.mass = 1667. + STD_CARGO_KG # mean of 4 models in kg ret.wheelbase = 2.66 ret.centerToFront = ret.wheelbase * 0.41 @@ -178,7 +173,6 @@ class CarInterface(CarInterfaceBase): ret.wheelSpeedFactor = 1.025 elif candidate == CAR.FIT: - stop_and_go = False ret.mass = 2644. * CV.LB_TO_KG + STD_CARGO_KG ret.wheelbase = 2.53 ret.centerToFront = ret.wheelbase * 0.39 @@ -188,7 +182,6 @@ class CarInterface(CarInterfaceBase): ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.2], [0.05]] elif candidate == CAR.FREED: - stop_and_go = False ret.mass = 3086. * CV.LB_TO_KG + STD_CARGO_KG ret.wheelbase = 2.74 # the remaining parameters were copied from FIT @@ -199,7 +192,6 @@ class CarInterface(CarInterfaceBase): ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.2], [0.05]] elif candidate == CAR.HRV: - stop_and_go = False ret.mass = 3125 * CV.LB_TO_KG + STD_CARGO_KG ret.wheelbase = 2.61 ret.centerToFront = ret.wheelbase * 0.41 @@ -210,17 +202,15 @@ class CarInterface(CarInterfaceBase): ret.wheelSpeedFactor = 1.025 elif candidate == CAR.ACURA_RDX: - stop_and_go = False 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 - ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0, 1000], [0, 1000]] # TODO: determine if there is a dead zone at the top end tire_stiffness_factor = 0.444 + ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0, 1000], [0, 1000]] # TODO: determine if there is a dead zone at the top end ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.8], [0.24]] elif candidate == CAR.ACURA_RDX_3G: - stop_and_go = True ret.mass = 4068. * CV.LB_TO_KG + STD_CARGO_KG ret.wheelbase = 2.75 ret.centerToFront = ret.wheelbase * 0.41 @@ -229,28 +219,19 @@ class CarInterface(CarInterfaceBase): ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.2], [0.06]] tire_stiffness_factor = 0.677 - elif candidate == CAR.ODYSSEY: - stop_and_go = False - ret.mass = 4471. * CV.LB_TO_KG + STD_CARGO_KG + elif candidate in (CAR.ODYSSEY, CAR.ODYSSEY_CHN): + ret.mass = 1900. + STD_CARGO_KG ret.wheelbase = 3.00 ret.centerToFront = ret.wheelbase * 0.41 ret.steerRatio = 14.35 # as spec - ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0, 4096], [0, 4096]] # TODO: determine if there is a dead zone at the top end - tire_stiffness_factor = 0.82 - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.28], [0.08]] - - elif candidate == CAR.ODYSSEY_CHN: - stop_and_go = False - ret.mass = 1849.2 + STD_CARGO_KG # mean of 4 models in kg - ret.wheelbase = 2.90 - ret.centerToFront = ret.wheelbase * 0.41 # from CAR.ODYSSEY - ret.steerRatio = 14.35 - ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0, 32767], [0, 32767]] # TODO: determine if there is a dead zone at the top end tire_stiffness_factor = 0.82 ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.28], [0.08]] + if candidate == CAR.ODYSSEY_CHN: + ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0, 32767], [0, 32767]] # TODO: determine if there is a dead zone at the top end + else: + ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0, 4096], [0, 4096]] # TODO: determine if there is a dead zone at the top end elif candidate in (CAR.PILOT, CAR.PASSPORT): - stop_and_go = False ret.mass = 4204. * CV.LB_TO_KG + STD_CARGO_KG # average weight ret.wheelbase = 2.82 ret.centerToFront = ret.wheelbase * 0.428 @@ -260,7 +241,6 @@ class CarInterface(CarInterfaceBase): ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.38], [0.11]] elif candidate == CAR.RIDGELINE: - stop_and_go = False ret.mass = 4515. * CV.LB_TO_KG + STD_CARGO_KG ret.wheelbase = 3.18 ret.centerToFront = ret.wheelbase * 0.41 @@ -270,7 +250,6 @@ class CarInterface(CarInterfaceBase): ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.38], [0.11]] elif candidate == CAR.INSIGHT: - stop_and_go = True ret.mass = 2987. * CV.LB_TO_KG + STD_CARGO_KG ret.wheelbase = 2.7 ret.centerToFront = ret.wheelbase * 0.39 @@ -280,7 +259,6 @@ class CarInterface(CarInterfaceBase): ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.6], [0.18]] elif candidate == CAR.HONDA_E: - stop_and_go = True ret.mass = 3338.8 * CV.LB_TO_KG + STD_CARGO_KG ret.wheelbase = 2.5 ret.centerToFront = ret.wheelbase * 0.5 @@ -303,14 +281,14 @@ class CarInterface(CarInterfaceBase): if ret.openpilotLongitudinalControl and candidate in HONDA_BOSCH: ret.safetyConfigs[0].safetyParam |= Panda.FLAG_HONDA_BOSCH_LONG + if candidate in HONDA_BOSCH_RADARLESS: + ret.safetyConfigs[0].safetyParam |= Panda.FLAG_HONDA_RADARLESS + # min speed to enable ACC. if car can do stop and go, then set enabling speed # to a negative value, so it won't matter. Otherwise, add 0.5 mph margin to not # conflict with PCM acc - ret.minEnableSpeed = -1. if (stop_and_go or ret.enableGasInterceptor) else 25.5 * CV.MPH_TO_MS - - # TODO: get actual value, for now starting with reasonable value for - # civic and scaling by mass and wheelbase - ret.rotationalInertia = scale_rot_inertia(ret.mass, ret.wheelbase) + stop_and_go = candidate in (HONDA_BOSCH | {CAR.CIVIC}) or ret.enableGasInterceptor + ret.minEnableSpeed = -1. if stop_and_go else 25.5 * CV.MPH_TO_MS # TODO: start from empirically derived lateral slip stiffness for the civic and scale by # mass and CG position, so all cars will have approximately similar dyn behaviors @@ -318,70 +296,33 @@ class CarInterface(CarInterfaceBase): tire_stiffness_factor=tire_stiffness_factor) ret.steerActuatorDelay = 0.1 - ret.steerRateCost = 0.5 ret.steerLimitTimer = 0.8 return ret @staticmethod def init(CP, logcan, sendcan): - if CP.carFingerprint in HONDA_BOSCH and CP.openpilotLongitudinalControl: + if CP.carFingerprint in (HONDA_BOSCH - HONDA_BOSCH_RADARLESS) and CP.openpilotLongitudinalControl: disable_ecu(logcan, sendcan, bus=1, addr=0x18DAB0F1, com_cont_req=b'\x28\x83\x03') # returns a car.CarState - def update(self, c, can_strings): - # ******************* do can recv ******************* - self.cp.update_strings(can_strings) - self.cp_cam.update_strings(can_strings) - if self.cp_body: - self.cp_body.update_strings(can_strings) - + def _update(self, c): ret = self.CS.update(self.cp, self.cp_cam, self.cp_body) - ret.canValid = self.cp.can_valid and self.cp_cam.can_valid and (self.cp_body is None or self.cp_body.can_valid) - buttonEvents = [] if self.CS.cruise_buttons != self.CS.prev_cruise_buttons: - be = car.CarState.ButtonEvent.new_message() - be.type = ButtonType.unknown - if self.CS.cruise_buttons != 0: - be.pressed = True - but = self.CS.cruise_buttons - else: - be.pressed = False - but = self.CS.prev_cruise_buttons - if but == CruiseButtons.RES_ACCEL: - be.type = ButtonType.accelCruise - elif but == CruiseButtons.DECEL_SET: - be.type = ButtonType.decelCruise - elif but == CruiseButtons.CANCEL: - be.type = ButtonType.cancel - elif but == CruiseButtons.MAIN: - be.type = ButtonType.altButton3 - buttonEvents.append(be) + buttonEvents.append(create_button_event(self.CS.cruise_buttons, self.CS.prev_cruise_buttons, BUTTONS_DICT)) if self.CS.cruise_setting != self.CS.prev_cruise_setting: - be = car.CarState.ButtonEvent.new_message() - be.type = ButtonType.unknown - if self.CS.cruise_setting != 0: - be.pressed = True - but = self.CS.cruise_setting - else: - be.pressed = False - but = self.CS.prev_cruise_setting - if but == 1: - be.type = ButtonType.altButton1 - # TODO: more buttons? - buttonEvents.append(be) + buttonEvents.append(create_button_event(self.CS.cruise_setting, self.CS.prev_cruise_setting, {1: ButtonType.altButton1})) + ret.buttonEvents = buttonEvents # events events = self.create_common_events(ret, pcm_enable=False) if self.CS.brake_error: events.add(EventName.brakeUnavailable) - if self.CS.park_brake: - events.add(EventName.parkBrake) if self.CP.pcmCruise and ret.vEgo < self.CP.minEnableSpeed: events.add(EventName.belowEngageSpeed) @@ -401,39 +342,11 @@ class CarInterface(CarInterfaceBase): if self.CS.CP.minEnableSpeed > 0 and ret.vEgo < 0.001: events.add(EventName.manualRestart) - # handle button presses - for b in ret.buttonEvents: - - # do enable on both accel and decel buttons - if b.type in (ButtonType.accelCruise, ButtonType.decelCruise) and not b.pressed: - if not self.CP.pcmCruise: - events.add(EventName.buttonEnable) - - # do disable on button down - if b.type == ButtonType.cancel and b.pressed: - events.add(EventName.buttonCancel) - ret.events = events.to_msg() - self.CS.out = ret.as_reader() - return self.CS.out + return ret # pass in a car.CarControl # to be called @ 100hz def apply(self, c): - hud_control = c.hudControl - if hud_control.speedVisible: - hud_v_cruise = hud_control.setSpeed * CV.MS_TO_KPH - else: - hud_v_cruise = 255 - - ret = self.CC.update(c.enabled, c.active, self.CS, self.frame, - c.actuators, - c.cruiseControl.cancel, - hud_v_cruise, - hud_control.lanesVisible, - hud_show_car=hud_control.leadVisible, - hud_alert=hud_control.visualAlert) - - self.frame += 1 - return ret + return self.CC.update(c, self.CS) diff --git a/selfdrive/car/honda/values.py b/selfdrive/car/honda/values.py index 50ea52faae..905c9f4b4f 100644 --- a/selfdrive/car/honda/values.py +++ b/selfdrive/car/honda/values.py @@ -1,13 +1,18 @@ -from enum import IntFlag +from dataclasses import dataclass +from enum import Enum, IntFlag +from typing import Dict, List, Optional, Union from cereal import car +from common.conversions import Conversions as CV from selfdrive.car import dbc_dict +from selfdrive.car.docs_definitions import CarFootnote, CarInfo, Column, Harness +from selfdrive.car.fw_query_definitions import FwQueryConfig, Request, StdQueries Ecu = car.CarParams.Ecu VisualAlert = car.CarControl.HUDControl.VisualAlert -class CarControllerParams(): +class CarControllerParams: # Allow small margin below -3.5 m/s^2 from ISO 15622:2018 since we # perform the closed loop control, and might need some # to apply some more braking if we're on a downhill slope. @@ -22,6 +27,7 @@ class CarControllerParams(): NIDEC_MAX_ACCEL_V = [0.5, 2.4, 1.4, 0.6] NIDEC_MAX_ACCEL_BP = [0.0, 4.0, 10., 20.] + NIDEC_GAS_MAX = 198 # 0xc6 NIDEC_BRAKE_MAX = 1024 // 4 BOSCH_ACCEL_MIN = -3.5 # m/s^2 @@ -51,6 +57,7 @@ class CruiseButtons: CANCEL = 2 MAIN = 1 + # See dbc files for info on values VISUAL_HUD = { VisualAlert.none: 0, @@ -63,12 +70,14 @@ VISUAL_HUD = { VisualAlert.speedTooHigh: 8 } + class CAR: ACCORD = "HONDA ACCORD 2018" ACCORDH = "HONDA ACCORD HYBRID 2018" CIVIC = "HONDA CIVIC 2016" CIVIC_BOSCH = "HONDA CIVIC (BOSCH) 2019" CIVIC_BOSCH_DIESEL = "HONDA CIVIC SEDAN 1.6 DIESEL 2019" + CIVIC_2022 = "HONDA CIVIC 2022" ACURA_ILX = "ACURA ILX 2016" CRV = "HONDA CR-V 2016" CRV_5G = "HONDA CR-V 2017" @@ -87,6 +96,68 @@ class CAR: INSIGHT = "HONDA INSIGHT 2019" HONDA_E = "HONDA E 2020" + +class Footnote(Enum): + CIVIC_DIESEL = CarFootnote( + "2019 Honda Civic 1.6L Diesel Sedan does not have ALC below 12mph.", + Column.FSR_STEERING) + + +@dataclass +class HondaCarInfo(CarInfo): + package: str = "Honda Sensing" + + def init_make(self, CP: car.CarParams): + if CP.carFingerprint in HONDA_BOSCH: + self.harness = Harness.bosch_b if CP.carFingerprint in HONDA_BOSCH_RADARLESS else Harness.bosch_a + else: + self.harness = Harness.nidec + + +CAR_INFO: Dict[str, Optional[Union[HondaCarInfo, List[HondaCarInfo]]]] = { + CAR.ACCORD: [ + HondaCarInfo("Honda Accord 2018-22", "All", "https://www.youtube.com/watch?v=mrUwlj3Mi58", min_steer_speed=3. * CV.MPH_TO_MS), + HondaCarInfo("Honda Inspire 2018", "All", min_steer_speed=3. * CV.MPH_TO_MS), + ], + CAR.ACCORDH: HondaCarInfo("Honda Accord Hybrid 2018-22", "All", min_steer_speed=3. * CV.MPH_TO_MS), + CAR.CIVIC: HondaCarInfo("Honda Civic 2016-18", min_steer_speed=12. * CV.MPH_TO_MS, video_link="https://youtu.be/-IkImTe1NYE"), + CAR.CIVIC_BOSCH: [ + HondaCarInfo("Honda Civic 2019-21", "All", "https://www.youtube.com/watch?v=4Iz1Mz5LGF8", [Footnote.CIVIC_DIESEL], 2. * CV.MPH_TO_MS), + HondaCarInfo("Honda Civic Hatchback 2017-21", min_steer_speed=12. * CV.MPH_TO_MS), + ], + CAR.CIVIC_BOSCH_DIESEL: None, # same platform + CAR.CIVIC_2022: [ + HondaCarInfo("Honda Civic 2022", "All"), + HondaCarInfo("Honda Civic Hatchback 2022", "All"), + ], + CAR.ACURA_ILX: HondaCarInfo("Acura ILX 2016-19", "AcuraWatch Plus", min_steer_speed=25. * CV.MPH_TO_MS), + CAR.CRV: HondaCarInfo("Honda CR-V 2015-16", "Touring Trim", min_steer_speed=12. * CV.MPH_TO_MS), + CAR.CRV_5G: HondaCarInfo("Honda CR-V 2017-22", min_steer_speed=12. * CV.MPH_TO_MS), + CAR.CRV_EU: None, # HondaCarInfo("Honda CR-V EU", "Touring"), # Euro version of CRV Touring + CAR.CRV_HYBRID: HondaCarInfo("Honda CR-V Hybrid 2017-19", min_steer_speed=12. * CV.MPH_TO_MS), + CAR.FIT: HondaCarInfo("Honda Fit 2018-20", min_steer_speed=12. * CV.MPH_TO_MS), + CAR.FREED: HondaCarInfo("Honda Freed 2020", min_steer_speed=12. * CV.MPH_TO_MS), + CAR.HRV: HondaCarInfo("Honda HR-V 2019-22", min_steer_speed=12. * CV.MPH_TO_MS), + CAR.ODYSSEY: HondaCarInfo("Honda Odyssey 2018-20"), + CAR.ODYSSEY_CHN: None, # Chinese version of Odyssey + CAR.ACURA_RDX: HondaCarInfo("Acura RDX 2016-18", "AcuraWatch Plus", min_steer_speed=12. * CV.MPH_TO_MS), + CAR.ACURA_RDX_3G: HondaCarInfo("Acura RDX 2019-22", "All", min_steer_speed=3. * CV.MPH_TO_MS), + CAR.PILOT: HondaCarInfo("Honda Pilot 2016-22", min_steer_speed=12. * CV.MPH_TO_MS), + CAR.PASSPORT: HondaCarInfo("Honda Passport 2019-21", "All", min_steer_speed=12. * CV.MPH_TO_MS), + CAR.RIDGELINE: HondaCarInfo("Honda Ridgeline 2017-22", min_steer_speed=12. * CV.MPH_TO_MS), + CAR.INSIGHT: HondaCarInfo("Honda Insight 2019-22", "All", min_steer_speed=3. * CV.MPH_TO_MS), + CAR.HONDA_E: HondaCarInfo("Honda e 2020", "All", min_steer_speed=3. * CV.MPH_TO_MS), +} + +FW_QUERY_CONFIG = FwQueryConfig( + requests=[ + Request( + [StdQueries.UDS_VERSION_REQUEST], + [StdQueries.UDS_VERSION_RESPONSE], + ), + ], +) + FW_VERSIONS = { CAR.ACCORD: { (Ecu.programmedFuelInjection, 0x18da10f1, None): [ @@ -102,6 +173,7 @@ FW_VERSIONS = { b'37805-6A0-A750\x00\x00', b'37805-6A0-A840\x00\x00', b'37805-6A0-A850\x00\x00', + b'37805-6A0-A930\x00\x00', b'37805-6A0-AF30\x00\x00', b'37805-6A0-AG30\x00\x00', b'37805-6B2-C520\x00\x00', @@ -171,7 +243,7 @@ FW_VERSIONS = { b'39990-TVA-A340\x00\x00', b'39990-TVA-X030\x00\x00', b'39990-TVA-X040\x00\x00', - b'39990-TVA,A150\x00\x00', + b'39990-TVA,A150\x00\x00', # modified firmware b'39990-TVE-H130\x00\x00', ], (Ecu.unknown, 0x18da3af1, None): [ @@ -193,6 +265,7 @@ FW_VERSIONS = { b'78109-TVA-A030\x00\x00', b'78109-TVA-A110\x00\x00', b'78109-TVA-A120\x00\x00', + b'78109-TVA-A130\x00\x00', b'78109-TVA-A210\x00\x00', b'78109-TVA-A220\x00\x00', b'78109-TVA-A230\x00\x00', @@ -380,7 +453,7 @@ FW_VERSIONS = { b'78109-TED-Q510\x00\x00', b'78109-TEG-A310\x00\x00', ], - (Ecu.fwdCamera, 0x18dab0f1, None): [ + (Ecu.fwdRadar, 0x18dab0f1, None): [ b'36161-TBA-A020\x00\x00', b'36161-TBA-A030\x00\x00', b'36161-TBA-A040\x00\x00', @@ -898,7 +971,7 @@ FW_VERSIONS = { b'77959-THR-A110\x00\x00', b'77959-THR-X010\x00\x00', ], - (Ecu.fwdCamera, 0x18dab0f1, None): [ + (Ecu.fwdRadar, 0x18dab0f1, None): [ b'36161-THR-A020\x00\x00', b'36161-THR-A030\x00\x00', b'36161-THR-A110\x00\x00', @@ -965,6 +1038,23 @@ FW_VERSIONS = { b'54008-THR-A020\x00\x00', ], }, + CAR.ODYSSEY_CHN: { + (Ecu.eps, 0x18da30f1, None): [ + b'39990-T6D-H220\x00\x00', + ], + (Ecu.gateway, 0x18daeff1, None): [ + b'38897-T6A-J010\x00\x00', + ], + (Ecu.combinationMeter, 0x18da60f1, None): [ + b'78109-T6A-F310\x00\x00', + ], + (Ecu.fwdRadar, 0x18dab0f1, None): [ + b'36161-T6A-P040\x00\x00', + ], + (Ecu.srs, 0x18da53f1, None): [ + b'77959-T6A-P110\x00\x00', + ], + }, CAR.PILOT: { (Ecu.shiftByWire, 0x18da0bf1, None): [ b'54008-TG7-A520\x00\x00', @@ -1002,7 +1092,7 @@ FW_VERSIONS = { b'39990-TG7-A070\x00\x00', b'39990-TGS-A230\x00\x00', ], - (Ecu.fwdCamera, 0x18dab0f1, None): [ + (Ecu.fwdRadar, 0x18dab0f1, None): [ b'36161-TG7-A310\x00\x00', b'36161-TG7-A520\x00\x00', b'36161-TG7-A630\x00\x00', @@ -1076,12 +1166,14 @@ FW_VERSIONS = { CAR.PASSPORT: { (Ecu.programmedFuelInjection, 0x18da10f1, None): [ b'37805-RLV-B220\x00\x00', + b'37805-RLV-B210\x00\x00', ], (Ecu.eps, 0x18da30f1, None): [ b'39990-TGS-A230\x00\x00', ], (Ecu.fwdRadar, 0x18dab0f1, None): [ b'36161-TGS-A030\x00\x00', + b'36161-TGS-A130\x00\x00', ], (Ecu.gateway, 0x18daeff1, None): [ b'38897-TG7-A040\x00\x00', @@ -1097,6 +1189,7 @@ FW_VERSIONS = { ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-TGS-AT20\x00\x00', + b'78109-TGS-AX20\x00\x00', ], (Ecu.vsa, 0x18da28f1, None): [ b'57114-TGS-A530\x00\x00', @@ -1107,7 +1200,7 @@ FW_VERSIONS = { b'57114-TX5-A220\x00\x00', b'57114-TX4-A220\x00\x00', ], - (Ecu.fwdCamera, 0x18dab0f1, None): [ + (Ecu.fwdRadar, 0x18dab0f1, None): [ b'36161-TX5-A030\x00\x00', b'36161-TX4-A030\x00\x00', ], @@ -1204,7 +1297,7 @@ FW_VERSIONS = { b'39990-T6Z-A030\x00\x00', b'39990-T6Z-A050\x00\x00', ], - (Ecu.fwdCamera, 0x18dab0f1, None): [ + (Ecu.fwdRadar, 0x18dab0f1, None): [ b'36161-T6Z-A020\x00\x00', b'36161-T6Z-A310\x00\x00', b'36161-T6Z-A420\x00\x00', @@ -1242,6 +1335,7 @@ FW_VERSIONS = { ], (Ecu.fwdRadar, 0x18dab0f1, None): [ b'36802-TXM-A070\x00\x00', + b'36802-TXM-A080\x00\x00', ], (Ecu.fwdCamera, 0x18dab5f1, None): [ b'36161-TXM-A050\x00\x00', @@ -1280,6 +1374,7 @@ FW_VERSIONS = { b'36161-T7A-A140\x00\x00', b'36161-T7A-A240\x00\x00', b'36161-T7A-C440\x00\x00', + b'36161-T7A-A040\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-T7A-A230\x00\x00', @@ -1290,6 +1385,7 @@ FW_VERSIONS = { b'78109-THX-A210\x00\x00', b'78109-THX-A220\x00\x00', b'78109-THX-C220\x00\x00', + b'78109-THW-A110\x00\x00', ], }, CAR.ACURA_ILX: { @@ -1336,6 +1432,48 @@ FW_VERSIONS = { b'57114-TYF-E030\x00\x00' ], }, + CAR.CIVIC_2022: { + (Ecu.eps, 0x18DA30F1, None): [ + b'39990-T39-A130\x00\x00', + b'39990-T43-J020\x00\x00', + ], + (Ecu.gateway, 0x18DAEFF1, None): [ + b'38897-T20-A020\x00\x00', + b'38897-T20-A510\x00\x00', + b'38897-T21-A010\x00\x00', + b'38897-T20-A210\x00\x00', + b'38897-T20-A310\x00\x00', + ], + (Ecu.srs, 0x18DA53F1, None): [ + b'77959-T20-A970\x00\x00', + b'77959-T47-A940\x00\x00', + b'77959-T47-A950\x00\x00', + ], + (Ecu.combinationMeter, 0x18DA60F1, None): [ + b'78108-T21-A220\x00\x00', + b'78108-T21-A620\x00\x00', + b'78108-T23-A110\x00\x00', + b'78108-T21-A230\x00\x00', + b'78108-T22-A020\x00\x00', + ], + (Ecu.vsa, 0x18DA28F1, None): [ + b'57114-T20-AB40\x00\x00', + b'57114-T43-JB30\x00\x00', + ], + (Ecu.transmission, 0x18da1ef1, None): [ + b'28101-65D-A020\x00\x00', + b'28101-65D-A120\x00\x00', + b'28101-65H-A020\x00\x00', + b'28101-65H-A120\x00\x00', + ], + (Ecu.programmedFuelInjection, 0x18da10f1, None): [ + b'37805-64L-A540\x00\x00', + b'37805-64S-A540\x00\x00', + b'37805-64S-A720\x00\x00', + b'37805-64A-A540\x00\x00', + b'37805-64A-A620\x00\x00', + ], + }, } DBC = { @@ -1361,6 +1499,7 @@ DBC = { CAR.RIDGELINE: dbc_dict('acura_ilx_2016_can_generated', 'acura_ilx_2016_nidec'), CAR.INSIGHT: dbc_dict('honda_insight_ex_2019_can_generated', None), CAR.HONDA_E: dbc_dict('acura_rdx_2020_can_generated', None), + CAR.CIVIC_2022: dbc_dict('honda_civic_ex_2022_can_generated', None), } STEER_THRESHOLD = { @@ -1373,5 +1512,6 @@ HONDA_NIDEC_ALT_PCM_ACCEL = {CAR.ODYSSEY} HONDA_NIDEC_ALT_SCM_MESSAGES = {CAR.ACURA_ILX, CAR.ACURA_RDX, CAR.CRV, CAR.CRV_EU, CAR.FIT, CAR.FREED, CAR.HRV, CAR.ODYSSEY_CHN, CAR.PILOT, CAR.PASSPORT, CAR.RIDGELINE} HONDA_BOSCH = {CAR.ACCORD, CAR.ACCORDH, CAR.CIVIC_BOSCH, CAR.CIVIC_BOSCH_DIESEL, CAR.CRV_5G, - CAR.CRV_HYBRID, CAR.INSIGHT, CAR.ACURA_RDX_3G, CAR.HONDA_E} + CAR.CRV_HYBRID, CAR.INSIGHT, CAR.ACURA_RDX_3G, CAR.HONDA_E, CAR.CIVIC_2022} HONDA_BOSCH_ALT_BRAKE_SIGNAL = {CAR.ACCORD, CAR.CRV_5G, CAR.ACURA_RDX_3G} +HONDA_BOSCH_RADARLESS = {CAR.CIVIC_2022} diff --git a/selfdrive/car/hyundai/carcontroller.py b/selfdrive/car/hyundai/carcontroller.py index f7c43bd6e3..3f128b1598 100644 --- a/selfdrive/car/hyundai/carcontroller.py +++ b/selfdrive/car/hyundai/carcontroller.py @@ -1,125 +1,192 @@ from cereal import car +from common.conversions import Conversions as CV +from common.numpy_fast import clip from common.realtime import DT_CTRL -from common.numpy_fast import clip, interp -from selfdrive.config import Conversions as CV -from selfdrive.car import apply_std_steer_torque_limits -from selfdrive.car.hyundai.hyundaican import create_lkas11, create_clu11, create_lfahda_mfc, create_acc_commands, create_acc_opt, create_frt_radar_opt -from selfdrive.car.hyundai.values import Buttons, CarControllerParams, CAR from opendbc.can.packer import CANPacker +from selfdrive.car import apply_std_steer_torque_limits +from selfdrive.car.hyundai import hyundaicanfd, hyundaican +from selfdrive.car.hyundai.values import HyundaiFlags, Buttons, CarControllerParams, CANFD_CAR, CAR VisualAlert = car.CarControl.HUDControl.VisualAlert LongCtrlState = car.CarControl.Actuators.LongControlState +# EPS faults if you apply torque while the steering angle is above 90 degrees for more than 1 second +# All slightly below EPS thresholds to avoid fault +MAX_ANGLE = 85 +MAX_ANGLE_FRAMES = 89 +MAX_ANGLE_CONSECUTIVE_FRAMES = 2 -def process_hud_alert(enabled, fingerprint, visual_alert, left_lane, - right_lane, left_lane_depart, right_lane_depart): - sys_warning = (visual_alert in (VisualAlert.steerRequired, VisualAlert.ldw)) + +def process_hud_alert(enabled, fingerprint, hud_control): + sys_warning = (hud_control.visualAlert in (VisualAlert.steerRequired, VisualAlert.ldw)) # initialize to no line visible + # TODO: this is not accurate for all cars sys_state = 1 - if left_lane and right_lane or sys_warning: # HUD alert only display when LKAS status is active + if hud_control.leftLaneVisible and hud_control.rightLaneVisible or sys_warning: # HUD alert only display when LKAS status is active sys_state = 3 if enabled or sys_warning else 4 - elif left_lane: + elif hud_control.leftLaneVisible: sys_state = 5 - elif right_lane: + elif hud_control.rightLaneVisible: sys_state = 6 # initialize to no warnings left_lane_warning = 0 right_lane_warning = 0 - if left_lane_depart: + if hud_control.leftLaneDepart: left_lane_warning = 1 if fingerprint in (CAR.GENESIS_G90, CAR.GENESIS_G80) else 2 - if right_lane_depart: + if hud_control.rightLaneDepart: right_lane_warning = 1 if fingerprint in (CAR.GENESIS_G90, CAR.GENESIS_G80) else 2 return sys_warning, sys_state, left_lane_warning, right_lane_warning -class CarController(): +class CarController: def __init__(self, dbc_name, CP, VM): - self.p = CarControllerParams(CP) + self.CP = CP + self.params = CarControllerParams(CP) self.packer = CANPacker(dbc_name) + self.angle_limit_counter = 0 + self.frame = 0 + self.accel_last = 0 self.apply_steer_last = 0 self.car_fingerprint = CP.carFingerprint - self.steer_rate_limited = False - self.last_resume_frame = 0 - self.accel = 0 + self.last_button_frame = 0 - def update(self, c, enabled, CS, frame, actuators, pcm_cancel_cmd, visual_alert, hud_speed, - left_lane, right_lane, left_lane_depart, right_lane_depart): - # Steering Torque - new_steer = int(round(actuators.steer * self.p.STEER_MAX)) - apply_steer = apply_std_steer_torque_limits(new_steer, self.apply_steer_last, CS.out.steeringTorque, self.p) - self.steer_rate_limited = new_steer != apply_steer + def update(self, CC, CS): + actuators = CC.actuators + hud_control = CC.hudControl - # disable when temp fault is active, or below LKA minimum speed - lkas_active = c.active and not CS.out.steerWarning and CS.out.vEgo >= CS.CP.minSteerSpeed + # steering torque + steer = actuators.steer + new_steer = int(round(steer * self.params.STEER_MAX)) + apply_steer = apply_std_steer_torque_limits(new_steer, self.apply_steer_last, CS.out.steeringTorque, self.params) - if not lkas_active: + if not CC.latActive: apply_steer = 0 self.apply_steer_last = apply_steer - sys_warning, sys_state, left_lane_warning, right_lane_warning = \ - process_hud_alert(enabled, self.car_fingerprint, visual_alert, - left_lane, right_lane, left_lane_depart, right_lane_depart) + # accel + longitudinal + accel = clip(actuators.accel, CarControllerParams.ACCEL_MIN, CarControllerParams.ACCEL_MAX) + stopping = actuators.longControlState == LongCtrlState.stopping + set_speed_in_units = hud_control.setSpeed * (CV.MS_TO_KPH if CS.is_metric else CV.MS_TO_MPH) + + # HUD messages + sys_warning, sys_state, left_lane_warning, right_lane_warning = process_hud_alert(CC.enabled, self.car_fingerprint, + hud_control) can_sends = [] - # tester present - w/ no response (keeps radar disabled) - if CS.CP.openpilotLongitudinalControl: - if (frame % 100) == 0: - can_sends.append([0x7D0, 0, b"\x02\x3E\x80\x00\x00\x00\x00\x00", 0]) - - can_sends.append(create_lkas11(self.packer, frame, self.car_fingerprint, apply_steer, lkas_active, - CS.lkas11, sys_warning, sys_state, enabled, - left_lane, right_lane, - left_lane_warning, right_lane_warning)) - - if not CS.CP.openpilotLongitudinalControl: - if pcm_cancel_cmd: - can_sends.append(create_clu11(self.packer, frame, CS.clu11, Buttons.CANCEL)) - elif CS.out.cruiseState.standstill: - # send resume at a max freq of 10Hz - if (frame - self.last_resume_frame) * DT_CTRL > 0.1: - # send 25 messages at a time to increases the likelihood of resume being accepted - can_sends.extend([create_clu11(self.packer, frame, CS.clu11, Buttons.RES_ACCEL)] * 25) - self.last_resume_frame = frame - - if frame % 2 == 0 and CS.CP.openpilotLongitudinalControl: - lead_visible = False - accel = actuators.accel if c.active else 0 - - jerk = clip(2.0 * (accel - CS.out.aEgo), -12.7, 12.7) - - if accel < 0: - accel = interp(accel - CS.out.aEgo, [-1.0, -0.5], [2 * accel, accel]) - - accel = clip(accel, CarControllerParams.ACCEL_MIN, CarControllerParams.ACCEL_MAX) - - stopping = (actuators.longControlState == LongCtrlState.stopping) - set_speed_in_units = hud_speed * (CV.MS_TO_MPH if CS.clu11["CF_Clu_SPEED_UNIT"] == 1 else CV.MS_TO_KPH) - can_sends.extend(create_acc_commands(self.packer, enabled, accel, jerk, int(frame / 2), lead_visible, set_speed_in_units, stopping)) - self.accel = accel - - # 20 Hz LFA MFA message - if frame % 5 == 0 and self.car_fingerprint in (CAR.SONATA, CAR.PALISADE, CAR.IONIQ, CAR.KIA_NIRO_EV, CAR.KIA_NIRO_HEV_2021, - CAR.IONIQ_EV_2020, CAR.IONIQ_PHEV, CAR.KIA_CEED, CAR.KIA_SELTOS, CAR.KONA_EV, - CAR.ELANTRA_2021, CAR.ELANTRA_HEV_2021, CAR.SONATA_HYBRID, CAR.KONA_HEV, CAR.SANTA_FE_2022, - CAR.KIA_K5_2021, CAR.IONIQ_HEV_2022, CAR.SANTA_FE_HEV_2022, CAR.GENESIS_G70_2020, CAR.SANTA_FE_PHEV_2022): - can_sends.append(create_lfahda_mfc(self.packer, enabled)) - - # 5 Hz ACC options - if frame % 20 == 0 and CS.CP.openpilotLongitudinalControl: - can_sends.extend(create_acc_opt(self.packer)) - - # 2 Hz front radar options - if frame % 50 == 0 and CS.CP.openpilotLongitudinalControl: - can_sends.append(create_frt_radar_opt(self.packer)) + # *** common hyundai stuff *** + + # tester present - w/ no response (keeps relevant ECU disabled) + if self.frame % 100 == 0 and not (self.CP.flags & HyundaiFlags.CANFD_CAMERA_SCC.value) and self.CP.openpilotLongitudinalControl: + addr, bus = 0x7d0, 0 + if self.CP.flags & HyundaiFlags.CANFD_HDA2.value: + addr, bus = 0x730, 5 + can_sends.append([addr, 0, b"\x02\x3E\x80\x00\x00\x00\x00\x00", bus]) + + # >90 degree steering fault prevention + # Count up to MAX_ANGLE_FRAMES, at which point we need to cut torque to avoid a steering fault + if CC.latActive and abs(CS.out.steeringAngleDeg) >= MAX_ANGLE: + self.angle_limit_counter += 1 + else: + self.angle_limit_counter = 0 + + # Cut steer actuation bit for two frames and hold torque with induced temporary fault + torque_fault = CC.latActive and self.angle_limit_counter > MAX_ANGLE_FRAMES + lat_active = CC.latActive and not torque_fault + + if self.angle_limit_counter >= MAX_ANGLE_FRAMES + MAX_ANGLE_CONSECUTIVE_FRAMES: + self.angle_limit_counter = 0 + + # CAN-FD platforms + if self.CP.carFingerprint in CANFD_CAR: + hda2 = self.CP.flags & HyundaiFlags.CANFD_HDA2 + hda2_long = hda2 and self.CP.openpilotLongitudinalControl + + # steering control + can_sends.extend(hyundaicanfd.create_steering_messages(self.packer, self.CP, CC.enabled, lat_active, apply_steer)) + + # disable LFA on HDA2 + if self.frame % 5 == 0 and hda2: + can_sends.append(hyundaicanfd.create_cam_0x2a4(self.packer, CS.cam_0x2a4)) + + # LFA and HDA icons + if self.frame % 5 == 0 and (not hda2 or hda2_long): + can_sends.append(hyundaicanfd.create_lfahda_cluster(self.packer, self.CP, CC.enabled)) + + if self.CP.openpilotLongitudinalControl: + if hda2: + can_sends.extend(hyundaicanfd.create_adrv_messages(self.packer, self.frame)) + if self.frame % 2 == 0: + can_sends.append(hyundaicanfd.create_acc_control(self.packer, self.CP, CC.enabled, self.accel_last, accel, stopping, CC.cruiseControl.override, + set_speed_in_units)) + self.accel_last = accel + else: + # button presses + if (self.frame - self.last_button_frame) * DT_CTRL > 0.25: + # cruise cancel + if CC.cruiseControl.cancel: + if self.CP.flags & HyundaiFlags.CANFD_ALT_BUTTONS: + can_sends.append(hyundaicanfd.create_acc_cancel(self.packer, self.CP, CS.cruise_info)) + self.last_button_frame = self.frame + else: + for _ in range(20): + can_sends.append(hyundaicanfd.create_buttons(self.packer, self.CP, CS.buttons_counter+1, Buttons.CANCEL)) + self.last_button_frame = self.frame + + # cruise standstill resume + elif CC.cruiseControl.resume: + if self.CP.flags & HyundaiFlags.CANFD_ALT_BUTTONS: + # TODO: resume for alt button cars + pass + else: + for _ in range(20): + can_sends.append(hyundaicanfd.create_buttons(self.packer, self.CP, CS.buttons_counter+1, Buttons.RES_ACCEL)) + self.last_button_frame = self.frame + else: + can_sends.append(hyundaican.create_lkas11(self.packer, self.frame, self.car_fingerprint, apply_steer, lat_active, + torque_fault, CS.lkas11, sys_warning, sys_state, CC.enabled, + hud_control.leftLaneVisible, hud_control.rightLaneVisible, + left_lane_warning, right_lane_warning)) + + if not self.CP.openpilotLongitudinalControl: + if CC.cruiseControl.cancel: + can_sends.append(hyundaican.create_clu11(self.packer, self.frame, CS.clu11, Buttons.CANCEL, self.CP.carFingerprint)) + elif CC.cruiseControl.resume: + # send resume at a max freq of 10Hz + if (self.frame - self.last_button_frame) * DT_CTRL > 0.1: + # send 25 messages at a time to increases the likelihood of resume being accepted + can_sends.extend([hyundaican.create_clu11(self.packer, self.frame, CS.clu11, Buttons.RES_ACCEL, self.CP.carFingerprint)] * 25) + self.last_button_frame = self.frame + + if self.frame % 2 == 0 and self.CP.openpilotLongitudinalControl: + # TODO: unclear if this is needed + jerk = 3.0 if actuators.longControlState == LongCtrlState.pid else 1.0 + can_sends.extend(hyundaican.create_acc_commands(self.packer, CC.enabled, accel, jerk, int(self.frame / 2), + hud_control.leadVisible, set_speed_in_units, stopping, CC.cruiseControl.override)) + + # 20 Hz LFA MFA message + if self.frame % 5 == 0 and self.car_fingerprint in (CAR.SONATA, CAR.PALISADE, CAR.IONIQ, CAR.KIA_NIRO_EV, CAR.KIA_NIRO_HEV_2021, + CAR.IONIQ_EV_2020, CAR.IONIQ_PHEV, CAR.KIA_CEED, CAR.KIA_SELTOS, CAR.KONA_EV, CAR.KONA_EV_2022, + CAR.ELANTRA_2021, CAR.ELANTRA_HEV_2021, CAR.SONATA_HYBRID, CAR.KONA_HEV, CAR.SANTA_FE_2022, + CAR.KIA_K5_2021, CAR.IONIQ_HEV_2022, CAR.SANTA_FE_HEV_2022, CAR.GENESIS_G70_2020, CAR.SANTA_FE_PHEV_2022, CAR.KIA_STINGER_2022): + can_sends.append(hyundaican.create_lfahda_mfc(self.packer, CC.enabled)) + + # 5 Hz ACC options + if self.frame % 20 == 0 and self.CP.openpilotLongitudinalControl: + can_sends.extend(hyundaican.create_acc_opt(self.packer)) + + # 2 Hz front radar options + if self.frame % 50 == 0 and self.CP.openpilotLongitudinalControl: + can_sends.append(hyundaican.create_frt_radar_opt(self.packer)) new_actuators = actuators.copy() - new_actuators.steer = apply_steer / self.p.STEER_MAX - new_actuators.accel = self.accel + new_actuators.steer = apply_steer / self.params.STEER_MAX + new_actuators.accel = accel + self.frame += 1 return new_actuators, can_sends diff --git a/selfdrive/car/hyundai/carstate.py b/selfdrive/car/hyundai/carstate.py index bdd49e2067..bd6b72f461 100644 --- a/selfdrive/car/hyundai/carstate.py +++ b/selfdrive/car/hyundai/carstate.py @@ -1,10 +1,16 @@ +from collections import deque import copy +import math + from cereal import car -from selfdrive.car.hyundai.values import DBC, STEER_THRESHOLD, FEATURES, EV_CAR, HYBRID_CAR -from selfdrive.car.interfaces import CarStateBase +from common.conversions import Conversions as CV from opendbc.can.parser import CANParser from opendbc.can.can_define import CANDefine -from selfdrive.config import Conversions as CV +from selfdrive.car.hyundai.values import HyundaiFlags, CAR, DBC, FEATURES, CAMERA_SCC_CAR, CANFD_CAR, EV_CAR, HYBRID_CAR, Buttons, CarControllerParams +from selfdrive.car.interfaces import CarStateBase + +PREV_BUTTON_SAMPLES = 8 +CLUSTER_SAMPLE_RATE = 20 # frames class CarState(CarStateBase): @@ -12,16 +18,39 @@ class CarState(CarStateBase): super().__init__(CP) can_define = CANDefine(DBC[CP.carFingerprint]["pt"]) - if self.CP.carFingerprint in FEATURES["use_cluster_gears"]: + self.cruise_buttons = deque([Buttons.NONE] * PREV_BUTTON_SAMPLES, maxlen=PREV_BUTTON_SAMPLES) + self.main_buttons = deque([Buttons.NONE] * PREV_BUTTON_SAMPLES, maxlen=PREV_BUTTON_SAMPLES) + + self.gear_msg_canfd = "GEAR_ALT" if CP.flags & HyundaiFlags.CANFD_ALT_GEARS else "GEAR_SHIFTER" + if CP.carFingerprint in CANFD_CAR: + self.shifter_values = can_define.dv[self.gear_msg_canfd]["GEAR"] + elif self.CP.carFingerprint in FEATURES["use_cluster_gears"]: self.shifter_values = can_define.dv["CLU15"]["CF_Clu_Gear"] elif self.CP.carFingerprint in FEATURES["use_tcu_gears"]: self.shifter_values = can_define.dv["TCU12"]["CUR_GR"] else: # preferred and elect gear methods use same definition self.shifter_values = can_define.dv["LVR12"]["CF_Lvr_Gear"] + self.is_metric = False + self.brake_error = False + self.buttons_counter = 0 + + self.cruise_info = {} + + # On some cars, CLU15->CF_Clu_VehicleSpeed can oscillate faster than the dash updates. Sample at 5 Hz + self.cluster_speed = 0 + self.cluster_speed_counter = CLUSTER_SAMPLE_RATE + + self.params = CarControllerParams(CP) def update(self, cp, cp_cam): + if self.CP.carFingerprint in CANFD_CAR: + return self.update_canfd(cp, cp_cam) + ret = car.CarState.new_message() + cp_cruise = cp_cam if self.CP.carFingerprint in CAMERA_SCC_CAR else cp + self.is_metric = cp.vl["CLU11"]["CF_Clu_SPEED_UNIT"] == 0 + speed_conv = CV.KPH_TO_MS if self.is_metric else CV.MPH_TO_MS ret.doorOpen = any([cp.vl["CGW1"]["CF_Gway_DrvDrSw"], cp.vl["CGW1"]["CF_Gway_AstDrSw"], cp.vl["CGW2"]["CF_Gway_RLDrSw"], cp.vl["CGW2"]["CF_Gway_RRDrSw"]]) @@ -36,9 +65,21 @@ class CarState(CarStateBase): ) ret.vEgoRaw = (ret.wheelSpeeds.fl + ret.wheelSpeeds.fr + ret.wheelSpeeds.rl + ret.wheelSpeeds.rr) / 4. ret.vEgo, ret.aEgo = self.update_speed_kf(ret.vEgoRaw) - ret.standstill = ret.vEgoRaw < 0.1 + self.cluster_speed_counter += 1 + if self.cluster_speed_counter > CLUSTER_SAMPLE_RATE: + self.cluster_speed = cp.vl["CLU15"]["CF_Clu_VehicleSpeed"] + self.cluster_speed_counter = 0 + + # Mimic how dash converts to imperial. + # Sorento is the only platform where CF_Clu_VehicleSpeed is already imperial when not is_metric + # TODO: CGW_USM1->CF_Gway_DrLockSoundRValue may describe this + if not self.is_metric and self.CP.carFingerprint not in (CAR.KIA_SORENTO,): + self.cluster_speed = math.floor(self.cluster_speed * CV.KPH_TO_MPH + CV.KPH_TO_MPH) + + ret.vEgoCluster = self.cluster_speed * speed_conv + ret.steeringAngleDeg = cp.vl["SAS11"]["SAS_Angle"] ret.steeringRateDeg = cp.vl["SAS11"]["SAS_Speed"] ret.yawRate = cp.vl["ESP12"]["YAW_RATE"] @@ -46,8 +87,8 @@ class CarState(CarStateBase): 50, cp.vl["CGW1"]["CF_Gway_TurnSigLh"], cp.vl["CGW1"]["CF_Gway_TurnSigRh"]) ret.steeringTorque = cp.vl["MDPS12"]["CR_Mdps_StrColTq"] ret.steeringTorqueEps = cp.vl["MDPS12"]["CR_Mdps_OutTq"] - ret.steeringPressed = abs(ret.steeringTorque) > STEER_THRESHOLD - ret.steerWarning = cp.vl["MDPS12"]["CF_Mdps_ToiUnavail"] != 0 or cp.vl["MDPS12"]["CF_Mdps_ToiFlt"] != 0 + ret.steeringPressed = abs(ret.steeringTorque) > self.params.STEER_THRESHOLD + ret.steerFaultTemporary = cp.vl["MDPS12"]["CF_Mdps_ToiUnavail"] != 0 or cp.vl["MDPS12"]["CF_Mdps_ToiFlt"] != 0 # cruise state if self.CP.openpilotLongitudinalControl: @@ -56,20 +97,16 @@ class CarState(CarStateBase): ret.cruiseState.enabled = cp.vl["TCS13"]["ACC_REQ"] == 1 ret.cruiseState.standstill = False else: - ret.cruiseState.available = cp.vl["SCC11"]["MainMode_ACC"] == 1 - ret.cruiseState.enabled = cp.vl["SCC12"]["ACCMode"] != 0 - ret.cruiseState.standstill = cp.vl["SCC11"]["SCCInfoDisplay"] == 4. - - if ret.cruiseState.enabled: - speed_conv = CV.MPH_TO_MS if cp.vl["CLU11"]["CF_Clu_SPEED_UNIT"] else CV.KPH_TO_MS - ret.cruiseState.speed = cp.vl["SCC11"]["VSetDis"] * speed_conv - else: - ret.cruiseState.speed = 0 + ret.cruiseState.available = cp_cruise.vl["SCC11"]["MainMode_ACC"] == 1 + ret.cruiseState.enabled = cp_cruise.vl["SCC12"]["ACCMode"] != 0 + ret.cruiseState.standstill = cp_cruise.vl["SCC11"]["SCCInfoDisplay"] == 4. + ret.cruiseState.speed = cp_cruise.vl["SCC11"]["VSetDis"] * speed_conv # TODO: Find brake pressure ret.brake = 0 ret.brakePressed = cp.vl["TCS13"]["DriverBraking"] != 0 ret.brakeHoldActive = cp.vl["TCS15"]["AVH_LAMP"] == 2 # 0 OFF, 1 ERROR, 2 ACTIVE, 3 READY + ret.parkingBrake = cp.vl["TCS13"]["PBRAKE_ACT"] == 1 if self.CP.carFingerprint in (HYBRID_CAR | EV_CAR): if self.CP.carFingerprint in HYBRID_CAR: @@ -95,12 +132,12 @@ class CarState(CarStateBase): ret.gearShifter = self.parse_gear_shifter(self.shifter_values.get(gear)) if not self.CP.openpilotLongitudinalControl: - if self.CP.carFingerprint in FEATURES["use_fca"]: - ret.stockAeb = cp.vl["FCA11"]["FCA_CmdAct"] != 0 - ret.stockFcw = cp.vl["FCA11"]["CF_VSM_Warn"] == 2 - else: - ret.stockAeb = cp.vl["SCC12"]["AEB_CmdAct"] != 0 - ret.stockFcw = cp.vl["SCC12"]["CF_VSM_Warn"] == 2 + aeb_src = "FCA11" if self.CP.carFingerprint in FEATURES["use_fca"] else "SCC12" + aeb_sig = "FCA_CmdAct" if self.CP.carFingerprint in FEATURES["use_fca"] else "AEB_CmdAct" + aeb_warning = cp_cruise.vl[aeb_src]["CF_VSM_Warn"] != 0 + aeb_braking = cp_cruise.vl[aeb_src]["CF_VSM_DecCmdAct"] != 0 or cp_cruise.vl[aeb_src][aeb_sig] != 0 + ret.stockFcw = aeb_warning and not aeb_braking + ret.stockAeb = aeb_warning and aeb_braking if self.CP.enableBsm: ret.leftBlindspot = cp.vl["LCA11"]["CF_Lca_IndLeft"] != 0 @@ -109,18 +146,87 @@ class CarState(CarStateBase): # save the entire LKAS11 and CLU11 self.lkas11 = copy.copy(cp_cam.vl["LKAS11"]) self.clu11 = copy.copy(cp.vl["CLU11"]) - self.park_brake = cp.vl["TCS13"]["PBRAKE_ACT"] == 1 self.steer_state = cp.vl["MDPS12"]["CF_Mdps_ToiActive"] # 0 NOT ACTIVE, 1 ACTIVE - self.brake_error = cp.vl["TCS13"]["ACCEnable"] != 0 # 0 ACC CONTROL ENABLED, 1-3 ACC CONTROL DISABLED - self.prev_cruise_buttons = self.cruise_buttons - self.cruise_buttons = cp.vl["CLU11"]["CF_Clu_CruiseSwState"] + self.brake_error = cp.vl["TCS13"]["ACCEnable"] != 0 # 0 ACC CONTROL ENABLED, 1-3 ACC CONTROL DISABLED + self.prev_cruise_buttons = self.cruise_buttons[-1] + self.cruise_buttons.extend(cp.vl_all["CLU11"]["CF_Clu_CruiseSwState"]) + self.main_buttons.extend(cp.vl_all["CLU11"]["CF_Clu_CruiseSwMain"]) + + return ret + + def update_canfd(self, cp, cp_cam): + ret = car.CarState.new_message() + + if self.CP.carFingerprint in (EV_CAR | HYBRID_CAR): + if self.CP.carFingerprint in EV_CAR: + ret.gas = cp.vl["ACCELERATOR"]["ACCELERATOR_PEDAL"] / 255. + else: + ret.gas = cp.vl["ACCELERATOR_ALT"]["ACCELERATOR_PEDAL"] / 1023. + ret.gasPressed = ret.gas > 1e-5 + else: + ret.gasPressed = bool(cp.vl["ACCELERATOR_BRAKE_ALT"]["ACCELERATOR_PEDAL_PRESSED"]) + + ret.brakePressed = cp.vl["TCS"]["DriverBraking"] == 1 + + ret.doorOpen = cp.vl["DOORS_SEATBELTS"]["DRIVER_DOOR_OPEN"] == 1 + ret.seatbeltUnlatched = cp.vl["DOORS_SEATBELTS"]["DRIVER_SEATBELT_LATCHED"] == 0 + + gear = cp.vl[self.gear_msg_canfd]["GEAR"] + ret.gearShifter = self.parse_gear_shifter(self.shifter_values.get(gear)) + + # TODO: figure out positions + ret.wheelSpeeds = self.get_wheel_speeds( + cp.vl["WHEEL_SPEEDS"]["WHEEL_SPEED_1"], + cp.vl["WHEEL_SPEEDS"]["WHEEL_SPEED_2"], + cp.vl["WHEEL_SPEEDS"]["WHEEL_SPEED_3"], + cp.vl["WHEEL_SPEEDS"]["WHEEL_SPEED_4"], + ) + ret.vEgoRaw = (ret.wheelSpeeds.fl + ret.wheelSpeeds.fr + ret.wheelSpeeds.rl + ret.wheelSpeeds.rr) / 4. + ret.vEgo, ret.aEgo = self.update_speed_kf(ret.vEgoRaw) + ret.standstill = ret.vEgoRaw < 0.1 + + ret.steeringRateDeg = cp.vl["STEERING_SENSORS"]["STEERING_RATE"] + ret.steeringAngleDeg = cp.vl["STEERING_SENSORS"]["STEERING_ANGLE"] * -1 + ret.steeringTorque = cp.vl["MDPS"]["STEERING_COL_TORQUE"] + ret.steeringTorqueEps = cp.vl["MDPS"]["STEERING_OUT_TORQUE"] + ret.steeringPressed = abs(ret.steeringTorque) > self.params.STEER_THRESHOLD + ret.steerFaultTemporary = cp.vl["MDPS"]["LKA_FAULT"] != 0 + + ret.leftBlinker, ret.rightBlinker = self.update_blinker_from_lamp(50, cp.vl["BLINKERS"]["LEFT_LAMP"], + cp.vl["BLINKERS"]["RIGHT_LAMP"]) + if self.CP.enableBsm: + ret.leftBlindspot = cp.vl["BLINDSPOTS_REAR_CORNERS"]["FL_INDICATOR"] != 0 + ret.rightBlindspot = cp.vl["BLINDSPOTS_REAR_CORNERS"]["FR_INDICATOR"] != 0 + + ret.cruiseState.available = True + cruise_btn_msg = "CRUISE_BUTTONS_ALT" if self.CP.flags & HyundaiFlags.CANFD_ALT_BUTTONS else "CRUISE_BUTTONS" + distance_unit_msg = cruise_btn_msg if self.CP.carFingerprint == CAR.KIA_SORENTO_PHEV_4TH_GEN else "CLUSTER_INFO" + self.is_metric = cp.vl[distance_unit_msg]["DISTANCE_UNIT"] != 1 + if not self.CP.openpilotLongitudinalControl: + speed_factor = CV.KPH_TO_MS if self.is_metric else CV.MPH_TO_MS + cp_cruise_info = cp_cam if self.CP.flags & HyundaiFlags.CANFD_CAMERA_SCC else cp + ret.cruiseState.speed = cp_cruise_info.vl["SCC_CONTROL"]["VSetDis"] * speed_factor + ret.cruiseState.standstill = cp_cruise_info.vl["SCC_CONTROL"]["CRUISE_STANDSTILL"] == 1 + ret.cruiseState.enabled = cp_cruise_info.vl["SCC_CONTROL"]["ACCMode"] in (1, 2) + self.cruise_info = copy.copy(cp_cruise_info.vl["SCC_CONTROL"]) + + self.prev_cruise_buttons = self.cruise_buttons[-1] + self.cruise_buttons.extend(cp.vl_all[cruise_btn_msg]["CRUISE_BUTTONS"]) + self.main_buttons.extend(cp.vl_all[cruise_btn_msg]["ADAPTIVE_CRUISE_MAIN_BTN"]) + self.buttons_counter = cp.vl[cruise_btn_msg]["COUNTER"] + + if self.CP.flags & HyundaiFlags.CANFD_HDA2: + self.cam_0x2a4 = copy.copy(cp_cam.vl["CAM_0x2a4"]) return ret @staticmethod def get_can_parser(CP): + if CP.carFingerprint in CANFD_CAR: + return CarState.get_can_parser_canfd(CP) + signals = [ - # sig_name, sig_address + # signal_name, signal_address ("WHL_SPD_FL", "WHL_SPD11"), ("WHL_SPD_FR", "WHL_SPD11"), ("WHL_SPD_RL", "WHL_SPD11"), @@ -132,9 +238,9 @@ class CarState(CarStateBase): ("CF_Gway_DrvSeatBeltSw", "CGW1"), ("CF_Gway_DrvDrSw", "CGW1"), # Driver Door - ("CF_Gway_AstDrSw", "CGW1"), # Passenger door - ("CF_Gway_RLDrSw", "CGW2"), # Rear reft door - ("CF_Gway_RRDrSw", "CGW2"), # Rear right door + ("CF_Gway_AstDrSw", "CGW1"), # Passenger Door + ("CF_Gway_RLDrSw", "CGW2"), # Rear left Door + ("CF_Gway_RRDrSw", "CGW2"), # Rear right Door ("CF_Gway_TurnSigLh", "CGW1"), ("CF_Gway_TurnSigRh", "CGW1"), ("CF_Gway_ParkBrakeSw", "CGW1"), @@ -154,6 +260,8 @@ class CarState(CarStateBase): ("CF_Clu_AmpInfo", "CLU11"), ("CF_Clu_AliveCnt1", "CLU11"), + ("CF_Clu_VehicleSpeed", "CLU15"), + ("ACCEnable", "TCS13"), ("ACC_REQ", "TCS13"), ("DriverBraking", "TCS13"), @@ -172,13 +280,13 @@ class CarState(CarStateBase): ("SAS_Angle", "SAS11"), ("SAS_Speed", "SAS11"), ] - checks = [ # address, frequency ("MDPS12", 50), ("TCS13", 50), ("TCS15", 10), ("CLU11", 50), + ("CLU15", 5), ("ESP12", 100), ("CGW1", 10), ("CGW2", 5), @@ -187,7 +295,7 @@ class CarState(CarStateBase): ("SAS11", 100), ] - if not CP.openpilotLongitudinalControl: + if not CP.openpilotLongitudinalControl and CP.carFingerprint not in CAMERA_SCC_CAR: signals += [ ("MainMode_ACC", "SCC11"), ("VSetDis", "SCC11"), @@ -195,7 +303,6 @@ class CarState(CarStateBase): ("ACC_ObjDist", "SCC11"), ("ACCMode", "SCC12"), ] - checks += [ ("SCC11", 50), ("SCC12", 50), @@ -205,12 +312,14 @@ class CarState(CarStateBase): signals += [ ("FCA_CmdAct", "FCA11"), ("CF_VSM_Warn", "FCA11"), + ("CF_VSM_DecCmdAct", "FCA11"), ] checks.append(("FCA11", 50)) else: signals += [ ("AEB_CmdAct", "SCC12"), ("CF_VSM_Warn", "SCC12"), + ("CF_VSM_DecCmdAct", "SCC12"), ] if CP.enableBsm: @@ -238,7 +347,6 @@ class CarState(CarStateBase): if CP.carFingerprint in FEATURES["use_cluster_gears"]: signals.append(("CF_Clu_Gear", "CLU15")) - checks.append(("CLU15", 5)) elif CP.carFingerprint in FEATURES["use_tcu_gears"]: signals.append(("CUR_GR", "TCU12")) checks.append(("TCU12", 100)) @@ -253,8 +361,11 @@ class CarState(CarStateBase): @staticmethod def get_cam_can_parser(CP): + if CP.carFingerprint in CANFD_CAR: + return CarState.get_cam_can_parser_canfd(CP) + signals = [ - # sig_name, sig_address + # signal_name, signal_address ("CF_Lkas_LdwsActivemode", "LKAS11"), ("CF_Lkas_LdwsSysState", "LKAS11"), ("CF_Lkas_SysWarning", "LKAS11"), @@ -271,9 +382,155 @@ class CarState(CarStateBase): ("CF_Lkas_FcwOpt_USM", "LKAS11"), ("CF_Lkas_LdwsOpt_USM", "LKAS11"), ] - checks = [ ("LKAS11", 100) ] + if not CP.openpilotLongitudinalControl and CP.carFingerprint in CAMERA_SCC_CAR: + signals += [ + ("MainMode_ACC", "SCC11"), + ("VSetDis", "SCC11"), + ("SCCInfoDisplay", "SCC11"), + ("ACC_ObjDist", "SCC11"), + ("ACCMode", "SCC12"), + ] + checks += [ + ("SCC11", 50), + ("SCC12", 50), + ] + + if CP.carFingerprint in FEATURES["use_fca"]: + signals += [ + ("FCA_CmdAct", "FCA11"), + ("CF_VSM_Warn", "FCA11"), + ("CF_VSM_DecCmdAct", "FCA11"), + ] + checks.append(("FCA11", 50)) + else: + signals += [ + ("AEB_CmdAct", "SCC12"), + ("CF_VSM_Warn", "SCC12"), + ("CF_VSM_DecCmdAct", "SCC12"), + ] + return CANParser(DBC[CP.carFingerprint]["pt"], signals, checks, 2) + + @staticmethod + def get_can_parser_canfd(CP): + + cruise_btn_msg = "CRUISE_BUTTONS_ALT" if CP.flags & HyundaiFlags.CANFD_ALT_BUTTONS else "CRUISE_BUTTONS" + gear_msg = "GEAR_ALT" if CP.flags & HyundaiFlags.CANFD_ALT_GEARS else "GEAR_SHIFTER" + signals = [ + ("WHEEL_SPEED_1", "WHEEL_SPEEDS"), + ("WHEEL_SPEED_2", "WHEEL_SPEEDS"), + ("WHEEL_SPEED_3", "WHEEL_SPEEDS"), + ("WHEEL_SPEED_4", "WHEEL_SPEEDS"), + + ("GEAR", gear_msg), + + ("STEERING_RATE", "STEERING_SENSORS"), + ("STEERING_ANGLE", "STEERING_SENSORS"), + ("STEERING_COL_TORQUE", "MDPS"), + ("STEERING_OUT_TORQUE", "MDPS"), + ("LKA_FAULT", "MDPS"), + + ("DriverBraking", "TCS"), + + ("COUNTER", cruise_btn_msg), + ("CRUISE_BUTTONS", cruise_btn_msg), + ("ADAPTIVE_CRUISE_MAIN_BTN", cruise_btn_msg), + + ("DISTANCE_UNIT", "CLUSTER_INFO"), + + ("LEFT_LAMP", "BLINKERS"), + ("RIGHT_LAMP", "BLINKERS"), + + ("DRIVER_DOOR_OPEN", "DOORS_SEATBELTS"), + ("DRIVER_SEATBELT_LATCHED", "DOORS_SEATBELTS"), + ] + + if CP.carFingerprint == CAR.KIA_SORENTO_PHEV_4TH_GEN: + signals.append(("DISTANCE_UNIT", cruise_btn_msg)) + + checks = [ + ("WHEEL_SPEEDS", 100), + (gear_msg, 100), + ("STEERING_SENSORS", 100), + ("MDPS", 100), + ("TCS", 50), + (cruise_btn_msg, 50), + ("CLUSTER_INFO", 4), + ("BLINKERS", 4), + ("DOORS_SEATBELTS", 4), + ] + + if CP.enableBsm: + signals += [ + ("FL_INDICATOR", "BLINDSPOTS_REAR_CORNERS"), + ("FR_INDICATOR", "BLINDSPOTS_REAR_CORNERS"), + ] + checks += [ + ("BLINDSPOTS_REAR_CORNERS", 20), + ] + + if not (CP.flags & HyundaiFlags.CANFD_CAMERA_SCC.value) and not CP.openpilotLongitudinalControl: + signals += [ + ("ACCMode", "SCC_CONTROL"), + ("VSetDis", "SCC_CONTROL"), + ("CRUISE_STANDSTILL", "SCC_CONTROL"), + ] + checks += [ + ("SCC_CONTROL", 50), + ] + + if CP.carFingerprint in EV_CAR: + signals += [ + ("ACCELERATOR_PEDAL", "ACCELERATOR"), + ] + checks += [ + ("ACCELERATOR", 100), + ] + elif CP.carFingerprint in HYBRID_CAR: + signals += [ + ("ACCELERATOR_PEDAL", "ACCELERATOR_ALT"), + ] + checks += [ + ("ACCELERATOR_ALT", 100), + ] + else: + signals += [ + ("ACCELERATOR_PEDAL_PRESSED", "ACCELERATOR_BRAKE_ALT"), + ] + checks += [ + ("ACCELERATOR_BRAKE_ALT", 100), + ] + + bus = 5 if CP.flags & HyundaiFlags.CANFD_HDA2 else 4 + return CANParser(DBC[CP.carFingerprint]["pt"], signals, checks, bus) + + @staticmethod + def get_cam_can_parser_canfd(CP): + signals = [] + checks = [] + if CP.flags & HyundaiFlags.CANFD_HDA2: + signals += [(f"BYTE{i}", "CAM_0x2a4") for i in range(3, 24)] + checks += [("CAM_0x2a4", 20)] + elif CP.flags & HyundaiFlags.CANFD_CAMERA_SCC: + signals += [ + ("COUNTER", "SCC_CONTROL"), + ("NEW_SIGNAL_1", "SCC_CONTROL"), + ("MainMode_ACC", "SCC_CONTROL"), + ("ACCMode", "SCC_CONTROL"), + ("CRUISE_INACTIVE", "SCC_CONTROL"), + ("ZEROS_9", "SCC_CONTROL"), + ("CRUISE_STANDSTILL", "SCC_CONTROL"), + ("ZEROS_5", "SCC_CONTROL"), + ("DISTANCE_SETTING", "SCC_CONTROL"), + ("VSetDis", "SCC_CONTROL"), + ] + + checks += [ + ("SCC_CONTROL", 50), + ] + + return CANParser(DBC[CP.carFingerprint]["pt"], signals, checks, 6) diff --git a/selfdrive/car/hyundai/hyundaican.py b/selfdrive/car/hyundai/hyundaican.py index fd3fc78e88..c2ffffbf22 100644 --- a/selfdrive/car/hyundai/hyundaican.py +++ b/selfdrive/car/hyundai/hyundaican.py @@ -1,10 +1,10 @@ import crcmod -from selfdrive.car.hyundai.values import CAR, CHECKSUM +from selfdrive.car.hyundai.values import CAR, CHECKSUM, CAMERA_SCC_CAR hyundai_checksum = crcmod.mkCrcFun(0x11D, initCrc=0xFD, rev=False, xorOut=0xdf) def create_lkas11(packer, frame, car_fingerprint, apply_steer, steer_req, - lkas11, sys_warning, sys_state, enabled, + torque_fault, lkas11, sys_warning, sys_state, enabled, left_lane, right_lane, left_lane_depart, right_lane_depart): values = lkas11 @@ -14,12 +14,14 @@ def create_lkas11(packer, frame, car_fingerprint, apply_steer, steer_req, values["CF_Lkas_LdwsRHWarning"] = right_lane_depart values["CR_Lkas_StrToqReq"] = apply_steer values["CF_Lkas_ActToi"] = steer_req + values["CF_Lkas_ToiFlt"] = torque_fault # seems to allow actuation on CR_Lkas_StrToqReq values["CF_Lkas_MsgCount"] = frame % 0x10 if car_fingerprint in (CAR.SONATA, CAR.PALISADE, CAR.KIA_NIRO_EV, CAR.KIA_NIRO_HEV_2021, CAR.SANTA_FE, CAR.IONIQ_EV_2020, CAR.IONIQ_PHEV, CAR.KIA_SELTOS, CAR.ELANTRA_2021, CAR.GENESIS_G70_2020, - CAR.ELANTRA_HEV_2021, CAR.SONATA_HYBRID, CAR.KONA_EV, CAR.KONA_HEV, CAR.SANTA_FE_2022, - CAR.KIA_K5_2021, CAR.IONIQ_HEV_2022, CAR.SANTA_FE_HEV_2022, CAR.SANTA_FE_PHEV_2022): + CAR.ELANTRA_HEV_2021, CAR.SONATA_HYBRID, CAR.KONA_EV, CAR.KONA_HEV, CAR.KONA_EV_2022, + CAR.SANTA_FE_2022, CAR.KIA_K5_2021, CAR.IONIQ_HEV_2022, CAR.SANTA_FE_HEV_2022, + CAR.SANTA_FE_PHEV_2022, CAR.KIA_STINGER_2022): values["CF_Lkas_LdwsActivemode"] = int(left_lane) + (int(right_lane) << 1) values["CF_Lkas_LdwsOpt_USM"] = 2 @@ -37,12 +39,26 @@ def create_lkas11(packer, frame, car_fingerprint, apply_steer, steer_req, # Note: the warning is hidden while the blinkers are on values["CF_Lkas_SysWarning"] = 4 if sys_warning else 0 + # Likely cars lacking the ability to show individual lane lines in the dash + elif car_fingerprint in (CAR.KIA_OPTIMA_G4, CAR.KIA_OPTIMA_G4_FL): + # SysWarning 4 = keep hands on wheel + beep + values["CF_Lkas_SysWarning"] = 4 if sys_warning else 0 + + # SysState 0 = no icons + # SysState 1-2 = white car + lanes + # SysState 3 = green car + lanes, green steering wheel + # SysState 4 = green car + lanes + values["CF_Lkas_LdwsSysState"] = 3 if enabled else 1 + values["CF_Lkas_LdwsOpt_USM"] = 2 # non-2 changes above SysState definition + + # these have no effect + values["CF_Lkas_LdwsActivemode"] = 0 + values["CF_Lkas_FcwOpt_USM"] = 0 + elif car_fingerprint == CAR.HYUNDAI_GENESIS: # This field is actually LdwsActivemode # Genesis and Optima fault when forwarding while engaged values["CF_Lkas_LdwsActivemode"] = 2 - elif car_fingerprint == CAR.KIA_OPTIMA: - values["CF_Lkas_LdwsActivemode"] = 0 dat = packer.make_can_msg("LKAS11", 0, values)[2] @@ -62,11 +78,13 @@ def create_lkas11(packer, frame, car_fingerprint, apply_steer, steer_req, return packer.make_can_msg("LKAS11", 0, values) -def create_clu11(packer, frame, clu11, button): +def create_clu11(packer, frame, clu11, button, car_fingerprint): values = clu11 values["CF_Clu_CruiseSwState"] = button values["CF_Clu_AliveCnt1"] = frame % 0x10 - return packer.make_can_msg("CLU11", 0, values) + # send buttons to camera on camera-scc based cars + bus = 2 if car_fingerprint in CAMERA_SCC_CAR else 0 + return packer.make_can_msg("CLU11", bus, values) def create_lfahda_mfc(packer, enabled, hda_set_speed=0): @@ -78,7 +96,7 @@ def create_lfahda_mfc(packer, enabled, hda_set_speed=0): } return packer.make_can_msg("LFAHDA_MFC", 0, values) -def create_acc_commands(packer, enabled, accel, jerk, idx, lead_visible, set_speed, stopping): +def create_acc_commands(packer, enabled, accel, upper_jerk, idx, lead_visible, set_speed, stopping, long_override): commands = [] scc11_values = { @@ -86,19 +104,19 @@ def create_acc_commands(packer, enabled, accel, jerk, idx, lead_visible, set_spe "TauGapSet": 4, "VSetDis": set_speed if enabled else 0, "AliveCounterACC": idx % 0x10, - "ObjValid": 1 if lead_visible else 0, - "ACC_ObjStatus": 1 if lead_visible else 0, + "ObjValid": 1, # close lead makes controls tighter + "ACC_ObjStatus": 1, # close lead makes controls tighter "ACC_ObjLatPos": 0, "ACC_ObjRelSpd": 0, - "ACC_ObjDist": 0, - } + "ACC_ObjDist": 1, # close lead makes controls tighter + } commands.append(packer.make_can_msg("SCC11", 0, scc11_values)) scc12_values = { - "ACCMode": 1 if enabled else 0, - "StopReq": 1 if enabled and stopping else 0, - "aReqRaw": accel if enabled else 0, - "aReqValue": accel if enabled else 0, # stock ramps up and down respecting jerk limit until it reaches aReqRaw + "ACCMode": 2 if enabled and long_override else 1 if enabled else 0, + "StopReq": 1 if stopping else 0, + "aReqRaw": accel, + "aReqValue": accel, # stock ramps up and down respecting jerk limit until it reaches aReqRaw "CR_VSM_Alive": idx % 0xF, } scc12_dat = packer.make_can_msg("SCC12", 0, scc12_values)[2] @@ -109,25 +127,23 @@ def create_acc_commands(packer, enabled, accel, jerk, idx, lead_visible, set_spe scc14_values = { "ComfortBandUpper": 0.0, # stock usually is 0 but sometimes uses higher values "ComfortBandLower": 0.0, # stock usually is 0 but sometimes uses higher values - "JerkUpperLimit": max(jerk, 1.0) if (enabled and not stopping) else 0, # stock usually is 1.0 but sometimes uses higher values - "JerkLowerLimit": max(-jerk, 1.0) if enabled else 0, # stock usually is 0.5 but sometimes uses higher values - "ACCMode": 1 if enabled else 4, # stock will always be 4 instead of 0 after first disengage + "JerkUpperLimit": upper_jerk, # stock usually is 1.0 but sometimes uses higher values + "JerkLowerLimit": 5.0, # stock usually is 0.5 but sometimes uses higher values + "ACCMode": 2 if enabled and long_override else 1 if enabled else 4, # stock will always be 4 instead of 0 after first disengage "ObjGap": 2 if lead_visible else 0, # 5: >30, m, 4: 25-30 m, 3: 20-25 m, 2: < 20 m, 0: no lead } commands.append(packer.make_can_msg("SCC14", 0, scc14_values)) + # note that some vehicles most likely have an alternate checksum/counter definition + # https://github.com/commaai/opendbc/commit/9ddcdb22c4929baf310295e832668e6e7fcfa602 fca11_values = { - # seems to count 2,1,0,3,2,1,0,3,2,1,0,3,2,1,0,repeat... - # (where first value is aligned to Supplemental_Counter == 0) - # test: [(idx % 0xF, -((idx % 0xF) + 2) % 4) for idx in range(0x14)] - "CR_FCA_Alive": ((-((idx % 0xF) + 2) % 4) << 2) + 1, - "Supplemental_Counter": idx % 0xF, + "CR_FCA_Alive": idx % 0xF, "PAINT1_Status": 1, "FCA_DrvSetStatus": 1, "FCA_Status": 1, # AEB disabled } fca11_dat = packer.make_can_msg("FCA11", 0, fca11_values)[2] - fca11_values["CR_FCA_ChkSum"] = 0x10 - sum(sum(divmod(i, 16)) for i in fca11_dat) % 0x10 + fca11_values["CR_FCA_ChkSum"] = hyundai_checksum(fca11_dat[:7]) commands.append(packer.make_can_msg("FCA11", 0, fca11_values)) return commands diff --git a/selfdrive/car/hyundai/hyundaicanfd.py b/selfdrive/car/hyundai/hyundaicanfd.py new file mode 100644 index 0000000000..8b53e7c378 --- /dev/null +++ b/selfdrive/car/hyundai/hyundaicanfd.py @@ -0,0 +1,150 @@ +from common.numpy_fast import clip +from selfdrive.car.hyundai.values import HyundaiFlags + + +def get_e_can_bus(CP): + # On the CAN-FD platforms, the LKAS camera is on both A-CAN and E-CAN. HDA2 cars + # have a different harness than the HDA1 and non-HDA variants in order to split + # a different bus, since the steering is done by different ECUs. + return 5 if CP.flags & HyundaiFlags.CANFD_HDA2 else 4 + + +def create_steering_messages(packer, CP, enabled, lat_active, apply_steer): + + ret = [] + + values = { + "LKA_MODE": 2, + "LKA_ICON": 2 if enabled else 1, + "TORQUE_REQUEST": apply_steer, + "LKA_ASSIST": 0, + "STEER_REQ": 1 if lat_active else 0, + "STEER_MODE": 0, + "SET_ME_1": 0, + "NEW_SIGNAL_1": 0, + "NEW_SIGNAL_2": 0, + } + + if CP.flags & HyundaiFlags.CANFD_HDA2: + if CP.openpilotLongitudinalControl: + ret.append(packer.make_can_msg("LFA", 5, values)) + ret.append(packer.make_can_msg("LKAS", 4, values)) + else: + ret.append(packer.make_can_msg("LFA", 4, values)) + + return ret + +def create_cam_0x2a4(packer, camera_values): + camera_values.update({ + "BYTE7": 0, + }) + return packer.make_can_msg("CAM_0x2a4", 4, camera_values) + +def create_buttons(packer, CP, cnt, btn): + values = { + "COUNTER": cnt, + "SET_ME_1": 1, + "CRUISE_BUTTONS": btn, + } + + bus = 5 if CP.flags & HyundaiFlags.CANFD_HDA2 else 6 + return packer.make_can_msg("CRUISE_BUTTONS", bus, values) + +def create_acc_cancel(packer, CP, cruise_info_copy): + values = cruise_info_copy + values.update({ + "ACCMode": 4, + }) + return packer.make_can_msg("SCC_CONTROL", get_e_can_bus(CP), values) + +def create_lfahda_cluster(packer, CP, enabled): + values = { + "HDA_ICON": 1 if enabled else 0, + "LFA_ICON": 2 if enabled else 0, + } + return packer.make_can_msg("LFAHDA_CLUSTER", get_e_can_bus(CP), values) + + +def create_acc_control(packer, CP, enabled, accel_last, accel, stopping, gas_override, set_speed): + jerk = 5 + jn = jerk / 50 + if not enabled or gas_override: + a_val, a_raw = 0, 0 + else: + a_raw = accel + a_val = clip(accel, accel_last - jn, accel_last + jn) + if stopping: + a_raw = 0 + + values = { + "ACCMode": 0 if not enabled else (2 if gas_override else 1), + "MainMode_ACC": 1, + "StopReq": 1 if stopping else 0, + "aReqValue": a_val, + "aReqRaw": a_raw, + "VSetDis": set_speed, + "JerkLowerLimit": jerk if enabled else 1, + + "ACC_ObjDist": 1, + "ObjValid": 0, + "OBJ_STATUS": 2, + "SET_ME_2": 0x4, + "SET_ME_3": 0x3, + "SET_ME_TMP_64": 0x64, + "NEW_SIGNAL_10": 4, + "DISTANCE_SETTING": 4, + } + + return packer.make_can_msg("SCC_CONTROL", get_e_can_bus(CP), values) + + + +def create_adrv_messages(packer, frame): + # messages needed to car happy after disabling + # the ADAS Driving ECU to do longitudinal control + + ret = [] + + values = { + } + ret.append(packer.make_can_msg("ADRV_0x51", 4, values)) + + if frame % 2 == 0: + values = { + 'AEB_SETTING': 0x1, # show AEB disabled icon + 'SET_ME_2': 0x2, + 'SET_ME_FF': 0xff, + 'SET_ME_FC': 0xfc, + 'SET_ME_9': 0x9, + } + ret.append(packer.make_can_msg("ADRV_0x160", 5, values)) + + if frame % 5 == 0: + values = { + 'SET_ME_1C': 0x1c, + 'SET_ME_FF': 0xff, + 'SET_ME_TMP_F': 0xf, + 'SET_ME_TMP_F_2': 0xf, + } + ret.append(packer.make_can_msg("ADRV_0x1ea", 5, values)) + + values = { + 'SET_ME_E1': 0xe1, + 'SET_ME_3A': 0x3a, + } + ret.append(packer.make_can_msg("ADRV_0x200", 5, values)) + + if frame % 20 == 0: + values = { + 'SET_ME_15': 0x15, + } + ret.append(packer.make_can_msg("ADRV_0x345", 5, values)) + + if frame % 100 == 0: + values = { + 'SET_ME_22': 0x22, + 'SET_ME_41': 0x41, + } + ret.append(packer.make_can_msg("ADRV_0x1da", 5, values)) + + return ret diff --git a/selfdrive/car/hyundai/interface.py b/selfdrive/car/hyundai/interface.py index 379e6937ae..b9f6b8fc58 100644 --- a/selfdrive/car/hyundai/interface.py +++ b/selfdrive/car/hyundai/interface.py @@ -1,341 +1,311 @@ #!/usr/bin/env python3 from cereal import car from panda import Panda -from common.params import Params -from selfdrive.config import Conversions as CV -from selfdrive.car.hyundai.values import CAR, EV_CAR, HYBRID_CAR, LEGACY_SAFETY_MODE_CAR, Buttons, CarControllerParams +from common.conversions import Conversions as CV +from selfdrive.car.hyundai.values import HyundaiFlags, CAR, DBC, CANFD_CAR, CAMERA_SCC_CAR, CANFD_RADAR_SCC_CAR, EV_CAR, HYBRID_CAR, LEGACY_SAFETY_MODE_CAR, Buttons from selfdrive.car.hyundai.radar_interface import RADAR_START_ADDR -from selfdrive.car import STD_CARGO_KG, scale_rot_inertia, scale_tire_stiffness, gen_empty_fingerprint, get_safety_config +from selfdrive.car import STD_CARGO_KG, create_button_event, scale_tire_stiffness, get_safety_config from selfdrive.car.interfaces import CarInterfaceBase from selfdrive.car.disable_ecu import disable_ecu +Ecu = car.CarParams.Ecu ButtonType = car.CarState.ButtonEvent.Type EventName = car.CarEvent.EventName +ENABLE_BUTTONS = (Buttons.RES_ACCEL, Buttons.SET_DECEL, Buttons.CANCEL) +BUTTONS_DICT = {Buttons.RES_ACCEL: ButtonType.accelCruise, Buttons.SET_DECEL: ButtonType.decelCruise, + Buttons.GAP_DIST: ButtonType.gapAdjustCruise, Buttons.CANCEL: ButtonType.cancel} -class CarInterface(CarInterfaceBase): - @staticmethod - def get_pid_accel_limits(CP, current_speed, cruise_speed): - return CarControllerParams.ACCEL_MIN, CarControllerParams.ACCEL_MAX +class CarInterface(CarInterfaceBase): @staticmethod - def get_params(candidate, fingerprint=gen_empty_fingerprint(), car_fw=[]): # pylint: disable=dangerous-default-value - ret = CarInterfaceBase.get_std_params(candidate, fingerprint) - + def _get_params(ret, candidate, fingerprint, car_fw, experimental_long): ret.carName = "hyundai" - ret.safetyConfigs = [get_safety_config(car.CarParams.SafetyModel.hyundai, 0)] - ret.radarOffCan = RADAR_START_ADDR not in fingerprint[1] - - # WARNING: disabling radar also disables AEB (and we show the same warning on the instrument cluster as if you manually disabled AEB) - ret.openpilotLongitudinalControl = Params().get_bool("DisableRadar") and (candidate not in LEGACY_SAFETY_MODE_CAR) - - ret.pcmCruise = not ret.openpilotLongitudinalControl + ret.radarOffCan = RADAR_START_ADDR not in fingerprint[1] or DBC[ret.carFingerprint]["radar"] is None # These cars have been put into dashcam only due to both a lack of users and test coverage. # These cars likely still work fine. Once a user confirms each car works and a test route is - # added to selfdrive/test/test_routes, we can remove it from this list. - ret.dashcamOnly = candidate in {CAR.KIA_OPTIMA_H, CAR.ELANTRA_GT_I30} + # added to selfdrive/car/tests/routes.py, we can remove it from this list. + ret.dashcamOnly = candidate in {CAR.KIA_OPTIMA_H, } + + if candidate in CANFD_CAR: + # detect HDA2 with ADAS Driving ECU + if Ecu.adas in [fw.ecu for fw in car_fw]: + ret.flags |= HyundaiFlags.CANFD_HDA2.value + else: + # non-HDA2 + if 0x1cf not in fingerprint[4]: + ret.flags |= HyundaiFlags.CANFD_ALT_BUTTONS.value + # ICE cars do not have 0x130; GEARS message on 0x40 instead + if 0x130 not in fingerprint[4]: + ret.flags |= HyundaiFlags.CANFD_ALT_GEARS.value + if candidate not in CANFD_RADAR_SCC_CAR: + ret.flags |= HyundaiFlags.CANFD_CAMERA_SCC.value ret.steerActuatorDelay = 0.1 # Default delay - ret.steerRateCost = 0.5 ret.steerLimitTimer = 0.4 tire_stiffness_factor = 1. - - ret.stoppingControl = True - ret.vEgoStopping = 1.0 - - ret.longitudinalTuning.kpV = [0.1] - ret.longitudinalTuning.kiV = [0.0] - ret.stopAccel = 0.0 - - ret.longitudinalActuatorDelayUpperBound = 1.0 # s + CarInterfaceBase.configure_torque_tune(candidate, ret.lateralTuning) if candidate in (CAR.SANTA_FE, CAR.SANTA_FE_2022, CAR.SANTA_FE_HEV_2022, CAR.SANTA_FE_PHEV_2022): - ret.lateralTuning.pid.kf = 0.00005 ret.mass = 3982. * CV.LB_TO_KG + STD_CARGO_KG ret.wheelbase = 2.766 # Values from optimizer ret.steerRatio = 16.55 # 13.8 is spec end-to-end tire_stiffness_factor = 0.82 - ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[9., 22.], [9., 22.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.2, 0.35], [0.05, 0.09]] elif candidate in (CAR.SONATA, CAR.SONATA_HYBRID): - ret.lateralTuning.pid.kf = 0.00005 ret.mass = 1513. + STD_CARGO_KG ret.wheelbase = 2.84 ret.steerRatio = 13.27 * 1.15 # 15% higher at the center seems reasonable tire_stiffness_factor = 0.65 - ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.25], [0.05]] elif candidate == CAR.SONATA_LF: - ret.lateralTuning.pid.kf = 0.00005 ret.mass = 4497. * CV.LB_TO_KG ret.wheelbase = 2.804 ret.steerRatio = 13.27 * 1.15 # 15% higher at the center seems reasonable - ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.25], [0.05]] elif candidate == CAR.PALISADE: - ret.lateralTuning.pid.kf = 0.00005 ret.mass = 1999. + STD_CARGO_KG ret.wheelbase = 2.90 ret.steerRatio = 15.6 * 1.15 tire_stiffness_factor = 0.63 - ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.3], [0.05]] - elif candidate in (CAR.ELANTRA, CAR.ELANTRA_GT_I30): - ret.lateralTuning.pid.kf = 0.00006 + elif candidate == CAR.ELANTRA: ret.mass = 1275. + STD_CARGO_KG ret.wheelbase = 2.7 ret.steerRatio = 15.4 # 14 is Stock | Settled Params Learner values are steerRatio: 15.401566348670535 tire_stiffness_factor = 0.385 # stiffnessFactor settled on 1.0081302973865127 - ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.25], [0.05]] ret.minSteerSpeed = 32 * CV.MPH_TO_MS elif candidate == CAR.ELANTRA_2021: - ret.lateralTuning.pid.kf = 0.00005 ret.mass = (2800. * CV.LB_TO_KG) + STD_CARGO_KG ret.wheelbase = 2.72 ret.steerRatio = 12.9 tire_stiffness_factor = 0.65 - ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.25], [0.05]] elif candidate == CAR.ELANTRA_HEV_2021: - ret.lateralTuning.pid.kf = 0.00005 ret.mass = (3017. * CV.LB_TO_KG) + STD_CARGO_KG ret.wheelbase = 2.72 ret.steerRatio = 12.9 tire_stiffness_factor = 0.65 - ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.25], [0.05]] elif candidate == CAR.HYUNDAI_GENESIS: - ret.lateralTuning.pid.kf = 0.00005 ret.mass = 2060. + STD_CARGO_KG ret.wheelbase = 3.01 ret.steerRatio = 16.5 - ret.lateralTuning.init('indi') - ret.lateralTuning.indi.innerLoopGainBP = [0.] - ret.lateralTuning.indi.innerLoopGainV = [3.5] - ret.lateralTuning.indi.outerLoopGainBP = [0.] - ret.lateralTuning.indi.outerLoopGainV = [2.0] - ret.lateralTuning.indi.timeConstantBP = [0.] - ret.lateralTuning.indi.timeConstantV = [1.4] - ret.lateralTuning.indi.actuatorEffectivenessBP = [0.] - ret.lateralTuning.indi.actuatorEffectivenessV = [2.3] ret.minSteerSpeed = 60 * CV.KPH_TO_MS - elif candidate in (CAR.KONA, CAR.KONA_EV, CAR.KONA_HEV): - ret.lateralTuning.pid.kf = 0.00005 - ret.mass = {CAR.KONA_EV: 1685., CAR.KONA_HEV: 1425.}.get(candidate, 1275.) + STD_CARGO_KG - ret.wheelbase = 2.7 - ret.steerRatio = 13.73 * 1.15 # Spec + elif candidate in (CAR.KONA, CAR.KONA_EV, CAR.KONA_HEV, CAR.KONA_EV_2022): + ret.mass = {CAR.KONA_EV: 1685., CAR.KONA_HEV: 1425., CAR.KONA_EV_2022: 1743.}.get(candidate, 1275.) + STD_CARGO_KG + ret.wheelbase = 2.6 + ret.steerRatio = 13.42 # Spec tire_stiffness_factor = 0.385 - ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.25], [0.05]] elif candidate in (CAR.IONIQ, CAR.IONIQ_EV_LTD, CAR.IONIQ_EV_2020, CAR.IONIQ_PHEV, CAR.IONIQ_HEV_2022): - ret.lateralTuning.pid.kf = 0.00006 ret.mass = 1490. + STD_CARGO_KG # weight per hyundai site https://www.hyundaiusa.com/ioniq-electric/specifications.aspx ret.wheelbase = 2.7 ret.steerRatio = 13.73 # Spec tire_stiffness_factor = 0.385 - ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.25], [0.05]] if candidate not in (CAR.IONIQ_EV_2020, CAR.IONIQ_PHEV, CAR.IONIQ_HEV_2022): ret.minSteerSpeed = 32 * CV.MPH_TO_MS + elif candidate == CAR.IONIQ_PHEV_2019: + ret.mass = 1550. + STD_CARGO_KG # weight per hyundai site https://www.hyundaiusa.com/us/en/vehicles/2019-ioniq-plug-in-hybrid/compare-specs + ret.wheelbase = 2.7 + ret.steerRatio = 13.73 + ret.minSteerSpeed = 32 * CV.MPH_TO_MS elif candidate == CAR.VELOSTER: - ret.lateralTuning.pid.kf = 0.00005 ret.mass = 3558. * CV.LB_TO_KG ret.wheelbase = 2.80 ret.steerRatio = 13.75 * 1.15 tire_stiffness_factor = 0.5 - ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.25], [0.05]] + elif candidate == CAR.TUCSON: + ret.mass = 3520. * CV.LB_TO_KG + ret.wheelbase = 2.67 + ret.steerRatio = 14.00 * 1.15 + tire_stiffness_factor = 0.385 + elif candidate in (CAR.TUCSON_4TH_GEN, CAR.TUCSON_HYBRID_4TH_GEN): + ret.mass = 1630. + STD_CARGO_KG # average + ret.wheelbase = 2.756 + ret.steerRatio = 16. + tire_stiffness_factor = 0.385 + elif candidate == CAR.SANTA_CRUZ_1ST_GEN: + ret.mass = 1870. + STD_CARGO_KG # weight from Limited trim - the only supported trim + ret.wheelbase = 3.000 + ret.steerRatio = 14.2 # steering ratio according to Hyundai News https://www.hyundainews.com/assets/documents/original/48035-2022SantaCruzProductGuideSpecsv2081521.pdf # Kia elif candidate == CAR.KIA_SORENTO: - ret.lateralTuning.pid.kf = 0.00005 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.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.25], [0.05]] - elif candidate in (CAR.KIA_NIRO_EV, CAR.KIA_NIRO_HEV, CAR.KIA_NIRO_HEV_2021): - ret.lateralTuning.pid.kf = 0.00006 + elif candidate in (CAR.KIA_NIRO_EV, CAR.KIA_NIRO_PHEV, CAR.KIA_NIRO_HEV_2021): ret.mass = 1737. + STD_CARGO_KG ret.wheelbase = 2.7 ret.steerRatio = 13.9 if CAR.KIA_NIRO_HEV_2021 else 13.73 # Spec tire_stiffness_factor = 0.385 - ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.25], [0.05]] - if candidate == CAR.KIA_NIRO_HEV: + if candidate == CAR.KIA_NIRO_PHEV: ret.minSteerSpeed = 32 * CV.MPH_TO_MS elif candidate == CAR.KIA_SELTOS: ret.mass = 1337. + STD_CARGO_KG ret.wheelbase = 2.63 ret.steerRatio = 14.56 tire_stiffness_factor = 1 - ret.lateralTuning.init('indi') - ret.lateralTuning.indi.innerLoopGainBP = [0.] - ret.lateralTuning.indi.innerLoopGainV = [4.] - ret.lateralTuning.indi.outerLoopGainBP = [0.] - ret.lateralTuning.indi.outerLoopGainV = [3.] - ret.lateralTuning.indi.timeConstantBP = [0.] - ret.lateralTuning.indi.timeConstantV = [1.4] - ret.lateralTuning.indi.actuatorEffectivenessBP = [0.] - ret.lateralTuning.indi.actuatorEffectivenessV = [1.8] - elif candidate in (CAR.KIA_OPTIMA, CAR.KIA_OPTIMA_H): - ret.lateralTuning.pid.kf = 0.00005 + elif candidate == CAR.KIA_SPORTAGE_5TH_GEN: + ret.mass = 1700. + STD_CARGO_KG # weight from SX and above trims, average of FWD and AWD versions + ret.wheelbase = 2.756 + ret.steerRatio = 13.6 # steering ratio according to Kia News https://www.kiamedia.com/us/en/models/sportage/2023/specifications + elif candidate in (CAR.KIA_OPTIMA_G4, CAR.KIA_OPTIMA_G4_FL, CAR.KIA_OPTIMA_H): ret.mass = 3558. * CV.LB_TO_KG ret.wheelbase = 2.80 ret.steerRatio = 13.75 tire_stiffness_factor = 0.5 - ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.25], [0.05]] - elif candidate == CAR.KIA_STINGER: - ret.lateralTuning.pid.kf = 0.00005 + if candidate == CAR.KIA_OPTIMA_G4: + ret.minSteerSpeed = 32 * CV.MPH_TO_MS + elif candidate in (CAR.KIA_STINGER, CAR.KIA_STINGER_2022): 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.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.25], [0.05]] elif candidate == CAR.KIA_FORTE: - ret.lateralTuning.pid.kf = 0.00005 ret.mass = 3558. * CV.LB_TO_KG ret.wheelbase = 2.80 ret.steerRatio = 13.75 tire_stiffness_factor = 0.5 - ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.25], [0.05]] elif candidate == CAR.KIA_CEED: - ret.lateralTuning.pid.kf = 0.00005 ret.mass = 1450. + STD_CARGO_KG ret.wheelbase = 2.65 ret.steerRatio = 13.75 tire_stiffness_factor = 0.5 - ret.lateralTuning.pid.kf = 0.00005 - ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.25], [0.05]] elif candidate == CAR.KIA_K5_2021: - ret.lateralTuning.pid.kf = 0.00005 ret.mass = 3228. * CV.LB_TO_KG ret.wheelbase = 2.85 ret.steerRatio = 13.27 # 2021 Kia K5 Steering Ratio (all trims) tire_stiffness_factor = 0.5 - ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.25], [0.05]] + elif candidate == CAR.KIA_EV6: + ret.mass = 2055 + STD_CARGO_KG + ret.wheelbase = 2.9 + ret.steerRatio = 16. + tire_stiffness_factor = 0.65 + elif candidate == CAR.IONIQ_5: + ret.mass = 2012 + STD_CARGO_KG + ret.wheelbase = 3.0 + ret.steerRatio = 16. + tire_stiffness_factor = 0.65 + elif candidate == CAR.KIA_SPORTAGE_HYBRID_5TH_GEN: + ret.mass = 1767. + STD_CARGO_KG # SX Prestige trim support only + ret.wheelbase = 2.756 + ret.steerRatio = 13.6 + elif candidate == CAR.KIA_SORENTO_PHEV_4TH_GEN: + ret.mass = 4095.8 * CV.LB_TO_KG + STD_CARGO_KG # weight from EX and above trims, average of FWD and AWD versions (EX, X-Line EX AWD, SX, SX Pestige, X-Line SX Prestige AWD) + ret.wheelbase = 2.81 + ret.steerRatio = 13.27 # steering ratio according to Kia News https://www.kiamedia.com/us/en/models/sorento-phev/2022/specifications # Genesis elif candidate == CAR.GENESIS_G70: - ret.lateralTuning.init('indi') - ret.lateralTuning.indi.innerLoopGainBP = [0.] - ret.lateralTuning.indi.innerLoopGainV = [2.5] - ret.lateralTuning.indi.outerLoopGainBP = [0.] - ret.lateralTuning.indi.outerLoopGainV = [3.5] - ret.lateralTuning.indi.timeConstantBP = [0.] - ret.lateralTuning.indi.timeConstantV = [1.4] - ret.lateralTuning.indi.actuatorEffectivenessBP = [0.] - ret.lateralTuning.indi.actuatorEffectivenessV = [1.8] ret.steerActuatorDelay = 0.1 ret.mass = 1640.0 + STD_CARGO_KG ret.wheelbase = 2.84 ret.steerRatio = 13.56 elif candidate == CAR.GENESIS_G70_2020: - ret.lateralTuning.pid.kf = 0. - ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.112], [0.004]] ret.mass = 3673.0 * CV.LB_TO_KG + STD_CARGO_KG ret.wheelbase = 2.83 ret.steerRatio = 12.9 + elif candidate == CAR.GENESIS_GV70_1ST_GEN: + ret.mass = 1950. + STD_CARGO_KG + ret.wheelbase = 2.87 + ret.steerRatio = 14.6 elif candidate == CAR.GENESIS_G80: - ret.lateralTuning.pid.kf = 0.00005 ret.mass = 2060. + STD_CARGO_KG ret.wheelbase = 3.01 ret.steerRatio = 16.5 - ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.16], [0.01]] elif candidate == CAR.GENESIS_G90: ret.mass = 2200 ret.wheelbase = 3.15 ret.steerRatio = 12.069 - ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.16], [0.01]] - # these cars require a special panda safety mode due to missing counters and checksums in the messages - if candidate in LEGACY_SAFETY_MODE_CAR: - ret.safetyConfigs = [get_safety_config(car.CarParams.SafetyModel.hyundaiLegacy)] + # *** longitudinal control *** + if candidate in CANFD_CAR: + ret.longitudinalTuning.kpV = [0.1] + ret.longitudinalTuning.kiV = [0.0] + ret.experimentalLongitudinalAvailable = candidate in (HYBRID_CAR | EV_CAR) and candidate not in CANFD_RADAR_SCC_CAR + else: + ret.longitudinalTuning.kpV = [0.5] + ret.longitudinalTuning.kiV = [0.0] + ret.experimentalLongitudinalAvailable = candidate not in (LEGACY_SAFETY_MODE_CAR | CAMERA_SCC_CAR) + ret.openpilotLongitudinalControl = experimental_long and ret.experimentalLongitudinalAvailable + ret.pcmCruise = not ret.openpilotLongitudinalControl + + ret.stoppingControl = True + ret.startingState = True + ret.vEgoStarting = 0.1 + ret.startAccel = 2.0 + ret.longitudinalActuatorDelayLowerBound = 0.5 + ret.longitudinalActuatorDelayUpperBound = 0.5 + + # *** feature detection *** + if candidate in CANFD_CAR: + bus = 5 if ret.flags & HyundaiFlags.CANFD_HDA2 else 4 + ret.enableBsm = 0x1e5 in fingerprint[bus] + else: + ret.enableBsm = 0x58b in fingerprint[0] + + # *** panda safety config *** + if candidate in CANFD_CAR: + ret.safetyConfigs = [get_safety_config(car.CarParams.SafetyModel.noOutput), + get_safety_config(car.CarParams.SafetyModel.hyundaiCanfd)] + + if ret.flags & HyundaiFlags.CANFD_HDA2: + ret.safetyConfigs[1].safetyParam |= Panda.FLAG_HYUNDAI_CANFD_HDA2 + if ret.flags & HyundaiFlags.CANFD_ALT_BUTTONS: + ret.safetyConfigs[1].safetyParam |= Panda.FLAG_HYUNDAI_CANFD_ALT_BUTTONS + if ret.flags & HyundaiFlags.CANFD_CAMERA_SCC: + ret.safetyConfigs[1].safetyParam |= Panda.FLAG_HYUNDAI_CAMERA_SCC + else: + if candidate in LEGACY_SAFETY_MODE_CAR: + # these cars require a special panda safety mode due to missing counters and checksums in the messages + ret.safetyConfigs = [get_safety_config(car.CarParams.SafetyModel.hyundaiLegacy)] + else: + ret.safetyConfigs = [get_safety_config(car.CarParams.SafetyModel.hyundai, 0)] + + if candidate in CAMERA_SCC_CAR: + ret.safetyConfigs[0].safetyParam |= Panda.FLAG_HYUNDAI_CAMERA_SCC - # set appropriate safety param for gas signal + if ret.openpilotLongitudinalControl: + ret.safetyConfigs[-1].safetyParam |= Panda.FLAG_HYUNDAI_LONG if candidate in HYBRID_CAR: - ret.safetyConfigs[0].safetyParam = 2 + ret.safetyConfigs[-1].safetyParam |= Panda.FLAG_HYUNDAI_HYBRID_GAS elif candidate in EV_CAR: - ret.safetyConfigs[0].safetyParam = 1 + ret.safetyConfigs[-1].safetyParam |= Panda.FLAG_HYUNDAI_EV_GAS - ret.centerToFront = ret.wheelbase * 0.4 + if candidate in (CAR.KONA, CAR.KONA_EV, CAR.KONA_HEV, CAR.KONA_EV_2022): + ret.flags |= HyundaiFlags.ALT_LIMITS.value + ret.safetyConfigs[-1].safetyParam |= Panda.FLAG_HYUNDAI_ALT_LIMITS - # TODO: get actual value, for now starting with reasonable value for - # civic and scaling by mass and wheelbase - ret.rotationalInertia = scale_rot_inertia(ret.mass, ret.wheelbase) + ret.centerToFront = ret.wheelbase * 0.4 # TODO: start from empirically derived lateral slip stiffness for the civic and scale by # mass and CG position, so all cars will have approximately similar dyn behaviors ret.tireStiffnessFront, ret.tireStiffnessRear = scale_tire_stiffness(ret.mass, ret.wheelbase, ret.centerToFront, tire_stiffness_factor=tire_stiffness_factor) - - ret.enableBsm = 0x58b in fingerprint[0] - - if ret.openpilotLongitudinalControl: - ret.safetyConfigs[0].safetyParam |= Panda.FLAG_HYUNDAI_LONG - return ret @staticmethod def init(CP, logcan, sendcan): - if CP.openpilotLongitudinalControl: - disable_ecu(logcan, sendcan, addr=0x7d0, com_cont_req=b'\x28\x83\x01') - - def update(self, c, can_strings): - self.cp.update_strings(can_strings) - self.cp_cam.update_strings(can_strings) + if CP.openpilotLongitudinalControl and not (CP.flags & HyundaiFlags.CANFD_CAMERA_SCC.value): + addr, bus = 0x7d0, 0 + if CP.flags & HyundaiFlags.CANFD_HDA2.value: + addr, bus = 0x730, 5 + disable_ecu(logcan, sendcan, bus=bus, addr=addr, com_cont_req=b'\x28\x83\x01') + def _update(self, c): ret = self.CS.update(self.cp, self.cp_cam) - ret.canValid = self.cp.can_valid and self.cp_cam.can_valid - ret.steeringRateLimited = self.CC.steer_rate_limited if self.CC is not None else False - - events = self.create_common_events(ret, pcm_enable=self.CS.CP.pcmCruise) - - if self.CS.brake_error: - events.add(EventName.brakeUnavailable) - if self.CS.park_brake: - events.add(EventName.parkBrake) - if self.CS.CP.openpilotLongitudinalControl: - buttonEvents = [] + if self.CS.CP.openpilotLongitudinalControl and self.CS.cruise_buttons[-1] != self.CS.prev_cruise_buttons: + buttonEvents = [create_button_event(self.CS.cruise_buttons[-1], self.CS.prev_cruise_buttons, BUTTONS_DICT)] + # Handle CF_Clu_CruiseSwState changing buttons mid-press + if self.CS.cruise_buttons[-1] != 0 and self.CS.prev_cruise_buttons != 0: + buttonEvents.append(create_button_event(0, self.CS.prev_cruise_buttons, BUTTONS_DICT)) - if self.CS.cruise_buttons != self.CS.prev_cruise_buttons: - be = car.CarState.ButtonEvent.new_message() - be.type = ButtonType.unknown - if self.CS.cruise_buttons != 0: - be.pressed = True - but = self.CS.cruise_buttons - else: - be.pressed = False - but = self.CS.prev_cruise_buttons - if but == Buttons.RES_ACCEL: - be.type = ButtonType.accelCruise - elif but == Buttons.SET_DECEL: - be.type = ButtonType.decelCruise - elif but == Buttons.GAP_DIST: - be.type = ButtonType.gapAdjustCruise - elif but == Buttons.CANCEL: - be.type = ButtonType.cancel - buttonEvents.append(be) + ret.buttonEvents = buttonEvents - ret.buttonEvents = buttonEvents + # On some newer model years, the CANCEL button acts as a pause/resume button based on the PCM state + # To avoid re-engaging when openpilot cancels, check user engagement intention via buttons + # Main button also can trigger an engagement on these cars + allow_enable = any(btn in ENABLE_BUTTONS for btn in self.CS.cruise_buttons) or any(self.CS.main_buttons) + events = self.create_common_events(ret, pcm_enable=self.CS.CP.pcmCruise, allow_enable=allow_enable) - for b in ret.buttonEvents: - # do enable on both accel and decel buttons - if b.type in (ButtonType.accelCruise, ButtonType.decelCruise) and not b.pressed: - events.add(EventName.buttonEnable) - # do disable on button down - if b.type == ButtonType.cancel and b.pressed: - events.add(EventName.buttonCancel) + if self.CS.brake_error: + events.add(EventName.brakeUnavailable) # 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.: @@ -347,13 +317,7 @@ class CarInterface(CarInterfaceBase): ret.events = events.to_msg() - self.CS.out = ret.as_reader() - return self.CS.out + return ret def apply(self, c): - hud_control = c.hudControl - ret = self.CC.update(c, c.enabled, self.CS, self.frame, c.actuators, - c.cruiseControl.cancel, hud_control.visualAlert, hud_control.setSpeed, hud_control.leftLaneVisible, - hud_control.rightLaneVisible, hud_control.leftLaneDepart, hud_control.rightLaneDepart) - self.frame += 1 - return ret + return self.CC.update(c, self.CS) diff --git a/selfdrive/car/hyundai/tests/test_hyundai.py b/selfdrive/car/hyundai/tests/test_hyundai.py new file mode 100755 index 0000000000..a52027f448 --- /dev/null +++ b/selfdrive/car/hyundai/tests/test_hyundai.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 +import unittest + +from cereal import car +from selfdrive.car.car_helpers import get_interface_attr +from selfdrive.car.fw_versions import FW_QUERY_CONFIGS +from selfdrive.car.hyundai.values import CANFD_CAR + +Ecu = car.CarParams.Ecu + +ECU_NAME = {v: k for k, v in Ecu.schema.enumerants.items()} +VERSIONS = get_interface_attr("FW_VERSIONS", ignore_none=True) + + +class TestHyundaiFingerprint(unittest.TestCase): + def test_auxiliary_request_ecu_whitelist(self): + # Asserts only auxiliary Ecus can exist in database for CAN-FD cars + config = FW_QUERY_CONFIGS['hyundai'] + whitelisted_ecus = {ecu for r in config.requests for ecu in r.whitelist_ecus if r.bus > 3} + + for car_model in CANFD_CAR: + ecus = {fw[0] for fw in VERSIONS['hyundai'][car_model].keys()} + ecus_not_in_whitelist = ecus - whitelisted_ecus + ecu_strings = ", ".join([f'Ecu.{ECU_NAME[ecu]}' for ecu in ecus_not_in_whitelist]) + self.assertEqual(len(ecus_not_in_whitelist), 0, f'{car_model}: Car model has ECUs not in auxiliary request whitelists: {ecu_strings}') + + +if __name__ == "__main__": + unittest.main() diff --git a/selfdrive/car/hyundai/values.py b/selfdrive/car/hyundai/values.py index e26d17b241..1e9d0f7f62 100644 --- a/selfdrive/car/hyundai/values.py +++ b/selfdrive/car/hyundai/values.py @@ -1,41 +1,79 @@ +from dataclasses import dataclass +from enum import Enum, IntFlag +from typing import Dict, List, Optional, Union + from cereal import car +from panda.python import uds +from common.conversions import Conversions as CV from selfdrive.car import dbc_dict +from selfdrive.car.docs_definitions import CarFootnote, CarInfo, Column, Harness +from selfdrive.car.fw_query_definitions import FwQueryConfig, Request, p16 + Ecu = car.CarParams.Ecu -# Steer torque limits + class CarControllerParams: ACCEL_MIN = -3.5 # m/s ACCEL_MAX = 2.0 # m/s def __init__(self, CP): - # To determine the limit for your car, find the maximum value that the stock LKAS will request. - # If the max stock LKAS request is <384, add your car to this list. - if CP.carFingerprint in (CAR.GENESIS_G80, CAR.GENESIS_G90, CAR.ELANTRA, CAR.HYUNDAI_GENESIS, CAR.ELANTRA_GT_I30, CAR.IONIQ, - CAR.IONIQ_EV_LTD, CAR.IONIQ_PHEV, CAR.SANTA_FE_PHEV_2022, CAR.SONATA_LF, CAR.KIA_FORTE, CAR.KIA_NIRO_HEV, - CAR.KIA_NIRO_HEV_2021, CAR.KIA_OPTIMA_H, CAR.KIA_OPTIMA, CAR.KIA_SORENTO, CAR.KIA_STINGER): - self.STEER_MAX = 255 - else: - self.STEER_MAX = 384 self.STEER_DELTA_UP = 3 self.STEER_DELTA_DOWN = 7 self.STEER_DRIVER_ALLOWANCE = 50 self.STEER_DRIVER_MULTIPLIER = 2 self.STEER_DRIVER_FACTOR = 1 + self.STEER_THRESHOLD = 150 + + if CP.carFingerprint in CANFD_CAR: + self.STEER_MAX = 270 + self.STEER_DRIVER_ALLOWANCE = 250 + self.STEER_DRIVER_MULTIPLIER = 2 + self.STEER_THRESHOLD = 250 + self.STEER_DELTA_UP = 2 + self.STEER_DELTA_DOWN = 3 + + # To determine the limit for your car, find the maximum value that the stock LKAS will request. + # If the max stock LKAS request is <384, add your car to this list. + elif CP.carFingerprint in (CAR.GENESIS_G80, CAR.GENESIS_G90, CAR.ELANTRA, CAR.HYUNDAI_GENESIS, CAR.IONIQ, + CAR.IONIQ_EV_LTD, CAR.SANTA_FE_PHEV_2022, CAR.SONATA_LF, CAR.KIA_FORTE, CAR.KIA_NIRO_PHEV, + CAR.KIA_OPTIMA_H, CAR.KIA_SORENTO): + self.STEER_MAX = 255 + + # these cars have significantly more torque than most HKG; limit to 70% of max + elif CP.flags & HyundaiFlags.ALT_LIMITS: + self.STEER_MAX = 270 + self.STEER_DELTA_UP = 2 + self.STEER_DELTA_DOWN = 3 + + # Default for most HKG + else: + self.STEER_MAX = 384 + + +class HyundaiFlags(IntFlag): + CANFD_HDA2 = 1 + CANFD_ALT_BUTTONS = 2 + CANFD_ALT_GEARS = 4 + CANFD_CAMERA_SCC = 8 + + ALT_LIMITS = 16 + class CAR: # Hyundai ELANTRA = "HYUNDAI ELANTRA 2017" ELANTRA_2021 = "HYUNDAI ELANTRA 2021" ELANTRA_HEV_2021 = "HYUNDAI ELANTRA HYBRID 2021" - ELANTRA_GT_I30 = "HYUNDAI I30 N LINE 2019 & GT 2018 DCT" HYUNDAI_GENESIS = "HYUNDAI GENESIS 2015-2016" IONIQ = "HYUNDAI IONIQ HYBRID 2017-2019" IONIQ_HEV_2022 = "HYUNDAI IONIQ HYBRID 2020-2022" IONIQ_EV_LTD = "HYUNDAI IONIQ ELECTRIC LIMITED 2019" IONIQ_EV_2020 = "HYUNDAI IONIQ ELECTRIC 2020" + IONIQ_PHEV_2019 = "HYUNDAI IONIQ PLUG-IN HYBRID 2019" IONIQ_PHEV = "HYUNDAI IONIQ PHEV 2020" KONA = "HYUNDAI KONA 2020" KONA_EV = "HYUNDAI KONA ELECTRIC 2019" + KONA_EV_2022 = "HYUNDAI KONA ELECTRIC 2022" KONA_HEV = "HYUNDAI KONA HYBRID 2020" SANTA_FE = "HYUNDAI SANTA FE 2019" SANTA_FE_2022 = "HYUNDAI SANTA FE 2022" @@ -43,50 +81,159 @@ class CAR: SANTA_FE_PHEV_2022 = "HYUNDAI SANTA FE PlUG-IN HYBRID 2022" SONATA = "HYUNDAI SONATA 2020" SONATA_LF = "HYUNDAI SONATA 2019" + TUCSON = "HYUNDAI TUCSON 2019" PALISADE = "HYUNDAI PALISADE 2020" VELOSTER = "HYUNDAI VELOSTER 2019" SONATA_HYBRID = "HYUNDAI SONATA HYBRID 2021" + IONIQ_5 = "HYUNDAI IONIQ 5 2022" + TUCSON_4TH_GEN = "HYUNDAI TUCSON 4TH GEN" + TUCSON_HYBRID_4TH_GEN = "HYUNDAI TUCSON HYBRID 4TH GEN" + SANTA_CRUZ_1ST_GEN = "HYUNDAI SANTA CRUZ 1ST GEN" # Kia KIA_FORTE = "KIA FORTE E 2018 & GT 2021" KIA_K5_2021 = "KIA K5 2021" KIA_NIRO_EV = "KIA NIRO EV 2020" - KIA_NIRO_HEV = "KIA NIRO HYBRID 2019" + KIA_NIRO_PHEV = "KIA NIRO HYBRID 2019" KIA_NIRO_HEV_2021 = "KIA NIRO HYBRID 2021" - KIA_OPTIMA = "KIA OPTIMA SX 2019 & 2016" + KIA_OPTIMA_G4 = "KIA OPTIMA 4TH GEN" + KIA_OPTIMA_G4_FL = "KIA OPTIMA 4TH GEN FACELIFT" KIA_OPTIMA_H = "KIA OPTIMA HYBRID 2017 & SPORTS 2019" KIA_SELTOS = "KIA SELTOS 2021" + KIA_SPORTAGE_5TH_GEN = "KIA SPORTAGE 5TH GEN" KIA_SORENTO = "KIA SORENTO GT LINE 2018" + KIA_SORENTO_PHEV_4TH_GEN = "KIA SORENTO PLUG-IN HYBRID 4TH GEN" + KIA_SPORTAGE_HYBRID_5TH_GEN = "KIA SPORTAGE HYBRID 5TH GEN" KIA_STINGER = "KIA STINGER GT2 2018" + KIA_STINGER_2022 = "KIA STINGER 2022" KIA_CEED = "KIA CEED INTRO ED 2019" + KIA_EV6 = "KIA EV6 2022" # Genesis GENESIS_G70 = "GENESIS G70 2018" GENESIS_G70_2020 = "GENESIS G70 2020" + GENESIS_GV70_1ST_GEN = "GENESIS GV70 1ST GEN" GENESIS_G80 = "GENESIS G80 2017" GENESIS_G90 = "GENESIS G90 2017" +class Footnote(Enum): + CANFD = CarFootnote( + "Requires a red panda, additional harness box, " + + "additional OBD-C cable, USB-A to USB-A cable, and a USB-A to USB-C OTG dongle.", + Column.MODEL, shop_footnote=True) + + +@dataclass +class HyundaiCarInfo(CarInfo): + package: str = "Smart Cruise Control (SCC)" + + def init_make(self, CP: car.CarParams): + if CP.carFingerprint in CANFD_CAR: + self.footnotes.insert(0, Footnote.CANFD) + + +CAR_INFO: Dict[str, Optional[Union[HyundaiCarInfo, List[HyundaiCarInfo]]]] = { + CAR.ELANTRA: [ + HyundaiCarInfo("Hyundai Elantra 2017-19", min_enable_speed=19 * CV.MPH_TO_MS, harness=Harness.hyundai_b), + HyundaiCarInfo("Hyundai Elantra GT 2017-19", harness=Harness.hyundai_e), + HyundaiCarInfo("Hyundai i30 2019", harness=Harness.hyundai_e), + ], + CAR.ELANTRA_2021: HyundaiCarInfo("Hyundai Elantra 2021-22", video_link="https://youtu.be/_EdYQtV52-c", harness=Harness.hyundai_k), + CAR.ELANTRA_HEV_2021: HyundaiCarInfo("Hyundai Elantra Hybrid 2021-23", video_link="https://youtu.be/_EdYQtV52-c", harness=Harness.hyundai_k), + CAR.HYUNDAI_GENESIS: HyundaiCarInfo("Hyundai Genesis 2015-16", min_enable_speed=19 * CV.MPH_TO_MS, harness=Harness.hyundai_j), # TODO: check 2015 packages + CAR.IONIQ: HyundaiCarInfo("Hyundai Ioniq Hybrid 2017-19", harness=Harness.hyundai_c), + CAR.IONIQ_HEV_2022: HyundaiCarInfo("Hyundai Ioniq Hybrid 2020-22", harness=Harness.hyundai_h), # TODO: confirm 2020-21 harness + CAR.IONIQ_EV_LTD: HyundaiCarInfo("Hyundai Ioniq Electric 2019", harness=Harness.hyundai_c), + CAR.IONIQ_EV_2020: HyundaiCarInfo("Hyundai Ioniq Electric 2020", "All", harness=Harness.hyundai_h), + CAR.IONIQ_PHEV_2019: HyundaiCarInfo("Hyundai Ioniq Plug-in Hybrid 2019", harness=Harness.hyundai_c), + CAR.IONIQ_PHEV: HyundaiCarInfo("Hyundai Ioniq Plug-in Hybrid 2020-21", "All", harness=Harness.hyundai_h), + CAR.KONA: HyundaiCarInfo("Hyundai Kona 2020", harness=Harness.hyundai_b), + CAR.KONA_EV: HyundaiCarInfo("Hyundai Kona Electric 2018-21", harness=Harness.hyundai_g), + CAR.KONA_EV_2022: HyundaiCarInfo("Hyundai Kona Electric 2022", harness=Harness.hyundai_o), + CAR.KONA_HEV: HyundaiCarInfo("Hyundai Kona Hybrid 2020", video_link="https://youtu.be/0dwpAHiZgFo", harness=Harness.hyundai_i), # TODO: check packages + CAR.SANTA_FE: HyundaiCarInfo("Hyundai Santa Fe 2019-20", "All", harness=Harness.hyundai_d), + CAR.SANTA_FE_2022: HyundaiCarInfo("Hyundai Santa Fe 2021-22", "All", "https://youtu.be/VnHzSTygTS4", harness=Harness.hyundai_l), + CAR.SANTA_FE_HEV_2022: HyundaiCarInfo("Hyundai Santa Fe Hybrid 2022", "All", harness=Harness.hyundai_l), + CAR.SANTA_FE_PHEV_2022: HyundaiCarInfo("Hyundai Santa Fe Plug-in Hybrid 2022", "All", harness=Harness.hyundai_l), + CAR.SONATA: HyundaiCarInfo("Hyundai Sonata 2020-22", "All", "https://www.youtube.com/watch?v=ix63r9kE3Fw", harness=Harness.hyundai_a), + CAR.SONATA_LF: HyundaiCarInfo("Hyundai Sonata 2018-19", harness=Harness.hyundai_e), + CAR.TUCSON: [ + HyundaiCarInfo("Hyundai Tucson 2021", min_enable_speed=19 * CV.MPH_TO_MS, harness=Harness.hyundai_l), + HyundaiCarInfo("Hyundai Tucson Diesel 2019", harness=Harness.hyundai_l), + ], + CAR.PALISADE: [ + HyundaiCarInfo("Hyundai Palisade 2020-22", "All", "https://youtu.be/TAnDqjF4fDY?t=456", harness=Harness.hyundai_h), + HyundaiCarInfo("Kia Telluride 2020-22", "All", harness=Harness.hyundai_h), + ], + CAR.VELOSTER: HyundaiCarInfo("Hyundai Veloster 2019-20", min_enable_speed=5. * CV.MPH_TO_MS, harness=Harness.hyundai_e), + CAR.SONATA_HYBRID: HyundaiCarInfo("Hyundai Sonata Hybrid 2020-22", "All", harness=Harness.hyundai_a), + CAR.IONIQ_5: [ + HyundaiCarInfo("Hyundai Ioniq 5 (without HDA II) 2022-23", "Highway Driving Assist", harness=Harness.hyundai_k), + HyundaiCarInfo("Hyundai Ioniq 5 (with HDA II) 2022-23", "Highway Driving Assist II", harness=Harness.hyundai_q), + ], + CAR.TUCSON_4TH_GEN: [ + HyundaiCarInfo("Hyundai Tucson 2022", harness=Harness.hyundai_n), + HyundaiCarInfo("Hyundai Tucson 2023", "All", harness=Harness.hyundai_n), + ], + CAR.TUCSON_HYBRID_4TH_GEN: HyundaiCarInfo("Hyundai Tucson Hybrid 2022", "All", harness=Harness.hyundai_n), + CAR.SANTA_CRUZ_1ST_GEN: HyundaiCarInfo("Hyundai Santa Cruz 2021-22", harness=Harness.hyundai_n), + + # Kia + CAR.KIA_FORTE: HyundaiCarInfo("Kia Forte 2019-21", harness=Harness.hyundai_g), + CAR.KIA_K5_2021: HyundaiCarInfo("Kia K5 2021-22", harness=Harness.hyundai_a), + CAR.KIA_NIRO_EV: [ + HyundaiCarInfo("Kia Niro EV 2019", "All", "https://www.youtube.com/watch?v=lT7zcG6ZpGo", harness=Harness.hyundai_h), + HyundaiCarInfo("Kia Niro EV 2020", "All", "https://www.youtube.com/watch?v=lT7zcG6ZpGo", harness=Harness.hyundai_f), + HyundaiCarInfo("Kia Niro EV 2021", "All", "https://www.youtube.com/watch?v=lT7zcG6ZpGo", harness=Harness.hyundai_c), + HyundaiCarInfo("Kia Niro EV 2022", "All", "https://www.youtube.com/watch?v=lT7zcG6ZpGo", harness=Harness.hyundai_h), + ], + CAR.KIA_NIRO_PHEV: HyundaiCarInfo("Kia Niro Plug-in Hybrid 2018-19", "All", min_enable_speed=10. * CV.MPH_TO_MS, harness=Harness.hyundai_c), + CAR.KIA_NIRO_HEV_2021: [ + HyundaiCarInfo("Kia Niro Hybrid 2021", harness=Harness.hyundai_f), # TODO: could be hyundai_d, verify + HyundaiCarInfo("Kia Niro Hybrid 2022", harness=Harness.hyundai_h), + ], + CAR.KIA_OPTIMA_G4: HyundaiCarInfo("Kia Optima 2017", "Advanced Smart Cruise Control", harness=Harness.hyundai_b), # TODO: may support 2016, 2018 + CAR.KIA_OPTIMA_G4_FL: HyundaiCarInfo("Kia Optima 2019-20", harness=Harness.hyundai_g), + CAR.KIA_OPTIMA_H: [ + HyundaiCarInfo("Kia Optima Hybrid 2017", "Advanced Smart Cruise Control"), # TODO: may support adjacent years + HyundaiCarInfo("Kia Optima Hybrid 2019"), + ], + CAR.KIA_SELTOS: HyundaiCarInfo("Kia Seltos 2021", harness=Harness.hyundai_a), + CAR.KIA_SPORTAGE_5TH_GEN: HyundaiCarInfo("Kia Sportage 2023", harness=Harness.hyundai_n), + CAR.KIA_SORENTO: [ + HyundaiCarInfo("Kia Sorento 2018", "Advanced Smart Cruise Control", "https://www.youtube.com/watch?v=Fkh3s6WHJz8", harness=Harness.hyundai_c), + HyundaiCarInfo("Kia Sorento 2019", video_link="https://www.youtube.com/watch?v=Fkh3s6WHJz8", harness=Harness.hyundai_e), + ], + CAR.KIA_SORENTO_PHEV_4TH_GEN: HyundaiCarInfo("Kia Sorento Plug-in Hybrid 2022-23", "Smart Cruise Control (SCC)", harness=Harness.hyundai_a), + CAR.KIA_SPORTAGE_HYBRID_5TH_GEN: HyundaiCarInfo("Kia Sportage Hybrid 2023", harness=Harness.hyundai_n), + CAR.KIA_STINGER: HyundaiCarInfo("Kia Stinger 2018-20", video_link="https://www.youtube.com/watch?v=MJ94qoofYw0", harness=Harness.hyundai_c), + CAR.KIA_STINGER_2022: HyundaiCarInfo("Kia Stinger 2022", "All", harness=Harness.hyundai_k), + CAR.KIA_CEED: HyundaiCarInfo("Kia Ceed 2019", harness=Harness.hyundai_e), + CAR.KIA_EV6: [ + HyundaiCarInfo("Kia EV6 (without HDA II) 2022", "Highway Driving Assist", harness=Harness.hyundai_l), + HyundaiCarInfo("Kia EV6 (with HDA II) 2022", "Highway Driving Assist II", harness=Harness.hyundai_p) + ], + + # Genesis + CAR.GENESIS_G70: HyundaiCarInfo("Genesis G70 2018-19", "All", harness=Harness.hyundai_f), + CAR.GENESIS_G70_2020: HyundaiCarInfo("Genesis G70 2020", "All", harness=Harness.hyundai_f), + CAR.GENESIS_GV70_1ST_GEN: HyundaiCarInfo("Genesis GV70 2022-23", "All", harness=Harness.hyundai_l), + CAR.GENESIS_G80: HyundaiCarInfo("Genesis G80 2017-19", "All", harness=Harness.hyundai_h), + CAR.GENESIS_G90: HyundaiCarInfo("Genesis G90 2017-18", "All", harness=Harness.hyundai_c), +} + class Buttons: NONE = 0 RES_ACCEL = 1 SET_DECEL = 2 GAP_DIST = 3 - CANCEL = 4 + CANCEL = 4 # on newer models, this is a pause/resume button FINGERPRINTS = { CAR.ELANTRA: [{ 66: 8, 67: 8, 68: 8, 127: 8, 273: 8, 274: 8, 275: 8, 339: 8, 356: 4, 399: 8, 512: 6, 544: 8, 593: 8, 608: 8, 688: 5, 790: 8, 809: 8, 897: 8, 832: 8, 899: 8, 902: 8, 903: 8, 905: 8, 909: 8, 916: 8, 1040: 8, 1056: 8, 1057: 8, 1078: 4, 1170: 8, 1265: 4, 1280: 1, 1282: 4, 1287: 4, 1290: 8, 1292: 8, 1294: 8, 1312: 8, 1314: 8, 1322: 8, 1345: 8, 1349: 8, 1351: 8, 1353: 8, 1363: 8, 1366: 8, 1367: 8, 1369: 8, 1407: 8, 1415: 8, 1419: 8, 1425: 2, 1427: 6, 1440: 8, 1456: 4, 1472: 8, 1486: 8, 1487: 8, 1491: 8, 1530: 8, 1532: 5, 2001: 8, 2003: 8, 2004: 8, 2009: 8, 2012: 8, 2016: 8, 2017: 8, 2024: 8, 2025: 8 }], - CAR.ELANTRA_GT_I30: [{ - 66: 8, 67: 8, 68: 8, 127: 8, 128: 8, 129: 8, 273: 8, 274: 8, 275: 8, 339: 8, 354: 3, 356: 4, 399: 8, 512: 6, 544: 8, 593: 8, 608: 8, 688: 5, 790: 8, 809: 8, 884: 8, 897: 8, 899: 8, 902: 8, 903: 8, 905: 8, 909: 8, 916: 8, 1040: 8, 1056: 8, 1057: 8, 1078: 4, 1151: 6, 1168: 7, 1170: 8, 1193: 8, 1265: 4, 1280: 1, 1282: 4, 1287: 4, 1290: 8, 1292: 8, 1294: 8, 1312: 8, 1322: 8, 1345: 8, 1348: 8, 1349: 8, 1351: 8, 1353: 8, 1356: 8, 1363: 8, 1365: 8, 1366: 8, 1367: 8, 1369: 8, 1407: 8, 1414: 3, 1415: 8, 1427: 6, 1440: 8, 1456: 4, 1470: 8, 1486: 8, 1487: 8, 1491: 8, 1530: 8, 1952: 8, 1960: 8, 1988: 8, 2000: 8, 2001: 8, 2005: 8, 2008: 8, 2009: 8, 2013: 8, 2017: 8, 2025: 8 - }, - { - 66: 8, 67: 8, 68: 8, 127: 8, 128: 8, 129: 8, 273: 8, 274: 8, 275: 8, 339: 8, 354: 3, 356: 4, 399: 8, 512: 6, 544: 8, 593: 8, 608: 8, 688: 5, 790: 8, 809: 8, 832: 8, 897: 8, 899: 8, 902: 8, 903: 8, 905: 8, 909: 8, 916: 8, 1040: 8, 1056: 8, 1057: 8, 1078: 4, 1151: 6, 1168: 7, 1170: 8, 1265: 4, 1280: 1, 1282: 4, 1287: 4, 1290: 8, 1292: 8, 1294: 8, 1312: 8, 1322: 8, 1342: 6, 1345: 8, 1348: 8, 1349: 8, 1351: 8, 1353: 8, 1356: 8, 1363: 8, 1366: 8, 1367: 8, 1369: 8, 1407: 8, 1414: 3, 1415: 8, 1419: 8, 1440: 8, 1456: 4, 1470: 8, 1486: 8, 1487: 8, 1491: 8, 1530: 8 - }, - { - 66: 8, 67: 8, 68: 8, 127: 8, 128: 8, 129: 8, 273: 8, 274: 8, 275: 8, 339: 8, 354: 3, 356: 4, 399: 8, 512: 6, 544: 8, 593: 8, 608: 8, 688: 5, 790: 8, 809: 8, 832: 8, 897: 8, 899: 8, 902: 8, 903: 8, 905: 8, 909: 8, 916: 8, 1040: 8, 1056: 8, 1057: 8, 1078: 4, 1151: 6, 1168: 7, 1170: 8, 1265: 4, 1280: 1, 1282: 4, 1287: 4, 1290: 8, 1292: 8, 1294: 8, 1312: 8, 1322: 8, 1342: 6, 1345: 8, 1348: 8, 1349: 8, 1351: 8, 1353: 8, 1356: 8, 1363: 8, 1366: 8, 1367: 8, 1369: 8, 1407: 8, 1414: 3, 1419: 8, 1427: 6, 1440: 8, 1456: 4, 1470: 8, 1486: 8, 1487: 8, 1491: 8, 1960: 8, 1990: 8, 1998: 8, 2000: 8, 2001: 8, 2004: 8, 2005: 8, 2008: 8, 2009: 8, 2012: 8, 2013: 8, 2015: 8, 2016: 8, 2017: 8, 2024: 8, 2025: 8 - }], CAR.HYUNDAI_GENESIS: [{ 67: 8, 68: 8, 304: 8, 320: 8, 339: 8, 356: 4, 544: 7, 593: 8, 608: 8, 688: 5, 809: 8, 832: 8, 854: 7, 870: 7, 871: 8, 872: 5, 897: 8, 902: 8, 903: 6, 916: 8, 1024: 2, 1040: 8, 1056: 8, 1057: 8, 1078: 4, 1107: 5, 1136: 8, 1151: 6, 1168: 7, 1170: 8, 1173: 8, 1184: 8, 1265: 4, 1280: 1, 1287: 4, 1292: 8, 1312: 8, 1322: 8, 1331: 8, 1332: 8, 1333: 8, 1334: 8, 1335: 8, 1342: 6, 1345: 8, 1363: 8, 1369: 8, 1370: 8, 1371: 8, 1378: 4, 1384: 5, 1407: 8, 1419: 8, 1427: 6, 1434: 2, 1456: 4 }, @@ -117,9 +264,6 @@ FINGERPRINTS = { CAR.SONATA_LF: [ {66: 8, 67: 8, 68: 8, 127: 8, 273: 8, 274: 8, 275: 8, 339: 8, 356: 4, 399: 8, 447: 8, 512: 6, 544: 8, 593: 8, 608: 8, 688: 5, 790: 8, 809: 8, 832: 8, 884: 8, 897: 8, 899: 8, 902: 8, 903: 6, 916: 8, 1040: 8, 1056: 8, 1057: 8, 1078: 4, 1151: 6, 1168: 7, 1170: 8, 1253: 8, 1254: 8, 1255: 8, 1265: 4, 1280: 1, 1287: 4, 1290: 8, 1292: 8, 1294: 8, 1312: 8, 1314: 8, 1322: 8, 1331: 8, 1332: 8, 1333: 8, 1342: 6, 1345: 8, 1348: 8, 1349: 8, 1351: 8, 1353: 8, 1363: 8, 1365: 8, 1366: 8, 1367: 8, 1369: 8, 1397: 8, 1407: 8, 1415: 8, 1419: 8, 1425: 2, 1427: 6, 1440: 8, 1456: 4, 1470: 8, 1472: 8, 1486: 8, 1487: 8, 1491: 8, 1530: 8, 1532: 5, 2000: 8, 2001: 8, 2004: 8, 2005: 8, 2008: 8, 2009: 8, 2012: 8, 2013: 8, 2014: 8, 2016: 8, 2017: 8, 2024: 8, 2025: 8}, ], - CAR.KIA_OPTIMA: [{ - 64: 8, 66: 8, 67: 8, 68: 8, 127: 8, 128: 8, 129: 8, 273: 8, 274: 8, 275: 8, 339: 8, 354: 3, 356: 4, 399: 8, 447: 8, 512: 6, 544: 8, 558: 8, 593: 8, 608: 8, 640: 8, 688: 5, 790: 8, 809: 8, 832: 8, 884: 8, 897: 8, 899: 8, 902: 8, 903: 6, 909: 8, 912: 7, 916: 8, 1040: 8, 1056: 8, 1057: 8, 1078: 4, 1151: 6, 1168: 7, 1170: 8, 1186: 2, 1191: 2, 1253: 8, 1254: 8, 1255: 8, 1265: 4, 1268: 8, 1280: 1, 1282: 4, 1287: 4, 1290: 8, 1292: 8, 1294: 8, 1312: 8, 1322: 8, 1331: 8, 1332: 8, 1333: 8, 1342: 6, 1345: 8, 1348: 8, 1349: 8, 1351: 8, 1353: 8, 1356: 8, 1363: 8, 1365: 8, 1366: 8, 1367: 8, 1369: 8, 1407: 8, 1414: 3, 1415: 8, 1419: 8, 1425: 2, 1427: 6, 1440: 8, 1456: 4, 1470: 8, 1472: 8, 1486: 8, 1487: 8, 1491: 8, 1492: 8, 1530: 8, 1532: 5, 1792: 8, 1872: 8, 1937: 8, 1953: 8, 1968: 8, 1988: 8, 1996: 8, 2000: 8, 2001: 8, 2004: 8, 2008: 8, 2009: 8, 2012: 8, 2015: 8, 2016: 8, 2017: 8, 2024: 8, 2025: 8, 1371: 8, 1397: 8, 1961: 8 - }], CAR.KIA_SORENTO: [{ 67: 8, 68: 8, 127: 8, 304: 8, 320: 8, 339: 8, 356: 4, 544: 8, 593: 8, 608: 8, 688: 5, 809: 8, 832: 8, 854: 7, 870: 7, 871: 8, 872: 8, 897: 8, 902: 8, 903: 8, 916: 8, 1040: 8, 1042: 8, 1056: 8, 1057: 8, 1064: 8, 1078: 4, 1107: 5, 1136: 8, 1151: 6, 1168: 7, 1170: 8, 1173: 8, 1265: 4, 1280: 1, 1287: 4, 1290: 8, 1292: 8, 1294: 8, 1312: 8, 1322: 8, 1331: 8, 1332: 8, 1333: 8, 1342: 6, 1345: 8, 1348: 8, 1363: 8, 1369: 8, 1370: 8, 1371: 8, 1384: 8, 1407: 8, 1411: 8, 1419: 8, 1425: 2, 1427: 6, 1444: 8, 1456: 4, 1470: 8, 1489: 1 }], @@ -147,6 +291,9 @@ FINGERPRINTS = { CAR.KONA_EV: [{ 127: 8, 304: 8, 320: 8, 339: 8, 352: 8, 356: 4, 544: 8, 549: 8, 593: 8, 688: 5, 832: 8, 881: 8, 882: 8, 897: 8, 902: 8, 903: 8, 905: 8, 909: 8, 916: 8, 1040: 8, 1042: 8, 1056: 8, 1057: 8, 1078: 4, 1136: 8, 1151: 6, 1168: 7, 1173: 8, 1183: 8, 1186: 2, 1191: 2, 1225: 8, 1265: 4, 1280: 1, 1287: 4, 1290: 8, 1291: 8, 1292: 8, 1294: 8, 1307: 8, 1312: 8, 1322: 8, 1342: 6, 1345: 8, 1348: 8, 1355: 8, 1363: 8, 1369: 8, 1378: 4, 1407: 8, 1419: 8, 1426: 8, 1427: 6, 1429: 8, 1430: 8, 1456: 4, 1470: 8, 1473: 8, 1507: 8, 1535: 8, 2000: 8, 2004: 8, 2008: 8, 2012: 8, 1157: 4, 1193: 8, 1379: 8, 1988: 8, 1996: 8 }], + CAR.KONA_EV_2022: [{ + 127: 8, 304: 8, 320: 8, 339: 8, 352: 8, 356: 4, 544: 8, 593: 8, 688: 5, 832: 8, 881: 8, 882: 8, 897: 8, 902: 8, 903: 8, 905: 8, 909: 8, 913: 8, 916: 8, 1040: 8, 1042: 8, 1056: 8, 1057: 8, 1069: 8, 1078: 4, 1136: 8, 1145: 8, 1151: 8, 1155: 8, 1156: 8, 1157: 4, 1162: 8, 1164: 8, 1168: 8, 1173: 8, 1183: 8, 1188: 8, 1191: 2, 1193: 8, 1225: 8, 1227: 8, 1265: 4, 1280: 1, 1287: 4, 1290: 8, 1291: 8, 1292: 8, 1294: 8, 1312: 8, 1322: 8, 1339: 8, 1342: 8, 1343: 8, 1345: 8, 1348: 8, 1355: 8, 1363: 8, 1369: 8, 1379: 8, 1407: 8, 1419: 8, 1426: 8, 1427: 6, 1429: 8, 1430: 8, 1446: 8, 1456: 4, 1470: 8, 1473: 8, 1485: 8, 1507: 8, 1535: 8, 1990: 8, 1998: 8 + }], CAR.KIA_NIRO_EV: [{ 127: 8, 304: 8, 320: 8, 339: 8, 352: 8, 356: 4, 516: 8, 544: 8, 593: 8, 688: 5, 832: 8, 881: 8, 882: 8, 897: 8, 902: 8, 903: 8, 905: 8, 909: 8, 916: 8, 1040: 8, 1042: 8, 1056: 8, 1057: 8, 1078: 4, 1136: 8, 1151: 6, 1156: 8, 1157: 4, 1168: 7, 1173: 8, 1183: 8, 1186: 2, 1191: 2, 1193: 8, 1225: 8, 1260: 8, 1265: 4, 1280: 1, 1287: 4, 1290: 8, 1291: 8, 1292: 8, 1294: 8, 1312: 8, 1322: 8, 1342: 6, 1345: 8, 1348: 8, 1355: 8, 1363: 8, 1369: 8, 1407: 8, 1419: 8, 1426: 8, 1427: 6, 1429: 8, 1430: 8, 1456: 4, 1470: 8, 1473: 8, 1507: 8, 1535: 8, 1990: 8, 1998: 8, 1996: 8, 2000: 8, 2004: 8, 2008: 8, 2012: 8, 2015: 8 }], @@ -161,6 +308,47 @@ FINGERPRINTS = { }], } +HYUNDAI_VERSION_REQUEST_LONG = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER]) + \ + p16(0xf100) # Long description +HYUNDAI_VERSION_REQUEST_MULTI = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER]) + \ + p16(uds.DATA_IDENTIFIER_TYPE.VEHICLE_MANUFACTURER_SPARE_PART_NUMBER) + \ + p16(uds.DATA_IDENTIFIER_TYPE.APPLICATION_SOFTWARE_IDENTIFICATION) + \ + p16(0xf100) +HYUNDAI_VERSION_RESPONSE = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER + 0x40]) + +FW_QUERY_CONFIG = FwQueryConfig( + requests=[ + # TODO: minimize shared whitelists for CAN and cornerRadar for CAN-FD + # CAN queries (OBD-II port) + Request( + [HYUNDAI_VERSION_REQUEST_LONG], + [HYUNDAI_VERSION_RESPONSE], + whitelist_ecus=[Ecu.transmission, Ecu.eps, Ecu.abs, Ecu.fwdRadar, Ecu.fwdCamera], + ), + Request( + [HYUNDAI_VERSION_REQUEST_MULTI], + [HYUNDAI_VERSION_RESPONSE], + whitelist_ecus=[Ecu.engine, Ecu.transmission, Ecu.eps, Ecu.abs, Ecu.fwdRadar], + ), + # CAN-FD queries (camera) + Request( + [HYUNDAI_VERSION_REQUEST_LONG], + [HYUNDAI_VERSION_RESPONSE], + whitelist_ecus=[Ecu.fwdCamera, Ecu.fwdRadar, Ecu.cornerRadar], + bus=4, + ), + Request( + [HYUNDAI_VERSION_REQUEST_LONG], + [HYUNDAI_VERSION_RESPONSE], + whitelist_ecus=[Ecu.fwdCamera, Ecu.adas, Ecu.cornerRadar], + bus=5, + ), + ], + extra_ecus=[ + (Ecu.adas, 0x730, None), # ADAS Driving ECU on HDA2 platforms + (Ecu.cornerRadar, 0x7b7, None), + ], +) FW_VERSIONS = { CAR.IONIQ: { @@ -180,25 +368,49 @@ FW_VERSIONS = { b'\xf1\x816U3H1051\x00\x00\xf1\x006U3H0_C2\x00\x006U3H1051\x00\x00HAE0G16US2\x00\x00\x00\x00', ], }, + CAR.IONIQ_PHEV_2019: { + (Ecu.fwdRadar, 0x7d0, None): [ + b'\xf1\x00AEhe SCC H-CUP 1.01 1.01 96400-G2100 ', + ], + (Ecu.eps, 0x7d4, None): [ + b'\xf1\x00AE MDPS C 1.00 1.07 56310/G2501 4AEHC107', + ], + (Ecu.fwdCamera, 0x7c4, None): [ + b'\xf1\x00AEP MFC AT USA LHD 1.00 1.00 95740-G2400 180222', + ], + (Ecu.engine, 0x7e0, None): [ + b'\xf1\x816H6F6051\x00\x00\x00\x00\x00\x00\x00\x00', + ], + (Ecu.transmission, 0x7e1, None): [ + b'\xf1\x816U3J2051\x00\x00\xf1\x006U3H0_C2\x00\x006U3J2051\x00\x00PAE0G16NS1\xdbD\r\x81', + b'\xf1\x816U3J2051\x00\x00\xf1\x006U3H0_C2\x00\x006U3J2051\x00\x00PAE0G16NS1\x00\x00\x00\x00', + ], + }, CAR.IONIQ_PHEV: { (Ecu.fwdRadar, 0x7d0, None): [ b'\xf1\000AEhe SCC FHCUP 1.00 1.02 99110-G2100 ', b'\xf1\x00AEhe SCC F-CUP 1.00 1.00 99110-G2200 ', + b'\xf1\x00AEhe SCC F-CUP 1.00 1.00 99110-G2600 ', ], (Ecu.eps, 0x7d4, None): [ b'\xf1\000AE MDPS C 1.00 1.01 56310/G2510 4APHC101', b'\xf1\x00AE MDPS C 1.00 1.01 56310/G2560 4APHC101', + b'\xf1\x00AE MDPS C 1.00 1.01 56310G2510\x00 4APHC101', ], (Ecu.fwdCamera, 0x7c4, None): [ b'\xf1\000AEP MFC AT USA LHD 1.00 1.01 95740-G2600 190819', b'\xf1\x00AEP MFC AT EUR RHD 1.00 1.01 95740-G2600 190819', + b'\xf1\x00AEP MFC AT USA LHD 1.00 1.00 95740-G2700 201027', ], (Ecu.engine, 0x7e0, None): [ b'\xf1\x816H6F6051\x00\x00\x00\x00\x00\x00\x00\x00', + b'\xf1\x816H6G6051\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.transmission, 0x7e1, None): [ b'\xf1\x816U3J9051\000\000\xf1\0006U3H1_C2\000\0006U3J9051\000\000PAE0G16NL0\x82zT\xd2', b'\xf1\x816U3J8051\x00\x00\xf1\x006U3H1_C2\x00\x006U3J8051\x00\x00PAETG16UL0\x00\x00\x00\x00', + b'\xf1\x816U3J9051\x00\x00\xf1\x006U3H1_C2\x00\x006U3J9051\x00\x00PAE0G16NL2\xad\xeb\xabt', + b'\xf1\x816U3J9051\x00\x00\xf1\x006U3H1_C2\x00\x006U3J9051\x00\x00PAE0G16NL2\x00\x00\x00\x00', ], }, CAR.IONIQ_EV_2020: { @@ -225,6 +437,7 @@ FW_VERSIONS = { b'\xf1\x00AE MDPS C 1.00 1.02 56310G7300\x00 4AEEC102', b'\xf1\x00AE MDPS C 1.00 1.04 56310/G7501 4AEEC104', b'\xf1\x00AE MDPS C 1.00 1.03 56310/G7300 4AEEC103', + b'\xf1\x00AE MDPS C 1.00 1.03 56310G7300\x00 4AEEC103', ], (Ecu.fwdCamera, 0x7c4, None): [ b'\xf1\x00AEE MFC AT EUR LHD 1.00 1.00 95740-G7200 160418', @@ -262,14 +475,14 @@ FW_VERSIONS = { b'\xf1\x8799110L0000\xf1\x00DN8_ SCC F-CUP 1.00 1.00 99110-L0000 ', b'\xf1\x8799110L0000\xf1\x00DN8_ SCC FHCUP 1.00 1.00 99110-L0000 ', ], - (Ecu.esp, 0x7d1, None): [ - b'\xf1\x00DN ESC \a 106 \a\x01 58910-L0100', + (Ecu.abs, 0x7d1, None): [ + b'\xf1\x00DN ESC \x07 106 \x07\x01 58910-L0100', b'\xf1\x00DN ESC \x01 102\x19\x04\x13 58910-L1300', b'\xf1\x00DN ESC \x03 100 \x08\x01 58910-L0300', b'\xf1\x00DN ESC \x06 104\x19\x08\x01 58910-L0100', b'\xf1\x00DN ESC \x07 104\x19\x08\x01 58910-L0100', b'\xf1\x00DN ESC \x08 103\x19\x06\x01 58910-L1300', - b'\xf1\x8758910-L0100\xf1\x00DN ESC \a 106 \a\x01 58910-L0100', + b'\xf1\x8758910-L0100\xf1\x00DN ESC \x07 106 \x07\x01 58910-L0100', b'\xf1\x8758910-L0100\xf1\x00DN ESC \x06 104\x19\x08\x01 58910-L0100', b'\xf1\x8758910-L0100\xf1\x00DN ESC \x06 106 \x07\x01 58910-L0100', b'\xf1\x8758910-L0100\xf1\x00DN ESC \x07 104\x19\x08\x01 58910-L0100', @@ -283,6 +496,7 @@ FW_VERSIONS = { b'\xf1\x82DNBWN5TMDCXXXG2E', b'\xf1\x82DNCVN5GMCCXXXF0A', b'\xf1\x82DNCVN5GMCCXXXG2B', + b'\xf1\x870\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf1\x81HM6M1_0a0_J10', b'\xf1\x870\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf1\x82DNDWN5TMDCXXXJ1A', b'\xf1\x87391162M003', b'\xf1\x87391162M013', @@ -290,10 +504,11 @@ FW_VERSIONS = { b'HM6M1_0a0_F00', b'HM6M1_0a0_G20', b'HM6M2_0a0_BD0', + b'\xf1\x8739110-2S278\xf1\x82DNDVD5GMCCXXXL5B', ], (Ecu.eps, 0x7d4, None): [ - b'\xf1\x00DN8 MDPS C 1,00 1,01 56310L0010\x00 4DNAC101', # modified firmware - b'\xf1\x8756310L0010\x00\xf1\x00DN8 MDPS C 1,00 1,01 56310L0010\x00 4DNAC101', # modified firmware + b'\xf1\x00DN8 MDPS C 1,00 1,01 56310L0010\x00 4DNAC101', # modified firmware + b'\xf1\x8756310L0010\x00\xf1\x00DN8 MDPS C 1,00 1,01 56310L0010\x00 4DNAC101', # modified firmware b'\xf1\x00DN8 MDPS C 1.00 1.01 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 4DNAC101', b'\xf1\x00DN8 MDPS C 1.00 1.01 56310-L0010 4DNAC101', b'\xf1\x00DN8 MDPS C 1.00 1.01 56310L0010\x00 4DNAC101', @@ -306,6 +521,7 @@ FW_VERSIONS = { b'\xf1\x8756310L0010\x00\xf1\x00DN8 MDPS C 1.00 1.01 56310L0010\x00 4DNAC101', b'\xf1\x8756310L0210\x00\xf1\x00DN8 MDPS C 1.00 1.01 56310L0210\x00 4DNAC101', b'\xf1\x8757700-L0000\xf1\x00DN8 MDPS R 1.00 1.00 57700-L0000 4DNAP100', + b'\xf1\x00DN8 MDPS R 1.00 1.00 57700-L0000 4DNAP101', ], (Ecu.fwdCamera, 0x7c4, None): [ b'\xf1\x00DN8 MFC AT KOR LHD 1.00 1.02 99211-L1000 190422', @@ -326,6 +542,7 @@ FW_VERSIONS = { b'\xf1\x00HT6WA250BLHT6WA910A1SDN8G25NB1\x00\x00\x00\x00\x00\x00\x96\xa1\xf1\x92', b'\xf1\x00HT6WA280BLHT6WAD10A1SDN8G25NB2\x00\x00\x00\x00\x00\x00\x08\xc9O:', b'\xf1\x00T02601BL T02730A1 VDN8T25XXX730NS5\xf7_\x92\xf5', + b'\xf1\x00T02601BL T02832A1 VDN8T25XXX832NS8G\x0e\xfeE', b'\xf1\x87954A02N060\x00\x00\x00\x00\x00\xf1\x81T02730A1 \xf1\x00T02601BL T02730A1 VDN8T25XXX730NS5\xf7_\x92\xf5', b'\xf1\x87SAKFBA2926554GJ2VefVww\x87xwwwww\x88\x87xww\x87wTo\xfb\xffvUo\xff\x8d\x16\xf1\x81U903\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 U903\x00\x00\x00\x00\x00\x00SDN8T16NB0z{\xd4v', b'\xf1\x87SAKFBA3030524GJ2UVugww\x97yx\x88\x87\x88vw\x87gww\x87wto\xf9\xfffUo\xff\xa2\x0c\xf1\x81U903\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 U903\x00\x00\x00\x00\x00\x00SDN8T16NB0z{\xd4v', @@ -371,13 +588,17 @@ FW_VERSIONS = { b'\xf1\x87SAMFBA7978674GJ2gw\x87xgw\x97ywwwwvUGeUUeU\x87O\xfb\xff\x98w\x8f\xfffF\xf1\x81U913\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 U913\x00\x00\x00\x00\x00\x00SDN8T16NB2\n\xdd^\xbc', b'\xf1\x87SAMFBA9283024GJ2wwwwEUuWwwgwwwwwwwww\x87/\xfb\xff\x98w\x8f\xff<\xd3\xf1\x81U913\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 U913\x00\x00\x00\x00\x00\x00SDN8T16NB2\n\xdd^\xbc', b'\xf1\x87SAMFBA9708354GJ2wwwwVf\x86h\x88wx\x87xww\x87\x88\x88\x88\x88w/\xfa\xff\x97w\x8f\xff\x86\xa0\xf1\x81U913\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 U913\x00\x00\x00\x00\x00\x00SDN8T16NB2\n\xdd^\xbc', + b'\xf1\x87SANDB45316691GC6\x99\x99\x99\x99\x88\x88\xa8\x8avfwfwwww\x87wxwT\x9f\xfd\xff\x88wo\xff\x1c\xfa\xf1\x89HT6WAD10A1\xf1\x82SDN8G25NB3\x00\x00\x00\x00\x00\x00', + b'\xf1\x87SALFBA7460044GJ2gx\x87\x88Vf\x86hx\x88\x87\x88wwwwgw\x86wd?\xfa\xff\x86U_\xff\xaf\x1f\xf1\x81U913\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 U913\x00\x00\x00\x00\x00\x00SDN8T16NB2\n\xdd^\xbc', + b'\xf1\x87SAMFBA8105254GJ2wx\x87\x88Vf\x86hx\x88\x87\x88wwwwwwww\x86O\xfa\xff\x99\x88\x7f\xffZG\xf1\x81U913\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 U913\x00\x00\x00\x00\x00\x00SDN8T16NB2\n\xdd^\xbc', + b'\xf1\x87SANFB45889451GC7wx\x87\x88gw\x87x\x88\x88x\x88\x87wxw\x87wxw\x87\x8f\xfc\xffeU\x8f\xff+Q\xf1\x81U913\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 U913\x00\x00\x00\x00\x00\x00SDN8T16NB2\n\xdd^\xbc', ], }, CAR.SONATA_LF: { (Ecu.fwdRadar, 0x7d0, None): [ b'\xf1\x00LF__ SCC F-CUP 1.00 1.00 96401-C2200 ', ], - (Ecu.esp, 0x7d1, None): [ + (Ecu.abs, 0x7d1, None): [ b'\xf1\x00LF ESC \f 11 \x17\x01\x13 58920-C2610', b'\xf1\x00LF ESC \t 11 \x17\x01\x13 58920-C2610', ], @@ -388,6 +609,7 @@ FW_VERSIONS = { ], (Ecu.fwdCamera, 0x7c4, None): [ b'\xf1\x00LFF LKAS AT USA LHD 1.00 1.01 95740-C1000 E51', + b'\xf1\x00LFF LKAS AT USA LHD 1.01 1.02 95740-C1000 E52', ], (Ecu.transmission, 0x7e1, None): [ b'\xf1\x006T6H0_C2\x00\x006T6B4051\x00\x00TLF0G24NL1\xb0\x9f\xee\xf5', @@ -396,6 +618,25 @@ FW_VERSIONS = { b'\xf1\x87\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xf1\x816T6B4051\x00\x00\xf1\x006T6H0_C2\x00\x006T6B4051\x00\x00TLF0G24SL2n\x8d\xbe\xd8', b'\xf1\x87LAHSGN012918KF10\x98\x88x\x87\x88\x88x\x87\x88\x88\x98\x88\x87w\x88w\x88\x88\x98\x886o\xf6\xff\x98w\x7f\xff3\x00\xf1\x816W3B1051\x00\x00\xf1\x006W351_C2\x00\x006W3B1051\x00\x00TLF0T20NL2\x00\x00\x00\x00', b'\xf1\x87LAHSGN012918KF10\x98\x88x\x87\x88\x88x\x87\x88\x88\x98\x88\x87w\x88w\x88\x88\x98\x886o\xf6\xff\x98w\x7f\xff3\x00\xf1\x816W3B1051\x00\x00\xf1\x006W351_C2\x00\x006W3B1051\x00\x00TLF0T20NL2H\r\xbdm', + b'\xf1\x87LAJSG49645724HF0\x87x\x87\x88\x87www\x88\x99\xa8\x89\x88\x99\xa8\x89\x88\x99\xa8\x89S_\xfb\xff\x87f\x7f\xff^2\xf1\x816W3B1051\x00\x00\xf1\x006W351_C2\x00\x006W3B1051\x00\x00TLF0T20NL2H\r\xbdm', + ], + }, + CAR.TUCSON: { + (Ecu.fwdRadar, 0x7d0, None): [ + b'\xf1\x00TL__ FCA F-CUP 1.00 1.01 99110-D3500 ', + b'\xf1\x00TL__ FCA F-CUP 1.00 1.02 99110-D3510 ', + ], + (Ecu.engine, 0x7e0, None): [ + b'\xf1\x8971TLC2NAIDDIR002\xf1\x8271TLC2NAIDDIR002', + b'\xf1\x81606G3051\x00\x00\x00\x00\x00\x00\x00\x00', + ], + (Ecu.fwdCamera, 0x7c4, None): [ + b'\xf1\x00TL MFC AT KOR LHD 1.00 1.02 95895-D3800 180719', + b'\xf1\x00TL MFC AT USA LHD 1.00 1.06 95895-D3800 190107', + ], + (Ecu.transmission, 0x7e1, None): [ + b'\xf1\x87LBJXAN202299KF22\x87x\x87\x88ww\x87xx\x88\x97\x88\x87\x88\x98x\x88\x99\x98\x89\x87o\xf6\xff\x87w\x7f\xff\x12\x9a\xf1\x81U083\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 U083\x00\x00\x00\x00\x00\x00TTL2V20KL1\x8fRn\x8a', + b'\xf1\x87KMLDCU585233TJ20wx\x87\x88x\x88\x98\x89vfwfwwww\x87f\x9f\xff\x98\xff\x7f\xf9\xf7s\xf1\x816T6G4051\x00\x00\xf1\x006T6J0_C2\x00\x006T6G4051\x00\x00TTL4G24NH2\x00\x00\x00\x00', ], }, CAR.SANTA_FE: { @@ -404,7 +645,7 @@ FW_VERSIONS = { b'\xf1\x00TM__ SCC F-CUP 1.00 1.02 99110-S2000 ', b'\xf1\x00TM__ SCC F-CUP 1.00 1.03 99110-S2000 ', ], - (Ecu.esp, 0x7d1, None): [ + (Ecu.abs, 0x7d1, None): [ b'\xf1\x00TM ESC \r 100\x18\x031 58910-S2650', b'\xf1\x00TM ESC \r 103\x18\x11\x08 58910-S2650', b'\xf1\x00TM ESC \r 104\x19\a\b 58910-S2650', @@ -459,18 +700,26 @@ FW_VERSIONS = { (Ecu.fwdRadar, 0x7d0, None): [ b'\xf1\x00TM__ SCC F-CUP 1.00 1.00 99110-S1500 ', b'\xf1\x8799110S1500\xf1\x00TM__ SCC F-CUP 1.00 1.00 99110-S1500 ', + b'\xf1\x8799110S1500\xf1\x00TM__ SCC FHCUP 1.00 1.00 99110-S1500 ', + b'\xf1\x00TM__ SCC FHCUP 1.00 1.00 99110-S1500 ', ], - (Ecu.esp, 0x7d1, None): [ + (Ecu.abs, 0x7d1, None): [ b'\xf1\x00TM ESC \x02 101 \x08\x04 58910-S2GA0', b'\xf1\x00TM ESC \x03 101 \x08\x02 58910-S2DA0', b'\xf1\x8758910-S2DA0\xf1\x00TM ESC \x03 101 \x08\x02 58910-S2DA0', b'\xf1\x8758910-S2GA0\xf1\x00TM ESC \x02 101 \x08\x04 58910-S2GA0', b'\xf1\x8758910-S1DA0\xf1\x00TM ESC \x1e 102 \x08\x08 58910-S1DA0', + b'\xf1\x8758910-S2GA0\xf1\x00TM ESC \x04 102!\x04\x05 58910-S2GA0', + b'\xf1\x00TM ESC \x04 102!\x04\x05 58910-S2GA0', ], (Ecu.engine, 0x7e0, None): [ + b'\xf1\x82TACVN5GMI3XXXH0A', b'\xf1\x82TMBZN5TMD3XXXG2E', b'\xf1\x82TACVN5GSI3XXXH0A', b'\xf1\x82TMCFD5MMCXXXXG0A', + b'\xf1\x870\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf1\x82TMDWN5TMD3TXXJ1A', + b'\xf1\x81HM6M2_0a0_G00', + b'\xf1\x870\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf1\x81HM6M1_0a0_J10', ], (Ecu.eps, 0x7d4, None): [ b'\xf1\x00TM MDPS C 1.00 1.02 56370-S2AA0 0B19', @@ -480,12 +729,18 @@ FW_VERSIONS = { b'\xf1\x00TMA MFC AT MEX LHD 1.00 1.01 99211-S2500 210205', b'\xf1\x00TMA MFC AT USA LHD 1.00 1.00 99211-S2500 200720', b'\xf1\x00TM MFC AT EUR LHD 1.00 1.03 99211-S1500 210224', + b'\xf1\x00TMA MFC AT USA LHD 1.00 1.01 99211-S2500 210205', ], (Ecu.transmission, 0x7e1, None): [ + b'\xf1\x87SDMXCA9087684GN1VfvgUUeVwwgwwwwwffffU?\xfb\xff\x97\x88\x7f\xff+\xa4\xf1\x89HT6WAD00A1\xf1\x82STM4G25NH1\x00\x00\x00\x00\x00\x00', b'\xf1\x00T02601BL T02730A1 VTMPT25XXX730NS2\xa6\x06\x88\xf7', b'\xf1\x87SDMXCA8653204GN1EVugEUuWwwwwww\x87wwwwwv/\xfb\xff\xa8\x88\x9f\xff\xa5\x9c\xf1\x89HT6WAD00A1\xf1\x82STM4G25NH1\x00\x00\x00\x00\x00\x00', b'\xf1\x87954A02N250\x00\x00\x00\x00\x00\xf1\x81T02730A1 \xf1\x00T02601BL T02730A1 VTMPT25XXX730NS2\xa6\x06\x88\xf7', b'\xf1\x87KMMYBU034207SB72x\x89\x88\x98h\x88\x98\x89\x87fhvvfWf33_\xff\x87\xff\x8f\xfa\x81\xe5\xf1\x89HT6TAF00A1\xf1\x82STM0M25GS1\x00\x00\x00\x00\x00\x00', + b'\xf1\x87954A02N250\x00\x00\x00\x00\x00\xf1\x81T02730A1 \xf1\x00T02601BL T02730A1 VTMPT25XXX730NS2\xa6', + b'\xf1\x00HT6TA290BLHT6TAF00A1STM0M25GS1\x00\x00\x00\x00\x00\x006\xd8\x97\x15', + b'\xf1\x00T02601BL T02900A1 VTMPT25XXX900NS8\xb7\xaa\xfe\xfc', + b'\xf1\x87954A02N250\x00\x00\x00\x00\x00\xf1\x81T02900A1 \xf1\x00T02601BL T02900A1 VTMPT25XXX900NS8\xb7\xaa\xfe\xfc', ], }, CAR.SANTA_FE_HEV_2022: { @@ -511,12 +766,14 @@ FW_VERSIONS = { ], (Ecu.eps, 0x7d4, None): [ b'\xf1\x00TM MDPS C 1.00 1.02 56310-CLAC0 4TSHC102', + b'\xf1\x00TM MDPS C 1.00 1.02 56310-CLEC0 4TSHC102', ], (Ecu.fwdCamera, 0x7c4, None): [ b'\xf1\x00TMP MFC AT USA LHD 1.00 1.03 99211-S1500 210224', ], (Ecu.transmission, 0x7e1, None): [ b'\xf1\x8795441-3D121\x00\xf1\x81E16\x00\x00\x00\x00\x00\x00\x00\xf1\x00PSBG2333 E16\x00\x00\x00\x00\x00\x00\x00TTM2P16SA0o\x88^\xbe', + b'\xf1\x8795441-3D121\x00\xf1\x81E16\x00\x00\x00\x00\x00\x00\x00\xf1\x00PSBG2333 E16\x00\x00\x00\x00\x00\x00\x00TTM2P16SA1\x0b\xc5\x0f\xea', ], (Ecu.engine, 0x7e0, None): [ b'\xf1\x87391312MTF0', @@ -526,12 +783,14 @@ FW_VERSIONS = { (Ecu.fwdRadar, 0x7d0, None): [ b'\xf1\x00CK__ SCC F_CUP 1.00 1.01 96400-J5100 ', b'\xf1\x00CK__ SCC F_CUP 1.00 1.03 96400-J5100 ', + b'\xf1\x00CK__ SCC F_CUP 1.00 1.01 96400-J5000 ', ], (Ecu.engine, 0x7e0, None): [ b'\xf1\x81606DE051\x00\x00\x00\x00\x00\x00\x00\x00', b'\xf1\x81640E0051\x00\x00\x00\x00\x00\x00\x00\x00', b'\xf1\x82CKJN3TMSDE0B\x00\x00\x00\x00', b'\xf1\x82CKKN3TMD_H0A\x00\x00\x00\x00', + b'\xe0\x19\xff\xe7\xe7g\x01\xa2\x00\x0f\x00\x9e\x00\x06\x00\xff\xff\xff\xff\xff\xff\x00\x00\xff\xff\xff\xff\xff\xff\x00\x00\x0f\x0e\x0f\x0f\x0e\r\x00\x00\x7f\x02.\xff\x00\x00~p\x00\x00\x00\x00u\xff\xf9\xff\x00\x00\x00\x00V\t\xd5\x01\xc0\x00\x00\x00\x007\xfb\xfc\x0b\x8d\x00', ], (Ecu.eps, 0x7d4, None): [ b'\xf1\x00CK MDPS R 1.00 1.04 57700-J5200 4C2CL104', @@ -543,6 +802,7 @@ FW_VERSIONS = { (Ecu.fwdCamera, 0x7c4, None): [ b'\xf1\x00CK MFC AT USA LHD 1.00 1.03 95740-J5000 170822', b'\xf1\x00CK MFC AT USA LHD 1.00 1.04 95740-J5000 180504', + b'\xf1\x00CK MFC AT EUR LHD 1.00 1.03 95740-J5000 170822', ], (Ecu.transmission, 0x7e1, None): [ b'\xf1\x87VCJLE17622572DK0vd6D\x99\x98y\x97vwVffUfvfC%CuT&Dx\x87o\xff{\x1c\xf1\x81E21\x00\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 E21\x00\x00\x00\x00\x00\x00\x00SCK0T33NB0\x88\xa2\xe6\xf0', @@ -552,11 +812,33 @@ FW_VERSIONS = { b'\xf1\x87VDHLG17118862DK2\x8awWwgu\x96wVfUVwv\x97xWvfvUTGTx\x87o\xff\xc9\xed\xf1\x81E21\x00\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 E21\x00\x00\x00\x00\x00\x00\x00SCK0T33NB0\x88\xa2\xe6\xf0', b'\xf1\x87VDKLJ18675252DK6\x89vhgwwwwveVU\x88w\x87w\x99vgf\x97vXfgw_\xff\xc2\xfb\xf1\x89E25\x00\x00\x00\x00\x00\x00\x00\xf1\x82TCK0T33NB2', b'\xf1\x87WAJTE17552812CH4vfFffvfVeT5DwvvVVdFeegeg\x88\x88o\xff\x1a]\xf1\x81E21\x00\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 E21\x00\x00\x00\x00\x00\x00\x00TCK2T20NB1\x19\xd2\x00\x94', + b'\xf1\x87VDHLG17274082DK2wfFf\x89x\x98wUT5T\x88v\x97xgeGefTGTVvO\xff\x1c\x14\xf1\x81E19\x00\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 E19\x00\x00\x00\x00\x00\x00\x00SCK0T33UB2\xee[\x97S', + b'\xf1\x87VDHLG17000192DK2xdFffT\xa5VUD$DwT\x86wveVeeD&T\x99\xba\x8f\xff\xcc\x99\xf1\x81E21\x00\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 E21\x00\x00\x00\x00\x00\x00\x00SCK0T33NB0\t\xb7\x17\xf5', + b'\xf1\x00bcsh8p54 E21\x00\x00\x00\x00\x00\x00\x00SCK0T33NB0\t\xb7\x17\xf5', + b'\xf1\x00bcsh8p54 E21\x00\x00\x00\x00\x00\x00\x00SCK0T33NB0\x88\xa2\xe6\xf0', + ], + }, + CAR.KIA_STINGER_2022: { + (Ecu.fwdRadar, 0x7d0, None): [ + b'\xf1\x00CK__ SCC F-CUP 1.00 1.00 99110-J5500 ', + ], + (Ecu.engine, 0x7e0, None): [ + b'\xf1\x81640R0051\x00\x00\x00\x00\x00\x00\x00\x00', + ], + (Ecu.eps, 0x7d4, None): [ + b'\xf1\x00CK MDPS R 1.00 5.03 57700-J5380 4C2VR503', + ], + (Ecu.fwdCamera, 0x7c4, None): [ + b'\xf1\x00CK MFC AT AUS RHD 1.00 1.00 99211-J5500 210622', + ], + (Ecu.transmission, 0x7e1, None): [ + b'\xf1\x87VCNLF11383972DK1vffV\x99\x99\x89\x98\x86eUU\x88wg\x89vfff\x97fff\x99\x87o\xff"\xc1\xf1\x81E30\x00\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 E30\x00\x00\x00\x00\x00\x00\x00SCK0T33GH0\xbe`\xfb\xc6', ], }, CAR.PALISADE: { (Ecu.fwdRadar, 0x7d0, None): [ - b'\xf1\000LX2_ SCC F-CUP 1.00 1.05 99110-S8100 ', + b'\xf1\x00LX2_ SCC F-CUP 1.00 1.04 99110-S8100 ', + b'\xf1\x00LX2_ SCC F-CUP 1.00 1.05 99110-S8100 ', b'\xf1\x00LX2 SCC FHCUP 1.00 1.04 99110-S8100 ', b'\xf1\x00LX2_ SCC FHCU- 1.00 1.05 99110-S8100 ', b'\xf1\x00LX2_ SCC FHCUP 1.00 1.00 99110-S8110 ', @@ -564,16 +846,18 @@ FW_VERSIONS = { b'\xf1\x00LX2_ SCC FHCUP 1.00 1.05 99110-S8100 ', b'\xf1\x00ON__ FCA FHCUP 1.00 1.02 99110-S9100 ', ], - (Ecu.esp, 0x7d1, None): [ + (Ecu.abs, 0x7d1, None): [ b'\xf1\x00LX ESC \x01 103\x19\t\x10 58910-S8360', - b'\xf1\x00LX ESC \x01 103\x31\t\020 58910-S8360', + b'\xf1\x00LX ESC \x01 1031\t\x10 58910-S8360', b'\xf1\x00LX ESC \x0b 101\x19\x03\x17 58910-S8330', b'\xf1\x00LX ESC \x0b 102\x19\x05\x07 58910-S8330', + b'\xf1\x00LX ESC \x0b 103\x19\t\t 58910-S8350', b'\xf1\x00LX ESC \x0b 103\x19\t\x07 58910-S8330', b'\xf1\x00LX ESC \x0b 103\x19\t\x10 58910-S8360', b'\xf1\x00LX ESC \x0b 104 \x10\x16 58910-S8360', b'\xf1\x00ON ESC \x0b 100\x18\x12\x18 58910-S9360', b'\xf1\x00ON ESC \x0b 101\x19\t\x08 58910-S9360', + b'\xf1\x00ON ESC \x0b 101\x19\t\x05 58910-S9320', ], (Ecu.engine, 0x7e0, None): [ b'\xf1\x81640J0051\x00\x00\x00\x00\x00\x00\x00\x00', @@ -581,7 +865,8 @@ FW_VERSIONS = { b'\xf1\x81640S1051\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.eps, 0x7d4, None): [ - b'\xf1\x00LX2 MDPS C 1,00 1,03 56310-S8020 4LXDC103', # modified firmware + b'\xf1\x00LX2 MDPS C 1,00 1,03 56310-S8020 4LXDC103', + b'\xf1\x00LX2 MDPS C 1.00 1.03 56310-S8000 4LXDC103', b'\xf1\x00LX2 MDPS C 1.00 1.03 56310-S8020 4LXDC103', b'\xf1\x00LX2 MDPS C 1.00 1.04 56310-S8020 4LXDC104', b'\xf1\x00ON MDPS C 1.00 1.00 56340-S9000 8B13', @@ -594,14 +879,16 @@ FW_VERSIONS = { b'\xf1\x00LX2 MFC AT USA LHD 1.00 1.08 99211-S8100 200903', b'\xf1\x00ON MFC AT USA LHD 1.00 1.01 99211-S9100 181105', b'\xf1\x00ON MFC AT USA LHD 1.00 1.03 99211-S9100 200720', + b'\xf1\x00LX2 MFC AT USA LHD 1.00 1.00 99211-S8110 210226', ], (Ecu.transmission, 0x7e1, None): [ b'\xf1\x00bcsh8p54 U872\x00\x00\x00\x00\x00\x00TON4G38NB1\x96z28', + b'\xf1\x00bcsh8p54 U891\x00\x00\x00\x00\x00\x00SLX4G38NB3X\xa8\xc08', b'\xf1\x00bcsh8p54 U903\x00\x00\x00\x00\x00\x00TON4G38NB2[v\\\xb6', b'\xf1\x87LBLUFN591307KF25vgvw\x97wwwy\x99\xa7\x99\x99\xaa\xa9\x9af\x88\x96h\x95o\xf7\xff\x99f/\xff\xe4c\xf1\x81U891\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 U891\x00\x00\x00\x00\x00\x00SLX2G38NB2\xd7\xc1/\xd1', b'\xf1\x87LBLUFN650868KF36\xa9\x98\x89\x88\xa8\x88\x88\x88h\x99\xa6\x89fw\x86gw\x88\x97x\xaa\x7f\xf6\xff\xbb\xbb\x8f\xff+\x82\xf1\x81U891\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 U891\x00\x00\x00\x00\x00\x00SLX2G38NB3\xd1\xc3\xf8\xa8', b'\xf1\x87LBLUFN655162KF36\x98\x88\x88\x88\x98\x88\x88\x88x\x99\xa7\x89x\x99\xa7\x89x\x99\x97\x89g\x7f\xf7\xffwU_\xff\xe9!\xf1\x81U891\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 U891\x00\x00\x00\x00\x00\x00SLX2G38NB3\xd1\xc3\xf8\xa8', - b'\xf1\x87LBLUFN731381KF36\xb9\x99\x89\x98\x98\x88\x88\x88\x89\x99\xa8\x99\x88\x99\xa8\x89\x88\x88\x98\x88V\177\xf6\xff\x99w\x8f\xff\xad\xd8\xf1\x81U891\x00\x00\x00\x00\x00\x00\xf1\000bcsh8p54 U891\x00\x00\x00\x00\x00\x00SLX2G38NB3\xd1\xc3\xf8\xa8', + b'\xf1\x87LBLUFN731381KF36\xb9\x99\x89\x98\x98\x88\x88\x88\x89\x99\xa8\x99\x88\x99\xa8\x89\x88\x88\x98\x88V\x7f\xf6\xff\x99w\x8f\xff\xad\xd8\xf1\x81U891\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 U891\x00\x00\x00\x00\x00\x00SLX2G38NB3\xd1\xc3\xf8\xa8', b'\xf1\x87LDKVAA0028604HH1\xa8\x88x\x87vgvw\x88\x99\xa8\x89gw\x86ww\x88\x97x\x97o\xf9\xff\x97w\x7f\xffo\x02\xf1\x81U872\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 U872\x00\x00\x00\x00\x00\x00TON4G38NB1\x96z28', b'\xf1\x87LDKVAA3068374HH1wwww\x87xw\x87y\x99\xa7\x99w\x88\x87xw\x88\x97x\x85\xaf\xfa\xffvU/\xffU\xdc\xf1\x81U872\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 U872\x00\x00\x00\x00\x00\x00TON4G38NB1\x96z28', b'\xf1\x87LDKVBN382172KF26\x98\x88\x88\x88\xa8\x88\x88\x88x\x99\xa7\x89\x87\x88\x98x\x98\x99\xa9\x89\xa5_\xf6\xffDDO\xff\xcd\x16\xf1\x81U891\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 U891\x00\x00\x00\x00\x00\x00SLX4G38NB2\xafL]\xe7', @@ -642,6 +929,9 @@ FW_VERSIONS = { b'\xf1\x87LDMVBN895969KF37vefV\x87vgfx\x99\xa7\x89\x99\x99\xb9\x99f\x88\x96he_\xf7\xffxwo\xff\x14\xf9\xf1\x81U922\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 U922\x00\x00\x00\x00\x00\x00SLX4G38NB5\xb9\x94\xe8\x89', b'\xf1\x87LDMVBN899222KF37\xa8\x88x\x87\x97www\x98\x99\x99\x89\x88\x99\x98\x89f\x88\x96hdo\xf7\xff\xbb\xaa\x9f\xff\xe2U\xf1\x81U922\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 U922\x00\x00\x00\x00\x00\x00SLX4G38NB5\xb9\x94\xe8\x89', b"\xf1\x87LBLUFN622950KF36\xa8\x88\x88\x88\x87w\x87xh\x99\x96\x89\x88\x99\x98\x89\x88\x99\x98\x89\x87o\xf6\xff\x98\x88o\xffx'\xf1\x81U891\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 U891\x00\x00\x00\x00\x00\x00SLX2G38NB3\xd1\xc3\xf8\xa8", + b'\xf1\x87LDMVBN950669KF37\x97www\x96fffy\x99\xa7\x99\xa9\x99\xaa\x99g\x88\x96x\xb8\x8f\xf9\xffTD/\xff\xa7\xcb\xf1\x81U922\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 U922\x00\x00\x00\x00\x00\x00SLX4G38NB5\xb9\x94\xe8\x89', + b'\xf1\x87LDLVAA4478824HH1\x87wwwvfvg\x89\x99\xa8\x99w\x88\x87x\x89\x99\xa8\x99\xa6o\xfa\xfffU/\xffu\x92\xf1\x81U903\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 U903\x00\x00\x00\x00\x00\x00TON4G38NB2[v\\\xb6', + b'\xf1\x87LDMVBN871852KF37\xb9\x99\x99\x99\xa8\x88\x88\x88y\x99\xa7\x99x\x99\xa7\x89\x88\x88\x98\x88\x89o\xf7\xff\xaa\x88o\xff\x0e\xed\xf1\x81U922\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 U922\x00\x00\x00\x00\x00\x00SLX4G38NB5\xb9\x94\xe8\x89', ], }, CAR.VELOSTER: { @@ -649,7 +939,7 @@ FW_VERSIONS = { b'\xf1\x00JS__ SCC H-CUP 1.00 1.02 95650-J3200 ', b'\xf1\x00JS__ SCC HNCUP 1.00 1.02 95650-J3100 ', ], - (Ecu.esp, 0x7d1, None): [ + (Ecu.abs, 0x7d1, None): [ b'\xf1\x00\x00\x00\x00\x00\x00\x00', b'\xf1\x816V8RAC00121.ELF\xf1\x00\x00\x00\x00\x00\x00\x00', ], @@ -679,25 +969,38 @@ FW_VERSIONS = { CAR.GENESIS_G70_2020: { (Ecu.eps, 0x7d4, None): [ b'\xf1\x00IK MDPS R 1.00 1.07 57700-G9220 4I2VL107', + b'\xf1\x00IK MDPS R 1.00 1.07 57700-G9420 4I4VL107', + b'\xf1\x00IK MDPS R 1.00 1.08 57700-G9420 4I4VL108', ], (Ecu.transmission, 0x7e1, None): [ b'\xf1\x87VCJLP18407832DN3\x88vXfvUVT\x97eFU\x87d7v\x88eVeveFU\x89\x98\x7f\xff\xb2\xb0\xf1\x81E25\x00\x00\x00', b'\x00\x00\x00\x00\xf1\x00bcsh8p54 E25\x00\x00\x00\x00\x00\x00\x00SIK0T33NB4\xecE\xefL', + b'\xf1\x87VDKLT18912362DN4wfVfwefeveVUwfvw\x88vWfvUFU\x89\xa9\x8f\xff\x87w\xf1\x81E25\x00\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 E25\x00\x00\x00\x00\x00\x00\x00SIK0T33NB4\xecE\xefL', + b'\xf1\x87VDJLC18480772DK9\x88eHfwfff\x87eFUeDEU\x98eFe\x86T5DVyo\xff\x87s\xf1\x81E25\x00\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 E25\x00\x00\x00\x00\x00\x00\x00SIK0T33KB5\x9f\xa5&\x81', ], (Ecu.fwdRadar, 0x7d0, None): [ b'\xf1\x00IK__ SCC F-CUP 1.00 1.02 96400-G9100 ', b'\xf1\x00IK__ SCC F-CUP 1.00 1.02 96400-G9100 \xf1\xa01.02', + b'\xf1\x00IK__ SCC FHCUP 1.00 1.02 96400-G9000 ', ], (Ecu.fwdCamera, 0x7c4, None): [ b'\xf1\x00IK MFC AT USA LHD 1.00 1.01 95740-G9000 170920', + b'\xf1\x00IK MFC AT KOR LHD 1.00 1.01 95740-G9000 170920', ], (Ecu.engine, 0x7e0, None): [ b'\xf1\x81640J0051\x00\x00\x00\x00\x00\x00\x00\x00', + b'\xf1\x81640H0051\x00\x00\x00\x00\x00\x00\x00\x00', ], }, + CAR.GENESIS_G90: { + (Ecu.transmission, 0x7e1, None): [b'\xf1\x87VDGMD15866192DD3x\x88x\x89wuFvvfUf\x88vWwgwwwvfVgx\x87o\xff\xbc^\xf1\x81E14\x00\x00\x00\x00\x00\x00\x00\xf1\x00bcshcm49 E14\x00\x00\x00\x00\x00\x00\x00SHI0G50NB1tc5\xb7'], + (Ecu.fwdRadar, 0x7d0, None): [b'\xf1\x00HI__ SCC F-CUP 1.00 1.01 96400-D2100 '], + (Ecu.fwdCamera, 0x7c4, None): [b'\xf1\x00HI LKAS AT USA LHD 1.00 1.00 95895-D2020 160302'], + (Ecu.engine, 0x7e0, None): [b'\xf1\x810000000000\x00'], + }, CAR.KONA: { (Ecu.fwdRadar, 0x7d0, None): [b'\xf1\x00OS__ SCC F-CUP 1.00 1.00 95655-J9200 ', ], - (Ecu.esp, 0x7d1, None): [b'\xf1\x816V5RAK00018.ELF\xf1\x00\x00\x00\x00\x00\x00\x00', ], + (Ecu.abs, 0x7d1, None): [b'\xf1\x816V5RAK00018.ELF\xf1\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.engine, 0x7e0, None): [b'"\x01TOS-0NU06F301J02', ], (Ecu.eps, 0x7d4, None): [b'\xf1\x00OS MDPS C 1.00 1.05 56310J9030\x00 4OSDC105', ], (Ecu.fwdCamera, 0x7c4, None): [b'\xf1\x00OS9 LKAS AT USA LHD 1.00 1.00 95740-J9300 g21', ], @@ -705,14 +1008,14 @@ FW_VERSIONS = { }, CAR.KIA_CEED: { (Ecu.fwdRadar, 0x7D0, None): [b'\xf1\000CD__ SCC F-CUP 1.00 1.02 99110-J7000 ', ], - (Ecu.esp, 0x7D4, None): [b'\xf1\000CD MDPS C 1.00 1.06 56310-XX000 4CDEC106', ], + (Ecu.eps, 0x7D4, None): [b'\xf1\000CD MDPS C 1.00 1.06 56310-XX000 4CDEC106', ], (Ecu.fwdCamera, 0x7C4, None): [b'\xf1\000CD LKAS AT EUR LHD 1.00 1.01 99211-J7000 B40', ], (Ecu.engine, 0x7E0, None): [b'\001TCD-JECU4F202H0K', ], (Ecu.transmission, 0x7E1, None): [ b'\xf1\x816U2V7051\000\000\xf1\0006U2V0_C2\000\0006U2V7051\000\000DCD0T14US1\000\000\000\000', b'\xf1\x816U2V7051\x00\x00\xf1\x006U2V0_C2\x00\x006U2V7051\x00\x00DCD0T14US1U\x867Z', ], - (Ecu.esp, 0x7D1, None): [b'\xf1\000CD ESC \003 102\030\b\005 58920-J7350', ], + (Ecu.abs, 0x7D1, None): [b'\xf1\000CD ESC \003 102\030\b\005 58920-J7350', ], }, CAR.KIA_FORTE: { (Ecu.eps, 0x7D4, None): [ @@ -730,7 +1033,7 @@ FW_VERSIONS = { b'\x01TBDM1NU06F200H01', b'391182B945\x00', ], - (Ecu.esp, 0x7d1, None): [ + (Ecu.abs, 0x7d1, None): [ b'\xf1\x816VGRAH00018.ELF\xf1\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.transmission, 0x7e1, None): [ @@ -744,21 +1047,24 @@ FW_VERSIONS = { b'\xf1\x8799110L2000\xf1\000DL3_ SCC FHCUP 1.00 1.03 99110-L2000 ', b'\xf1\x8799110L2100\xf1\x00DL3_ SCC F-CUP 1.00 1.03 99110-L2100 ', b'\xf1\x8799110L2100\xf1\x00DL3_ SCC FHCUP 1.00 1.03 99110-L2100 ', + b'\xf1\x00DL3_ SCC F-CUP 1.00 1.03 99110-L2100 ', ], (Ecu.eps, 0x7D4, None): [ b'\xf1\x8756310-L3110\xf1\000DL3 MDPS C 1.00 1.01 56310-L3110 4DLAC101', b'\xf1\x8756310-L3220\xf1\x00DL3 MDPS C 1.00 1.01 56310-L3220 4DLAC101', b'\xf1\x8757700-L3000\xf1\x00DL3 MDPS R 1.00 1.02 57700-L3000 4DLAP102', + b'\xf1\x00DL3 MDPS C 1.00 1.01 56310-L3220 4DLAC101', ], (Ecu.fwdCamera, 0x7C4, None): [ b'\xf1\x00DL3 MFC AT USA LHD 1.00 1.03 99210-L3000 200915', b'\xf1\x00DL3 MFC AT USA LHD 1.00 1.04 99210-L3000 210208', ], - (Ecu.esp, 0x7D1, None): [ + (Ecu.abs, 0x7D1, None): [ b'\xf1\000DL ESC \006 101 \004\002 58910-L3200', b'\xf1\x8758910-L3200\xf1\000DL ESC \006 101 \004\002 58910-L3200', b'\xf1\x8758910-L3800\xf1\x00DL ESC \t 101 \x07\x02 58910-L3800', b'\xf1\x8758910-L3600\xf1\x00DL ESC \x03 100 \x08\x02 58910-L3600', + b'\xf1\x00DL ESC \t 100 \x06\x02 58910-L3800', ], (Ecu.engine, 0x7E0, None): [ b'\xf1\x87391212MKT0', @@ -771,10 +1077,11 @@ FW_VERSIONS = { b'\xf1\x87SALFEA6046104GK2wvwgeTeFg\x88\x96xwwwwffvfe?\xfd\xff\x86fo\xff\x97A\xf1\x81U913\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 U913\x00\x00\x00\x00\x00\x00TDL2T16NB1ia\x0b\xb8', b'\xf1\x87SCMSAA8572454GK1\x87x\x87\x88Vf\x86hgwvwvwwgvwwgT?\xfb\xff\x97fo\xffH\xb8\xf1\x81U913\x00\x00\x00\x00\x00\x00\xf1\x00bcsh8p54 U913\x00\x00\x00\x00\x00\x00TDL4T16NB05\x94t\x18', b'\xf1\x87954A02N300\x00\x00\x00\x00\x00\xf1\x81T02730A1 \xf1\x00T02601BL T02730A1 WDL3T25XXX730NS2b\x1f\xb8%', + b'\xf1\x00bcsh8p54 U913\x00\x00\x00\x00\x00\x00TDL4T16NB05\x94t\x18', ], }, CAR.KONA_EV: { - (Ecu.esp, 0x7D1, None): [ + (Ecu.abs, 0x7D1, None): [ b'\xf1\x00OS IEB \r 105\x18\t\x18 58520-K4000', b'\xf1\x00OS IEB \x01 212 \x11\x13 58520-K4000', b'\xf1\x00OS IEB \x02 212 \x11\x13 58520-K4000', @@ -800,20 +1107,50 @@ FW_VERSIONS = { b'\xf1\x00OSev SCC FNCUP 1.00 1.01 99110-K4000 ', ], }, + CAR.KONA_EV_2022: { + (Ecu.abs, 0x7D1, None): [ + b'\xf1\x8758520-K4010\xf1\x00OS IEB \x02 101 \x11\x13 58520-K4010', + b'\xf1\x8758520-K4010\xf1\x00OS IEB \x04 101 \x11\x13 58520-K4010', + b'\xf1\x8758520-K4010\xf1\x00OS IEB \x03 101 \x11\x13 58520-K4010', + b'\xf1\x00OS IEB \r 102"\x05\x16 58520-K4010', + # TODO: these return from the MULTI request, above return from LONG + b'\x01\x04\x7f\xff\xff\xf8\xff\xff\x00\x00\x01\xd3\x00\x00\x00\x00\xff\xb7\xff\xee\xff\xe0\x00\xc0\xc0\xfc\xd5\xfc\x00\x00U\x10\xffP\xf5\xff\xfd\x00\x00\x00\x00\xfc\x00\x01', + b'\x01\x04\x7f\xff\xff\xf8\xff\xff\x00\x00\x01\xdb\x00\x00\x00\x00\xff\xb1\xff\xd9\xff\xd2\x00\xc0\xc0\xfc\xd5\xfc\x00\x00U\x10\xff\xd6\xf5\x00\x06\x00\x00\x00\x14\xfd\x00\x04', + b'\x01\x04\x7f\xff\xff\xf8\xff\xff\x00\x00\x01\xd3\x00\x00\x00\x00\xff\xb7\xff\xf4\xff\xd9\x00\xc0', + ], + (Ecu.fwdCamera, 0x7C4, None): [ + b'\xf1\x00OSP LKA AT CND LHD 1.00 1.02 99211-J9110 802', + b'\xf1\x00OSP LKA AT EUR RHD 1.00 1.02 99211-J9110 802', + b'\xf1\x00OSP LKA AT AUS RHD 1.00 1.04 99211-J9200 904', + b'\xf1\x00OSP LKA AT EUR LHD 1.00 1.04 99211-J9200 904', + ], + (Ecu.eps, 0x7D4, None): [ + b'\xf1\x00OSP MDPS C 1.00 1.02 56310K4260\x00 4OEPC102', + b'\xf1\x00OSP MDPS C 1.00 1.02 56310/K4970 4OEPC102', + b'\xf1\x00OSP MDPS C 1.00 1.02 56310/K4271 4OEPC102', + ], + (Ecu.fwdRadar, 0x7D0, None): [ + b'\xf1\x00YB__ FCA ----- 1.00 1.01 99110-K4500 \x00\x00\x00', + ], + }, CAR.KIA_NIRO_EV: { (Ecu.fwdRadar, 0x7D0, None): [ b'\xf1\x00DEev SCC F-CUP 1.00 1.00 99110-Q4000 ', + b'\xf1\x00DEev SCC F-CUP 1.00 1.02 96400-Q4000 ', b'\xf1\x00DEev SCC F-CUP 1.00 1.02 96400-Q4100 ', b'\xf1\x00DEev SCC F-CUP 1.00 1.03 96400-Q4100 ', + b'\xf1\x00DEev SCC FHCUP 1.00 1.03 96400-Q4000 ', b'\xf1\x8799110Q4000\xf1\x00DEev SCC F-CUP 1.00 1.00 99110-Q4000 ', b'\xf1\x8799110Q4100\xf1\x00DEev SCC F-CUP 1.00 1.00 99110-Q4100 ', b'\xf1\x8799110Q4500\xf1\x00DEev SCC F-CUP 1.00 1.00 99110-Q4500 ', + b'\xf1\x8799110Q4600\xf1\x00DEev SCC F-CUP 1.00 1.00 99110-Q4600 ', b'\xf1\x8799110Q4600\xf1\x00DEev SCC FNCUP 1.00 1.00 99110-Q4600 ', b'\xf1\x8799110Q4600\xf1\x00DEev SCC FHCUP 1.00 1.00 99110-Q4600 ', ], (Ecu.eps, 0x7D4, None): [ b'\xf1\x00DE MDPS C 1.00 1.05 56310Q4000\x00 4DEEC105', b'\xf1\x00DE MDPS C 1.00 1.05 56310Q4100\x00 4DEEC105', + b'\xf1\x00DE MDPS C 1.00 1.04 56310Q4100\x00 4DEEC104', ], (Ecu.fwdCamera, 0x7C4, None): [ b'\xf1\x00DEE MFC AT EUR LHD 1.00 1.00 99211-Q4100 200706', @@ -821,24 +1158,30 @@ FW_VERSIONS = { b'\xf1\x00DEE MFC AT USA LHD 1.00 1.00 99211-Q4000 191211', b'\xf1\x00DEE MFC AT USA LHD 1.00 1.03 95740-Q4000 180821', b'\xf1\x00DEE MFC AT USA LHD 1.00 1.01 99211-Q4500 210428', + b'\xf1\x00DEE MFC AT EUR LHD 1.00 1.03 95740-Q4000 180821', + b'\xf1\x00DEE MFC AT KOR LHD 1.00 1.03 95740-Q4000 180821', ], }, - CAR.KIA_NIRO_HEV: { + CAR.KIA_NIRO_PHEV: { (Ecu.engine, 0x7e0, None): [ - b'\xf1\x816H6F4051\000\000\000\000\000\000\000\000', + b'\xf1\x816H6F4051\x00\x00\x00\x00\x00\x00\x00\x00', + b'\xf1\x816H6D1051\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.transmission, 0x7e1, None): [ - b"\xf1\x816U3J2051\000\000\xf1\0006U3H0_C2\000\0006U3J2051\000\000PDE0G16NS2\xf4\'\\\x91", - b'\xf1\x816U3J2051\000\000\xf1\0006U3H0_C2\000\0006U3J2051\000\000PDE0G16NS2\000\000\000\000', + b"\xf1\x816U3J2051\x00\x00\xf1\x006U3H0_C2\x00\x006U3J2051\x00\x00PDE0G16NS2\xf4'\\\x91", + b'\xf1\x816U3J2051\x00\x00\xf1\x006U3H0_C2\x00\x006U3J2051\x00\x00PDE0G16NS2\x00\x00\x00\x00', + b'\xf1\x816U3H3051\x00\x00\xf1\x006U3H0_C2\x00\x006U3H3051\x00\x00PDE0G16NS1\x00\x00\x00\x00', + b'\xf1\x816U3H3051\x00\x00\xf1\x006U3H0_C2\x00\x006U3H3051\x00\x00PDE0G16NS1\x13\xcd\x88\x92', ], (Ecu.eps, 0x7D4, None): [ - b'\xf1\000DE MDPS C 1.00 1.09 56310G5301\000 4DEHC109', + b'\xf1\x00DE MDPS C 1.00 1.09 56310G5301\x00 4DEHC109', ], (Ecu.fwdCamera, 0x7C4, None): [ - b'\xf1\000DEP MFC AT USA LHD 1.00 1.01 95740-G5010 170424', + b'\xf1\x00DEP MFC AT USA LHD 1.00 1.01 95740-G5010 170424', + b'\xf1\x00DEP MFC AT USA LHD 1.00 1.00 95740-G5010 170117', ], (Ecu.fwdRadar, 0x7D0, None): [ - b'\xf1\000DEhe SCC H-CUP 1.01 1.02 96400-G5100 ', + b'\xf1\x00DEhe SCC H-CUP 1.01 1.02 96400-G5100 ', ], }, CAR.KIA_NIRO_HEV_2021: { @@ -854,6 +1197,7 @@ FW_VERSIONS = { ], (Ecu.fwdCamera, 0x7c4, None): [ b'\xf1\x00DEH MFC AT USA LHD 1.00 1.07 99211-G5000 201221', + b'\xf1\x00DEH MFC AT USA LHD 1.00 1.00 99211-G5500 210428', ], (Ecu.fwdRadar, 0x7d0, None): [ b'\xf1\x00DEhe SCC FHCUP 1.00 1.00 99110-G5600 ', @@ -861,16 +1205,16 @@ FW_VERSIONS = { }, CAR.KIA_SELTOS: { (Ecu.fwdRadar, 0x7d0, None): [b'\xf1\x8799110Q5100\xf1\000SP2_ SCC FHCUP 1.01 1.05 99110-Q5100 ',], - (Ecu.esp, 0x7d1, None): [ + (Ecu.abs, 0x7d1, None): [ b'\xf1\x8758910-Q5450\xf1\000SP ESC \a 101\031\t\005 58910-Q5450', b'\xf1\x8758910-Q5450\xf1\000SP ESC \t 101\031\t\005 58910-Q5450', - ], + ], (Ecu.engine, 0x7e0, None): [ b'\xf1\x81616D2051\000\000\000\000\000\000\000\000', b'\xf1\x81616D5051\000\000\000\000\000\000\000\000', b'\001TSP2KNL06F100J0K', b'\001TSP2KNL06F200J0K', - ], + ], (Ecu.eps, 0x7d4, None): [ b'\xf1\000SP2 MDPS C 1.00 1.04 56300Q5200 ', b'\xf1\000SP2 MDPS C 1.01 1.05 56300Q5200 ', @@ -883,42 +1227,88 @@ FW_VERSIONS = { b'\xf1\x87CZLUB49370612JF7h\xa8y\x87\x99\xa7hv\x99\x97fv\x88\x87x\x89x\x96O\xff\x88\xff\xff\xff.@\xf1\x816V2C2051\000\000\xf1\0006V2B0_C2\000\0006V2C2051\000\000CSP4N20NS3\000\000\000\000', b'\xf1\x87954A22D200\xf1\x81T01950A1 \xf1\000T0190XBL T01950A1 DSP2T16X4X950NS6\xd30\xa5\xb9', b'\xf1\x87954A22D200\xf1\x81T01950A1 \xf1\000T0190XBL T01950A1 DSP2T16X4X950NS8\r\xfe\x9c\x8b', - ], + ], }, - CAR.KIA_OPTIMA: { - (Ecu.fwdRadar, 0x7d0, None): [b'\xf1\x00JF__ SCC F-CUP 1.00 1.00 96400-D4110 '], - (Ecu.esp, 0x7d1, None): [b'\xf1\x00JF ESC \v 11 \x18\x030 58920-D5180',], - (Ecu.engine, 0x7e0, None): [ - b'\x01TJFAJNU06F201H03', - b'\xf1\x89F1JF600AISEIU702\xf1\x82F1JF600AISEIU702', + CAR.KIA_OPTIMA_G4: { + (Ecu.fwdRadar, 0x7d0, None): [ + b'\xf1\x00JF__ SCC F-CUP 1.00 1.00 96400-D4100 ', + ], + (Ecu.abs, 0x7d1, None): [ + b'\xf1\x00JF ESC \x0f 16 \x16\x06\x17 58920-D5080', + ], + (Ecu.fwdCamera, 0x7c4, None): [ + b'\xf1\x00JFWGN LDWS AT USA LHD 1.00 1.02 95895-D4100 G21', + ], + (Ecu.transmission, 0x7e1, None): [ + b'\xf1\x87\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xf1\x816T6J0051\x00\x00\xf1\x006T6J0_C2\x00\x006T6J0051\x00\x00TJF0T20NSB\x00\x00\x00\x00', + ], + }, + CAR.KIA_OPTIMA_G4_FL: { + (Ecu.fwdRadar, 0x7d0, None): [ + b'\xf1\x00JF__ SCC F-CUP 1.00 1.00 96400-D4110 ', + ], + (Ecu.abs, 0x7d1, None): [ + b'\xf1\x00JF ESC \x0b 11 \x18\x030 58920-D5180', + b"\xf1\x00JF ESC \t 11 \x18\x03' 58920-D5260", ], - (Ecu.eps, 0x7d4, None): [b'\xf1\x00TM MDPS C 1.00 1.00 56340-S2000 8409'], (Ecu.fwdCamera, 0x7c4, None): [ b'\xf1\x00JFA LKAS AT USA LHD 1.00 1.00 95895-D5001 h32', - b'\xf1\x00JFA LKAS AT USA LHD 1.00 1.02 95895-D5000 h31', - ], - (Ecu.transmission, 0x7e1, None): [b'\xf1\x816U2V8051\x00\x00\xf1\x006U2V0_C2\x00\x006U2V8051\x00\x00DJF0T16NL0\t\xd2GW'], + b'\xf1\x00JFA LKAS AT USA LHD 1.00 1.00 95895-D5100 h32', + ], + (Ecu.transmission, 0x7e1, None): [ + b'\xf1\x006U2V0_C2\x00\x006U2V8051\x00\x00DJF0T16NL0\t\xd2GW', + b'\xf1\x006U2V0_C2\x00\x006U2VA051\x00\x00DJF0T16NL1\xca3\xeb.', + b'\xf1\x006U2V0_C2\x00\x006U2VC051\x00\x00DJF0T16NL2\x9eA\x80\x01', + b'\xf1\x006U2V0_C2\x00\x006U2VA051\x00\x00DJF0T16NL1\x00\x00\x00\x00', + b'\xf1\x816U2V8051\x00\x00\xf1\x006U2V0_C2\x00\x006U2V8051\x00\x00DJF0T16NL0\t\xd2GW', + b'\xf1\x816U2VA051\x00\x00\xf1\x006U2V0_C2\x00\x006U2VA051\x00\x00DJF0T16NL1\xca3\xeb.', + b'\xf1\x816U2VC051\x00\x00\xf1\x006U2V0_C2\x00\x006U2VC051\x00\x00DJF0T16NL2\x9eA\x80\x01', + b'\xf1\x816U2VA051\x00\x00\xf1\x006U2V0_C2\x00\x006U2VA051\x00\x00DJF0T16NL1\x00\x00\x00\x00', + b'\xf1\x87\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xf1\x816T6B8051\x00\x00\xf1\x006T6H0_C2\x00\x006T6B8051\x00\x00TJFSG24NH27\xa7\xc2\xb4', + ], + }, + CAR.ELANTRA: { + (Ecu.fwdCamera, 0x7c4, None): [ + b'\xf1\x00PD LKAS AT USA LHD 1.01 1.01 95740-G3100 A54', + ], + (Ecu.transmission, 0x7e1, None): [ + b'\xf1\x006U2V0_C2\x00\x006U2VA051\x00\x00DPD0H16NS0e\x0e\xcd\x8e', + ], + (Ecu.eps, 0x7d4, None): [ + b'\xf1\x00PD MDPS C 1.00 1.04 56310/G3300 4PDDC104', + ], + (Ecu.abs, 0x7d1, None): [ + b'\xf1\x00PD ESC \x0b 104\x18\t\x03 58920-G3350', + ], + (Ecu.fwdRadar, 0x7d0, None): [ + b'\xf1\x00PD__ SCC F-CUP 1.00 1.00 96400-G3300 ', + ], }, CAR.ELANTRA_2021: { (Ecu.fwdRadar, 0x7d0, None): [ b'\xf1\x00CN7_ SCC F-CUP 1.00 1.01 99110-AA000 ', b'\xf1\x00CN7_ SCC FHCUP 1.00 1.01 99110-AA000 ', b'\xf1\x8799110AA000\xf1\x00CN7_ SCC FHCUP 1.00 1.01 99110-AA000 ', + b'\xf1\x8799110AA000\xf1\x00CN7_ SCC F-CUP 1.00 1.01 99110-AA000 ', ], (Ecu.eps, 0x7d4, None): [ b'\xf1\x87\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf1\x00CN7 MDPS C 1.00 1.06 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 4CNDC106', b'\xf1\x8756310/AA070\xf1\x00CN7 MDPS C 1.00 1.06 56310/AA070 4CNDC106', b'\xf1\x8756310AA050\x00\xf1\x00CN7 MDPS C 1.00 1.06 56310AA050\x00 4CNDC106', + b'\xf1\x8756310AA050\x00\xf1\x00CN7 MDPS C 1.00 1.06 56310AA050\x00 4CNDC106\xf1\xa01.06', ], (Ecu.fwdCamera, 0x7c4, None): [ b'\xf1\x00CN7 MFC AT USA LHD 1.00 1.00 99210-AB000 200819', b'\xf1\x00CN7 MFC AT USA LHD 1.00 1.03 99210-AA000 200819', b'\xf1\x00CN7 MFC AT USA LHD 1.00 1.01 99210-AB000 210205', + b'\xf1\x00CN7 MFC AT USA LHD 1.00 1.06 99210-AA000 220111', ], - (Ecu.esp, 0x7d1, None): [ + (Ecu.abs, 0x7d1, None): [ b'\xf1\x00CN ESC \t 101 \x10\x03 58910-AB800', b'\xf1\x8758910-AA800\xf1\x00CN ESC \t 104 \x08\x03 58910-AA800', b'\xf1\x8758910-AB800\xf1\x00CN ESC \t 101 \x10\x03 58910-AB800', + b'\xf1\x8758910-AA800\xf1\x00CN ESC \t 105 \x10\x03 58910-AA800', + b'\xf1\x8758910-AB800\xf1\x00CN ESC \t 101 \x10\x03 58910-AB800\xf1\xa01.01', ], (Ecu.transmission, 0x7e1, None): [ b'\xf1\x00HT6WA280BLHT6VA640A1CCN0N20NS5\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', @@ -926,38 +1316,44 @@ FW_VERSIONS = { b'\xf1\x87CXMQFM2135005JB2E\xb9\x89\x98W\xa9y\x97h\xa9\x98\x99wxvwh\x87\177\xffx\xff\xff\xff,,\xf1\x89HT6VA640A1\xf1\x82CCN0N20NS5\x00\x00\x00\x00\x00\x00', b'\xf1\x87CXMQFM1916035JB2\x88vvgg\x87Wuwgev\xa9\x98\x88\x98h\x99\x9f\xffh\xff\xff\xff\xa5\xee\xf1\x89HT6VA640A1\xf1\x82CCN0N20NS5\x00\x00\x00\x00\x00\x00', b'\xf1\x87CXLQF40189012JL2f\x88\x86\x88\x88vUex\xb8\x88\x88\x88\x87\x88\x89fh?\xffz\xff\xff\xff\x08z\xf1\x89HT6VA640A1\xf1\x82CCN0N20NS5\x00\x00\x00\x00\x00\x00', - b'\xf1\x87CXMQFM2728305JB2E\x97\x87xw\x87vwgw\x84x\x88\x88w\x89EI\xbf\xff{\xff\xff\xff\xe6\x0e\xf1\x89HT6VA640A1\xf1\x82CCN0N20NS5\x00\x00\x00\x00\x00\x00' + b'\xf1\x87CXMQFM2728305JB2E\x97\x87xw\x87vwgw\x84x\x88\x88w\x89EI\xbf\xff{\xff\xff\xff\xe6\x0e\xf1\x89HT6VA640A1\xf1\x82CCN0N20NS5\x00\x00\x00\x00\x00\x00', + b'\xf1\x87CXMQFM3806705JB2\x89\x87wwx\x88g\x86\x99\x87\x86xwwv\x88yv\x7f\xffz\xff\xff\xffV\x15\xf1\x89HT6VA640A1\xf1\x82CCN0N20NS5\x00\x00\x00\x00\x00\x00', ], (Ecu.engine, 0x7e0, None): [ b'\xf1\x82CNCWD0AMFCXCSFFA', - b'\xf1\x82CNCWD0AMFCXCSFFB', + b'\xf1\x81HM6M2_0a0_FF0', b'\xf1\x82CNCVD0AMFCXCSFFB', - b'\xf1\x870\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf1\x82CNDWD0AMFCXCSG8A', + b'\xf1\x870\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf1\x81HM6M2_0a0_G80', ], }, CAR.ELANTRA_HEV_2021: { - (Ecu.fwdCamera, 0x7c4, None) : [ + (Ecu.fwdCamera, 0x7c4, None): [ + b'\xf1\x00CN7HMFC AT USA LHD 1.00 1.05 99210-AA000 210930', b'\xf1\000CN7HMFC AT USA LHD 1.00 1.03 99210-AA000 200819', + b'\xf1\x00CN7HMFC AT USA LHD 1.00 1.07 99210-AA000 220426', ], - (Ecu.fwdRadar, 0x7d0, None) : [ + (Ecu.fwdRadar, 0x7d0, None): [ b'\xf1\000CNhe SCC FHCUP 1.00 1.01 99110-BY000 ', b'\xf1\x8799110BY000\xf1\x00CNhe SCC FHCUP 1.00 1.01 99110-BY000 ', ], - (Ecu.eps, 0x7d4, None) :[ + (Ecu.eps, 0x7d4, None): [ + b'\xf1\x00CN7 MDPS C 1.00 1.03 56310BY0500 4CNHC103', + b'\xf1\x8756310/BY050\xf1\x00CN7 MDPS C 1.00 1.03 56310/BY050 4CNHC103', b'\xf1\x8756310/BY050\xf1\000CN7 MDPS C 1.00 1.02 56310/BY050 4CNHC102', ], - (Ecu.transmission, 0x7e1, None) :[ + (Ecu.transmission, 0x7e1, None): [ b'\xf1\0006U3L0_C2\000\0006U3K3051\000\000HCN0G16NS0\xb9?A\xaa', b'\xf1\0006U3L0_C2\000\0006U3K3051\000\000HCN0G16NS0\000\000\000\000', b'\xf1\x816U3K3051\000\000\xf1\0006U3L0_C2\000\0006U3K3051\000\000HCN0G16NS0\xb9?A\xaa', b'\xf1\x816U3K3051\x00\x00\xf1\x006U3L0_C2\x00\x006U3K3051\x00\x00HCN0G16NS0\x00\x00\x00\x00', ], - (Ecu.engine, 0x7e0, None) : [ + (Ecu.engine, 0x7e0, None): [ b'\xf1\x816H6G5051\x00\x00\x00\x00\x00\x00\x00\x00', + b'\xf1\x816H6G6051\x00\x00\x00\x00\x00\x00\x00\x00', ] }, CAR.KONA_HEV: { - (Ecu.esp, 0x7d1, None): [ + (Ecu.abs, 0x7d1, None): [ b'\xf1\x00OS IEB \x01 104 \x11 58520-CM000', ], (Ecu.fwdRadar, 0x7d0, None): [ @@ -982,35 +1378,36 @@ FW_VERSIONS = { b'\xf1\x8799110L5000\xf1\000DNhe SCC FHCUP 1.00 1.02 99110-L5000 ', b'\xf1\000DNhe SCC F-CUP 1.00 1.02 99110-L5000 ', b'\xf1\x8799110L5000\xf1\000DNhe SCC F-CUP 1.00 1.02 99110-L5000 ', - ], + ], (Ecu.eps, 0x7d4, None): [ b'\xf1\x8756310-L5500\xf1\x00DN8 MDPS C 1.00 1.02 56310-L5500 4DNHC102', b'\xf1\x8756310-L5450\xf1\x00DN8 MDPS C 1.00 1.02 56310-L5450 4DNHC102', b'\xf1\x8756310-L5450\xf1\000DN8 MDPS C 1.00 1.03 56310-L5450 4DNHC103', - ], + ], (Ecu.fwdCamera, 0x7c4, None): [ b'\xf1\x00DN8HMFC AT USA LHD 1.00 1.04 99211-L1000 191016', b'\xf1\x00DN8HMFC AT USA LHD 1.00 1.05 99211-L1000 201109', b'\xf1\000DN8HMFC AT USA LHD 1.00 1.06 99211-L1000 210325', - ], + ], (Ecu.transmission, 0x7e1, None): [ b'\xf1\000PSBG2333 E14\x00\x00\x00\x00\x00\x00\x00TDN2H20SA6N\xc2\xeeW', - b'\xf1\x87959102T250\000\000\000\000\000\xf1\x81E09\000\000\000\000\000\000\000\xf1\000PSBG2323 E09\000\000\000\000\000\000\000TDN2H20SA5\x97R\x88\x9e', + b'\xf1\x87959102T250\x00\x00\x00\x00\x00\xf1\x81E09\x00\x00\x00\x00\x00\x00\x00\xf1\x00PSBG2323 E09\x00\x00\x00\x00\x00\x00\x00TDN2H20SA5\x97R\x88\x9e', b'\xf1\000PSBG2323 E09\000\000\000\000\000\000\000TDN2H20SA5\x97R\x88\x9e', b'\xf1\000PSBG2333 E16\000\000\000\000\000\000\000TDN2H20SA7\0323\xf9\xab', b'\xf1\x87PCU\000\000\000\000\000\000\000\000\000\xf1\x81E16\000\000\000\000\000\000\000\xf1\000PSBG2333 E16\000\000\000\000\000\000\000TDN2H20SA7\0323\xf9\xab', b'\xf1\x87959102T250\x00\x00\x00\x00\x00\xf1\x81E14\x00\x00\x00\x00\x00\x00\x00\xf1\x00PSBG2333 E14\x00\x00\x00\x00\x00\x00\x00TDN2H20SA6N\xc2\xeeW', - ], + ], (Ecu.engine, 0x7e0, None): [ b'\xf1\x87391162J012', b'\xf1\x87391162J013', - ], + b'\xf1\x87391062J002', + ], }, CAR.KIA_SORENTO: { (Ecu.fwdCamera, 0x7c4, None): [ b'\xf1\x00UMP LKAS AT USA LHD 1.01 1.01 95740-C6550 d01' ], - (Ecu.esp, 0x7d1, None): [ + (Ecu.abs, 0x7d1, None): [ b'\xf1\x00UM ESC \x0c 12 \x18\x05\x06 58910-C6330' ], (Ecu.fwdRadar, 0x7D0, None): [ @@ -1023,6 +1420,89 @@ FW_VERSIONS = { b'\xf1\x81640F0051\x00\x00\x00\x00\x00\x00\x00\x00' ], }, + CAR.KIA_SORENTO_PHEV_4TH_GEN: { + (Ecu.fwdRadar, 0x7d0, None): [ + b'\xf1\x00MQhe SCC FHCUP 1.00 1.06 99110-P4000 ', + ], + (Ecu.fwdCamera, 0x7c4, None): [ + b'\xf1\x00MQ4HMFC AT USA LHD 1.00 1.11 99210-P2000 211217', + ] + }, + CAR.KIA_EV6: { + (Ecu.fwdRadar, 0x7d0, None): [ + b'\xf1\x00CV1_ RDR ----- 1.00 1.01 99110-CV000 ', + b'\xf1\x8799110CV000\xf1\x00CV1_ RDR ----- 1.00 1.01 99110-CV000 ', + ], + (Ecu.fwdCamera, 0x7c4, None): [ + b'\xf1\x00CV1 MFC AT USA LHD 1.00 1.05 99210-CV000 211027', + b'\xf1\x00CV1 MFC AT USA LHD 1.00 1.06 99210-CV000 220328', + b'\xf1\x00CV1 MFC AT EUR LHD 1.00 1.05 99210-CV000 211027', + b'\xf1\x00CV1 MFC AT EUR LHD 1.00 1.06 99210-CV000 220328', + ], + }, + CAR.IONIQ_5: { + (Ecu.fwdRadar, 0x7d0, None): [ + b'\xf1\x00NE1_ RDR ----- 1.00 1.00 99110-GI000 ', + b'\xf1\x8799110GI000\xf1\x00NE1_ RDR ----- 1.00 1.00 99110-GI000 ', + ], + (Ecu.fwdCamera, 0x7c4, None): [ + b'\xf1\x00NE1 MFC AT USA LHD 1.00 1.02 99211-GI010 211206', + b'\xf1\x00NE1 MFC AT EUR LHD 1.00 1.06 99211-GI000 210813', + b'\xf1\x00NE1 MFC AT USA LHD 1.00 1.05 99211-GI010 220614', + ], + }, + CAR.TUCSON_4TH_GEN: { + (Ecu.fwdCamera, 0x7c4, None): [ + b'\xf1\x00NX4 FR_CMR AT USA LHD 1.00 1.01 99211-N9240 14T', + ], + (Ecu.fwdRadar, 0x7d0, None): [ + b'\xf1\x00NX4__ 1.01 1.00 99110-N9100 ', + ], + }, + CAR.TUCSON_HYBRID_4TH_GEN: { + (Ecu.fwdCamera, 0x7c4, None): [ + b'\xf1\x00NX4 FR_CMR AT USA LHD 1.00 1.00 99211-N9240 14Q', + b'\xf1\x00NX4 FR_CMR AT USA LHD 1.00 1.00 99211-N9220 14K', + b'\xf1\x00NX4 FR_CMR AT USA LHD 1.00 1.01 99211-N9100 14A', + ], + (Ecu.fwdRadar, 0x7d0, None): [ + b'\xf1\x00NX4__ 1.00 1.00 99110-N9100 ', + ], + }, + CAR.KIA_SPORTAGE_HYBRID_5TH_GEN: { + (Ecu.fwdCamera, 0x7c4, None): [ + b'\xf1\x00NQ5 FR_CMR AT USA LHD 1.00 1.00 99211-P1060 665', + ], + (Ecu.fwdRadar, 0x7d0, None): [ + b'\xf1\x00NQ5__ 1.01 1.03 99110-CH000 ', + ], + }, + CAR.SANTA_CRUZ_1ST_GEN: { + (Ecu.fwdCamera, 0x7c4, None): [ + b'\xf1\x00NX4 FR_CMR AT USA LHD 1.00 1.00 99211-CW000 14M', + ], + (Ecu.fwdRadar, 0x7d0, None): [ + b'\xf1\x00NX4__ 1.00 1.00 99110-K5000 ', + ], + }, + CAR.KIA_SPORTAGE_5TH_GEN: { + (Ecu.fwdCamera, 0x7c4, None): [ + b'\xf1\x00NQ5 FR_CMR AT USA LHD 1.00 1.00 99211-P1030 662', + b'\xf1\x00NQ5 FR_CMR AT USA LHD 1.00 1.00 99211-P1040 663', + ], + (Ecu.fwdRadar, 0x7d0, None): [ + b'\xf1\x00NQ5__ 1.00 1.02 99110-P1000 ', + b'\xf1\x00NQ5__ 1.00 1.03 99110-P1000 ', + ], + }, + CAR.GENESIS_GV70_1ST_GEN: { + (Ecu.fwdCamera, 0x7c4, None): [ + b'\xf1\x00JK1 MFC AT USA LHD 1.00 1.04 99211-AR000 210204', + ], + (Ecu.fwdRadar, 0x7d0, None): [ + b'\xf1\x00JK1_ SCC FHCUP 1.00 1.02 99110-AR000 ', + ], + }, } CHECKSUM = { @@ -1032,19 +1512,27 @@ CHECKSUM = { FEATURES = { # which message has the gear - "use_cluster_gears": {CAR.ELANTRA, CAR.ELANTRA_GT_I30, CAR.KONA}, - "use_tcu_gears": {CAR.KIA_OPTIMA, CAR.SONATA_LF, CAR.VELOSTER}, - "use_elect_gears": {CAR.KIA_NIRO_EV, CAR.KIA_NIRO_HEV, CAR.KIA_NIRO_HEV_2021, CAR.KIA_OPTIMA_H, CAR.IONIQ_EV_LTD, CAR.KONA_EV, CAR.IONIQ, CAR.IONIQ_EV_2020, CAR.IONIQ_PHEV, CAR.ELANTRA_HEV_2021,CAR.SONATA_HYBRID, CAR.KONA_HEV, CAR.IONIQ_HEV_2022, CAR.SANTA_FE_HEV_2022, CAR.SANTA_FE_PHEV_2022}, + "use_cluster_gears": {CAR.ELANTRA, CAR.KONA}, + "use_tcu_gears": {CAR.KIA_OPTIMA_G4, CAR.KIA_OPTIMA_G4_FL, CAR.SONATA_LF, CAR.VELOSTER, CAR.TUCSON}, + "use_elect_gears": {CAR.KIA_NIRO_EV, CAR.KIA_NIRO_PHEV, CAR.KIA_NIRO_HEV_2021, CAR.KIA_OPTIMA_H, CAR.IONIQ_EV_LTD, CAR.KONA_EV, CAR.IONIQ, CAR.IONIQ_EV_2020, CAR.IONIQ_PHEV, CAR.ELANTRA_HEV_2021, CAR.SONATA_HYBRID, CAR.KONA_HEV, CAR.IONIQ_HEV_2022, CAR.SANTA_FE_HEV_2022, CAR.SANTA_FE_PHEV_2022, CAR.IONIQ_PHEV_2019, CAR.KONA_EV_2022}, # these cars use the FCA11 message for the AEB and FCW signals, all others use SCC12 - "use_fca": {CAR.SONATA, CAR.SONATA_HYBRID, CAR.ELANTRA, CAR.ELANTRA_2021, CAR.ELANTRA_HEV_2021, CAR.ELANTRA_GT_I30, CAR.KIA_STINGER, CAR.IONIQ_EV_2020, CAR.IONIQ_PHEV, CAR.KONA_EV, CAR.KIA_FORTE, CAR.KIA_NIRO_EV, CAR.PALISADE, CAR.GENESIS_G70, CAR.GENESIS_G70_2020, CAR.KONA, CAR.SANTA_FE, CAR.KIA_SELTOS, CAR.KONA_HEV, CAR.SANTA_FE_2022, CAR.KIA_K5_2021, CAR.IONIQ_HEV_2022, CAR.SANTA_FE_HEV_2022, CAR.SANTA_FE_PHEV_2022}, + "use_fca": {CAR.SONATA, CAR.SONATA_HYBRID, CAR.ELANTRA, CAR.ELANTRA_2021, CAR.ELANTRA_HEV_2021, CAR.KIA_STINGER, CAR.IONIQ_EV_2020, CAR.IONIQ_PHEV, CAR.KONA_EV, CAR.KIA_FORTE, CAR.KIA_NIRO_EV, CAR.PALISADE, CAR.GENESIS_G70, CAR.GENESIS_G70_2020, CAR.KONA, CAR.SANTA_FE, CAR.KIA_SELTOS, CAR.KONA_HEV, CAR.SANTA_FE_2022, CAR.KIA_K5_2021, CAR.IONIQ_HEV_2022, CAR.SANTA_FE_HEV_2022, CAR.SANTA_FE_PHEV_2022, CAR.TUCSON, CAR.KONA_EV_2022, CAR.KIA_STINGER_2022}, } -HYBRID_CAR = {CAR.IONIQ_PHEV, CAR.ELANTRA_HEV_2021, CAR.KIA_NIRO_HEV, CAR.KIA_NIRO_HEV_2021, CAR.SONATA_HYBRID, CAR.KONA_HEV, CAR.IONIQ, CAR.IONIQ_HEV_2022, CAR.SANTA_FE_HEV_2022, CAR.SANTA_FE_PHEV_2022} # these cars use a different gas signal -EV_CAR = {CAR.IONIQ_EV_2020, CAR.IONIQ_EV_LTD, CAR.KONA_EV, CAR.KIA_NIRO_EV} +CANFD_CAR = {CAR.KIA_EV6, CAR.IONIQ_5, CAR.TUCSON_4TH_GEN, CAR.TUCSON_HYBRID_4TH_GEN, CAR.KIA_SPORTAGE_HYBRID_5TH_GEN, CAR.SANTA_CRUZ_1ST_GEN, CAR.KIA_SPORTAGE_5TH_GEN, CAR.GENESIS_GV70_1ST_GEN, CAR.KIA_SORENTO_PHEV_4TH_GEN} + +# The radar does SCC on these cars when HDA I, rather than the camera +CANFD_RADAR_SCC_CAR = {CAR.GENESIS_GV70_1ST_GEN, CAR.KIA_SORENTO_PHEV_4TH_GEN} + +# The camera does SCC on these cars, rather than the radar +CAMERA_SCC_CAR = {CAR.KONA_EV_2022, } + +HYBRID_CAR = {CAR.IONIQ_PHEV, CAR.ELANTRA_HEV_2021, CAR.KIA_NIRO_PHEV, CAR.KIA_NIRO_HEV_2021, CAR.SONATA_HYBRID, CAR.KONA_HEV, CAR.IONIQ, CAR.IONIQ_HEV_2022, CAR.SANTA_FE_HEV_2022, CAR.SANTA_FE_PHEV_2022, CAR.IONIQ_PHEV_2019, CAR.TUCSON_HYBRID_4TH_GEN, CAR.KIA_SPORTAGE_HYBRID_5TH_GEN, CAR.KIA_SORENTO_PHEV_4TH_GEN} # these cars use a different gas signal +EV_CAR = {CAR.IONIQ_EV_2020, CAR.IONIQ_EV_LTD, CAR.KONA_EV, CAR.KIA_NIRO_EV, CAR.KONA_EV_2022, CAR.KIA_EV6, CAR.IONIQ_5} # these cars require a special panda safety mode due to missing counters and checksums in the messages -LEGACY_SAFETY_MODE_CAR = {CAR.HYUNDAI_GENESIS, CAR.IONIQ_EV_2020, CAR.IONIQ_EV_LTD, CAR.IONIQ_PHEV, CAR.IONIQ, CAR.KONA_EV, CAR.KIA_SORENTO, CAR.SONATA_LF, CAR.KIA_OPTIMA, CAR.VELOSTER, CAR.KIA_STINGER, CAR.GENESIS_G70, CAR.GENESIS_G80, CAR.KIA_CEED, CAR.ELANTRA, CAR.IONIQ_HEV_2022} +LEGACY_SAFETY_MODE_CAR = {CAR.HYUNDAI_GENESIS, CAR.IONIQ_EV_2020, CAR.IONIQ_EV_LTD, CAR.IONIQ_PHEV, CAR.IONIQ, CAR.KONA_EV, CAR.KIA_SORENTO, CAR.SONATA_LF, CAR.KIA_OPTIMA_G4, CAR.KIA_OPTIMA_G4_FL, CAR.VELOSTER, CAR.KIA_STINGER, CAR.GENESIS_G70, CAR.GENESIS_G80, CAR.KIA_CEED, CAR.ELANTRA, CAR.IONIQ_HEV_2022} # If 0x500 is present on bus 1 it probably has a Mando radar outputting radar points. # If no points are outputted by default it might be possible to turn it on using selfdrive/debug/hyundai_enable_radar_points.py @@ -1052,40 +1540,51 @@ DBC = { CAR.ELANTRA: dbc_dict('hyundai_kia_generic', None), CAR.ELANTRA_2021: dbc_dict('hyundai_kia_generic', None), CAR.ELANTRA_HEV_2021: dbc_dict('hyundai_kia_generic', None), - CAR.ELANTRA_GT_I30: dbc_dict('hyundai_kia_generic', None), CAR.GENESIS_G70: dbc_dict('hyundai_kia_generic', None), - CAR.GENESIS_G70_2020: dbc_dict('hyundai_kia_generic', 'hyundai_kia_mando_front_radar'), + CAR.GENESIS_G70_2020: dbc_dict('hyundai_kia_generic', 'hyundai_kia_mando_front_radar_generated'), CAR.GENESIS_G80: dbc_dict('hyundai_kia_generic', None), CAR.GENESIS_G90: dbc_dict('hyundai_kia_generic', None), CAR.HYUNDAI_GENESIS: dbc_dict('hyundai_kia_generic', None), + CAR.IONIQ_PHEV_2019: dbc_dict('hyundai_kia_generic', None), CAR.IONIQ_PHEV: dbc_dict('hyundai_kia_generic', None), CAR.IONIQ_EV_2020: dbc_dict('hyundai_kia_generic', None), - CAR.IONIQ_EV_LTD: dbc_dict('hyundai_kia_generic', 'hyundai_kia_mando_front_radar'), + CAR.IONIQ_EV_LTD: dbc_dict('hyundai_kia_generic', 'hyundai_kia_mando_front_radar_generated'), CAR.IONIQ: dbc_dict('hyundai_kia_generic', None), CAR.IONIQ_HEV_2022: dbc_dict('hyundai_kia_generic', None), CAR.KIA_FORTE: dbc_dict('hyundai_kia_generic', None), CAR.KIA_K5_2021: dbc_dict('hyundai_kia_generic', None), - CAR.KIA_NIRO_EV: dbc_dict('hyundai_kia_generic', 'hyundai_kia_mando_front_radar'), - CAR.KIA_NIRO_HEV: dbc_dict('hyundai_kia_generic', 'hyundai_kia_mando_front_radar'), + CAR.KIA_NIRO_EV: dbc_dict('hyundai_kia_generic', 'hyundai_kia_mando_front_radar_generated'), + CAR.KIA_NIRO_PHEV: dbc_dict('hyundai_kia_generic', 'hyundai_kia_mando_front_radar_generated'), CAR.KIA_NIRO_HEV_2021: dbc_dict('hyundai_kia_generic', None), - CAR.KIA_OPTIMA: dbc_dict('hyundai_kia_generic', None), + CAR.KIA_OPTIMA_G4: dbc_dict('hyundai_kia_generic', None), + CAR.KIA_OPTIMA_G4_FL: dbc_dict('hyundai_kia_generic', None), CAR.KIA_OPTIMA_H: dbc_dict('hyundai_kia_generic', None), CAR.KIA_SELTOS: dbc_dict('hyundai_kia_generic', None), CAR.KIA_SORENTO: dbc_dict('hyundai_kia_generic', None), # Has 0x5XX messages, but different format CAR.KIA_STINGER: dbc_dict('hyundai_kia_generic', None), + CAR.KIA_STINGER_2022: dbc_dict('hyundai_kia_generic', None), CAR.KONA: dbc_dict('hyundai_kia_generic', None), CAR.KONA_EV: dbc_dict('hyundai_kia_generic', None), + CAR.KONA_EV_2022: dbc_dict('hyundai_kia_generic', None), CAR.KONA_HEV: dbc_dict('hyundai_kia_generic', None), - CAR.SANTA_FE: dbc_dict('hyundai_kia_generic', 'hyundai_kia_mando_front_radar'), + CAR.SANTA_FE: dbc_dict('hyundai_kia_generic', 'hyundai_kia_mando_front_radar_generated'), CAR.SANTA_FE_2022: dbc_dict('hyundai_kia_generic', None), CAR.SANTA_FE_HEV_2022: dbc_dict('hyundai_kia_generic', None), CAR.SANTA_FE_PHEV_2022: dbc_dict('hyundai_kia_generic', None), - CAR.SONATA: dbc_dict('hyundai_kia_generic', 'hyundai_kia_mando_front_radar'), + CAR.SONATA: dbc_dict('hyundai_kia_generic', 'hyundai_kia_mando_front_radar_generated'), CAR.SONATA_LF: dbc_dict('hyundai_kia_generic', None), # Has 0x5XX messages, but different format - CAR.PALISADE: dbc_dict('hyundai_kia_generic', 'hyundai_kia_mando_front_radar'), + CAR.TUCSON: dbc_dict('hyundai_kia_generic', None), + CAR.PALISADE: dbc_dict('hyundai_kia_generic', 'hyundai_kia_mando_front_radar_generated'), CAR.VELOSTER: dbc_dict('hyundai_kia_generic', None), CAR.KIA_CEED: dbc_dict('hyundai_kia_generic', None), - CAR.SONATA_HYBRID: dbc_dict('hyundai_kia_generic', 'hyundai_kia_mando_front_radar'), + CAR.KIA_EV6: dbc_dict('hyundai_canfd', None), + CAR.SONATA_HYBRID: dbc_dict('hyundai_kia_generic', 'hyundai_kia_mando_front_radar_generated'), + CAR.TUCSON_4TH_GEN: dbc_dict('hyundai_canfd', None), + CAR.TUCSON_HYBRID_4TH_GEN: dbc_dict('hyundai_canfd', None), + CAR.IONIQ_5: dbc_dict('hyundai_canfd', None), + CAR.SANTA_CRUZ_1ST_GEN: dbc_dict('hyundai_canfd', None), + CAR.KIA_SPORTAGE_5TH_GEN: dbc_dict('hyundai_canfd', None), + CAR.KIA_SPORTAGE_HYBRID_5TH_GEN: dbc_dict('hyundai_canfd', None), + CAR.GENESIS_GV70_1ST_GEN: dbc_dict('hyundai_canfd', None), + CAR.KIA_SORENTO_PHEV_4TH_GEN: dbc_dict('hyundai_canfd', None), } - -STEER_THRESHOLD = 150 diff --git a/selfdrive/car/interfaces.py b/selfdrive/car/interfaces.py index 98ede7fad1..0458178ee3 100644 --- a/selfdrive/car/interfaces.py +++ b/selfdrive/car/interfaces.py @@ -1,27 +1,60 @@ +import yaml import os import time from abc import abstractmethod, ABC -from typing import Dict, Tuple, List +from typing import Any, Dict, Optional, Tuple, List, Callable from cereal import car +from common.basedir import BASEDIR +from common.conversions import Conversions as CV from common.kalman.simple_kalman import KF1D +from common.numpy_fast import interp from common.realtime import DT_CTRL -from selfdrive.car import gen_empty_fingerprint -from selfdrive.config import Conversions as CV -from selfdrive.controls.lib.drive_helpers import V_CRUISE_MAX +from selfdrive.car import apply_hysteresis, gen_empty_fingerprint, scale_rot_inertia, scale_tire_stiffness +from selfdrive.controls.lib.drive_helpers import V_CRUISE_MAX, apply_center_deadzone from selfdrive.controls.lib.events import Events from selfdrive.controls.lib.vehicle_model import VehicleModel +ButtonType = car.CarState.ButtonEvent.Type GearShifter = car.CarState.GearShifter EventName = car.CarEvent.EventName +TorqueFromLateralAccelCallbackType = Callable[[float, car.CarParams.LateralTorqueTuning, float, float, bool], float] MAX_CTRL_SPEED = (V_CRUISE_MAX + 4) * CV.KPH_TO_MS ACCEL_MAX = 2.0 ACCEL_MIN = -3.5 +FRICTION_THRESHOLD = 0.3 +TORQUE_PARAMS_PATH = os.path.join(BASEDIR, 'selfdrive/car/torque_data/params.yaml') +TORQUE_OVERRIDE_PATH = os.path.join(BASEDIR, 'selfdrive/car/torque_data/override.yaml') +TORQUE_SUBSTITUTE_PATH = os.path.join(BASEDIR, 'selfdrive/car/torque_data/substitute.yaml') + + +def get_torque_params(candidate): + with open(TORQUE_SUBSTITUTE_PATH) as f: + sub = yaml.load(f, Loader=yaml.CSafeLoader) + if candidate in sub: + candidate = sub[candidate] + + with open(TORQUE_PARAMS_PATH) as f: + params = yaml.load(f, Loader=yaml.CSafeLoader) + with open(TORQUE_OVERRIDE_PATH) as f: + override = yaml.load(f, Loader=yaml.CSafeLoader) + + # Ensure no overlap + if sum([candidate in x for x in [sub, params, override]]) > 1: + raise RuntimeError(f'{candidate} is defined twice in torque config') + + if candidate in override: + out = override[candidate] + elif candidate in params: + out = params[candidate] + else: + raise NotImplementedError(f"Did not find torque params for {candidate}") + return {key: out[i] for i, key in enumerate(params['legend'])} -# generic car and radar interfaces +# generic car and radar interfaces class CarInterfaceBase(ABC): def __init__(self, CP, CarController, CarState): @@ -32,13 +65,19 @@ class CarInterfaceBase(ABC): self.steering_unpressed = 0 self.low_speed_alert = False self.silent_steer_warning = True + self.v_ego_cluster_seen = False + self.CS = None + self.can_parsers = [] if CarState is not None: self.CS = CarState(CP) + self.cp = self.CS.get_can_parser(CP) self.cp_cam = self.CS.get_cam_can_parser(CP) + self.cp_adas = self.CS.get_adas_can_parser(CP) self.cp_body = self.CS.get_body_can_parser(CP) self.cp_loopback = self.CS.get_loopback_can_parser(CP) + self.can_parsers = [self.cp, self.cp_cam, self.cp_adas, self.cp_body, self.cp_loopback] self.CC = None if CarController is not None: @@ -48,10 +87,34 @@ class CarInterfaceBase(ABC): def get_pid_accel_limits(CP, current_speed, cruise_speed): return ACCEL_MIN, ACCEL_MAX + @classmethod + def get_params(cls, candidate: str, fingerprint: Optional[Dict[int, Dict[int, int]]] = None, car_fw: Optional[List[car.CarParams.CarFw]] = None, experimental_long: bool = False): + if fingerprint is None: + fingerprint = gen_empty_fingerprint() + + if car_fw is None: + car_fw = list() + + ret = CarInterfaceBase.get_std_params(candidate) + ret = cls._get_params(ret, candidate, fingerprint, car_fw, experimental_long) + + # Set common params using fields set by the car interface + # TODO: get actual value, for now starting with reasonable value for + # civic and scaling by mass and wheelbase + ret.rotationalInertia = scale_rot_inertia(ret.mass, ret.wheelbase) + + # TODO: some car interfaces set stiffness factor + if ret.tireStiffnessFront == 0 or ret.tireStiffnessRear == 0: + # TODO: start from empirically derived lateral slip stiffness for the civic and scale by + # mass and CG position, so all cars will have approximately similar dyn behaviors + ret.tireStiffnessFront, ret.tireStiffnessRear = scale_tire_stiffness(ret.mass, ret.wheelbase, ret.centerToFront) + + return ret + @staticmethod @abstractmethod - def get_params(candidate, fingerprint=gen_empty_fingerprint(), car_fw=None): - pass + def _get_params(ret: car.CarParams, candidate: str, fingerprint: Dict[int, Dict[int, int]], car_fw: List[car.CarParams.CarFw], experimental_long: bool): + raise NotImplementedError @staticmethod def init(CP, logcan, sendcan): @@ -63,21 +126,35 @@ class CarInterfaceBase(ABC): # TODO: something with lateralPlan.curvatureRates return desired_angle * (v_ego**2) - @classmethod - def get_steer_feedforward_function(cls): - return cls.get_steer_feedforward_default + def get_steer_feedforward_function(self): + return self.get_steer_feedforward_default + + @staticmethod + def torque_from_lateral_accel_linear(lateral_accel_value, torque_params, lateral_accel_error, lateral_accel_deadzone, friction_compensation): + # The default is a linear relationship between torque and lateral acceleration (accounting for road roll and steering friction) + friction_interp = interp( + apply_center_deadzone(lateral_accel_error, lateral_accel_deadzone), + [-FRICTION_THRESHOLD, FRICTION_THRESHOLD], + [-torque_params.friction, torque_params.friction] + ) + friction = friction_interp if friction_compensation else 0.0 + return (lateral_accel_value / torque_params.latAccelFactor) + friction + + def torque_from_lateral_accel(self) -> TorqueFromLateralAccelCallbackType: + return self.torque_from_lateral_accel_linear # returns a set of default params to avoid repetition in car specific params @staticmethod - def get_std_params(candidate, fingerprint): + def get_std_params(candidate): ret = car.CarParams.new_message() ret.carFingerprint = candidate - ret.unsafeMode = 0 # see panda/board/safety_declarations.h for allowed values + + # Car docs fields + ret.maxLateralAccel = get_torque_params(candidate)['MAX_LAT_ACCEL_MEASURED'] + ret.autoResumeSng = True # describes whether car can resume from a stop automatically # standard ALC params ret.steerControlType = car.CarParams.SteerControlType.torque - ret.steerMaxBP = [0.] - ret.steerMaxV = [1.] ret.minSteerSpeed = 0. ret.wheelSpeedFactor = 1.0 @@ -88,7 +165,7 @@ class CarInterfaceBase(ABC): ret.stopAccel = -2.0 ret.stoppingDecelRate = 0.8 # brake_travel/s while trying to stop ret.vEgoStopping = 0.5 - ret.vEgoStarting = 0.5 # needs to be >= vEgoStopping to avoid state transition oscillation + ret.vEgoStarting = 0.5 ret.stoppingControl = True ret.longitudinalTuning.deadzoneBP = [0.] ret.longitudinalTuning.deadzoneV = [0.] @@ -103,15 +180,63 @@ class CarInterfaceBase(ABC): ret.steerLimitTimer = 1.0 return ret + @staticmethod + def configure_torque_tune(candidate, tune, steering_angle_deadzone_deg=0.0, use_steering_angle=True): + params = get_torque_params(candidate) + + tune.init('torque') + tune.torque.useSteeringAngle = use_steering_angle + tune.torque.kp = 1.0 + tune.torque.kf = 1.0 + tune.torque.ki = 0.1 + tune.torque.friction = params['FRICTION'] + tune.torque.latAccelFactor = params['LAT_ACCEL_FACTOR'] + tune.torque.latAccelOffset = 0.0 + tune.torque.steeringAngleDeadzoneDeg = steering_angle_deadzone_deg + @abstractmethod - def update(self, c: car.CarControl, can_strings: List[bytes]) -> car.CarState: + def _update(self, c: car.CarControl) -> car.CarState: pass + def update(self, c: car.CarControl, can_strings: List[bytes]) -> car.CarState: + # parse can + for cp in self.can_parsers: + if cp is not None: + cp.update_strings(can_strings) + + # get CarState + ret = self._update(c) + + ret.canValid = all(cp.can_valid for cp in self.can_parsers if cp is not None) + ret.canTimeout = any(cp.bus_timeout for cp in self.can_parsers if cp is not None) + + if ret.vEgoCluster == 0.0 and not self.v_ego_cluster_seen: + ret.vEgoCluster = ret.vEgo + else: + self.v_ego_cluster_seen = True + + # Many cars apply hysteresis to the ego dash speed + if self.CS is not None: + ret.vEgoCluster = apply_hysteresis(ret.vEgoCluster, self.CS.out.vEgoCluster, self.CS.cluster_speed_hyst_gap) + if abs(ret.vEgo) < self.CS.cluster_min_speed: + ret.vEgoCluster = 0.0 + + if ret.cruiseState.speedCluster == 0: + ret.cruiseState.speedCluster = ret.cruiseState.speed + + # copy back for next iteration + reader = ret.as_reader() + if self.CS is not None: + self.CS.out = reader + + return reader + @abstractmethod def apply(self, c: car.CarControl) -> Tuple[car.CarControl.Actuators, List[bytes]]: pass - def create_common_events(self, cs_out, extra_gears=None, pcm_enable=True): + def create_common_events(self, cs_out, extra_gears=None, pcm_enable=True, allow_enable=True, + enable_buttons=(ButtonType.accelCruise, ButtonType.decelCruise)): events = Events() if cs_out.doorOpen: @@ -127,8 +252,6 @@ class CarInterfaceBase(ABC): events.add(EventName.wrongCarMode) if cs_out.espDisabled: events.add(EventName.espDisabled) - if cs_out.gasPressed: - events.add(EventName.gasPressed) if cs_out.stockFcw: events.add(EventName.stockFcw) if cs_out.stockAeb: @@ -139,11 +262,25 @@ class CarInterfaceBase(ABC): events.add(EventName.wrongCruiseMode) if cs_out.brakeHoldActive and self.CP.openpilotLongitudinalControl: events.add(EventName.brakeHold) - + if cs_out.parkingBrake: + events.add(EventName.parkBrake) + if cs_out.accFaulted: + events.add(EventName.accFaulted) + if cs_out.steeringPressed: + events.add(EventName.steerOverride) + + # Handle button presses + for b in cs_out.buttonEvents: + # Enable OP long on falling edge of enable buttons (defaults to accelCruise and decelCruise, overridable per-port) + if not self.CP.pcmCruise and (b.type in enable_buttons and not b.pressed): + events.add(EventName.buttonEnable) + # Disable on rising and falling edge of cancel for both stock and OP long + if b.type == ButtonType.cancel: + events.add(EventName.buttonCancel) # Handle permanent and temporary steering faults self.steering_unpressed = 0 if cs_out.steeringPressed else self.steering_unpressed + 1 - if cs_out.steerWarning: + if cs_out.steerFaultTemporary: # if the user overrode recently, show a less harsh alert if self.silent_steer_warning or cs_out.standstill or self.steering_unpressed < int(1.5 / DT_CTRL): self.silent_steer_warning = True @@ -152,17 +289,13 @@ class CarInterfaceBase(ABC): events.add(EventName.steerTempUnavailable) else: self.silent_steer_warning = False - if cs_out.steerError: + if cs_out.steerFaultPermanent: events.add(EventName.steerUnavailable) - # Disable on rising edge of gas or brake. Also disable on brake when speed > 0. - if (cs_out.gasPressed and not self.CS.out.gasPressed) or \ - (cs_out.brakePressed and (not self.CS.out.brakePressed or not cs_out.standstill)): - events.add(EventName.pedalPressed) - # we engage when pcm is active (rising edge) + # enabling can optionally be blocked by the car interface if pcm_enable: - if cs_out.cruiseState.enabled and not self.CS.out.cruiseState.enabled: + if cs_out.cruiseState.enabled and not self.CS.out.cruiseState.enabled and allow_enable: events.add(EventName.pcmEnable) elif not cs_out.cruiseState.enabled: events.add(EventName.pcmDisable) @@ -172,6 +305,7 @@ class CarInterfaceBase(ABC): class RadarInterfaceBase(ABC): def __init__(self, CP): + self.rcp = None self.pts = {} self.delay = 0 self.radar_ts = CP.radarTimeStep @@ -195,13 +329,15 @@ class CarStateBase(ABC): self.right_blinker_cnt = 0 self.left_blinker_prev = False self.right_blinker_prev = False + self.cluster_speed_hyst_gap = 0.0 + self.cluster_min_speed = 0.0 # min speed before dropping to 0 - # Q = np.matrix([[10.0, 0.0], [0.0, 100.0]]) - # R = 1e3 + # Q = np.matrix([[0.0, 0.0], [0.0, 100.0]]) + # R = 0.3 self.v_ego_kf = KF1D(x0=[[0.0], [0.0]], A=[[1.0, DT_CTRL], [0.0, 1.0]], C=[1.0, 0.0], - K=[[0.12287673], [0.29666309]]) + K=[[0.17406039], [1.65925647]]) def update_speed_kf(self, v_ego_raw): if abs(v_ego_raw - self.v_ego_kf.x[0][0]) > 2.0: # Prevent large accelerations when car starts at non zero speed @@ -252,18 +388,31 @@ class CarStateBase(ABC): return bool(left_blinker_stalk or self.left_blinker_cnt > 0), bool(right_blinker_stalk or self.right_blinker_cnt > 0) @staticmethod - def parse_gear_shifter(gear: str) -> car.CarState.GearShifter: + def parse_gear_shifter(gear: Optional[str]) -> car.CarState.GearShifter: + if gear is None: + return GearShifter.unknown + d: Dict[str, car.CarState.GearShifter] = { - 'P': GearShifter.park, 'R': GearShifter.reverse, 'N': GearShifter.neutral, - 'E': GearShifter.eco, 'T': GearShifter.manumatic, 'D': GearShifter.drive, - 'S': GearShifter.sport, 'L': GearShifter.low, 'B': GearShifter.brake + 'P': GearShifter.park, 'PARK': GearShifter.park, + 'R': GearShifter.reverse, 'REVERSE': GearShifter.reverse, + 'N': GearShifter.neutral, 'NEUTRAL': GearShifter.neutral, + 'E': GearShifter.eco, 'ECO': GearShifter.eco, + 'T': GearShifter.manumatic, 'MANUAL': GearShifter.manumatic, + 'D': GearShifter.drive, 'DRIVE': GearShifter.drive, + 'S': GearShifter.sport, 'SPORT': GearShifter.sport, + 'L': GearShifter.low, 'LOW': GearShifter.low, + 'B': GearShifter.brake, 'BRAKE': GearShifter.brake, } - return d.get(gear, GearShifter.unknown) + return d.get(gear.upper(), GearShifter.unknown) @staticmethod def get_cam_can_parser(CP): return None + @staticmethod + def get_adas_can_parser(CP): + return None + @staticmethod def get_body_can_parser(CP): return None @@ -271,3 +420,31 @@ class CarStateBase(ABC): @staticmethod def get_loopback_can_parser(CP): return None + + +# interface-specific helpers + +def get_interface_attr(attr: str, combine_brands: bool = False, ignore_none: bool = False) -> Dict[str, Any]: + # read all the folders in selfdrive/car and return a dict where: + # - keys are all the car models or brand names + # - values are attr values from all car folders + result = {} + for car_folder in sorted([x[0] for x in os.walk(BASEDIR + '/selfdrive/car')]): + try: + brand_name = car_folder.split('/')[-1] + brand_values = __import__(f'selfdrive.car.{brand_name}.values', fromlist=[attr]) + if hasattr(brand_values, attr) or not ignore_none: + attr_data = getattr(brand_values, attr, None) + else: + continue + + if combine_brands: + if isinstance(attr_data, dict): + for f, v in attr_data.items(): + result[f] = v + else: + result[brand_name] = attr_data + except (ImportError, OSError): + pass + + return result diff --git a/selfdrive/car/isotp_parallel_query.py b/selfdrive/car/isotp_parallel_query.py index 1209a8f1a1..d9c658a14c 100644 --- a/selfdrive/car/isotp_parallel_query.py +++ b/selfdrive/car/isotp_parallel_query.py @@ -1,32 +1,29 @@ import time from collections import defaultdict from functools import partial -from typing import Optional import cereal.messaging as messaging -from selfdrive.swaglog import cloudlog +from system.swaglog import cloudlog from selfdrive.boardd.boardd import can_list_to_can_capnp from panda.python.uds import CanClient, IsoTpMessage, FUNCTIONAL_ADDRS, get_rx_addr_for_tx_addr class IsoTpParallelQuery: - def __init__(self, sendcan, logcan, bus, addrs, request, response, response_offset=0x8, functional_addr=False, debug=False): + def __init__(self, sendcan, logcan, bus, addrs, request, response, response_offset=0x8, functional_addrs=None, debug=False, response_pending_timeout=10): self.sendcan = sendcan self.logcan = logcan self.bus = bus self.request = request self.response = response + self.functional_addrs = functional_addrs or [] self.debug = debug - self.functional_addr = functional_addr + self.response_pending_timeout = response_pending_timeout - self.real_addrs = [] - for a in addrs: - if isinstance(a, tuple): - self.real_addrs.append(a) - else: - self.real_addrs.append((a, None)) + real_addrs = [a if isinstance(a, tuple) else (a, None) for a in addrs] + for tx_addr, _ in real_addrs: + assert tx_addr not in FUNCTIONAL_ADDRS, f"Functional address should be defined in functional_addrs: {hex(tx_addr)}" - self.msg_addrs = {tx_addr: get_rx_addr_for_tx_addr(tx_addr[0], rx_offset=response_offset) for tx_addr in self.real_addrs} + self.msg_addrs = {tx_addr: get_rx_addr_for_tx_addr(tx_addr[0], rx_offset=response_offset) for tx_addr in real_addrs} self.msg_buffer = defaultdict(list) def rx(self): @@ -35,13 +32,8 @@ class IsoTpParallelQuery: for packet in can_packets: for msg in packet.can: - if msg.src == self.bus: - if self.functional_addr: - if (0x7E8 <= msg.address <= 0x7EF) or (0x18DAF100 <= msg.address <= 0x18DAF1FF): - fn_addr = next(a for a in FUNCTIONAL_ADDRS if msg.address - a <= 32) - self.msg_buffer[fn_addr].append((msg.address, msg.busTime, msg.dat, msg.src)) - elif msg.address in self.msg_addrs.values(): - self.msg_buffer[msg.address].append((msg.address, msg.busTime, msg.dat, msg.src)) + if msg.src == self.bus and msg.address in self.msg_addrs.values(): + self.msg_buffer[msg.address].append((msg.address, msg.busTime, msg.dat, msg.src)) def _can_tx(self, tx_addr, dat, bus): """Helper function to send single message""" @@ -71,10 +63,17 @@ class IsoTpParallelQuery: messaging.drain_sock(self.logcan) self.msg_buffer = defaultdict(list) - def get_data(self, timeout, total_timeout=None): - if total_timeout is None: - total_timeout = 10 * timeout + def _create_isotp_msg(self, tx_addr, sub_addr, rx_addr): + can_client = CanClient(self._can_tx, partial(self._can_rx, rx_addr, sub_addr=sub_addr), tx_addr, rx_addr, + self.bus, sub_addr=sub_addr, debug=self.debug) + max_len = 8 if sub_addr is None else 7 + # uses iso-tp frame separation time of 10 ms + # TODO: use single_frame_mode so ECUs can send as fast as they want, + # as well as reduces chances we process messages from previous queries + return IsoTpMessage(can_client, timeout=0, separation_time=0.01, debug=self.debug, max_len=max_len) + + def get_data(self, timeout, total_timeout=60.): self._drain_rx() # Create message objects @@ -82,25 +81,22 @@ class IsoTpParallelQuery: request_counter = {} request_done = {} for tx_addr, rx_addr in self.msg_addrs.items(): - # rx_addr not set when using functional tx addr - id_addr = rx_addr or tx_addr[0] - sub_addr = tx_addr[1] - - can_client = CanClient(self._can_tx, partial(self._can_rx, id_addr, sub_addr=sub_addr), tx_addr[0], rx_addr, - self.bus, sub_addr=sub_addr, debug=self.debug) - - max_len = 8 if sub_addr is None else 7 - - msg = IsoTpMessage(can_client, timeout=0, max_len=max_len, debug=self.debug) - msg.send(self.request[0]) - - msgs[tx_addr] = msg + msgs[tx_addr] = self._create_isotp_msg(*tx_addr, rx_addr) request_counter[tx_addr] = 0 request_done[tx_addr] = False + # Send first request to functional addrs, subsequent responses are handled on physical addrs + if len(self.functional_addrs): + for addr in self.functional_addrs: + self._create_isotp_msg(addr, None, -1).send(self.request[0]) + + # If querying functional addrs, set up physical IsoTpMessages to send consecutive frames + for msg in msgs.values(): + msg.send(self.request[0], setup_only=len(self.functional_addrs) > 0) + results = {} start_time = time.monotonic() - last_response_time = start_time + response_timeouts = {tx_addr: start_time + timeout for tx_addr in self.msg_addrs} while True: self.rx() @@ -109,12 +105,15 @@ class IsoTpParallelQuery: for tx_addr, msg in msgs.items(): try: - dat: Optional[bytes] = msg.recv() + dat, updated = msg.recv() except Exception: - cloudlog.exception("Error processing UDS response") + cloudlog.exception(f"Error processing UDS response: {tx_addr}") request_done[tx_addr] = True continue + if updated: + response_timeouts[tx_addr] = time.monotonic() + timeout + if not dat: continue @@ -123,7 +122,6 @@ class IsoTpParallelQuery: response_valid = dat[:len(expected_response)] == expected_response if response_valid: - last_response_time = time.monotonic() if counter + 1 < len(self.request): msg.send(self.request[counter + 1]) request_counter[tx_addr] += 1 @@ -131,18 +129,25 @@ class IsoTpParallelQuery: results[tx_addr] = dat[len(expected_response):] request_done[tx_addr] = True else: - request_done[tx_addr] = True - cloudlog.warning(f"iso-tp query bad response: 0x{dat.hex()}") + error_code = dat[2] if len(dat) > 2 else -1 + if error_code == 0x78: + response_timeouts[tx_addr] = time.monotonic() + self.response_pending_timeout + if self.debug: + cloudlog.warning(f"iso-tp query response pending: {tx_addr}") + else: + response_timeouts[tx_addr] = 0 + request_done[tx_addr] = True + cloudlog.error(f"iso-tp query bad response: {tx_addr} - 0x{dat.hex()}") cur_time = time.monotonic() - if cur_time - last_response_time > timeout: + if cur_time - max(response_timeouts.values()) > 0: for tx_addr in msgs: - if (request_counter[tx_addr] > 0) and (not request_done[tx_addr]): - cloudlog.warning(f"iso-tp query timeout after receiving response: {tx_addr}") + if request_counter[tx_addr] > 0 and not request_done[tx_addr]: + cloudlog.error(f"iso-tp query timeout after receiving response: {tx_addr}") break if cur_time - start_time > total_timeout: - cloudlog.warning("iso-tp query timeout while receiving data") + cloudlog.error("iso-tp query timeout while receiving data") break return results diff --git a/selfdrive/car/mazda/carcontroller.py b/selfdrive/car/mazda/carcontroller.py index 60bb620377..2add59ccb0 100644 --- a/selfdrive/car/mazda/carcontroller.py +++ b/selfdrive/car/mazda/carcontroller.py @@ -1,65 +1,64 @@ from cereal import car from opendbc.can.packer import CANPacker +from selfdrive.car import apply_std_steer_torque_limits from selfdrive.car.mazda import mazdacan from selfdrive.car.mazda.values import CarControllerParams, Buttons -from selfdrive.car import apply_std_steer_torque_limits VisualAlert = car.CarControl.HUDControl.VisualAlert -class CarController(): + +class CarController: def __init__(self, dbc_name, CP, VM): + self.CP = CP self.apply_steer_last = 0 self.packer = CANPacker(dbc_name) - self.steer_rate_limited = False self.brake_counter = 0 + self.frame = 0 - def update(self, c, CS, frame): + def update(self, CC, CS): can_sends = [] apply_steer = 0 - self.steer_rate_limited = False - if c.active: + if CC.latActive: # calculate steer and also set limits due to driver torque - new_steer = int(round(c.actuators.steer * CarControllerParams.STEER_MAX)) + new_steer = int(round(CC.actuators.steer * CarControllerParams.STEER_MAX)) apply_steer = apply_std_steer_torque_limits(new_steer, self.apply_steer_last, CS.out.steeringTorque, CarControllerParams) - self.steer_rate_limited = new_steer != apply_steer - if CS.out.standstill and frame % 5 == 0: - # Mazda Stop and Go requires a RES button (or gas) press if the car stops more than 3 seconds - # Send Resume button at 20hz if we're engaged at standstill to support full stop and go! - # TODO: improve the resume trigger logic by looking at actual radar data - can_sends.append(mazdacan.create_button_cmd(self.packer, CS.CP.carFingerprint, CS.crz_btns_counter, Buttons.RESUME)) - - if c.cruiseControl.cancel or (CS.out.cruiseState.enabled and not c.enabled): + if CC.cruiseControl.cancel: # If brake is pressed, let us wait >70ms before trying to disable crz to avoid # a race condition with the stock system, where the second cancel from openpilot # will disable the crz 'main on'. crz ctrl msg runs at 50hz. 70ms allows us to # read 3 messages and most likely sync state before we attempt cancel. self.brake_counter = self.brake_counter + 1 - if frame % 10 == 0 and not (CS.out.brakePressed and self.brake_counter < 7): + if self.frame % 10 == 0 and not (CS.out.brakePressed and self.brake_counter < 7): # Cancel Stock ACC if it's enabled while OP is disengaged # Send at a rate of 10hz until we sync with stock ACC state - can_sends.append(mazdacan.create_button_cmd(self.packer, CS.CP.carFingerprint, CS.crz_btns_counter, Buttons.CANCEL)) + can_sends.append(mazdacan.create_button_cmd(self.packer, self.CP.carFingerprint, CS.crz_btns_counter, Buttons.CANCEL)) else: self.brake_counter = 0 + if CC.cruiseControl.resume and self.frame % 5 == 0: + # Mazda Stop and Go requires a RES button (or gas) press if the car stops more than 3 seconds + # Send Resume button when planner wants car to move + can_sends.append(mazdacan.create_button_cmd(self.packer, self.CP.carFingerprint, CS.crz_btns_counter, Buttons.RESUME)) self.apply_steer_last = apply_steer # send HUD alerts - if frame % 50 == 0: - ldw = c.hudControl.visualAlert == VisualAlert.ldw - steer_required = c.hudControl.visualAlert == VisualAlert.steerRequired + if self.frame % 50 == 0: + ldw = CC.hudControl.visualAlert == VisualAlert.ldw + steer_required = CC.hudControl.visualAlert == VisualAlert.steerRequired # TODO: find a way to silence audible warnings so we can add more hud alerts steer_required = steer_required and CS.lkas_allowed_speed can_sends.append(mazdacan.create_alert_command(self.packer, CS.cam_laneinfo, ldw, steer_required)) # send steering command - can_sends.append(mazdacan.create_steering_control(self.packer, CS.CP.carFingerprint, - frame, apply_steer, CS.cam_lkas)) + can_sends.append(mazdacan.create_steering_control(self.packer, self.CP.carFingerprint, + self.frame, apply_steer, CS.cam_lkas)) - new_actuators = c.actuators.copy() + new_actuators = CC.actuators.copy() new_actuators.steer = apply_steer / CarControllerParams.STEER_MAX + self.frame += 1 return new_actuators, can_sends diff --git a/selfdrive/car/mazda/carstate.py b/selfdrive/car/mazda/carstate.py index feb1147549..944d79809b 100644 --- a/selfdrive/car/mazda/carstate.py +++ b/selfdrive/car/mazda/carstate.py @@ -1,5 +1,5 @@ from cereal import car -from selfdrive.config import Conversions as CV +from common.conversions import Conversions as CV from opendbc.can.can_define import CANDefine from opendbc.can.parser import CANParser from selfdrive.car.interfaces import CarStateBase @@ -72,11 +72,14 @@ class CarState(CarStateBase): self.lkas_allowed_speed = True elif speed_kph < LKAS_LIMITS.DISABLE_SPEED: self.lkas_allowed_speed = False + else: + self.lkas_allowed_speed = True # TODO: the signal used for available seems to be the adaptive cruise signal, instead of the main on # it should be used for carState.cruiseState.nonAdaptive instead ret.cruiseState.available = cp.vl["CRZ_CTRL"]["CRZ_AVAILABLE"] == 1 ret.cruiseState.enabled = cp.vl["CRZ_CTRL"]["CRZ_ACTIVE"] == 1 + ret.cruiseState.standstill = cp.vl["PEDALS"]["STANDSTILL"] == 1 ret.cruiseState.speed = cp.vl["CRZ_EVENTS"]["CRZ_SPEED"] * CV.KPH_TO_MS if ret.cruiseState.enabled: @@ -88,7 +91,7 @@ class CarState(CarStateBase): # Check if LKAS is disabled due to lack of driver torque when all other states indicate # it should be enabled (steer lockout). Don't warn until we actually get lkas active # and lose it again, i.e, after initial lkas activation - ret.steerWarning = self.lkas_allowed_speed and lkas_blocked + ret.steerFaultTemporary = self.lkas_allowed_speed and lkas_blocked self.acc_active_last = ret.cruiseState.enabled @@ -98,7 +101,7 @@ class CarState(CarStateBase): self.lkas_disabled = cp_cam.vl["CAM_LANEINFO"]["LANE_LINES"] == 0 self.cam_lkas = cp_cam.vl["CAM_LKAS"] self.cam_laneinfo = cp_cam.vl["CAM_LANEINFO"] - ret.steerError = cp_cam.vl["CAM_LKAS"]["ERR_BIT_1"] == 1 + ret.steerFaultPermanent = cp_cam.vl["CAM_LKAS"]["ERR_BIT_1"] == 1 return ret diff --git a/selfdrive/car/mazda/interface.py b/selfdrive/car/mazda/interface.py index fb8edd6f42..fdd2439ff9 100755 --- a/selfdrive/car/mazda/interface.py +++ b/selfdrive/car/mazda/interface.py @@ -1,8 +1,8 @@ #!/usr/bin/env python3 from cereal import car -from selfdrive.config import Conversions as CV +from common.conversions import Conversions as CV from selfdrive.car.mazda.values import CAR, LKAS_LIMITS -from selfdrive.car import STD_CARGO_KG, scale_rot_inertia, scale_tire_stiffness, gen_empty_fingerprint, get_safety_config +from selfdrive.car import STD_CARGO_KG, scale_tire_stiffness, get_safety_config from selfdrive.car.interfaces import CarInterfaceBase ButtonType = car.CarState.ButtonEvent.Type @@ -11,13 +11,7 @@ EventName = car.CarEvent.EventName class CarInterface(CarInterfaceBase): @staticmethod - def compute_gb(accel, speed): - return float(accel) / 4.0 - - @staticmethod - def get_params(candidate, fingerprint=gen_empty_fingerprint(), car_fw=None): - ret = CarInterfaceBase.get_std_params(candidate, fingerprint) - + def _get_params(ret, candidate, fingerprint, car_fw, experimental_long): ret.carName = "mazda" ret.safetyConfigs = [get_safety_config(car.CarParams.SafetyModel.mazda)] ret.radarOffCan = True @@ -25,48 +19,33 @@ class CarInterface(CarInterfaceBase): ret.dashcamOnly = candidate not in (CAR.CX5_2022, CAR.CX9_2021) ret.steerActuatorDelay = 0.1 - ret.steerRateCost = 1.0 ret.steerLimitTimer = 0.8 tire_stiffness_factor = 0.70 # not optimized yet + CarInterfaceBase.configure_torque_tune(candidate, ret.lateralTuning) + if candidate in (CAR.CX5, CAR.CX5_2022): ret.mass = 3655 * CV.LB_TO_KG + STD_CARGO_KG ret.wheelbase = 2.7 ret.steerRatio = 15.5 - ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.19], [0.019]] - ret.lateralTuning.pid.kf = 0.00006 elif candidate in (CAR.CX9, CAR.CX9_2021): ret.mass = 4217 * CV.LB_TO_KG + STD_CARGO_KG ret.wheelbase = 3.1 ret.steerRatio = 17.6 - ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.19], [0.019]] - ret.lateralTuning.pid.kf = 0.00006 elif candidate == CAR.MAZDA3: ret.mass = 2875 * CV.LB_TO_KG + STD_CARGO_KG ret.wheelbase = 2.7 ret.steerRatio = 14.0 - ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.19], [0.019]] - ret.lateralTuning.pid.kf = 0.00006 elif candidate == CAR.MAZDA6: ret.mass = 3443 * CV.LB_TO_KG + STD_CARGO_KG ret.wheelbase = 2.83 ret.steerRatio = 15.5 - ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.19], [0.019]] - ret.lateralTuning.pid.kf = 0.00006 if candidate not in (CAR.CX5_2022, ): ret.minSteerSpeed = LKAS_LIMITS.DISABLE_SPEED * CV.KPH_TO_MS ret.centerToFront = ret.wheelbase * 0.41 - # TODO: get actual value, for now starting with reasonable value for - # civic and scaling by mass and wheelbase - ret.rotationalInertia = scale_rot_inertia(ret.mass, ret.wheelbase) - # TODO: start from empirically derived lateral slip stiffness for the civic and scale by # mass and CG position, so all cars will have approximately similar dyn behaviors ret.tireStiffnessFront, ret.tireStiffnessRear = scale_tire_stiffness(ret.mass, ret.wheelbase, ret.centerToFront, @@ -75,13 +54,8 @@ class CarInterface(CarInterfaceBase): return ret # returns a car.CarState - def update(self, c, can_strings): - - self.cp.update_strings(can_strings) - self.cp_cam.update_strings(can_strings) - + def _update(self, c): ret = self.CS.update(self.cp, self.cp_cam) - ret.canValid = self.cp.can_valid and self.cp_cam.can_valid # events events = self.create_common_events(ret) @@ -93,10 +67,7 @@ class CarInterface(CarInterfaceBase): ret.events = events.to_msg() - self.CS.out = ret.as_reader() - return self.CS.out + return ret def apply(self, c): - ret = self.CC.update(c, self.CS, self.frame) - self.frame += 1 - return ret + return self.CC.update(c, self.CS) diff --git a/selfdrive/car/mazda/values.py b/selfdrive/car/mazda/values.py index 1fcf184281..e6e9b3aee8 100644 --- a/selfdrive/car/mazda/values.py +++ b/selfdrive/car/mazda/values.py @@ -1,5 +1,12 @@ -from selfdrive.car import dbc_dict +from dataclasses import dataclass +from enum import Enum +from typing import Dict, List, Union + from cereal import car +from selfdrive.car import dbc_dict +from selfdrive.car.docs_definitions import CarInfo, Harness +from selfdrive.car.fw_query_definitions import FwQueryConfig, Request, StdQueries + Ecu = car.CarParams.Ecu @@ -14,6 +21,7 @@ class CarControllerParams: STEER_DRIVER_FACTOR = 1 # from dbc STEER_ERROR_MAX = 350 # max delta between torque cmd and torque motor + class CAR: CX5 = "MAZDA CX-5" CX9 = "MAZDA CX-9" @@ -22,11 +30,29 @@ class CAR: CX9_2021 = "MAZDA CX-9 2021" CX5_2022 = "MAZDA CX-5 2022" + +@dataclass +class MazdaCarInfo(CarInfo): + package: str = "All" + harness: Enum = Harness.mazda + + +CAR_INFO: Dict[str, Union[MazdaCarInfo, List[MazdaCarInfo]]] = { + CAR.CX5: MazdaCarInfo("Mazda CX-5 2017-21"), + CAR.CX9: MazdaCarInfo("Mazda CX-9 2016-20"), + CAR.MAZDA3: MazdaCarInfo("Mazda 3 2017-18"), + CAR.MAZDA6: MazdaCarInfo("Mazda 6 2017-20"), + CAR.CX9_2021: MazdaCarInfo("Mazda CX-9 2021-23", video_link="https://youtu.be/dA3duO4a0O4"), + CAR.CX5_2022: MazdaCarInfo("Mazda CX-5 2022-23"), +} + + class LKAS_LIMITS: STEER_THRESHOLD = 15 DISABLE_SPEED = 45 # kph ENABLE_SPEED = 52 # kph + class Buttons: NONE = 0 SET_PLUS = 1 @@ -35,36 +61,53 @@ class Buttons: CANCEL = 4 +FW_QUERY_CONFIG = FwQueryConfig( + requests=[ + Request( + [StdQueries.MANUFACTURER_SOFTWARE_VERSION_REQUEST], + [StdQueries.MANUFACTURER_SOFTWARE_VERSION_RESPONSE], + ), + ], +) + FW_VERSIONS = { - CAR.CX5_2022 : { + CAR.CX5_2022: { (Ecu.eps, 0x730, None): [ b'KSD5-3210X-C-00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.engine, 0x7e0, None): [ b'PX2G-188K2-H\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'PX2H-188K2-H\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'SH54-188K2-D\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'PXFG-188K2-C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.fwdRadar, 0x764, None): [ b'K131-67XK2-F\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], - (Ecu.esp, 0x760, None): [ + (Ecu.abs, 0x760, None): [ b'KSD5-437K2-A\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.fwdCamera, 0x706, None): [ b'GSH7-67XK2-S\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'GSH7-67XK2-T\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.transmission, 0x7e1, None): [ b'PYB2-21PS1-H\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'SH51-21PS1-C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'PXFG-21PS1-A\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], }, CAR.CX5: { (Ecu.eps, 0x730, None): [ + b'K319-3210X-A-00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'KCB8-3210X-B-00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'KJ01-3210X-G-00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'KJ01-3210X-J-00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'KJ01-3210X-M-00\x00\x00\x00\x00\x00\x00\x00\x00\x00', - b'K319-3210X-A-00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.engine, 0x7e0, None): [ b'PA53-188K2-A\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'PAR4-188K2-E\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'PYFA-188K2-J\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'PYFC-188K2-J\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'PYFD-188K2-J\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', @@ -88,7 +131,7 @@ FW_VERSIONS = { b'K131-67XK2-E\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'K131-67XK2-F\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], - (Ecu.esp, 0x760, None): [ + (Ecu.abs, 0x760, None): [ b'K123-437K2-E\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'KBJ5-437K2-B\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'KL2K-437K2-A\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', @@ -106,6 +149,7 @@ FW_VERSIONS = { ], (Ecu.transmission, 0x7e1, None): [ b'PA66-21PS1-A\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'PA66-21PS1-D\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'PX39-21PS1-B\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'PX39-21PS1-D\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'PX68-21PS1-B\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', @@ -145,7 +189,7 @@ FW_VERSIONS = { b'TK80-67XK2-E\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'TK80-67XK2-F\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], - (Ecu.esp, 0x760, None): [ + (Ecu.abs, 0x760, None): [ b'TA0B-437K2-C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'TK79-437K2-E\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'TK79-437K2-F\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', @@ -189,7 +233,7 @@ FW_VERSIONS = { b'GHP9-67Y10---41\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'K131-67XK2-C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], - (Ecu.esp, 0x760, None): [ + (Ecu.abs, 0x760, None): [ b'B45A-437AS-0-08\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.fwdCamera, 0x706, None): [ @@ -220,7 +264,7 @@ FW_VERSIONS = { b'K131-67XK2-A\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'K131-67XK2-E\000\000\000\000\000\000\000\000\000\000\000\000', ], - (Ecu.esp, 0x760, None): [ + (Ecu.abs, 0x760, None): [ b'GBVH-437K2-B\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'GDDM-437K2-A\000\000\000\000\000\000\000\000\000\000\000\000', ], @@ -239,23 +283,28 @@ FW_VERSIONS = { b'TC3M-3210X-A-00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.engine, 0x7e0, None): [ + b'PXGW-188K2-C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'PXM4-188K2-C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'PXM4-188K2-D\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'PXM6-188K2-E\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.fwdRadar, 0x764, None): [ b'K131-67XK2-E\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'K131-67XK2-F\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], - (Ecu.esp, 0x760, None): [ + (Ecu.abs, 0x760, None): [ b'TA0B-437K2-C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.fwdCamera, 0x706, None): [ b'GSH7-67XK2-M\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'GSH7-67XK2-N\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'GSH7-67XK2-P\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'GSH7-67XK2-S\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'GSH7-67XK2-T\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.transmission, 0x7e1, None): [ b'PXM4-21PS1-B\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'PXM6-21PS1-B\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], } } diff --git a/selfdrive/car/mock/interface.py b/selfdrive/car/mock/interface.py index b2e315a5f9..3ac487dbb7 100755 --- a/selfdrive/car/mock/interface.py +++ b/selfdrive/car/mock/interface.py @@ -1,44 +1,28 @@ #!/usr/bin/env python3 -import math from cereal import car -from selfdrive.config import Conversions as CV -from selfdrive.swaglog import cloudlog +from system.swaglog import cloudlog import cereal.messaging as messaging -from selfdrive.car import gen_empty_fingerprint, get_safety_config +from selfdrive.car import get_safety_config from selfdrive.car.interfaces import CarInterfaceBase -# mocked car interface to work with chffrplus -TS = 0.01 # 100Hz -YAW_FR = 0.2 # ~0.8s time constant on yaw rate filter -# low pass gain -LPG = 2 * math.pi * YAW_FR * TS / (1 + 2 * math.pi * YAW_FR * TS) - +# mocked car interface to work with chffrplus class CarInterface(CarInterfaceBase): def __init__(self, CP, CarController, CarState): super().__init__(CP, CarController, CarState) cloudlog.debug("Using Mock Car Interface") - self.sensor = messaging.sub_sock('sensorEvents') - self.gps = messaging.sub_sock('gpsLocationExternal') + self.sm = messaging.SubMaster(['gpsLocation', 'gpsLocationExternal']) self.speed = 0. self.prev_speed = 0. - self.yaw_rate = 0. - self.yaw_rate_meas = 0. - - @staticmethod - def compute_gb(accel, speed): - return accel @staticmethod - def get_params(candidate, fingerprint=gen_empty_fingerprint(), car_fw=None): - ret = CarInterfaceBase.get_std_params(candidate, fingerprint) + def _get_params(ret, candidate, fingerprint, car_fw, experimental_long): ret.carName = "mock" ret.safetyConfigs = [get_safety_config(car.CarParams.SafetyModel.noOutput)] ret.mass = 1700. - ret.rotationalInertia = 2500. ret.wheelbase = 2.70 ret.centerToFront = ret.wheelbase * 0.5 ret.steerRatio = 13. # reasonable @@ -48,30 +32,22 @@ class CarInterface(CarInterfaceBase): return ret # returns a car.CarState - def update(self, c, can_strings): - # get basic data from phone and gps since CAN isn't connected - sensors = messaging.recv_sock(self.sensor) - if sensors is not None: - for sensor in sensors.sensorEvents: - if sensor.type == 4: # gyro - self.yaw_rate_meas = -sensor.gyro.v[0] - - gps = messaging.recv_sock(self.gps) - if gps is not None: + def _update(self, c): + self.sm.update(0) + gps_sock = 'gpsLocationExternal' if self.sm.rcv_frame['gpsLocationExternal'] > 1 else 'gpsLocation' + if self.sm.updated[gps_sock]: self.prev_speed = self.speed - self.speed = gps.gpsLocationExternal.speed + self.speed = self.sm[gps_sock].speed # create message ret = car.CarState.new_message() - ret.canValid = True # speeds ret.vEgo = self.speed ret.vEgoRaw = self.speed - a = self.speed - self.prev_speed - ret.aEgo = a - ret.brakePressed = a < -0.5 + ret.aEgo = self.speed - self.prev_speed + ret.brakePressed = ret.aEgo < -0.5 ret.standstill = self.speed < 0.01 ret.wheelSpeeds.fl = self.speed @@ -79,11 +55,7 @@ class CarInterface(CarInterfaceBase): ret.wheelSpeeds.rl = self.speed ret.wheelSpeeds.rr = self.speed - self.yawRate = LPG * self.yaw_rate_meas + (1. - LPG) * self.yaw_rate - curvature = self.yaw_rate / max(self.speed, 1.) - ret.steeringAngleDeg = curvature * self.CP.steerRatio * self.CP.wheelbase * CV.RAD_TO_DEG - - return ret.as_reader() + return ret def apply(self, c): # in mock no carcontrols diff --git a/selfdrive/car/mock/values.py b/selfdrive/car/mock/values.py index 0dd91565bd..dfc7902e41 100644 --- a/selfdrive/car/mock/values.py +++ b/selfdrive/car/mock/values.py @@ -1,2 +1,12 @@ +from typing import Dict, List, Optional, Union + +from selfdrive.car.docs_definitions import CarInfo + + class CAR: MOCK = 'mock' + + +CAR_INFO: Dict[str, Optional[Union[CarInfo, List[CarInfo]]]] = { + CAR.MOCK: None, +} diff --git a/selfdrive/car/nissan/carcontroller.py b/selfdrive/car/nissan/carcontroller.py index 8b30c11249..dbc2b33c6b 100644 --- a/selfdrive/car/nissan/carcontroller.py +++ b/selfdrive/car/nissan/carcontroller.py @@ -1,38 +1,39 @@ from cereal import car from common.numpy_fast import clip, interp -from selfdrive.car.nissan import nissancan from opendbc.can.packer import CANPacker +from selfdrive.car.nissan import nissancan from selfdrive.car.nissan.values import CAR, CarControllerParams - VisualAlert = car.CarControl.HUDControl.VisualAlert -class CarController(): +class CarController: def __init__(self, dbc_name, CP, VM): self.CP = CP self.car_fingerprint = CP.carFingerprint + self.frame = 0 self.lkas_max_torque = 0 self.last_angle = 0 self.packer = CANPacker(dbc_name) - def update(self, c, enabled, CS, frame, actuators, cruise_cancel, hud_alert, - left_line, right_line, left_lane_depart, right_lane_depart): + def update(self, CC, CS): + actuators = CC.actuators + hud_control = CC.hudControl + pcm_cancel_cmd = CC.cruiseControl.cancel can_sends = [] ### STEER ### - acc_active = CS.out.cruiseState.enabled lkas_hud_msg = CS.lkas_hud_msg lkas_hud_info_msg = CS.lkas_hud_info_msg apply_angle = actuators.steeringAngleDeg - steer_hud_alert = 1 if hud_alert in (VisualAlert.steerRequired, VisualAlert.ldw) else 0 + steer_hud_alert = 1 if hud_control.visualAlert in (VisualAlert.steerRequired, VisualAlert.ldw) else 0 - if c.active: - # # windup slower + if CC.latActive: + # windup slower if self.last_angle * apply_angle > 0. and abs(apply_angle) > abs(self.last_angle): angle_rate_lim = interp(CS.out.vEgo, CarControllerParams.ANGLE_DELTA_BP, CarControllerParams.ANGLE_DELTA_V) else: @@ -58,29 +59,25 @@ class CarController(): self.last_angle = apply_angle - if not enabled and acc_active: - # send acc cancel cmd if drive is disabled but pcm is still on, or if the system can't be activated - cruise_cancel = 1 - - if self.CP.carFingerprint in (CAR.ROGUE, CAR.XTRAIL, CAR.ALTIMA) and cruise_cancel: - can_sends.append(nissancan.create_acc_cancel_cmd(self.packer, self.car_fingerprint, CS.cruise_throttle_msg, frame)) + if self.CP.carFingerprint in (CAR.ROGUE, CAR.XTRAIL, CAR.ALTIMA) and pcm_cancel_cmd: + can_sends.append(nissancan.create_acc_cancel_cmd(self.packer, self.car_fingerprint, CS.cruise_throttle_msg)) # TODO: Find better way to cancel! # For some reason spamming the cancel button is unreliable on the Leaf # We now cancel by making propilot think the seatbelt is unlatched, # this generates a beep and a warning message every time you disengage - if self.CP.carFingerprint in (CAR.LEAF, CAR.LEAF_IC) and frame % 2 == 0: - can_sends.append(nissancan.create_cancel_msg(self.packer, CS.cancel_msg, cruise_cancel)) + if self.CP.carFingerprint in (CAR.LEAF, CAR.LEAF_IC) and self.frame % 2 == 0: + can_sends.append(nissancan.create_cancel_msg(self.packer, CS.cancel_msg, pcm_cancel_cmd)) can_sends.append(nissancan.create_steering_control( - self.packer, apply_angle, frame, enabled, self.lkas_max_torque)) + self.packer, apply_angle, self.frame, CC.enabled, self.lkas_max_torque)) if lkas_hud_msg and lkas_hud_info_msg: - if frame % 2 == 0: + if self.frame % 2 == 0: can_sends.append(nissancan.create_lkas_hud_msg( - self.packer, lkas_hud_msg, enabled, left_line, right_line, left_lane_depart, right_lane_depart)) + self.packer, lkas_hud_msg, CC.enabled, hud_control.leftLaneVisible, hud_control.rightLaneVisible, hud_control.leftLaneDepart, hud_control.rightLaneDepart)) - if frame % 50 == 0: + if self.frame % 50 == 0: can_sends.append(nissancan.create_lkas_hud_info_msg( self.packer, lkas_hud_info_msg, steer_hud_alert )) @@ -88,4 +85,5 @@ class CarController(): new_actuators = actuators.copy() new_actuators.steeringAngleDeg = apply_angle + self.frame += 1 return new_actuators, can_sends diff --git a/selfdrive/car/nissan/carstate.py b/selfdrive/car/nissan/carstate.py index 6b030e9b45..d6b6d17d55 100644 --- a/selfdrive/car/nissan/carstate.py +++ b/selfdrive/car/nissan/carstate.py @@ -3,7 +3,7 @@ from collections import deque from cereal import car from opendbc.can.can_define import CANDefine from selfdrive.car.interfaces import CarStateBase -from selfdrive.config import Conversions as CV +from common.conversions import Conversions as CV from opendbc.can.parser import CANParser from selfdrive.car.nissan.values import CAR, DBC, CarControllerParams @@ -44,7 +44,7 @@ class CarState(CarStateBase): ret.vEgoRaw = (ret.wheelSpeeds.fl + ret.wheelSpeeds.fr + ret.wheelSpeeds.rl + ret.wheelSpeeds.rr) / 4. ret.vEgo, ret.aEgo = self.update_speed_kf(ret.vEgoRaw) - ret.standstill = ret.vEgoRaw < 0.01 + ret.standstill = cp.vl["WHEEL_SPEEDS_REAR"]["WHEEL_SPEED_RL"] == 0.0 and cp.vl["WHEEL_SPEEDS_REAR"]["WHEEL_SPEED_RR"] == 0.0 if self.CP.carFingerprint == CAR.ALTIMA: ret.cruiseState.enabled = bool(cp.vl["CRUISE_STATE"]["CRUISE_ENABLED"]) @@ -74,8 +74,8 @@ class CarState(CarStateBase): conversion = CV.MPH_TO_MS if cp.vl["HUD_SETTINGS"]["SPEED_MPH"] else CV.KPH_TO_MS else: conversion = CV.MPH_TO_MS if cp.vl["HUD"]["SPEED_MPH"] else CV.KPH_TO_MS - speed -= 1 # Speed on HUD is always 1 lower than actually sent on can bus ret.cruiseState.speed = speed * conversion + ret.cruiseState.speedCluster = (speed - 1) * conversion # Speed on HUD is always 1 lower than actually sent on can bus if self.CP.carFingerprint == CAR.ALTIMA: ret.steeringTorque = cp_cam.vl["STEER_TORQUE_SENSOR"]["STEER_TORQUE_DRIVER"] diff --git a/selfdrive/car/nissan/interface.py b/selfdrive/car/nissan/interface.py index c32fb13780..386e859089 100644 --- a/selfdrive/car/nissan/interface.py +++ b/selfdrive/car/nissan/interface.py @@ -1,67 +1,47 @@ #!/usr/bin/env python3 from cereal import car -from selfdrive.car.nissan.values import CAR -from selfdrive.car import STD_CARGO_KG, scale_rot_inertia, scale_tire_stiffness, gen_empty_fingerprint, get_safety_config +from selfdrive.car import STD_CARGO_KG, get_safety_config from selfdrive.car.interfaces import CarInterfaceBase +from selfdrive.car.nissan.values import CAR + class CarInterface(CarInterfaceBase): - def __init__(self, CP, CarController, CarState): - super().__init__(CP, CarController, CarState) - self.cp_adas = self.CS.get_adas_can_parser(CP) @staticmethod - def get_params(candidate, fingerprint=gen_empty_fingerprint(), car_fw=None): - - ret = CarInterfaceBase.get_std_params(candidate, fingerprint) + def _get_params(ret, candidate, fingerprint, car_fw, experimental_long): ret.carName = "nissan" ret.safetyConfigs = [get_safety_config(car.CarParams.SafetyModel.nissan)] + ret.autoResumeSng = False ret.steerLimitTimer = 1.0 - ret.steerRateCost = 0.5 ret.steerActuatorDelay = 0.1 + ret.steerRatio = 17 + + ret.steerControlType = car.CarParams.SteerControlType.angle + ret.radarOffCan = True if candidate in (CAR.ROGUE, CAR.XTRAIL): ret.mass = 1610 + STD_CARGO_KG ret.wheelbase = 2.705 ret.centerToFront = ret.wheelbase * 0.44 - ret.steerRatio = 17 elif candidate in (CAR.LEAF, CAR.LEAF_IC): ret.mass = 1610 + STD_CARGO_KG ret.wheelbase = 2.705 ret.centerToFront = ret.wheelbase * 0.44 - ret.steerRatio = 17 elif candidate == CAR.ALTIMA: # Altima has EPS on C-CAN unlike the others that have it on V-CAN ret.safetyConfigs[0].safetyParam = 1 # EPS is on alternate bus ret.mass = 1492 + STD_CARGO_KG ret.wheelbase = 2.824 ret.centerToFront = ret.wheelbase * 0.44 - ret.steerRatio = 17 - - ret.steerControlType = car.CarParams.SteerControlType.angle - ret.radarOffCan = True - - # TODO: get actual value, for now starting with reasonable value for - # civic and scaling by mass and wheelbase - ret.rotationalInertia = scale_rot_inertia(ret.mass, ret.wheelbase) - - # TODO: start from empirically derived lateral slip stiffness for the civic and scale by - # mass and CG position, so all cars will have approximately similar dyn behaviors - ret.tireStiffnessFront, ret.tireStiffnessRear = scale_tire_stiffness(ret.mass, ret.wheelbase, ret.centerToFront) return ret # returns a car.CarState - def update(self, c, can_strings): - self.cp.update_strings(can_strings) - self.cp_cam.update_strings(can_strings) - self.cp_adas.update_strings(can_strings) - + def _update(self, c): ret = self.CS.update(self.cp, self.cp_adas, self.cp_cam) - ret.canValid = self.cp.can_valid and self.cp_adas.can_valid and self.cp_cam.can_valid - buttonEvents = [] be = car.CarState.ButtonEvent.new_message() be.type = car.CarState.ButtonEvent.Type.accelCruise @@ -74,14 +54,7 @@ class CarInterface(CarInterfaceBase): ret.events = events.to_msg() - self.CS.out = ret.as_reader() - return self.CS.out + return ret def apply(self, c): - hud_control = c.hudControl - ret = self.CC.update(c, c.enabled, self.CS, self.frame, c.actuators, - c.cruiseControl.cancel, hud_control.visualAlert, - hud_control.leftLaneVisible, hud_control.rightLaneVisible, - hud_control.leftLaneDepart, hud_control.rightLaneDepart) - self.frame += 1 - return ret + return self.CC.update(c, self.CS) diff --git a/selfdrive/car/nissan/nissancan.py b/selfdrive/car/nissan/nissancan.py index ceace5088a..01fb3463a9 100644 --- a/selfdrive/car/nissan/nissancan.py +++ b/selfdrive/car/nissan/nissancan.py @@ -2,17 +2,17 @@ import copy import crcmod from selfdrive.car.nissan.values import CAR +# TODO: add this checksum to the CANPacker nissan_checksum = crcmod.mkCrcFun(0x11d, initCrc=0x00, rev=False, xorOut=0xff) def create_steering_control(packer, apply_steer, frame, steer_on, lkas_max_torque): - idx = (frame % 16) values = { + "COUNTER": frame % 0x10, "DESIRED_ANGLE": apply_steer, "SET_0x80_2": 0x80, "SET_0x80": 0x80, "MAX_TORQUE": lkas_max_torque if steer_on else 0, - "COUNTER": idx, "LKA_ACTIVE": steer_on, } @@ -22,12 +22,9 @@ def create_steering_control(packer, apply_steer, frame, steer_on, lkas_max_torqu return packer.make_can_msg("LKAS", 0, values) -def create_acc_cancel_cmd(packer, car_fingerprint, cruise_throttle_msg, frame): +def create_acc_cancel_cmd(packer, car_fingerprint, cruise_throttle_msg): values = copy.copy(cruise_throttle_msg) - can_bus = 2 - - if car_fingerprint == CAR.ALTIMA: - can_bus = 1 + can_bus = 1 if car_fingerprint == CAR.ALTIMA else 2 values["CANCEL_BUTTON"] = 1 values["NO_BUTTON_PRESSED"] = 0 @@ -35,7 +32,6 @@ def create_acc_cancel_cmd(packer, car_fingerprint, cruise_throttle_msg, frame): values["SET_BUTTON"] = 0 values["RES_BUTTON"] = 0 values["FOLLOW_DISTANCE_BUTTON"] = 0 - values["COUNTER"] = (frame % 4) return packer.make_can_msg("CRUISE_THROTTLE", can_bus, values) diff --git a/selfdrive/car/nissan/values.py b/selfdrive/car/nissan/values.py index f7001d1417..09bd7ca838 100644 --- a/selfdrive/car/nissan/values.py +++ b/selfdrive/car/nissan/values.py @@ -1,5 +1,13 @@ -from selfdrive.car import dbc_dict +from dataclasses import dataclass +from typing import Dict, List, Optional, Union +from enum import Enum + from cereal import car +from panda.python import uds +from selfdrive.car import dbc_dict +from selfdrive.car.docs_definitions import CarInfo, Harness +from selfdrive.car.fw_query_definitions import FwQueryConfig, Request, StdQueries + Ecu = car.CarParams.Ecu @@ -10,6 +18,7 @@ class CarControllerParams: LKAS_MAX_TORQUE = 1 # A value of 1 is easy to overpower STEER_THRESHOLD = 1.0 + class CAR: XTRAIL = "NISSAN X-TRAIL 2017" LEAF = "NISSAN LEAF 2018" @@ -20,6 +29,20 @@ class CAR: ALTIMA = "NISSAN ALTIMA 2020" +@dataclass +class NissanCarInfo(CarInfo): + package: str = "ProPILOT Assist" + harness: Enum = Harness.nissan_a + + +CAR_INFO: Dict[str, Optional[Union[NissanCarInfo, List[NissanCarInfo]]]] = { + CAR.XTRAIL: NissanCarInfo("Nissan X-Trail 2017"), + CAR.LEAF: NissanCarInfo("Nissan Leaf 2018-22"), + CAR.LEAF_IC: None, # same platforms + CAR.ROGUE: NissanCarInfo("Nissan Rogue 2018-20"), + CAR.ALTIMA: NissanCarInfo("Nissan Altima 2019-20", harness=Harness.nissan_b), +} + FINGERPRINTS = { CAR.XTRAIL: [ { @@ -55,6 +78,33 @@ FINGERPRINTS = { ] } +NISSAN_DIAGNOSTIC_REQUEST_KWP = bytes([uds.SERVICE_TYPE.DIAGNOSTIC_SESSION_CONTROL, 0xc0]) +NISSAN_DIAGNOSTIC_RESPONSE_KWP = bytes([uds.SERVICE_TYPE.DIAGNOSTIC_SESSION_CONTROL + 0x40, 0xc0]) + +NISSAN_VERSION_REQUEST_KWP = b'\x21\x83' +NISSAN_VERSION_RESPONSE_KWP = b'\x61\x83' + +NISSAN_RX_OFFSET = 0x20 + +FW_QUERY_CONFIG = FwQueryConfig( + requests=[ + Request( + [NISSAN_DIAGNOSTIC_REQUEST_KWP, NISSAN_VERSION_REQUEST_KWP], + [NISSAN_DIAGNOSTIC_RESPONSE_KWP, NISSAN_VERSION_RESPONSE_KWP], + ), + Request( + [NISSAN_DIAGNOSTIC_REQUEST_KWP, NISSAN_VERSION_REQUEST_KWP], + [NISSAN_DIAGNOSTIC_RESPONSE_KWP, NISSAN_VERSION_RESPONSE_KWP], + rx_offset=NISSAN_RX_OFFSET, + ), + Request( + [StdQueries.MANUFACTURER_SOFTWARE_VERSION_REQUEST], + [StdQueries.MANUFACTURER_SOFTWARE_VERSION_RESPONSE], + rx_offset=NISSAN_RX_OFFSET, + ), + ], +) + FW_VERSIONS = { CAR.ALTIMA: { (Ecu.fwdCamera, 0x707, None): [ @@ -75,7 +125,7 @@ FW_VERSIONS = { b'5SH1BDB\x04\x18\x00\x00\x00\x00\x00_-?\x04\x91\xf2\x00\x00\x00\x80', b'5SK0ADB\x04\x18\x00\x00\x00\x00\x00_(5\x07\x9aQ\x00\x00\x00\x80', ], - (Ecu.esp, 0x740, None): [ + (Ecu.abs, 0x740, None): [ b'476605SH1D', b'476605SK2A', ], @@ -92,7 +142,7 @@ FW_VERSIONS = { (Ecu.fwdCamera, 0x707, None): [ b'284N86FR2A', ], - (Ecu.esp, 0x740, None): [ + (Ecu.abs, 0x740, None): [ b'6FU1BD\x11\x02\x00\x02e\x95e\x80iX#\x01\x00\x00\x00\x00\x00\x80', b'6FU0AD\x11\x02\x00\x02e\x95e\x80iQ#\x01\x00\x00\x00\x00\x00\x80', ], diff --git a/selfdrive/car/subaru/carcontroller.py b/selfdrive/car/subaru/carcontroller.py index afc91f4755..b5429daef2 100644 --- a/selfdrive/car/subaru/carcontroller.py +++ b/selfdrive/car/subaru/carcontroller.py @@ -1,26 +1,33 @@ +from opendbc.can.packer import CANPacker from selfdrive.car import apply_std_steer_torque_limits from selfdrive.car.subaru import subarucan -from selfdrive.car.subaru.values import DBC, PREGLOBAL_CARS, CarControllerParams -from opendbc.can.packer import CANPacker +from selfdrive.car.subaru.values import DBC, GLOBAL_GEN2, PREGLOBAL_CARS, CarControllerParams -class CarController(): +class CarController: def __init__(self, dbc_name, CP, VM): + self.CP = CP self.apply_steer_last = 0 - self.es_distance_cnt = -1 + self.frame = 0 + self.es_lkas_cnt = -1 + self.es_distance_cnt = -1 + self.es_dashstatus_cnt = -1 self.cruise_button_prev = 0 - self.steer_rate_limited = False + self.last_cancel_frame = 0 self.p = CarControllerParams(CP) self.packer = CANPacker(DBC[CP.carFingerprint]['pt']) - def update(self, c, enabled, CS, frame, actuators, pcm_cancel_cmd, visual_alert, left_line, right_line, left_lane_depart, right_lane_depart): + def update(self, CC, CS): + actuators = CC.actuators + hud_control = CC.hudControl + pcm_cancel_cmd = CC.cruiseControl.cancel can_sends = [] # *** steering *** - if (frame % self.p.STEER_STEP) == 0: + if (self.frame % self.p.STEER_STEP) == 0: apply_steer = int(round(actuators.steer * self.p.STEER_MAX)) @@ -28,23 +35,22 @@ class CarController(): new_steer = int(round(apply_steer)) apply_steer = apply_std_steer_torque_limits(new_steer, self.apply_steer_last, CS.out.steeringTorque, self.p) - self.steer_rate_limited = new_steer != apply_steer - if not c.active: + if not CC.latActive: apply_steer = 0 - if CS.CP.carFingerprint in PREGLOBAL_CARS: - can_sends.append(subarucan.create_preglobal_steering_control(self.packer, apply_steer, frame, self.p.STEER_STEP)) + if self.CP.carFingerprint in PREGLOBAL_CARS: + can_sends.append(subarucan.create_preglobal_steering_control(self.packer, apply_steer)) else: - can_sends.append(subarucan.create_steering_control(self.packer, apply_steer, frame, self.p.STEER_STEP)) + can_sends.append(subarucan.create_steering_control(self.packer, apply_steer)) self.apply_steer_last = apply_steer # *** alerts and pcm cancel *** - if CS.CP.carFingerprint in PREGLOBAL_CARS: - if self.es_distance_cnt != CS.es_distance_msg["Counter"]: + if self.CP.carFingerprint in PREGLOBAL_CARS: + if self.es_distance_cnt != CS.es_distance_msg["COUNTER"]: # 1 = main, 2 = set shallow, 3 = set deep, 4 = resume shallow, 5 = resume deep # disengage ACC when OP is disengaged if pcm_cancel_cmd: @@ -61,18 +67,26 @@ class CarController(): self.cruise_button_prev = cruise_button can_sends.append(subarucan.create_preglobal_es_distance(self.packer, cruise_button, CS.es_distance_msg)) - self.es_distance_cnt = CS.es_distance_msg["Counter"] + self.es_distance_cnt = CS.es_distance_msg["COUNTER"] else: - if self.es_distance_cnt != CS.es_distance_msg["Counter"]: - can_sends.append(subarucan.create_es_distance(self.packer, CS.es_distance_msg, pcm_cancel_cmd)) - self.es_distance_cnt = CS.es_distance_msg["Counter"] + if pcm_cancel_cmd and (self.frame - self.last_cancel_frame) > 0.2: + bus = 1 if self.CP.carFingerprint in GLOBAL_GEN2 else 0 + can_sends.append(subarucan.create_es_distance(self.packer, CS.es_distance_msg, bus, pcm_cancel_cmd)) + self.last_cancel_frame = self.frame + + if self.es_dashstatus_cnt != CS.es_dashstatus_msg["COUNTER"]: + can_sends.append(subarucan.create_es_dashstatus(self.packer, CS.es_dashstatus_msg)) + self.es_dashstatus_cnt = CS.es_dashstatus_msg["COUNTER"] - if self.es_lkas_cnt != CS.es_lkas_msg["Counter"]: - can_sends.append(subarucan.create_es_lkas(self.packer, CS.es_lkas_msg, enabled, visual_alert, left_line, right_line, left_lane_depart, right_lane_depart)) - self.es_lkas_cnt = CS.es_lkas_msg["Counter"] + if self.es_lkas_cnt != CS.es_lkas_msg["COUNTER"]: + can_sends.append(subarucan.create_es_lkas(self.packer, CS.es_lkas_msg, CC.enabled, hud_control.visualAlert, + hud_control.leftLaneVisible, hud_control.rightLaneVisible, + hud_control.leftLaneDepart, hud_control.rightLaneDepart)) + self.es_lkas_cnt = CS.es_lkas_msg["COUNTER"] new_actuators = actuators.copy() new_actuators.steer = self.apply_steer_last / self.p.STEER_MAX + self.frame += 1 return new_actuators, can_sends diff --git a/selfdrive/car/subaru/carstate.py b/selfdrive/car/subaru/carstate.py index 1eefb18584..ba873c48d7 100644 --- a/selfdrive/car/subaru/carstate.py +++ b/selfdrive/car/subaru/carstate.py @@ -1,10 +1,10 @@ import copy from cereal import car from opendbc.can.can_define import CANDefine -from selfdrive.config import Conversions as CV +from common.conversions import Conversions as CV from selfdrive.car.interfaces import CarStateBase from opendbc.can.parser import CANParser -from selfdrive.car.subaru.values import DBC, STEER_THRESHOLD, CAR, PREGLOBAL_CARS +from selfdrive.car.subaru.values import DBC, CAR, GLOBAL_GEN2, PREGLOBAL_CARS class CarState(CarStateBase): @@ -13,7 +13,7 @@ class CarState(CarStateBase): can_define = CANDefine(DBC[CP.carFingerprint]["pt"]) self.shifter_values = can_define.dv["Transmission"]["Gear"] - def update(self, cp, cp_cam): + def update(self, cp, cp_cam, cp_body): ret = car.CarState.new_message() ret.gas = cp.vl["Throttle"]["Throttle_Pedal"] / 255. @@ -21,22 +21,23 @@ class CarState(CarStateBase): if self.car_fingerprint in PREGLOBAL_CARS: ret.brakePressed = cp.vl["Brake_Pedal"]["Brake_Pedal"] > 2 else: - ret.brakePressed = cp.vl["Brake_Status"]["Brake"] == 1 + cp_brakes = cp_body if self.car_fingerprint in GLOBAL_GEN2 else cp + ret.brakePressed = cp_brakes.vl["Brake_Status"]["Brake"] == 1 + cp_wheels = cp_body if self.car_fingerprint in GLOBAL_GEN2 else cp ret.wheelSpeeds = self.get_wheel_speeds( - cp.vl["Wheel_Speeds"]["FL"], - cp.vl["Wheel_Speeds"]["FR"], - cp.vl["Wheel_Speeds"]["RL"], - cp.vl["Wheel_Speeds"]["RR"], + cp_wheels.vl["Wheel_Speeds"]["FL"], + cp_wheels.vl["Wheel_Speeds"]["FR"], + cp_wheels.vl["Wheel_Speeds"]["RL"], + cp_wheels.vl["Wheel_Speeds"]["RR"], ) ret.vEgoRaw = (ret.wheelSpeeds.fl + ret.wheelSpeeds.fr + ret.wheelSpeeds.rl + ret.wheelSpeeds.rr) / 4. - # Kalman filter, even though Subaru raw wheel speed is heaviliy filtered by default ret.vEgo, ret.aEgo = self.update_speed_kf(ret.vEgoRaw) - ret.standstill = ret.vEgoRaw < 0.01 + ret.standstill = ret.vEgoRaw == 0 # continuous blinker signals for assisted lane change - ret.leftBlinker, ret.rightBlinker = self.update_blinker_from_lamp( - 50, cp.vl["Dashlights"]["LEFT_BLINKER"], cp.vl["Dashlights"]["RIGHT_BLINKER"]) + ret.leftBlinker, ret.rightBlinker = self.update_blinker_from_lamp(50, cp.vl["Dashlights"]["LEFT_BLINKER"], + cp.vl["Dashlights"]["RIGHT_BLINKER"]) if self.CP.enableBsm: ret.leftBlindspot = (cp.vl["BSD_RCTA"]["L_ADJACENT"] == 1) or (cp.vl["BSD_RCTA"]["L_APPROACHING"] == 1) @@ -47,10 +48,14 @@ class CarState(CarStateBase): ret.steeringAngleDeg = cp.vl["Steering_Torque"]["Steering_Angle"] ret.steeringTorque = cp.vl["Steering_Torque"]["Steer_Torque_Sensor"] - ret.steeringPressed = abs(ret.steeringTorque) > STEER_THRESHOLD[self.car_fingerprint] + ret.steeringTorqueEps = cp.vl["Steering_Torque"]["Steer_Torque_Output"] - ret.cruiseState.enabled = cp.vl["CruiseControl"]["Cruise_Activated"] != 0 - ret.cruiseState.available = cp.vl["CruiseControl"]["Cruise_On"] != 0 + steer_threshold = 75 if self.CP.carFingerprint in PREGLOBAL_CARS else 80 + ret.steeringPressed = abs(ret.steeringTorque) > steer_threshold + + cp_cruise = cp_body if self.car_fingerprint in GLOBAL_GEN2 else cp + ret.cruiseState.enabled = cp_cruise.vl["CruiseControl"]["Cruise_Activated"] != 0 + ret.cruiseState.available = cp_cruise.vl["CruiseControl"]["Cruise_On"] != 0 ret.cruiseState.speed = cp_cam.vl["ES_DashStatus"]["Cruise_Set_Speed"] * CV.KPH_TO_MS if (self.car_fingerprint in PREGLOBAL_CARS and cp.vl["Dash_State2"]["UNITS"] == 1) or \ @@ -62,37 +67,85 @@ class CarState(CarStateBase): cp.vl["BodyInfo"]["DOOR_OPEN_RL"], cp.vl["BodyInfo"]["DOOR_OPEN_FR"], cp.vl["BodyInfo"]["DOOR_OPEN_FL"]]) - ret.steerError = cp.vl["Steering_Torque"]["Steer_Error_1"] == 1 + ret.steerFaultPermanent = cp.vl["Steering_Torque"]["Steer_Error_1"] == 1 if self.car_fingerprint in PREGLOBAL_CARS: self.cruise_button = cp_cam.vl["ES_Distance"]["Cruise_Button"] self.ready = not cp_cam.vl["ES_DashStatus"]["Not_Ready_Startup"] else: - ret.steerWarning = cp.vl["Steering_Torque"]["Steer_Warning"] == 1 + ret.steerFaultTemporary = cp.vl["Steering_Torque"]["Steer_Warning"] == 1 ret.cruiseState.nonAdaptive = cp_cam.vl["ES_DashStatus"]["Conventional_Cruise"] == 1 + ret.cruiseState.standstill = cp_cam.vl["ES_DashStatus"]["Cruise_State"] == 3 + ret.stockFcw = cp_cam.vl["ES_LKAS_State"]["LKAS_Alert"] == 2 self.es_lkas_msg = copy.copy(cp_cam.vl["ES_LKAS_State"]) - self.es_distance_msg = copy.copy(cp_cam.vl["ES_Distance"]) + + cp_es_distance = cp_body if self.car_fingerprint in GLOBAL_GEN2 else cp_cam + self.es_distance_msg = copy.copy(cp_es_distance.vl["ES_Distance"]) + self.es_dashstatus_msg = copy.copy(cp_cam.vl["ES_DashStatus"]) return ret + @staticmethod + def get_common_global_signals(): + signals = [ + ("Cruise_On", "CruiseControl"), + ("Cruise_Activated", "CruiseControl"), + ("FL", "Wheel_Speeds"), + ("FR", "Wheel_Speeds"), + ("RL", "Wheel_Speeds"), + ("RR", "Wheel_Speeds"), + ("Brake", "Brake_Status"), + ] + checks = [ + ("CruiseControl", 20), + ("Wheel_Speeds", 50), + ("Brake_Status", 50), + ] + + return signals, checks + + @staticmethod + def get_global_es_distance_signals(): + signals = [ + ("COUNTER", "ES_Distance"), + ("Signal1", "ES_Distance"), + ("Cruise_Fault", "ES_Distance"), + ("Cruise_Throttle", "ES_Distance"), + ("Signal2", "ES_Distance"), + ("Car_Follow", "ES_Distance"), + ("Signal3", "ES_Distance"), + ("Cruise_Soft_Disable", "ES_Distance"), + ("Signal7", "ES_Distance"), + ("Cruise_Brake_Active", "ES_Distance"), + ("Distance_Swap", "ES_Distance"), + ("Cruise_EPB", "ES_Distance"), + ("Signal4", "ES_Distance"), + ("Close_Distance", "ES_Distance"), + ("Signal5", "ES_Distance"), + ("Cruise_Cancel", "ES_Distance"), + ("Cruise_Set", "ES_Distance"), + ("Cruise_Resume", "ES_Distance"), + ("Signal6", "ES_Distance"), + ] + checks = [ + ("ES_Distance", 20), + ] + + return signals, checks + @staticmethod def get_can_parser(CP): signals = [ # sig_name, sig_address ("Steer_Torque_Sensor", "Steering_Torque"), + ("Steer_Torque_Output", "Steering_Torque"), ("Steering_Angle", "Steering_Torque"), ("Steer_Error_1", "Steering_Torque"), - ("Cruise_On", "CruiseControl"), - ("Cruise_Activated", "CruiseControl"), ("Brake_Pedal", "Brake_Pedal"), ("Throttle_Pedal", "Throttle"), ("LEFT_BLINKER", "Dashlights"), ("RIGHT_BLINKER", "Dashlights"), ("SEATBELT_FL", "Dashlights"), - ("FL", "Wheel_Speeds"), - ("FR", "Wheel_Speeds"), - ("RL", "Wheel_Speeds"), - ("RR", "Wheel_Speeds"), ("DOOR_OPEN_FR", "BodyInfo"), ("DOOR_OPEN_FL", "BodyInfo"), ("DOOR_OPEN_RR", "BodyInfo"), @@ -105,7 +158,6 @@ class CarState(CarStateBase): ("Throttle", 100), ("Dashlights", 10), ("Brake_Pedal", 50), - ("Wheel_Speeds", 50), ("Transmission", 100), ("Steering_Torque", 50), ("BodyInfo", 1), @@ -121,36 +173,47 @@ class CarState(CarStateBase): checks.append(("BSD_RCTA", 17)) if CP.carFingerprint not in PREGLOBAL_CARS: + if CP.carFingerprint not in GLOBAL_GEN2: + signals += CarState.get_common_global_signals()[0] + checks += CarState.get_common_global_signals()[1] + signals += [ ("Steer_Warning", "Steering_Torque"), - ("Brake", "Brake_Status"), ("UNITS", "Dashlights"), ] checks += [ ("Dashlights", 10), ("BodyInfo", 10), - ("Brake_Status", 50), - ("CruiseControl", 20), ] else: - signals.append(("UNITS", "Dash_State2")) - - checks.append(("Dash_State2", 1)) - - if CP.carFingerprint == CAR.FORESTER_PREGLOBAL: - checks += [ - ("Dashlights", 20), - ("BodyInfo", 1), - ("CruiseControl", 50), + signals += [ + ("FL", "Wheel_Speeds"), + ("FR", "Wheel_Speeds"), + ("RL", "Wheel_Speeds"), + ("RR", "Wheel_Speeds"), + ("UNITS", "Dash_State2"), + ("Cruise_On", "CruiseControl"), + ("Cruise_Activated", "CruiseControl"), ] - - if CP.carFingerprint in (CAR.LEGACY_PREGLOBAL, CAR.OUTBACK_PREGLOBAL, CAR.OUTBACK_PREGLOBAL_2018): checks += [ - ("Dashlights", 10), - ("CruiseControl", 50), + ("Wheel_Speeds", 50), + ("Dash_State2", 1), ] + if CP.carFingerprint == CAR.FORESTER_PREGLOBAL: + checks += [ + ("Dashlights", 20), + ("BodyInfo", 1), + ("CruiseControl", 50), + ] + + if CP.carFingerprint in (CAR.LEGACY_PREGLOBAL, CAR.OUTBACK_PREGLOBAL, CAR.OUTBACK_PREGLOBAL_2018): + checks += [ + ("Dashlights", 10), + ("CruiseControl", 50), + ] + return CANParser(DBC[CP.carFingerprint]["pt"], signals, checks, 0) @staticmethod @@ -173,7 +236,7 @@ class CarState(CarStateBase): ("Standstill_2", "ES_Distance"), ("Cruise_Fault", "ES_Distance"), ("Signal5", "ES_Distance"), - ("Counter", "ES_Distance"), + ("COUNTER", "ES_Distance"), ("Signal6", "ES_Distance"), ("Cruise_Button", "ES_Distance"), ("Signal7", "ES_Distance"), @@ -185,28 +248,34 @@ class CarState(CarStateBase): ] else: signals = [ - ("Cruise_Set_Speed", "ES_DashStatus"), + ("Counter", "ES_DashStatus"), + ("PCB_Off", "ES_DashStatus"), + ("LDW_Off", "ES_DashStatus"), + ("Signal1", "ES_DashStatus"), + ("Cruise_State_Msg", "ES_DashStatus"), + ("LKAS_State_Msg", "ES_DashStatus"), + ("Signal2", "ES_DashStatus"), + ("Cruise_Soft_Disable", "ES_DashStatus"), + ("EyeSight_Status_Msg", "ES_DashStatus"), + ("Signal3", "ES_DashStatus"), + ("Cruise_Distance", "ES_DashStatus"), + ("Signal4", "ES_DashStatus"), ("Conventional_Cruise", "ES_DashStatus"), + ("Signal5", "ES_DashStatus"), + ("Cruise_Disengaged", "ES_DashStatus"), + ("Cruise_Activated", "ES_DashStatus"), + ("Signal6", "ES_DashStatus"), + ("Cruise_Set_Speed", "ES_DashStatus"), + ("Cruise_Fault", "ES_DashStatus"), + ("Cruise_On", "ES_DashStatus"), + ("Display_Own_Car", "ES_DashStatus"), + ("Brake_Lights", "ES_DashStatus"), + ("Car_Follow", "ES_DashStatus"), + ("Signal7", "ES_DashStatus"), + ("Far_Distance", "ES_DashStatus"), + ("Cruise_State", "ES_DashStatus"), - ("Counter", "ES_Distance"), - ("Signal1", "ES_Distance"), - ("Cruise_Fault", "ES_Distance"), - ("Cruise_Throttle", "ES_Distance"), - ("Signal2", "ES_Distance"), - ("Car_Follow", "ES_Distance"), - ("Signal3", "ES_Distance"), - ("Cruise_Brake_Active", "ES_Distance"), - ("Distance_Swap", "ES_Distance"), - ("Cruise_EPB", "ES_Distance"), - ("Signal4", "ES_Distance"), - ("Close_Distance", "ES_Distance"), - ("Signal5", "ES_Distance"), - ("Cruise_Cancel", "ES_Distance"), - ("Cruise_Set", "ES_Distance"), - ("Cruise_Resume", "ES_Distance"), - ("Signal6", "ES_Distance"), - - ("Counter", "ES_LKAS_State"), + ("COUNTER", "ES_LKAS_State"), ("LKAS_Alert_Msg", "ES_LKAS_State"), ("Signal1", "ES_LKAS_State"), ("LKAS_ACTIVE", "ES_LKAS_State"), @@ -225,8 +294,21 @@ class CarState(CarStateBase): checks = [ ("ES_DashStatus", 10), - ("ES_Distance", 20), ("ES_LKAS_State", 10), ] + if CP.carFingerprint not in GLOBAL_GEN2: + signals += CarState.get_global_es_distance_signals()[0] + checks += CarState.get_global_es_distance_signals()[1] + return CANParser(DBC[CP.carFingerprint]["pt"], signals, checks, 2) + + @staticmethod + def get_body_can_parser(CP): + if CP.carFingerprint in GLOBAL_GEN2: + signals, checks = CarState.get_common_global_signals() + signals += CarState.get_global_es_distance_signals()[0] + checks += CarState.get_global_es_distance_signals()[1] + return CANParser(DBC[CP.carFingerprint]["pt"], signals, checks, 1) + + return None diff --git a/selfdrive/car/subaru/interface.py b/selfdrive/car/subaru/interface.py index 8c6d188643..22468801ec 100644 --- a/selfdrive/car/subaru/interface.py +++ b/selfdrive/car/subaru/interface.py @@ -1,29 +1,32 @@ #!/usr/bin/env python3 from cereal import car -from selfdrive.car.subaru.values import CAR, PREGLOBAL_CARS -from selfdrive.car import STD_CARGO_KG, scale_rot_inertia, scale_tire_stiffness, gen_empty_fingerprint, get_safety_config +from panda import Panda +from selfdrive.car import STD_CARGO_KG, get_safety_config from selfdrive.car.interfaces import CarInterfaceBase +from selfdrive.car.subaru.values import CAR, GLOBAL_GEN2, PREGLOBAL_CARS + class CarInterface(CarInterfaceBase): @staticmethod - def get_params(candidate, fingerprint=gen_empty_fingerprint(), car_fw=None): - ret = CarInterfaceBase.get_std_params(candidate, fingerprint) - + def _get_params(ret, candidate, fingerprint, car_fw, experimental_long): ret.carName = "subaru" ret.radarOffCan = True + ret.dashcamOnly = candidate in PREGLOBAL_CARS + ret.autoResumeSng = False if candidate in PREGLOBAL_CARS: - ret.safetyConfigs = [get_safety_config(car.CarParams.SafetyModel.subaruLegacy)] ret.enableBsm = 0x25c in fingerprint[0] + ret.safetyConfigs = [get_safety_config(car.CarParams.SafetyModel.subaruLegacy)] else: - ret.safetyConfigs = [get_safety_config(car.CarParams.SafetyModel.subaru)] ret.enableBsm = 0x228 in fingerprint[0] + ret.safetyConfigs = [get_safety_config(car.CarParams.SafetyModel.subaru)] + if candidate in GLOBAL_GEN2: + ret.safetyConfigs[0].safetyParam |= Panda.FLAG_SUBARU_GEN2 - ret.dashcamOnly = candidate in PREGLOBAL_CARS - - ret.steerRateCost = 0.7 ret.steerLimitTimer = 0.4 + ret.steerActuatorDelay = 0.1 + CarInterfaceBase.configure_torque_tune(candidate, ret.lateralTuning) if candidate == CAR.ASCENT: ret.mass = 2031. + STD_CARGO_KG @@ -31,100 +34,83 @@ class CarInterface(CarInterfaceBase): ret.centerToFront = ret.wheelbase * 0.5 ret.steerRatio = 13.5 ret.steerActuatorDelay = 0.3 # end-to-end angle controller + ret.lateralTuning.init('pid') ret.lateralTuning.pid.kf = 0.00003 ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0., 20.], [0., 20.]] ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.0025, 0.1], [0.00025, 0.01]] - if candidate == CAR.IMPREZA: + elif candidate == CAR.IMPREZA: ret.mass = 1568. + STD_CARGO_KG ret.wheelbase = 2.67 ret.centerToFront = ret.wheelbase * 0.5 ret.steerRatio = 15 ret.steerActuatorDelay = 0.4 # end-to-end angle controller + ret.lateralTuning.init('pid') ret.lateralTuning.pid.kf = 0.00005 ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0., 20.], [0., 20.]] ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.2, 0.3], [0.02, 0.03]] - if candidate == CAR.IMPREZA_2020: + elif candidate == CAR.IMPREZA_2020: ret.mass = 1480. + STD_CARGO_KG ret.wheelbase = 2.67 ret.centerToFront = ret.wheelbase * 0.5 ret.steerRatio = 17 # learned, 14 stock - ret.steerActuatorDelay = 0.1 + ret.lateralTuning.init('pid') ret.lateralTuning.pid.kf = 0.00005 ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0., 14., 23.], [0., 14., 23.]] ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.045, 0.042, 0.20], [0.04, 0.035, 0.045]] - if candidate == CAR.FORESTER: + elif candidate == CAR.FORESTER: ret.mass = 1568. + STD_CARGO_KG ret.wheelbase = 2.67 ret.centerToFront = ret.wheelbase * 0.5 ret.steerRatio = 17 # learned, 14 stock - ret.steerActuatorDelay = 0.1 + ret.lateralTuning.init('pid') ret.lateralTuning.pid.kf = 0.000038 ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0., 14., 23.], [0., 14., 23.]] ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.01, 0.065, 0.2], [0.001, 0.015, 0.025]] - if candidate in (CAR.FORESTER_PREGLOBAL, CAR.OUTBACK_PREGLOBAL_2018): + elif candidate in (CAR.OUTBACK, CAR.LEGACY): + ret.mass = 1568. + STD_CARGO_KG + ret.wheelbase = 2.67 + ret.centerToFront = ret.wheelbase * 0.5 + ret.steerRatio = 17 + ret.steerActuatorDelay = 0.1 + CarInterfaceBase.configure_torque_tune(candidate, ret.lateralTuning) + + elif candidate in (CAR.FORESTER_PREGLOBAL, CAR.OUTBACK_PREGLOBAL_2018): ret.safetyConfigs[0].safetyParam = 1 # Outback 2018-2019 and Forester have reversed driver torque signal ret.mass = 1568 + STD_CARGO_KG ret.wheelbase = 2.67 ret.centerToFront = ret.wheelbase * 0.5 ret.steerRatio = 20 # learned, 14 stock - ret.steerActuatorDelay = 0.1 - ret.lateralTuning.pid.kf = 0.000039 - ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0., 10., 20.], [0., 10., 20.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.01, 0.05, 0.2], [0.003, 0.018, 0.025]] - if candidate == CAR.LEGACY_PREGLOBAL: + elif candidate == CAR.LEGACY_PREGLOBAL: ret.mass = 1568 + STD_CARGO_KG ret.wheelbase = 2.67 ret.centerToFront = ret.wheelbase * 0.5 ret.steerRatio = 12.5 # 14.5 stock ret.steerActuatorDelay = 0.15 - ret.lateralTuning.pid.kf = 0.00005 - ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0., 20.], [0., 20.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.1, 0.2], [0.01, 0.02]] - if candidate == CAR.OUTBACK_PREGLOBAL: + elif candidate == CAR.OUTBACK_PREGLOBAL: ret.mass = 1568 + STD_CARGO_KG ret.wheelbase = 2.67 ret.centerToFront = ret.wheelbase * 0.5 ret.steerRatio = 20 # learned, 14 stock - ret.steerActuatorDelay = 0.1 - ret.lateralTuning.pid.kf = 0.000039 - ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0., 10., 20.], [0., 10., 20.]] - ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.01, 0.05, 0.2], [0.003, 0.018, 0.025]] - - # TODO: get actual value, for now starting with reasonable value for - # civic and scaling by mass and wheelbase - ret.rotationalInertia = scale_rot_inertia(ret.mass, ret.wheelbase) - # TODO: start from empirically derived lateral slip stiffness for the civic and scale by - # mass and CG position, so all cars will have approximately similar dyn behaviors - ret.tireStiffnessFront, ret.tireStiffnessRear = scale_tire_stiffness(ret.mass, ret.wheelbase, ret.centerToFront) + else: + raise ValueError(f"unknown car: {candidate}") return ret # returns a car.CarState - def update(self, c, can_strings): - self.cp.update_strings(can_strings) - self.cp_cam.update_strings(can_strings) + def _update(self, c): - ret = self.CS.update(self.cp, self.cp_cam) - - ret.canValid = self.cp.can_valid and self.cp_cam.can_valid - ret.steeringRateLimited = self.CC.steer_rate_limited if self.CC is not None else False + ret = self.CS.update(self.cp, self.cp_cam, self.cp_body) ret.events = self.create_common_events(ret).to_msg() - self.CS.out = ret.as_reader() - return self.CS.out + return ret def apply(self, c): - hud_control = c.hudControl - ret = self.CC.update(c, c.enabled, self.CS, self.frame, c.actuators, - c.cruiseControl.cancel, hud_control.visualAlert, - hud_control.leftLaneVisible, hud_control.rightLaneVisible, hud_control.leftLaneDepart, hud_control.rightLaneDepart) - self.frame += 1 - return ret + return self.CC.update(c, self.CS) diff --git a/selfdrive/car/subaru/subarucan.py b/selfdrive/car/subaru/subarucan.py index 86ec5e8bd4..d83b639a41 100644 --- a/selfdrive/car/subaru/subarucan.py +++ b/selfdrive/car/subaru/subarucan.py @@ -3,29 +3,23 @@ from cereal import car VisualAlert = car.CarControl.HUDControl.VisualAlert -def create_steering_control(packer, apply_steer, frame, steer_step): - - idx = (frame / steer_step) % 16 - +def create_steering_control(packer, apply_steer): values = { - "Counter": idx, "LKAS_Output": apply_steer, "LKAS_Request": 1 if apply_steer != 0 else 0, "SET_1": 1 } - return packer.make_can_msg("ES_LKAS", 0, values) -def create_steering_status(packer, apply_steer, frame, steer_step): +def create_steering_status(packer): return packer.make_can_msg("ES_LKAS_State", 0, {}) -def create_es_distance(packer, es_distance_msg, pcm_cancel_cmd): - +def create_es_distance(packer, es_distance_msg, bus, pcm_cancel_cmd): values = copy.copy(es_distance_msg) + values["COUNTER"] = (values["COUNTER"] + 1) % 0x10 if pcm_cancel_cmd: values["Cruise_Cancel"] = 1 - - return packer.make_can_msg("ES_Distance", 0, values) + return packer.make_can_msg("ES_Distance", bus, values) def create_es_lkas(packer, es_lkas_msg, enabled, visual_alert, left_line, right_line, left_lane_depart, right_lane_depart): @@ -39,6 +33,18 @@ def create_es_lkas(packer, es_lkas_msg, enabled, visual_alert, left_line, right_ if values["LKAS_Alert"] == 27: values["LKAS_Alert"] = 0 + # Filter the stock LKAS sending an audible alert when "Keep hands on wheel" alert is active (2020+ models) + if values["LKAS_Alert"] == 28 and values["LKAS_Alert_Msg"] == 7: + values["LKAS_Alert"] = 0 + + # Filter the stock LKAS sending an audible alert when "Keep hands on wheel OFF" alert is active (2020+ models) + if values["LKAS_Alert"] == 30: + values["LKAS_Alert"] = 0 + + # Filter the stock LKAS sending "Keep hands on wheel OFF" alert (2020+ models) + if values["LKAS_Alert_Msg"] == 7: + values["LKAS_Alert_Msg"] = 0 + # Show Keep hands on wheel alert for openpilot steerRequired alert if visual_alert == VisualAlert.steerRequired: values["LKAS_Alert_Msg"] = 1 @@ -54,25 +60,30 @@ def create_es_lkas(packer, es_lkas_msg, enabled, visual_alert, left_line, right_ values["LKAS_ACTIVE"] = 1 # Show LKAS lane lines values["LKAS_Dash_State"] = 2 # Green enabled indicator else: - values["LKAS_Dash_State"] = 0 # LKAS Not enabled + values["LKAS_Dash_State"] = 0 # LKAS Not enabled values["LKAS_Left_Line_Visible"] = int(left_line) values["LKAS_Right_Line_Visible"] = int(right_line) return packer.make_can_msg("ES_LKAS_State", 0, values) +def create_es_dashstatus(packer, dashstatus_msg): + values = copy.copy(dashstatus_msg) + + # Filter stock LKAS disabled and Keep hands on steering wheel OFF alerts + if values["LKAS_State_Msg"] in [2, 3]: + values["LKAS_State_Msg"] = 0 + + return packer.make_can_msg("ES_DashStatus", 0, values) + # *** Subaru Pre-global *** def subaru_preglobal_checksum(packer, values, addr): dat = packer.make_can_msg(addr, 0, values)[2] return (sum(dat[:7])) % 256 -def create_preglobal_steering_control(packer, apply_steer, frame, steer_step): - - idx = (frame / steer_step) % 8 - +def create_preglobal_steering_control(packer, apply_steer): values = { - "Counter": idx, "LKAS_Command": apply_steer, "LKAS_Active": 1 if apply_steer != 0 else 0 } diff --git a/selfdrive/car/subaru/values.py b/selfdrive/car/subaru/values.py index 5c25bc10b4..6ac2637fa2 100644 --- a/selfdrive/car/subaru/values.py +++ b/selfdrive/car/subaru/values.py @@ -1,48 +1,95 @@ -from selfdrive.car import dbc_dict +from dataclasses import dataclass +from enum import Enum +from typing import Dict, List, Union + from cereal import car +from panda.python import uds +from selfdrive.car import dbc_dict +from selfdrive.car.docs_definitions import CarInfo, Harness +from selfdrive.car.fw_query_definitions import FwQueryConfig, Request, StdQueries, p16 + Ecu = car.CarParams.Ecu + class CarControllerParams: def __init__(self, CP): - if CP.carFingerprint == CAR.IMPREZA_2020: - self.STEER_MAX = 1439 - else: - self.STEER_MAX = 2047 self.STEER_STEP = 2 # how often we update the steer cmd self.STEER_DELTA_UP = 50 # torque increase per refresh, 0.8s to max self.STEER_DELTA_DOWN = 70 # torque decrease per refresh self.STEER_DRIVER_ALLOWANCE = 60 # allowed driver torque before start limiting - self.STEER_DRIVER_MULTIPLIER = 10 # weight driver torque heavily + self.STEER_DRIVER_MULTIPLIER = 50 # weight driver torque heavily self.STEER_DRIVER_FACTOR = 1 # from dbc + if CP.carFingerprint in GLOBAL_GEN2: + self.STEER_MAX = 1000 + self.STEER_DELTA_UP = 40 + self.STEER_DELTA_DOWN = 40 + elif CP.carFingerprint == CAR.IMPREZA_2020: + self.STEER_MAX = 1439 + else: + self.STEER_MAX = 2047 + + class CAR: + # Global platform ASCENT = "SUBARU ASCENT LIMITED 2019" IMPREZA = "SUBARU IMPREZA LIMITED 2019" IMPREZA_2020 = "SUBARU IMPREZA SPORT 2020" FORESTER = "SUBARU FORESTER 2019" + OUTBACK = "SUBARU OUTBACK 6TH GEN" + LEGACY = "SUBARU LEGACY 7TH GEN" + + # Pre-global FORESTER_PREGLOBAL = "SUBARU FORESTER 2017 - 2018" LEGACY_PREGLOBAL = "SUBARU LEGACY 2015 - 2018" OUTBACK_PREGLOBAL = "SUBARU OUTBACK 2015 - 2017" OUTBACK_PREGLOBAL_2018 = "SUBARU OUTBACK 2018 - 2019" -FINGERPRINTS = { - CAR.IMPREZA: [{ - 2: 8, 64: 8, 65: 8, 72: 8, 73: 8, 280: 8, 281: 8, 290: 8, 312: 8, 313: 8, 314: 8, 315: 8, 316: 8, 326: 8, 372: 8, 544: 8, 545: 8, 546: 8, 552: 8, 554: 8, 557: 8, 576: 8, 577: 8, 722: 8, 801: 8, 802: 8, 805: 8, 808: 8, 811: 8, 816: 8, 826: 8, 827: 8, 837: 8, 838: 8, 839: 8, 842: 8, 912: 8, 915: 8, 940: 8, 1614: 8, 1617: 8, 1632: 8, 1650: 8, 1657: 8, 1658: 8, 1677: 8, 1697: 8, 1722: 8, 1743: 8, 1759: 8, 1786: 5, 1787: 5, 1788: 8, 1809: 8, 1813: 8, 1817: 8, 1821: 8, 1840: 8, 1848: 8, 1924: 8, 1932: 8, 1952: 8, 1960: 8 - }], - CAR.IMPREZA_2020: [{ - 2: 8, 64: 8, 65: 8, 72: 8, 73: 8, 280: 8, 281: 8, 282: 8, 290: 8, 312: 8, 313: 8, 314: 8, 315: 8, 316: 8, 326: 8, 372: 8, 544: 8, 545: 8, 546: 8, 552: 8, 554: 8, 557: 8, 576: 8, 577: 8, 722: 8, 801: 8, 802: 8, 803: 8, 805: 8, 808: 8, 816: 8, 826: 8, 837: 8, 838: 8, 839: 8, 842: 8, 912: 8, 915: 8, 940: 8, 1617: 8, 1632: 8, 1650: 8, 1677: 8, 1697: 8, 1722: 8, 1743: 8, 1759: 8, 1786: 5, 1787: 5, 1788: 8, 1809: 8, 1813: 8, 1817: 8, 1821: 8, 1840: 8, 1848: 8, 1924: 8, 1932: 8, 1952: 8, 1960: 8, 1968: 8, 1976: 8, 2015: 8, 2016: 8, 2024: 8 - }, - { - 2: 8, 64: 8, 65: 8, 72: 8, 73: 8, 280: 8, 281: 8, 282: 8, 290: 8, 312: 8, 313: 8, 314: 8, 315: 8, 316: 8, 326: 8, 544: 8, 545: 8, 546: 8, 554: 8, 557: 8, 576: 8, 577: 8, 801: 8, 802: 8, 803: 8, 805: 8, 808: 8, 816: 8, 826: 8, 837: 8, 838: 8, 839: 8, 842: 8, 912: 8, 915: 8, 940: 8, 1614: 8, 1617: 8, 1632: 8, 1657: 8, 1658: 8, 1677: 8, 1697: 8, 1743: 8, 1759: 8, 1786: 5, 1787: 5, 1788: 8, 1809: 8, 1813: 8, 1817: 8, 1821: 8, 1840: 8, 1848: 8, 1924: 8, 1932: 8, 1952: 8, 1960: 8 - }], - CAR.FORESTER: [{ - 2: 8, 64: 8, 65: 8, 72: 8, 73: 8, 280: 8, 281: 8, 282: 8, 290: 8, 312: 8, 313: 8, 314: 8, 315: 8, 316: 8, 326: 8, 372: 8, 544: 8, 545: 8, 546: 8, 552: 8, 554: 8, 557: 8, 576: 8, 577: 8, 722: 8, 801: 8, 802: 8, 803: 8, 805: 8, 808: 8, 811: 8, 816: 8, 826: 8, 837: 8, 838: 8, 839: 8, 842: 8, 912: 8, 915: 8, 940: 8, 961: 8, 984: 8, 1614: 8, 1617: 8, 1632: 8, 1650: 8, 1651: 8, 1657: 8, 1658: 8, 1677: 8, 1697: 8, 1698: 8, 1722: 8, 1743: 8, 1759: 8, 1787: 5, 1788: 8, 1809: 8, 1813: 8, 1817: 8, 1821: 8, 1840: 8, 1848: 8, 1924: 8, 1932: 8, 1952: 8, 1960: 8 - }], + +@dataclass +class SubaruCarInfo(CarInfo): + package: str = "EyeSight Driver Assistance" + harness: Enum = Harness.subaru_a + + +CAR_INFO: Dict[str, Union[SubaruCarInfo, List[SubaruCarInfo]]] = { + CAR.ASCENT: SubaruCarInfo("Subaru Ascent 2019-21", "All"), + CAR.OUTBACK: SubaruCarInfo("Subaru Outback 2020-22", "All", harness=Harness.subaru_b), + CAR.LEGACY: SubaruCarInfo("Subaru Legacy 2020-22", "All", harness=Harness.subaru_b), + CAR.IMPREZA: [ + SubaruCarInfo("Subaru Impreza 2017-19"), + SubaruCarInfo("Subaru Crosstrek 2018-19", video_link="https://youtu.be/Agww7oE1k-s?t=26"), + SubaruCarInfo("Subaru XV 2018-19", video_link="https://youtu.be/Agww7oE1k-s?t=26"), + ], + CAR.IMPREZA_2020: [ + SubaruCarInfo("Subaru Impreza 2020-22"), + SubaruCarInfo("Subaru Crosstrek 2020-23"), + SubaruCarInfo("Subaru XV 2020-21"), + ], + CAR.FORESTER: SubaruCarInfo("Subaru Forester 2019-21", "All"), + CAR.FORESTER_PREGLOBAL: SubaruCarInfo("Subaru Forester 2017-18"), + CAR.LEGACY_PREGLOBAL: SubaruCarInfo("Subaru Legacy 2015-18"), + CAR.OUTBACK_PREGLOBAL: SubaruCarInfo("Subaru Outback 2015-17"), + CAR.OUTBACK_PREGLOBAL_2018: SubaruCarInfo("Subaru Outback 2018-19"), } +SUBARU_VERSION_REQUEST = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER]) + \ + p16(uds.DATA_IDENTIFIER_TYPE.APPLICATION_DATA_IDENTIFICATION) +SUBARU_VERSION_RESPONSE = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER + 0x40]) + \ + p16(uds.DATA_IDENTIFIER_TYPE.APPLICATION_DATA_IDENTIFICATION) + +FW_QUERY_CONFIG = FwQueryConfig( + requests=[ + Request( + [StdQueries.TESTER_PRESENT_REQUEST, SUBARU_VERSION_REQUEST], + [StdQueries.TESTER_PRESENT_RESPONSE, SUBARU_VERSION_RESPONSE], + ), + ], +) + FW_VERSIONS = { CAR.ASCENT: { - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'\xa5 \x19\x02\x00', b'\xa5 !\002\000', b'\xf1\x82\xa5 \x19\x02\x00', @@ -56,6 +103,8 @@ FW_VERSIONS = { b'\x00\x00d\xb9\x1f@ \x10', b'\000\000e~\037@ \'', b'\x00\x00e@\x1f@ $', + b'\x00\x00d\xb9\x00\x00\x00\x00', + b'\x00\x00e@\x00\x00\x00\x00', ], (Ecu.engine, 0x7e0, None): [ b'\xbb,\xa0t\a', @@ -63,32 +112,64 @@ FW_VERSIONS = { b'\xf1\x82\xbb,\xa0t\a', b'\xf1\x82\xd9,\xa0@\a', b'\xf1\x82\xd1,\xa0q\x07', + b'\xd1,\xa0q\x07', ], (Ecu.transmission, 0x7e1, None): [ b'\x00\xfe\xf7\x00\x00', b'\001\xfe\xf9\000\000', b'\x01\xfe\xf7\x00\x00', + b'\x01\xfe\xfa\x00\x00', + ], + }, + CAR.LEGACY: { + (Ecu.abs, 0x7b0, None): [ + b'\xa1\\ x04\x01', + b'\xa1 \x03\x03', + b'\xa1 \x02\x01', + ], + (Ecu.eps, 0x746, None): [ + b'\x9b\xc0\x11\x00', + b'\x9b\xc0\x11\x02', + ], + (Ecu.fwdCamera, 0x787, None): [ + b'\x00\x00e\x80\x00\x1f@ \x19\x00', + b'\x00\x00e\x9a\x00\x00\x00\x00\x00\x00', + ], + (Ecu.engine, 0x7e0, None): [ + b'\xde\"a0\x07', + b'\xe2"aq\x07', + b'\xde,\xa0@\x07', + ], + (Ecu.transmission, 0x7e1, None): [ + b'\xa5\xf6\x05@\x00', + b'\xa7\xf6\x04@\x00', + b'\xa5\xfe\xc7@\x00', ], }, CAR.IMPREZA: { - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'\x7a\x94\x3f\x90\x00', b'\xa2 \x185\x00', b'\xa2 \x193\x00', + b'\xa2 \x194\x00', b'z\x94.\x90\x00', b'z\x94\b\x90\x01', b'\xa2 \x19`\x00', b'z\x94\f\x90\001', b'z\x9c\x19\x80\x01', b'z\x94\x08\x90\x00', + b'z\x84\x19\x90\x00', + b'\xf1\x00\xb2\x06\x04', + b'z\x94\x0c\x90\x00', ], (Ecu.eps, 0x746, None): [ b'\x7a\xc0\x0c\x00', - b'z\xc0\b\x00', + b'z\xc0\x08\x00', b'\x8a\xc0\x00\x00', b'z\xc0\x04\x00', b'z\xc0\x00\x00', b'\x8a\xc0\x10\x00', + b'z\xc0\n\x00', ], (Ecu.fwdCamera, 0x787, None): [ b'\x00\x00\x64\xb5\x1f\x40\x20\x0e', @@ -101,6 +182,9 @@ FW_VERSIONS = { b'\000\000e\002\037@ \024', b'\x00\x00d)\x00\x00\x00\x00', b'\x00\x00c\xf4\x00\x00\x00\x00', + b'\x00\x00d\xdc\x00\x00\x00\x00', + b'\x00\x00dd\x00\x00\x00\x00', + b'\x00\x00c\xf4\x1f@ \x07', ], (Ecu.engine, 0x7e0, None): [ b'\xaa\x61\x66\x73\x07', @@ -110,9 +194,9 @@ FW_VERSIONS = { b'\xaa!`u\a', b'\xaa!dq\a', b'\xaa!dt\a', - b'\xf1\x00\xa2\x10\t', b'\xc5!ar\a', b'\xbe!as\a', + b'\xc5!as\x07', b'\xc5!ds\a', b'\xc5!`s\a', b'\xaa!au\a', @@ -120,6 +204,7 @@ FW_VERSIONS = { b'\xaa\x00Bu\x07', b'\xc5!dr\x07', b'\xaa!aw\x07', + b'\xaa!av\x07', ], (Ecu.transmission, 0x7e1, None): [ b'\xe3\xe5\x46\x31\x00', @@ -135,23 +220,29 @@ FW_VERSIONS = { b'\xe4\xf5\002\000\000', b'\xe3\xd0\x081\x00', b'\xe3\xf5\x06\x00\x00', - b'\xf1\x00\xa4\x10@', ], }, CAR.IMPREZA_2020: { - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'\xa2 \0314\000', b'\xa2 \0313\000', b'\xa2 !i\000', b'\xa2 !`\000', + b'\xf1\x00\xb2\x06\x04', + b'\xa2 `\x00', ], (Ecu.eps, 0x746, None): [ b'\x9a\xc0\000\000', b'\n\xc0\004\000', + b'\x9a\xc0\x04\x00', + b'\n\xc0\x04\x01', ], (Ecu.fwdCamera, 0x787, None): [ b'\000\000eb\037@ \"', b'\000\000e\x8f\037@ )', + b'\x00\x00eq\x1f@ "', + b'\x00\x00eq\x00\x00\x00\x00', + b'\x00\x00e\x8f\x00\x00\x00\x00', ], (Ecu.engine, 0x7e0, None): [ b'\xca!ap\a', @@ -159,47 +250,57 @@ FW_VERSIONS = { b'\xca!`0\a', b'\xcc\"f0\a', b'\xcc!fp\a', + b'\xca!f@\x07', + b'\xca!fp\x07', + b'\xf3"f@\x07', ], (Ecu.transmission, 0x7e1, None): [ b'\xe6\xf5\004\000\000', b'\xe6\xf5$\000\000', b'\xe7\xf6B0\000', b'\xe7\xf5D0\000', + b'\xf1\x00\xd7\x10@', + b'\xe6\xf5D0\x00', + b'\xe9\xf6F0\x00', ], }, CAR.FORESTER: { - (Ecu.esp, 0x7b0, None): [ - b'\xa3 \030\024\000', + (Ecu.abs, 0x7b0, None): [ + b'\xa3 \x18\x14\x00', b'\xa3 \024\000', b'\xa3 \031\024\000', - b'\xa3 \024\001', + b'\xa3 \x14\x01', + b'\xf1\x00\xbb\r\x05', ], (Ecu.eps, 0x746, None): [ - b'\x8d\xc0\004\000', + b'\x8d\xc0\x04\x00', ], (Ecu.fwdCamera, 0x787, None): [ - b'\000\000e!\037@ \021', - b'\000\000e\x97\037@ 0', + b'\x00\x00e!\x1f@ \x11', + b'\x00\x00e\x97\x1f@ 0', b'\000\000e`\037@ ', b'\xf1\x00\xac\x02\x00', + b'\x00\x00e!\x00\x00\x00\x00', + b'\x00\x00e\x97\x00\x00\x00\x00', ], (Ecu.engine, 0x7e0, None): [ - b'\xb6\"`A\a', - b'\xcf"`0\a', + b'\xb6"`A\x07', + b'\xcf"`0\x07', b'\xcb\"`@\a', b'\xcb\"`p\a', b'\xf1\x00\xa2\x10\n', + b'\xcf"`p\x07', ], (Ecu.transmission, 0x7e1, None): [ b'\032\xf6B0\000', - b'\032\xf6F`\000', + b'\x1a\xf6F`\x00', b'\032\xf6b`\000', - b'\032\xf6B`\000', - b'\xf1\x00\xa4\x10@', + b'\x1a\xf6B`\x00', + b'\x1a\xf6b0\x00', ], }, CAR.FORESTER_PREGLOBAL: { - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'\x7d\x97\x14\x40', b'\xf1\x00\xbb\x0c\x04', ], @@ -224,10 +325,11 @@ FW_VERSIONS = { b'\xda\xfd\xe0\x80\x00', b'\xdc\xf2`\x81\000', b'\xdc\xf2`\x80\x00', + b'\x1a\xf6F`\x00', ], }, CAR.LEGACY_PREGLOBAL: { - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'k\x97D\x00', b'[\xba\xc4\x03', b'{\x97D\x00', @@ -257,7 +359,7 @@ FW_VERSIONS = { ], }, CAR.OUTBACK_PREGLOBAL: { - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'{\x9a\xac\x00', b'k\x97\xac\x00', b'\x5b\xf7\xbc\x03', @@ -311,7 +413,7 @@ FW_VERSIONS = { ], }, CAR.OUTBACK_PREGLOBAL_2018: { - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'\x8b\x97\xac\x00', b'\x8b\x9a\xac\x00', b'\x9b\x97\xac\x00', @@ -353,17 +455,49 @@ FW_VERSIONS = { b'\xbb\xfb\xe0`\000', ], }, -} - -STEER_THRESHOLD = { - CAR.ASCENT: 80, - CAR.IMPREZA: 80, - CAR.IMPREZA_2020: 80, - CAR.FORESTER: 80, - CAR.FORESTER_PREGLOBAL: 75, - CAR.LEGACY_PREGLOBAL: 75, - CAR.OUTBACK_PREGLOBAL: 75, - CAR.OUTBACK_PREGLOBAL_2018: 75, + CAR.OUTBACK: { + (Ecu.abs, 0x7b0, None): [ + b'\xa1 \x06\x01', + b'\xa1 \a\x00', + b'\xa1 \b\001', + b'\xa1 \x06\x00', + b'\xa1 "\t\x01', + b'\xa1 \x08\x02', + b'\xa1 \x06\x02', + b'\xa1 \x08\x00', + b'\xa1 "\t\x00', + ], + (Ecu.eps, 0x746, None): [ + b'\x9b\xc0\x10\x00', + b'\x9b\xc0\x20\x00', + b'\x1b\xc0\x10\x00', + ], + (Ecu.fwdCamera, 0x787, None): [ + b'\x00\x00eJ\x00\x1f@ \x19\x00', + b'\000\000e\x80\000\037@ \031\000', + b'\x00\x00e\x9a\x00\x1f@ 1\x00', + b'\x00\x00eJ\x00\x00\x00\x00\x00\x00', + ], + (Ecu.engine, 0x7e0, None): [ + b'\xbc,\xa0q\x07', + b'\xbc\"`@\a', + b'\xde"`0\a', + b'\xf1\x82\xbc,\xa0q\a', + b'\xf1\x82\xe3,\xa0@\x07', + b'\xe2"`p\x07', + b'\xf1\x82\xe2,\xa0@\x07', + b'\xbc"`q\x07', + b'\xe3,\xa0@\x07', + ], + (Ecu.transmission, 0x7e1, None): [ + b'\xa5\xfe\xf7@\x00', + b'\xa5\xf6D@\x00', + b'\xa5\xfe\xf6@\x00', + b'\xa7\x8e\xf40\x00', + b'\xf1\x82\xa7\xf6D@\x00', + b'\xa7\xfe\xf4@\x00', + ], + }, } DBC = { @@ -371,10 +505,13 @@ DBC = { CAR.IMPREZA: dbc_dict('subaru_global_2017_generated', None), CAR.IMPREZA_2020: dbc_dict('subaru_global_2017_generated', None), CAR.FORESTER: dbc_dict('subaru_global_2017_generated', None), + CAR.OUTBACK: dbc_dict('subaru_global_2017_generated', None), + CAR.LEGACY: dbc_dict('subaru_global_2017_generated', None), CAR.FORESTER_PREGLOBAL: dbc_dict('subaru_forester_2017_generated', None), CAR.LEGACY_PREGLOBAL: dbc_dict('subaru_outback_2015_generated', None), CAR.OUTBACK_PREGLOBAL: dbc_dict('subaru_outback_2015_generated', None), CAR.OUTBACK_PREGLOBAL_2018: dbc_dict('subaru_outback_2019_generated', None), } -PREGLOBAL_CARS = [CAR.FORESTER_PREGLOBAL, CAR.LEGACY_PREGLOBAL, CAR.OUTBACK_PREGLOBAL, CAR.OUTBACK_PREGLOBAL_2018] +GLOBAL_GEN2 = (CAR.OUTBACK, CAR.LEGACY) +PREGLOBAL_CARS = (CAR.FORESTER_PREGLOBAL, CAR.LEGACY_PREGLOBAL, CAR.OUTBACK_PREGLOBAL, CAR.OUTBACK_PREGLOBAL_2018) diff --git a/selfdrive/car/tesla/carcontroller.py b/selfdrive/car/tesla/carcontroller.py index 03f09f2407..cf43b8ef00 100644 --- a/selfdrive/car/tesla/carcontroller.py +++ b/selfdrive/car/tesla/carcontroller.py @@ -3,66 +3,67 @@ from opendbc.can.packer import CANPacker from selfdrive.car.tesla.teslacan import TeslaCAN from selfdrive.car.tesla.values import DBC, CANBUS, CarControllerParams -class CarController(): + +class CarController: def __init__(self, dbc_name, CP, VM): self.CP = CP + self.frame = 0 self.last_angle = 0 - self.long_control_counter = 0 self.packer = CANPacker(dbc_name) self.pt_packer = CANPacker(DBC[CP.carFingerprint]['pt']) self.tesla_can = TeslaCAN(self.packer, self.pt_packer) - def update(self, c, enabled, CS, frame, actuators, cruise_cancel): + def update(self, CC, CS): + actuators = CC.actuators + pcm_cancel_cmd = CC.cruiseControl.cancel + can_sends = [] # Temp disable steering on a hands_on_fault, and allow for user override - hands_on_fault = (CS.steer_warning == "EAC_ERROR_HANDS_ON" and CS.hands_on_level >= 3) - lkas_enabled = c.active and (not hands_on_fault) + hands_on_fault = CS.steer_warning == "EAC_ERROR_HANDS_ON" and CS.hands_on_level >= 3 + lkas_enabled = CC.latActive and not hands_on_fault if lkas_enabled: apply_angle = actuators.steeringAngleDeg # Angular rate limit based on speed - steer_up = (self.last_angle * apply_angle > 0. and abs(apply_angle) > abs(self.last_angle)) + steer_up = self.last_angle * apply_angle > 0. and abs(apply_angle) > abs(self.last_angle) rate_limit = CarControllerParams.RATE_LIMIT_UP if steer_up else CarControllerParams.RATE_LIMIT_DOWN max_angle_diff = interp(CS.out.vEgo, rate_limit.speed_points, rate_limit.max_angle_diff_points) - apply_angle = clip(apply_angle, (self.last_angle - max_angle_diff), (self.last_angle + max_angle_diff)) + apply_angle = clip(apply_angle, self.last_angle - max_angle_diff, self.last_angle + max_angle_diff) # To not fault the EPS - apply_angle = clip(apply_angle, (CS.out.steeringAngleDeg - 20), (CS.out.steeringAngleDeg + 20)) + apply_angle = clip(apply_angle, CS.out.steeringAngleDeg - 20, CS.out.steeringAngleDeg + 20) else: apply_angle = CS.out.steeringAngleDeg self.last_angle = apply_angle - can_sends.append(self.tesla_can.create_steering_control(apply_angle, lkas_enabled, frame)) + can_sends.append(self.tesla_can.create_steering_control(apply_angle, lkas_enabled, self.frame)) - # Longitudinal control (40Hz) - if self.CP.openpilotLongitudinalControl and ((frame % 5) in (0, 2)): + # Longitudinal control (in sync with stock message, about 40Hz) + if self.CP.openpilotLongitudinalControl: target_accel = actuators.accel target_speed = max(CS.out.vEgo + (target_accel * CarControllerParams.ACCEL_TO_SPEED_MULTIPLIER), 0) max_accel = 0 if target_accel < 0 else target_accel min_accel = 0 if target_accel > 0 else target_accel - can_sends.extend(self.tesla_can.create_longitudinal_commands(CS.acc_state, target_speed, min_accel, max_accel, self.long_control_counter)) - self.long_control_counter += 1 + while len(CS.das_control_counters) > 0: + can_sends.extend(self.tesla_can.create_longitudinal_commands(CS.acc_state, target_speed, min_accel, max_accel, CS.das_control_counters.popleft())) # Cancel on user steering override, since there is no steering torque blending if hands_on_fault: - cruise_cancel = True - - # Cancel when openpilot is not enabled anymore - if not enabled and bool(CS.out.cruiseState.enabled): - cruise_cancel = True + pcm_cancel_cmd = True - if ((frame % 10) == 0 and cruise_cancel): + if self.frame % 10 == 0 and pcm_cancel_cmd: # Spam every possible counter value, otherwise it might not be accepted for counter in range(16): - can_sends.append(self.tesla_can.create_action_request(CS.msg_stw_actn_req, cruise_cancel, CANBUS.chassis, counter)) - can_sends.append(self.tesla_can.create_action_request(CS.msg_stw_actn_req, cruise_cancel, CANBUS.autopilot_chassis, counter)) + can_sends.append(self.tesla_can.create_action_request(CS.msg_stw_actn_req, pcm_cancel_cmd, CANBUS.chassis, counter)) + can_sends.append(self.tesla_can.create_action_request(CS.msg_stw_actn_req, pcm_cancel_cmd, CANBUS.autopilot_chassis, counter)) # TODO: HUD control new_actuators = actuators.copy() new_actuators.steeringAngleDeg = apply_angle + self.frame += 1 return new_actuators, can_sends diff --git a/selfdrive/car/tesla/carstate.py b/selfdrive/car/tesla/carstate.py index 51ae43ad1b..0f373842f2 100644 --- a/selfdrive/car/tesla/carstate.py +++ b/selfdrive/car/tesla/carstate.py @@ -1,10 +1,11 @@ import copy +from collections import deque from cereal import car +from common.conversions import Conversions as CV from selfdrive.car.tesla.values import DBC, CANBUS, GEAR_MAP, DOORS, BUTTONS from selfdrive.car.interfaces import CarStateBase from opendbc.can.parser import CANParser from opendbc.can.can_define import CANDefine -from selfdrive.config import Conversions as CV class CarState(CarStateBase): def __init__(self, CP): @@ -17,6 +18,7 @@ class CarState(CarStateBase): self.hands_on_level = 0 self.steer_warning = None self.acc_state = 0 + self.das_control_counters = deque(maxlen=32) def update(self, cp, cp_cam): ret = car.CarState.new_message() @@ -43,8 +45,8 @@ class CarState(CarStateBase): ret.steeringRateDeg = -cp.vl["STW_ANGLHP_STAT"]["StW_AnglHP_Spd"] # This is from a different angle sensor, and at different rate ret.steeringTorque = -cp.vl["EPAS_sysStatus"]["EPAS_torsionBarTorque"] ret.steeringPressed = (self.hands_on_level > 0) - ret.steerError = steer_status == "EAC_FAULT" - ret.steerWarning = self.steer_warning != "EAC_ERROR_IDLE" + ret.steerFaultPermanent = steer_status == "EAC_FAULT" + ret.steerFaultTemporary = (self.steer_warning not in ("EAC_ERROR_IDLE", "EAC_ERROR_HANDS_ON")) # Cruise state cruise_state = self.can_define.dv["DI_state"]["DI_cruiseState"].get(int(cp.vl["DI_state"]["DI_cruiseState"]), None) @@ -87,9 +89,13 @@ class CarState(CarStateBase): # TODO: blindspot + # AEB + ret.stockAeb = (cp_cam.vl["DAS_control"]["DAS_aebEvent"] == 1) + # Messages needed by carcontroller self.msg_stw_actn_req = copy.copy(cp.vl["STW_ACTN_RQ"]) self.acc_state = cp_cam.vl["DAS_control"]["DAS_accState"] + self.das_control_counters.extend(cp_cam.vl_all["DAS_control"]["DAS_controlCounter"]) return ret @@ -177,6 +183,8 @@ class CarState(CarStateBase): signals = [ # sig_name, sig_address ("DAS_accState", "DAS_control"), + ("DAS_aebEvent", "DAS_control"), + ("DAS_controlCounter", "DAS_control"), ] checks = [ # sig_address, frequency diff --git a/selfdrive/car/tesla/interface.py b/selfdrive/car/tesla/interface.py index 03012bc52e..49e06d8923 100755 --- a/selfdrive/car/tesla/interface.py +++ b/selfdrive/car/tesla/interface.py @@ -2,14 +2,13 @@ from cereal import car from panda import Panda from selfdrive.car.tesla.values import CANBUS, CAR -from selfdrive.car import STD_CARGO_KG, gen_empty_fingerprint, scale_rot_inertia, scale_tire_stiffness, get_safety_config +from selfdrive.car import STD_CARGO_KG, get_safety_config from selfdrive.car.interfaces import CarInterfaceBase class CarInterface(CarInterfaceBase): @staticmethod - def get_params(candidate, fingerprint=gen_empty_fingerprint(), car_fw=None): - ret = CarInterfaceBase.get_std_params(candidate, fingerprint) + def _get_params(ret, candidate, fingerprint, car_fw, experimental_long): ret.carName = "tesla" # There is no safe way to do steer blending with user torque, @@ -41,36 +40,24 @@ class CarInterface(CarInterfaceBase): ret.safetyConfigs = [get_safety_config(car.CarParams.SafetyModel.tesla, 0)] ret.steerLimitTimer = 1.0 - ret.steerActuatorDelay = 0.1 - ret.steerRateCost = 0.5 + ret.steerActuatorDelay = 0.25 if candidate in (CAR.AP2_MODELS, CAR.AP1_MODELS): ret.mass = 2100. + STD_CARGO_KG ret.wheelbase = 2.959 ret.centerToFront = ret.wheelbase * 0.5 - ret.steerRatio = 13.5 + ret.steerRatio = 15.0 else: raise ValueError(f"Unsupported car: {candidate}") - ret.rotationalInertia = scale_rot_inertia(ret.mass, ret.wheelbase) - ret.tireStiffnessFront, ret.tireStiffnessRear = scale_tire_stiffness(ret.mass, ret.wheelbase, ret.centerToFront) - return ret - def update(self, c, can_strings): - self.cp.update_strings(can_strings) - self.cp_cam.update_strings(can_strings) - + def _update(self, c): ret = self.CS.update(self.cp, self.cp_cam) - ret.canValid = self.cp.can_valid and self.cp_cam.can_valid - events = self.create_common_events(ret) + ret.events = self.create_common_events(ret).to_msg() - ret.events = events.to_msg() - self.CS.out = ret.as_reader() - return self.CS.out + return ret def apply(self, c): - ret = self.CC.update(c, c.enabled, self.CS, self.frame, c.actuators, c.cruiseControl.cancel) - self.frame += 1 - return ret + return self.CC.update(c, self.CS) diff --git a/selfdrive/car/tesla/teslacan.py b/selfdrive/car/tesla/teslacan.py index 1301802860..e5d904f80e 100644 --- a/selfdrive/car/tesla/teslacan.py +++ b/selfdrive/car/tesla/teslacan.py @@ -1,6 +1,7 @@ import copy import crcmod -from selfdrive.config import Conversions as CV + +from common.conversions import Conversions as CV from selfdrive.car.tesla.values import CANBUS, CarControllerParams @@ -50,7 +51,7 @@ class TeslaCAN: "DAS_jerkMax": CarControllerParams.JERK_LIMIT_MAX, "DAS_accelMin": min_accel, "DAS_accelMax": max_accel, - "DAS_controlCounter": (cnt % 8), + "DAS_controlCounter": cnt, "DAS_controlChecksum": 0, } diff --git a/selfdrive/car/tesla/values.py b/selfdrive/car/tesla/values.py index 616933789e..750fe885e8 100644 --- a/selfdrive/car/tesla/values.py +++ b/selfdrive/car/tesla/values.py @@ -1,20 +1,28 @@ from collections import namedtuple -from selfdrive.car import dbc_dict +from typing import Dict, List, Union + from cereal import car +from selfdrive.car import dbc_dict +from selfdrive.car.docs_definitions import CarInfo +from selfdrive.car.fw_query_definitions import FwQueryConfig, Request, StdQueries + +Ecu = car.CarParams.Ecu Button = namedtuple('Button', ['event_type', 'can_addr', 'can_msg', 'values']) AngleRateLimit = namedtuple('AngleRateLimit', ['speed_points', 'max_angle_diff_points']) + class CAR: AP1_MODELS = 'TESLA AP1 MODEL S' AP2_MODELS = 'TESLA AP2 MODEL S' + +CAR_INFO: Dict[str, Union[CarInfo, List[CarInfo]]] = { + CAR.AP1_MODELS: CarInfo("Tesla AP1 Model S", "All"), + CAR.AP2_MODELS: CarInfo("Tesla AP2 Model S", "All"), +} + FINGERPRINTS = { - CAR.AP2_MODELS: [ - { - 1: 8, 3: 8, 14: 8, 21: 4, 69: 8, 109: 4, 257: 3, 264: 8, 277: 6, 280: 6, 293: 4, 296: 4, 309: 5, 325: 8, 328: 5, 336: 8, 341: 8, 360: 7, 373: 8, 389: 8, 415: 8, 513: 5, 516: 8, 518: 8, 520: 4, 522: 8, 524: 8, 526: 8, 532: 3, 536: 8, 537: 3, 542: 8, 551: 5, 552: 2, 556: 8, 558: 8, 568: 8, 569: 8, 574: 8, 577: 8, 582: 5, 583: 8, 584: 4, 585: 8, 590: 8, 601: 8, 606: 8, 608: 1, 622: 8, 627: 6, 638: 8, 641: 8, 643: 8, 692: 8, 693: 8, 695: 8, 696: 8, 697: 8, 699: 8, 700: 8, 701: 8, 702: 8, 703: 8, 704: 8, 708: 8, 709: 8, 710: 8, 711: 8, 712: 8, 728: 8, 744: 8, 760: 8, 772: 8, 775: 8, 776: 8, 777: 8, 778: 8, 782: 8, 788: 8, 791: 8, 792: 8, 796: 2, 797: 8, 798: 6, 799: 8, 804: 8, 805: 8, 807: 8, 808: 1, 811: 8, 812: 8, 813: 8, 814: 5, 815: 8, 820: 8, 823: 8, 824: 8, 829: 8, 830: 5, 836: 8, 840: 8, 845: 8, 846: 5, 848: 8, 852: 8, 853: 8, 856: 4, 857: 6, 861: 8, 862: 5, 872: 8, 876: 8, 877: 8, 879: 8, 880: 8, 882: 8, 884: 8, 888: 8, 893: 8, 894: 8, 901: 6, 904: 3, 905: 8, 906: 8, 908: 2, 909: 8, 910: 8, 912: 8, 920: 8, 921: 8, 925: 4, 926: 6, 936: 8, 941: 8, 949: 8, 952: 8, 953: 6, 968: 8, 969: 6, 970: 8, 971: 8, 977: 8, 984: 8, 987: 8, 990: 8, 1000: 8, 1001: 8, 1006: 8, 1007: 8, 1008: 8, 1010: 6, 1014: 1, 1015: 8, 1016: 8, 1017: 8, 1018: 8, 1020: 8, 1026: 8, 1028: 8, 1029: 8, 1030: 8, 1032: 1, 1033: 1, 1034: 8, 1048: 1, 1049: 8, 1061: 8, 1064: 8, 1065: 8, 1070: 8, 1080: 8, 1081: 8, 1097: 8, 1113: 8, 1129: 8, 1145: 8, 1160: 4, 1177: 8, 1281: 8, 1328: 8, 1329: 8, 1332: 8, 1335: 8, 1337: 8, 1353: 8, 1368: 8, 1412: 8, 1436: 8, 1476: 8, 1481: 8, 1497: 8, 1513: 8, 1519: 8, 1601: 8, 1605: 8, 1617: 8, 1621: 8, 1800: 4, 1804: 8, 1812: 8, 1815: 8, 1816: 8, 1824: 8, 1828: 8, 1831: 8, 1832: 8, 1864: 8, 1880: 8, 1892: 8, 1896: 8, 1912: 8, 1960: 8, 1992: 8, 2008: 3, 2043: 5, 2045: 4 - }, - ], CAR.AP1_MODELS: [ { 1: 8, 3: 8, 14: 8, 21: 4, 69: 8, 109: 4, 257: 3, 264: 8, 267: 5, 277: 6, 280: 6, 283: 5, 293: 4, 296: 4, 309: 5, 325: 8, 328: 5, 336: 8, 341: 8, 360: 7, 373: 8, 389: 8, 415: 8, 513: 5, 516: 8, 520: 4, 522: 8, 524: 8, 526: 8, 532: 3, 536: 8, 537: 3, 542: 8, 551: 5, 552: 2, 556: 8, 558: 8, 568: 8, 569: 8, 574: 8, 577: 8, 582: 5, 584: 4, 585: 8, 590: 8, 606: 8, 622: 8, 627: 6, 638: 8, 641: 8, 643: 8, 660: 5, 693: 8, 696: 8, 697: 8, 712: 8, 728: 8, 744: 8, 760: 8, 772: 8, 775: 8, 776: 8, 777: 8, 778: 8, 782: 8, 788: 8, 791: 8, 792: 8, 796: 2, 797: 8, 798: 6, 799: 8, 804: 8, 805: 8, 807: 8, 808: 1, 809: 8, 812: 8, 813: 8, 814: 5, 815: 8, 820: 8, 823: 8, 824: 8, 829: 8, 830: 5, 836: 8, 840: 8, 841: 8, 845: 8, 846: 5, 852: 8, 856: 4, 857: 6, 861: 8, 862: 5, 872: 8, 873: 8, 877: 8, 878: 8, 879: 8, 880: 8, 884: 8, 888: 8, 889: 8, 893: 8, 896: 8, 901: 6, 904: 3, 905: 8, 908: 2, 909: 8, 920: 8, 921: 8, 925: 4, 936: 8, 937: 8, 941: 8, 949: 8, 952: 8, 953: 6, 957: 8, 968: 8, 973: 8, 984: 8, 987: 8, 989: 8, 990: 8, 1000: 8, 1001: 8, 1006: 8, 1016: 8, 1026: 8, 1028: 8, 1029: 8, 1030: 8, 1032: 1, 1033: 1, 1034: 8, 1048: 1, 1064: 8, 1070: 8, 1080: 8, 1160: 4, 1281: 8, 1329: 8, 1332: 8, 1335: 8, 1337: 8, 1368: 8, 1412: 8, 1436: 8, 1465: 8, 1476: 8, 1497: 8, 1524: 8, 1527: 8, 1601: 8, 1605: 8, 1611: 8, 1614: 8, 1617: 8, 1621: 8, 1627: 8, 1630: 8, 1800: 4, 1804: 8, 1812: 8, 1815: 8, 1816: 8, 1828: 8, 1831: 8, 1832: 8, 1840: 8, 1848: 8, 1864: 8, 1880: 8, 1892: 8, 1896: 8, 1912: 8, 1960: 8, 1992: 8, 2008: 3, 2043: 5, 2045: 4 @@ -27,6 +35,42 @@ DBC = { CAR.AP1_MODELS: dbc_dict('tesla_powertrain', 'tesla_radar', chassis_dbc='tesla_can'), } +FW_QUERY_CONFIG = FwQueryConfig( + requests=[ + Request( + [StdQueries.TESTER_PRESENT_REQUEST, StdQueries.UDS_VERSION_REQUEST], + [StdQueries.TESTER_PRESENT_RESPONSE, StdQueries.UDS_VERSION_RESPONSE], + whitelist_ecus=[Ecu.eps], + rx_offset=0x08, + bus=0, + ), + Request( + [StdQueries.TESTER_PRESENT_REQUEST, StdQueries.UDS_VERSION_REQUEST], + [StdQueries.TESTER_PRESENT_RESPONSE, StdQueries.UDS_VERSION_RESPONSE], + whitelist_ecus=[Ecu.adas, Ecu.electricBrakeBooster, Ecu.fwdRadar], + rx_offset=0x10, + bus=0, + ), + ] +) + +FW_VERSIONS = { + CAR.AP2_MODELS: { + (Ecu.adas, 0x649, None): [ + b'\x01\x00\x8b\x07\x01\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x11', + ], + (Ecu.electricBrakeBooster, 0x64d, None): [ + b'1037123-00-A', + ], + (Ecu.fwdRadar, 0x671, None): [ + b'\x01\x00W\x00\x00\x00\x07\x00\x00\x00\x00\x08\x01\x00\x00\x00\x07\xff\xfe', + ], + (Ecu.eps, 0x730, None): [ + b'\x10#\x01', + ], + }, +} + class CANBUS: # Lateral harness chassis = 0 @@ -55,8 +99,8 @@ BUTTONS = [ Button(car.CarState.ButtonEvent.Type.rightBlinker, "STW_ACTN_RQ", "TurnIndLvr_Stat", [2]), Button(car.CarState.ButtonEvent.Type.accelCruise, "STW_ACTN_RQ", "SpdCtrlLvr_Stat", [4, 16]), Button(car.CarState.ButtonEvent.Type.decelCruise, "STW_ACTN_RQ", "SpdCtrlLvr_Stat", [8, 32]), - Button(car.CarState.ButtonEvent.Type.cancel, "STW_ACTN_RQ", "SpdCtrlLvr_Stat", [2]), - Button(car.CarState.ButtonEvent.Type.resumeCruise, "STW_ACTN_RQ", "SpdCtrlLvr_Stat", [1]), + Button(car.CarState.ButtonEvent.Type.cancel, "STW_ACTN_RQ", "SpdCtrlLvr_Stat", [1]), + Button(car.CarState.ButtonEvent.Type.resumeCruise, "STW_ACTN_RQ", "SpdCtrlLvr_Stat", [2]), ] class CarControllerParams: diff --git a/selfdrive/car/tests/routes.py b/selfdrive/car/tests/routes.py new file mode 100644 index 0000000000..89b895864a --- /dev/null +++ b/selfdrive/car/tests/routes.py @@ -0,0 +1,240 @@ +#!/usr/bin/env python3 +from collections import namedtuple + +from selfdrive.car.chrysler.values import CAR as CHRYSLER +from selfdrive.car.gm.values import CAR as GM +from selfdrive.car.ford.values import CAR as FORD +from selfdrive.car.honda.values import CAR as HONDA +from selfdrive.car.hyundai.values import CAR as HYUNDAI +from selfdrive.car.nissan.values import CAR as NISSAN +from selfdrive.car.mazda.values import CAR as MAZDA +from selfdrive.car.subaru.values import CAR as SUBARU +from selfdrive.car.toyota.values import CAR as TOYOTA +from selfdrive.car.volkswagen.values import CAR as VOLKSWAGEN +from selfdrive.car.tesla.values import CAR as TESLA +from selfdrive.car.body.values import CAR as COMMA + +# TODO: add routes for these cars +non_tested_cars = [ + FORD.ESCAPE_MK4, + FORD.FOCUS_MK4, + GM.CADILLAC_ATS, + GM.HOLDEN_ASTRA, + GM.MALIBU, + GM.EQUINOX, + HYUNDAI.GENESIS_G90, + HYUNDAI.KIA_OPTIMA_H, + HONDA.ODYSSEY_CHN, +] + +CarTestRoute = namedtuple('CarTestRoute', ['route', 'car_model', 'segment'], defaults=(None,)) + +routes = [ + CarTestRoute("efdf9af95e71cd84|2022-05-13--19-03-31", COMMA.BODY), + + CarTestRoute("0c94aa1e1296d7c6|2021-05-05--19-48-37", CHRYSLER.JEEP_CHEROKEE), + CarTestRoute("91dfedae61d7bd75|2021-05-22--20-07-52", CHRYSLER.JEEP_CHEROKEE_2019), + CarTestRoute("420a8e183f1aed48|2020-03-05--07-15-29", CHRYSLER.PACIFICA_2017_HYBRID), + CarTestRoute("43a685a66291579b|2021-05-27--19-47-29", CHRYSLER.PACIFICA_2018), + CarTestRoute("378472f830ee7395|2021-05-28--07-38-43", CHRYSLER.PACIFICA_2018_HYBRID), + CarTestRoute("8190c7275a24557b|2020-01-29--08-33-58", CHRYSLER.PACIFICA_2019_HYBRID), + CarTestRoute("3d84727705fecd04|2021-05-25--08-38-56", CHRYSLER.PACIFICA_2020), + CarTestRoute("221c253375af4ee9|2022-06-15--18-38-24", CHRYSLER.RAM_1500), + CarTestRoute("8fb5eabf914632ae|2022-08-04--17-28-53", CHRYSLER.RAM_HD, segment=6), + + CarTestRoute("62241b0c7fea4589|2022-09-01--15-32-49", FORD.EXPLORER_MK6), + #TestRoute("f1b4c567731f4a1b|2018-04-30--10-15-35", FORD.FUSION), + + CarTestRoute("7cc2a8365b4dd8a9|2018-12-02--12-10-44", GM.ACADIA), + CarTestRoute("aa20e335f61ba898|2019-02-05--16-59-04", GM.BUICK_REGAL), + CarTestRoute("46460f0da08e621e|2021-10-26--07-21-46", GM.ESCALADE_ESV), + CarTestRoute("c950e28c26b5b168|2018-05-30--22-03-41", GM.VOLT), + CarTestRoute("f08912a233c1584f|2022-08-11--18-02-41", GM.BOLT_EUV, segment=1), + CarTestRoute("555d4087cf86aa91|2022-12-02--12-15-07", GM.BOLT_EUV, segment=14), # Bolt EV + CarTestRoute("38aa7da107d5d252|2022-08-15--16-01-12", GM.SILVERADO), + + CarTestRoute("0e7a2ba168465df5|2020-10-18--14-14-22", HONDA.ACURA_RDX_3G), + CarTestRoute("a74b011b32b51b56|2020-07-26--17-09-36", HONDA.CIVIC), + CarTestRoute("a859a044a447c2b0|2020-03-03--18-42-45", HONDA.CRV_EU), + CarTestRoute("68aac44ad69f838e|2021-05-18--20-40-52", HONDA.CRV), + CarTestRoute("14fed2e5fa0aa1a5|2021-05-25--14-59-42", HONDA.CRV_HYBRID), + CarTestRoute("52f3e9ae60c0d886|2021-05-23--15-59-43", HONDA.FIT), + CarTestRoute("2c4292a5cd10536c|2021-08-19--21-32-15", HONDA.FREED), + CarTestRoute("03be5f2fd5c508d1|2020-04-19--18-44-15", HONDA.HRV), + CarTestRoute("917b074700869333|2021-05-24--20-40-20", HONDA.ACURA_ILX), + CarTestRoute("08a3deb07573f157|2020-03-06--16-11-19", HONDA.ACCORD), # 1.5T + CarTestRoute("1da5847ac2488106|2021-05-24--19-31-50", HONDA.ACCORD), # 2.0T + CarTestRoute("085ac1d942c35910|2021-03-25--20-11-15", HONDA.ACCORD), # 2021 with new style HUD msgs + CarTestRoute("07585b0da3c88459|2021-05-26--18-52-04", HONDA.ACCORDH), + CarTestRoute("f29e2b57a55e7ad5|2021-03-24--20-52-38", HONDA.ACCORDH), # 2021 with new style HUD msgs + CarTestRoute("1ad763dd22ef1a0e|2020-02-29--18-37-03", HONDA.CRV_5G), + CarTestRoute("0a96f86fcfe35964|2020-02-05--07-25-51", HONDA.ODYSSEY), + CarTestRoute("d83f36766f8012a5|2020-02-05--18-42-21", HONDA.CIVIC_BOSCH_DIESEL), + CarTestRoute("f0890d16a07a236b|2021-05-25--17-27-22", HONDA.INSIGHT), + CarTestRoute("07d37d27996096b6|2020-03-04--21-57-27", HONDA.PILOT), + CarTestRoute("684e8f96bd491a0e|2021-11-03--11-08-42", HONDA.PASSPORT), + CarTestRoute("0a78dfbacc8504ef|2020-03-04--13-29-55", HONDA.CIVIC_BOSCH), + CarTestRoute("f34a60d68d83b1e5|2020-10-06--14-35-55", HONDA.ACURA_RDX), + CarTestRoute("54fd8451b3974762|2021-04-01--14-50-10", HONDA.RIDGELINE), + CarTestRoute("2d5808fae0b38ac6|2021-09-01--17-14-11", HONDA.HONDA_E), + CarTestRoute("f44aa96ace22f34a|2021-12-22--06-22-31", HONDA.CIVIC_2022), + + CarTestRoute("6fe86b4e410e4c37|2020-07-22--16-27-13", HYUNDAI.HYUNDAI_GENESIS), + CarTestRoute("70c5bec28ec8e345|2020-08-08--12-22-23", HYUNDAI.GENESIS_G70), + CarTestRoute("ca4de5b12321bd98|2022-10-18--21-15-59", HYUNDAI.GENESIS_GV70_1ST_GEN), + CarTestRoute("6b301bf83f10aa90|2020-11-22--16-45-07", HYUNDAI.GENESIS_G80), + CarTestRoute("f0709d2bc6ca451f|2022-10-15--08-13-54", HYUNDAI.SANTA_CRUZ_1ST_GEN), + CarTestRoute("4dbd55df87507948|2022-03-01--09-45-38", HYUNDAI.SANTA_FE), + CarTestRoute("bf43d9df2b660eb0|2021-09-23--14-16-37", HYUNDAI.SANTA_FE_2022), + CarTestRoute("37398f32561a23ad|2021-11-18--00-11-35", HYUNDAI.SANTA_FE_HEV_2022), + CarTestRoute("656ac0d830792fcc|2021-12-28--14-45-56", HYUNDAI.SANTA_FE_PHEV_2022, segment=1), + CarTestRoute("e0e98335f3ebc58f|2021-03-07--16-38-29", HYUNDAI.KIA_CEED), + CarTestRoute("7653b2bce7bcfdaa|2020-03-04--15-34-32", HYUNDAI.KIA_OPTIMA_G4), + CarTestRoute("018654717bc93d7d|2022-09-19--23-11-10", HYUNDAI.KIA_OPTIMA_G4_FL, segment=0), + CarTestRoute("c75a59efa0ecd502|2021-03-11--20-52-55", HYUNDAI.KIA_SELTOS), + CarTestRoute("b3537035ffe6a7d6|2022-10-17--15-23-49", HYUNDAI.KIA_SPORTAGE_HYBRID_5TH_GEN), + CarTestRoute("5b7c365c50084530|2020-04-15--16-13-24", HYUNDAI.SONATA), + CarTestRoute("b2a38c712dcf90bd|2020-05-18--18-12-48", HYUNDAI.SONATA_LF), + CarTestRoute("fb3fd42f0baaa2f8|2022-03-30--15-25-05", HYUNDAI.TUCSON), + CarTestRoute("db68bbe12250812c|2022-12-05--00-54-12", HYUNDAI.TUCSON_4TH_GEN), # 2023 + CarTestRoute("36e10531feea61a4|2022-07-25--13-37-42", HYUNDAI.TUCSON_HYBRID_4TH_GEN), + CarTestRoute("5875672fc1d4bf57|2020-07-23--21-33-28", HYUNDAI.KIA_SORENTO), + CarTestRoute("628935d7d3e5f4f7|2022-11-30--01-12-46", HYUNDAI.KIA_SORENTO_PHEV_4TH_GEN), + CarTestRoute("9c917ba0d42ffe78|2020-04-17--12-43-19", HYUNDAI.PALISADE), + CarTestRoute("05a8f0197fdac372|2022-10-19--14-14-09", HYUNDAI.IONIQ_5), # HDA2 + CarTestRoute("3f29334d6134fcd4|2022-03-30--22-00-50", HYUNDAI.IONIQ_PHEV_2019), + CarTestRoute("fa8db5869167f821|2021-06-10--22-50-10", HYUNDAI.IONIQ_PHEV), + CarTestRoute("2c5cf2dd6102e5da|2020-12-17--16-06-44", HYUNDAI.IONIQ_EV_2020), + CarTestRoute("610ebb9faaad6b43|2020-06-13--15-28-36", HYUNDAI.IONIQ_EV_LTD), + CarTestRoute("2c5cf2dd6102e5da|2020-06-26--16-00-08", HYUNDAI.IONIQ), + CarTestRoute("ab59fe909f626921|2021-10-18--18-34-28", HYUNDAI.IONIQ_HEV_2022), + CarTestRoute("22d955b2cd499c22|2020-08-10--19-58-21", HYUNDAI.KONA), + CarTestRoute("efc48acf44b1e64d|2021-05-28--21-05-04", HYUNDAI.KONA_EV), + CarTestRoute("ff973b941a69366f|2022-07-28--22-01-19", HYUNDAI.KONA_EV_2022, segment=11), + CarTestRoute("49f3c13141b6bc87|2021-07-28--08-05-13", HYUNDAI.KONA_HEV), + CarTestRoute("5dddcbca6eb66c62|2020-07-26--13-24-19", HYUNDAI.KIA_STINGER), + CarTestRoute("5b50b883a4259afb|2022-11-09--15-00-42", HYUNDAI.KIA_STINGER_2022), + CarTestRoute("d624b3d19adce635|2020-08-01--14-59-12", HYUNDAI.VELOSTER), + CarTestRoute("d545129f3ca90f28|2022-10-19--09-22-54", HYUNDAI.KIA_EV6), # HDA2 + CarTestRoute("68d6a96e703c00c9|2022-09-10--16-09-39", HYUNDAI.KIA_EV6), # HDA1 + CarTestRoute("007d5e4ad9f86d13|2021-09-30--15-09-23", HYUNDAI.KIA_K5_2021), + CarTestRoute("50c6c9b85fd1ff03|2020-10-26--17-56-06", HYUNDAI.KIA_NIRO_EV), + CarTestRoute("173219cf50acdd7b|2021-07-05--10-27-41", HYUNDAI.KIA_NIRO_PHEV), + CarTestRoute("34a875f29f69841a|2021-07-29--13-02-09", HYUNDAI.KIA_NIRO_HEV_2021), + CarTestRoute("50a2212c41f65c7b|2021-05-24--16-22-06", HYUNDAI.KIA_FORTE), + CarTestRoute("192283cdbb7a58c2|2022-10-15--01-43-18", HYUNDAI.KIA_SPORTAGE_5TH_GEN), + CarTestRoute("c5ac319aa9583f83|2021-06-01--18-18-31", HYUNDAI.ELANTRA), + CarTestRoute("734ef96182ddf940|2022-10-02--16-41-44", HYUNDAI.ELANTRA), # 2019 Elantra GT + CarTestRoute("82e9cdd3f43bf83e|2021-05-15--02-42-51", HYUNDAI.ELANTRA_2021), + CarTestRoute("715ac05b594e9c59|2021-06-20--16-21-07", HYUNDAI.ELANTRA_HEV_2021), + CarTestRoute("7120aa90bbc3add7|2021-08-02--07-12-31", HYUNDAI.SONATA_HYBRID), + CarTestRoute("715ac05b594e9c59|2021-10-27--23-24-56", HYUNDAI.GENESIS_G70_2020), + + CarTestRoute("00c829b1b7613dea|2021-06-24--09-10-10", TOYOTA.ALPHARD_TSS2), + CarTestRoute("912119ebd02c7a42|2022-03-19--07-24-50", TOYOTA.ALPHARDH_TSS2), + CarTestRoute("000cf3730200c71c|2021-05-24--10-42-05", TOYOTA.AVALON), + CarTestRoute("0bb588106852abb7|2021-05-26--12-22-01", TOYOTA.AVALON_2019), + CarTestRoute("87bef2930af86592|2021-05-30--09-40-54", TOYOTA.AVALONH_2019), + CarTestRoute("e9966711cfb04ce3|2022-01-11--07-59-43", TOYOTA.AVALON_TSS2), + CarTestRoute("eca1080a91720a54|2022-03-17--13-32-29", TOYOTA.AVALONH_TSS2), + CarTestRoute("6cdecc4728d4af37|2020-02-23--15-44-18", TOYOTA.CAMRY), + CarTestRoute("3456ad0cd7281b24|2020-12-13--17-45-56", TOYOTA.CAMRY_TSS2), + CarTestRoute("ffccc77938ddbc44|2021-01-04--16-55-41", TOYOTA.CAMRYH_TSS2), + CarTestRoute("54034823d30962f5|2021-05-24--06-37-34", TOYOTA.CAMRYH), + CarTestRoute("4e45c89c38e8ec4d|2021-05-02--02-49-28", TOYOTA.COROLLA), + CarTestRoute("5f5afb36036506e4|2019-05-14--02-09-54", TOYOTA.COROLLA_TSS2), + CarTestRoute("5ceff72287a5c86c|2019-10-19--10-59-02", TOYOTA.COROLLAH_TSS2), + CarTestRoute("d2525c22173da58b|2021-04-25--16-47-04", TOYOTA.PRIUS), + CarTestRoute("b14c5b4742e6fc85|2020-07-28--19-50-11", TOYOTA.RAV4), + CarTestRoute("32a7df20486b0f70|2020-02-06--16-06-50", TOYOTA.RAV4H), + CarTestRoute("cdf2f7de565d40ae|2019-04-25--03-53-41", TOYOTA.RAV4_TSS2), + CarTestRoute("a5c341bb250ca2f0|2022-05-18--16-05-17", TOYOTA.RAV4_TSS2_2022), + CarTestRoute("7e34a988419b5307|2019-12-18--19-13-30", TOYOTA.RAV4H_TSS2), + CarTestRoute("2475fb3eb2ffcc2e|2022-04-29--12-46-23", TOYOTA.RAV4H_TSS2_2022), + CarTestRoute("e6a24be49a6cd46e|2019-10-29--10-52-42", TOYOTA.LEXUS_ES_TSS2), + CarTestRoute("da23c367491f53e2|2021-05-21--09-09-11", TOYOTA.LEXUS_CTH, segment=3), + CarTestRoute("f49e8041283f2939|2019-05-30--11-51-51", TOYOTA.LEXUS_ESH_TSS2), + CarTestRoute("37041c500fd30100|2020-12-30--12-17-24", TOYOTA.LEXUS_ESH), + CarTestRoute("32696cea52831b02|2021-11-19--18-13-30", TOYOTA.LEXUS_RC), + CarTestRoute("886fcd8408d570e9|2020-01-29--02-18-55", TOYOTA.LEXUS_RX), + CarTestRoute("d27ad752e9b08d4f|2021-05-26--19-39-51", TOYOTA.LEXUS_RXH), + CarTestRoute("01b22eb2ed121565|2020-02-02--11-25-51", TOYOTA.LEXUS_RX_TSS2), + CarTestRoute("b74758c690a49668|2020-05-20--15-58-57", TOYOTA.LEXUS_RXH_TSS2), + CarTestRoute("ec429c0f37564e3c|2020-02-01--17-28-12", TOYOTA.LEXUS_NXH), + CarTestRoute("964c09eb11ca8089|2020-11-03--22-04-00", TOYOTA.LEXUS_NX), + CarTestRoute("3fd5305f8b6ca765|2021-04-28--19-26-49", TOYOTA.LEXUS_NX_TSS2), + CarTestRoute("09ae96064ed85a14|2022-06-09--12-22-31", TOYOTA.LEXUS_NXH_TSS2), + CarTestRoute("0a302ffddbb3e3d3|2020-02-08--16-19-08", TOYOTA.HIGHLANDER_TSS2), + CarTestRoute("437e4d2402abf524|2021-05-25--07-58-50", TOYOTA.HIGHLANDERH_TSS2), + CarTestRoute("3183cd9b021e89ce|2021-05-25--10-34-44", TOYOTA.HIGHLANDER), + CarTestRoute("80d16a262e33d57f|2021-05-23--20-01-43", TOYOTA.HIGHLANDERH), + CarTestRoute("eb6acd681135480d|2019-06-20--20-00-00", TOYOTA.SIENNA), + CarTestRoute("2e07163a1ba9a780|2019-08-25--13-15-13", TOYOTA.LEXUS_IS), + CarTestRoute("0a0de17a1e6a2d15|2020-09-21--21-24-41", TOYOTA.PRIUS_TSS2), + CarTestRoute("9b36accae406390e|2021-03-30--10-41-38", TOYOTA.MIRAI), + CarTestRoute("cd9cff4b0b26c435|2021-05-13--15-12-39", TOYOTA.CHR), + CarTestRoute("57858ede0369a261|2021-05-18--20-34-20", TOYOTA.CHRH), + CarTestRoute("14623aae37e549f3|2021-10-24--01-20-49", TOYOTA.PRIUS_V), + + CarTestRoute("202c40641158a6e5|2021-09-21--09-43-24", VOLKSWAGEN.ARTEON_MK1), + CarTestRoute("2c68dda277d887ac|2021-05-11--15-22-20", VOLKSWAGEN.ATLAS_MK1), + CarTestRoute("cae14e88932eb364|2021-03-26--14-43-28", VOLKSWAGEN.GOLF_MK7), # Stock ACC + CarTestRoute("3cfdec54aa035f3f|2022-10-13--14-58-58", VOLKSWAGEN.GOLF_MK7), # openpilot longitudinal + CarTestRoute("58a7d3b707987d65|2021-03-25--17-26-37", VOLKSWAGEN.JETTA_MK7), + CarTestRoute("4d134e099430fba2|2021-03-26--00-26-06", VOLKSWAGEN.PASSAT_MK8), + CarTestRoute("3cfdec54aa035f3f|2022-07-19--23-45-10", VOLKSWAGEN.PASSAT_NMS), + CarTestRoute("0cd0b7f7e31a3853|2021-11-03--19-30-22", VOLKSWAGEN.POLO_MK6), + CarTestRoute("064d1816e448f8eb|2022-09-29--15-32-34", VOLKSWAGEN.SHARAN_MK2), + CarTestRoute("7d82b2f3a9115f1f|2021-10-21--15-39-42", VOLKSWAGEN.TAOS_MK1), + CarTestRoute("2744c89a8dda9a51|2021-07-24--21-28-06", VOLKSWAGEN.TCROSS_MK1), + CarTestRoute("2cef8a0b898f331a|2021-03-25--20-13-57", VOLKSWAGEN.TIGUAN_MK2), + CarTestRoute("a589dcc642fdb10a|2021-06-14--20-54-26", VOLKSWAGEN.TOURAN_MK2), + CarTestRoute("a459f4556782eba1|2021-09-19--09-48-00", VOLKSWAGEN.TRANSPORTER_T61), + CarTestRoute("0cd0b7f7e31a3853|2021-11-18--00-38-32", VOLKSWAGEN.TROC_MK1), + CarTestRoute("07667b885add75fd|2021-01-23--19-48-42", VOLKSWAGEN.AUDI_A3_MK3), + CarTestRoute("6c6b466346192818|2021-06-06--14-17-47", VOLKSWAGEN.AUDI_Q2_MK1), + CarTestRoute("0cd0b7f7e31a3853|2021-12-03--03-12-05", VOLKSWAGEN.AUDI_Q3_MK2), + CarTestRoute("8f205bdd11bcbb65|2021-03-26--01-00-17", VOLKSWAGEN.SEAT_ATECA_MK1), + CarTestRoute("fc6b6c9a3471c846|2021-05-27--13-39-56", VOLKSWAGEN.SEAT_LEON_MK3), + CarTestRoute("12d6ae3057c04b0d|2021-09-15--00-04-07", VOLKSWAGEN.SKODA_KAMIQ_MK1), + CarTestRoute("12d6ae3057c04b0d|2021-09-04--21-21-21", VOLKSWAGEN.SKODA_KAROQ_MK1), + CarTestRoute("90434ff5d7c8d603|2021-03-15--12-07-31", VOLKSWAGEN.SKODA_KODIAQ_MK1), + CarTestRoute("66e5edc3a16459c5|2021-05-25--19-00-29", VOLKSWAGEN.SKODA_OCTAVIA_MK3), + CarTestRoute("026b6d18fba6417f|2021-03-26--09-17-04", VOLKSWAGEN.SKODA_SCALA_MK1), + CarTestRoute("b2e9858e29db492b|2021-03-26--16-58-42", VOLKSWAGEN.SKODA_SUPERB_MK3), + + CarTestRoute("3c8f0c502e119c1c|2020-06-30--12-58-02", SUBARU.ASCENT), + CarTestRoute("c321c6b697c5a5ff|2020-06-23--11-04-33", SUBARU.FORESTER), + CarTestRoute("791340bc01ed993d|2019-03-10--16-28-08", SUBARU.IMPREZA), + CarTestRoute("8bf7e79a3ce64055|2021-05-24--09-36-27", SUBARU.IMPREZA_2020), + CarTestRoute("1bbe6bf2d62f58a8|2022-07-14--17-11-43", SUBARU.OUTBACK, segment=10), + CarTestRoute("c56e69bbc74b8fad|2022-08-18--09-43-51", SUBARU.LEGACY, segment=3), + # Pre-global, dashcam + CarTestRoute("95441c38ae8c130e|2020-06-08--12-10-17", SUBARU.FORESTER_PREGLOBAL), + CarTestRoute("df5ca7660000fba8|2020-06-16--17-37-19", SUBARU.LEGACY_PREGLOBAL), + CarTestRoute("5ab784f361e19b78|2020-06-08--16-30-41", SUBARU.OUTBACK_PREGLOBAL), + CarTestRoute("e19eb5d5353b1ac1|2020-08-09--14-37-56", SUBARU.OUTBACK_PREGLOBAL_2018), + + CarTestRoute("fbbfa6af821552b9|2020-03-03--08-09-43", NISSAN.XTRAIL), + CarTestRoute("5b7c365c50084530|2020-03-25--22-10-13", NISSAN.LEAF), + CarTestRoute("22c3dcce2dd627eb|2020-12-30--16-38-48", NISSAN.LEAF_IC), + CarTestRoute("059ab9162e23198e|2020-05-30--09-41-01", NISSAN.ROGUE), + CarTestRoute("b72d3ec617c0a90f|2020-12-11--15-38-17", NISSAN.ALTIMA), + + CarTestRoute("32a319f057902bb3|2020-04-27--15-18-58", MAZDA.CX5), + CarTestRoute("10b5a4b380434151|2020-08-26--17-11-45", MAZDA.CX9), + CarTestRoute("74f1038827005090|2020-08-26--20-05-50", MAZDA.MAZDA3), + CarTestRoute("fb53c640f499b73d|2021-06-01--04-17-56", MAZDA.MAZDA6), + CarTestRoute("f6d5b1a9d7a1c92e|2021-07-08--06-56-59", MAZDA.CX9_2021), + CarTestRoute("a4af1602d8e668ac|2022-02-03--12-17-07", MAZDA.CX5_2022), + + CarTestRoute("6c14ee12b74823ce|2021-06-30--11-49-02", TESLA.AP1_MODELS), + CarTestRoute("bb50caf5f0945ab1|2021-06-19--17-20-18", TESLA.AP2_MODELS), + + # Segments that test specific issues + # Controls mismatch due to interceptor threshold + CarTestRoute("cfb32f0fb91b173b|2022-04-06--14-54-45", HONDA.CIVIC, segment=21), + CarTestRoute("5a8762b91fc70467|2022-04-14--21-26-20", TOYOTA.RAV4, segment=2), + # Controls mismatch due to standstill threshold + CarTestRoute("bec2dcfde6a64235|2022-04-08--14-21-32", HONDA.CRV_HYBRID, segment=22), +] diff --git a/selfdrive/car/tests/test_car_interfaces.py b/selfdrive/car/tests/test_car_interfaces.py index 930619ee67..48d85584b3 100755 --- a/selfdrive/car/tests/test_car_interfaces.py +++ b/selfdrive/car/tests/test_car_interfaces.py @@ -1,9 +1,11 @@ #!/usr/bin/env python3 +import math import unittest import importlib from parameterized import parameterized from cereal import car +from selfdrive.car import gen_empty_fingerprint from selfdrive.car.fingerprints import all_known_cars from selfdrive.car.car_helpers import interfaces from selfdrive.car.fingerprints import _FINGERPRINTS as FINGERPRINTS @@ -12,18 +14,14 @@ class TestCarInterfaces(unittest.TestCase): @parameterized.expand([(car,) for car in all_known_cars()]) def test_car_interfaces(self, car_name): - print(car_name) if car_name in FINGERPRINTS: fingerprint = FINGERPRINTS[car_name][0] else: fingerprint = {} CarInterface, CarController, CarState = interfaces[car_name] - fingerprints = { - 0: fingerprint, - 1: fingerprint, - 2: fingerprint, - } + fingerprints = gen_empty_fingerprint() + fingerprints.update({k: fingerprint for k in fingerprints.keys()}) car_fw = [] @@ -33,16 +31,23 @@ class TestCarInterfaces(unittest.TestCase): assert car_interface self.assertGreater(car_params.mass, 1) - self.assertGreater(car_params.steerRateCost, 1e-3) + self.assertGreater(car_params.wheelbase, 0) + self.assertGreater(car_params.centerToFront, 0) + self.assertGreater(car_params.maxLateralAccel, 0) if car_params.steerControlType != car.CarParams.SteerControlType.angle: - tuning = car_params.lateralTuning.which() - if tuning == 'pid': - self.assertTrue(len(car_params.lateralTuning.pid.kpV)) - elif tuning == 'lqr': - self.assertTrue(len(car_params.lateralTuning.lqr.a)) - elif tuning == 'indi': - self.assertTrue(len(car_params.lateralTuning.indi.outerLoopGainV)) + tune = car_params.lateralTuning + if tune.which() == 'pid': + self.assertTrue(not math.isnan(tune.pid.kf) and tune.pid.kf > 0) + self.assertTrue(len(tune.pid.kpV) > 0 and len(tune.pid.kpV) == len(tune.pid.kpBP)) + self.assertTrue(len(tune.pid.kiV) > 0 and len(tune.pid.kiV) == len(tune.pid.kiBP)) + + elif tune.which() == 'torque': + self.assertTrue(not math.isnan(tune.torque.kf) and tune.torque.kf > 0) + self.assertTrue(not math.isnan(tune.torque.friction)) + + elif tune.which() == 'indi': + self.assertTrue(len(tune.indi.outerLoopGainV)) # Run car interface CC = car.CarControl.new_message() @@ -65,7 +70,8 @@ class TestCarInterfaces(unittest.TestCase): # Run radar interface once radar_interface.update([]) - if not car_params.radarOffCan and hasattr(radar_interface, '_update') and hasattr(radar_interface, 'trigger_msg'): + if not car_params.radarOffCan and radar_interface.rcp is not None and \ + hasattr(radar_interface, '_update') and hasattr(radar_interface, 'trigger_msg'): radar_interface._update([radar_interface.trigger_msg]) if __name__ == "__main__": diff --git a/selfdrive/car/tests/test_docs.py b/selfdrive/car/tests/test_docs.py new file mode 100755 index 0000000000..e56f98f7a8 --- /dev/null +++ b/selfdrive/car/tests/test_docs.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +from collections import defaultdict +import re +import unittest + +from selfdrive.car.car_helpers import interfaces, get_interface_attr +from selfdrive.car.docs import CARS_MD_OUT, CARS_MD_TEMPLATE, generate_cars_md, get_all_car_info +from selfdrive.car.docs_definitions import Column, Harness, Star +from selfdrive.car.honda.values import CAR as HONDA + + +class TestCarDocs(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.all_cars = get_all_car_info() + + def test_generator(self): + generated_cars_md = generate_cars_md(self.all_cars, CARS_MD_TEMPLATE) + with open(CARS_MD_OUT, "r") as f: + current_cars_md = f.read() + + self.assertEqual(generated_cars_md, current_cars_md, + "Run selfdrive/car/docs.py to update the compatibility documentation") + + def test_duplicate_years(self): + make_model_years = defaultdict(list) + for car in self.all_cars: + with self.subTest(car_info_name=car.name): + make_model = (car.make, car.model) + for year in car.year_list: + self.assertNotIn(year, make_model_years[make_model], f"{car.name}: Duplicate model year") + make_model_years[make_model].append(year) + + def test_missing_car_info(self): + all_car_info_platforms = get_interface_attr("CAR_INFO", combine_brands=True).keys() + for platform in sorted(interfaces.keys()): + with self.subTest(platform=platform): + self.assertTrue(platform in all_car_info_platforms, "Platform: {} doesn't exist in CarInfo".format(platform)) + + def test_naming_conventions(self): + # Asserts market-standard car naming conventions by brand + for car in self.all_cars: + with self.subTest(car=car): + tokens = car.model.lower().split(" ") + if car.car_name == "hyundai": + self.assertNotIn("phev", tokens, "Use `Plug-in Hybrid`") + self.assertNotIn("hev", tokens, "Use `Hybrid`") + if "plug-in hybrid" in car.model.lower(): + self.assertIn("Plug-in Hybrid", car.model, "Use correct capitalization") + if car.make != "Kia": + self.assertNotIn("ev", tokens, "Use `Electric`") + elif car.car_name == "toyota": + if "rav4" in tokens: + self.assertIn("RAV4", car.model, "Use correct capitalization") + + def test_torque_star(self): + # Asserts brand-specific assumptions around steering torque star + for car in self.all_cars: + with self.subTest(car=car): + # honda sanity check, it's the definition of a no torque star + if car.car_fingerprint in (HONDA.ACCORD, HONDA.CIVIC, HONDA.CRV, HONDA.ODYSSEY, HONDA.PILOT): + self.assertEqual(car.row[Column.STEERING_TORQUE], Star.EMPTY, f"{car.name} has full torque star") + elif car.car_name in ("toyota", "hyundai"): + self.assertNotEqual(car.row[Column.STEERING_TORQUE], Star.EMPTY, f"{car.name} has no torque star") + + def test_year_format(self): + for car in self.all_cars: + with self.subTest(car=car): + self.assertIsNone(re.search(r"\d{4}-\d{4}", car.name), f"Format years correctly: {car.name}") + + def test_harnesses(self): + for car in self.all_cars: + with self.subTest(car=car): + if car.name == "comma body": + raise unittest.SkipTest + + self.assertNotIn(car.harness, [None, Harness.none], f"Need to specify car harness: {car.name}") + + +if __name__ == "__main__": + unittest.main() diff --git a/selfdrive/test/test_fingerprints.py b/selfdrive/car/tests/test_fingerprints.py similarity index 97% rename from selfdrive/test/test_fingerprints.py rename to selfdrive/car/tests/test_fingerprints.py index 01c7d753c3..26ade29e4a 100755 --- a/selfdrive/test/test_fingerprints.py +++ b/selfdrive/car/tests/test_fingerprints.py @@ -37,12 +37,12 @@ def check_fingerprint_consistency(f1, f2): is_f1_in_f2 = True for k in f1: if (k not in f2 or f1[k] != f2[k]) and k < max_msg: - is_f1_in_f2 = False + is_f1_in_f2 = False is_f2_in_f1 = True for k in f2: if (k not in f1 or f2[k] != f1[k]) and k < max_msg: - is_f2_in_f1 = False + is_f2_in_f1 = False return not is_f1_in_f2 and not is_f2_in_f1 @@ -94,4 +94,4 @@ if __name__ == "__main__": print("TEST FAILED") sys.exit(1) else: - print("TEST SUCESSFUL") + print("TEST SUCCESSFUL") diff --git a/selfdrive/car/tests/test_fw_fingerprint.py b/selfdrive/car/tests/test_fw_fingerprint.py index 97683b3709..2e43103852 100755 --- a/selfdrive/car/tests/test_fw_fingerprint.py +++ b/selfdrive/car/tests/test_fw_fingerprint.py @@ -1,16 +1,20 @@ #!/usr/bin/env python3 import random import unittest +from collections import defaultdict from parameterized import parameterized from cereal import car +from selfdrive.car.car_helpers import get_interface_attr, interfaces from selfdrive.car.fingerprints import FW_VERSIONS -from selfdrive.car.fw_versions import match_fw_to_car +from selfdrive.car.fw_versions import FW_QUERY_CONFIGS, match_fw_to_car CarFw = car.CarParams.CarFw Ecu = car.CarParams.Ecu ECU_NAME = {v: k for k, v in Ecu.schema.enumerants.items()} +VERSIONS = get_interface_attr("FW_VERSIONS", ignore_none=True) + class TestFwFingerprint(unittest.TestCase): def assertFingerprints(self, candidates, expected): @@ -18,29 +22,87 @@ class TestFwFingerprint(unittest.TestCase): self.assertEqual(len(candidates), 1, f"got more than one candidate: {candidates}") self.assertEqual(candidates[0], expected) - @parameterized.expand([(k, v) for k, v in FW_VERSIONS.items()]) - def test_fw_fingerprint(self, car_model, ecus): + @parameterized.expand([(b, c, e[c]) for b, e in VERSIONS.items() for c in e]) + def test_fw_fingerprint(self, brand, car_model, ecus): CP = car.CarParams.new_message() for _ in range(200): fw = [] for ecu, fw_versions in ecus.items(): + if not len(fw_versions): + raise unittest.SkipTest("Car model has no FW versions") ecu_name, addr, sub_addr = ecu - fw.append({"ecu": ecu_name, "fwVersion": random.choice(fw_versions), + fw.append({"ecu": ecu_name, "fwVersion": random.choice(fw_versions), 'brand': brand, "address": addr, "subAddress": 0 if sub_addr is None else sub_addr}) CP.carFw = fw _, matches = match_fw_to_car(CP.carFw) self.assertFingerprints(matches, car_model) def test_no_duplicate_fw_versions(self): - passed = True for car_model, ecus in FW_VERSIONS.items(): - for ecu, ecu_fw in ecus.items(): - duplicates = {fw for fw in ecu_fw if ecu_fw.count(fw) > 1} - if len(duplicates): - print(car_model, ECU_NAME[ecu[0]], duplicates) - passed = False + with self.subTest(car_model=car_model): + for ecu, ecu_fw in ecus.items(): + with self.subTest(ecu): + duplicates = {fw for fw in ecu_fw if ecu_fw.count(fw) > 1} + self.assertFalse(len(duplicates), f"{car_model}: Duplicate FW versions: Ecu.{ECU_NAME[ecu[0]]}, {duplicates}") + + def test_all_addrs_map_to_one_ecu(self): + for brand, cars in VERSIONS.items(): + addr_to_ecu = defaultdict(set) + for ecus in cars.values(): + for ecu_type, addr, sub_addr in ecus.keys(): + addr_to_ecu[(addr, sub_addr)].add(ecu_type) + ecus_for_addr = addr_to_ecu[(addr, sub_addr)] + ecu_strings = ", ".join([f'Ecu.{ECU_NAME[ecu]}' for ecu in ecus_for_addr]) + self.assertLessEqual(len(ecus_for_addr), 1, f"{brand} has multiple ECUs that map to one address: {ecu_strings} -> ({hex(addr)}, {sub_addr})") + + def test_data_collection_ecus(self): + # Asserts no extra ECUs are in the fingerprinting database + for brand, config in FW_QUERY_CONFIGS.items(): + for car_model, ecus in VERSIONS[brand].items(): + bad_ecus = set(ecus).intersection(config.extra_ecus) + with self.subTest(car_model=car_model): + self.assertFalse(len(bad_ecus), f'{car_model}: Fingerprints contain ECUs added for data collection: {bad_ecus}') + + def test_blacklisted_ecus(self): + blacklisted_addrs = (0x7c4, 0x7d0) # includes A/C ecu and an unknown ecu + for car_model, ecus in FW_VERSIONS.items(): + with self.subTest(car_model=car_model): + CP = interfaces[car_model][0].get_params(car_model) + if CP.carName == 'subaru': + for ecu in ecus.keys(): + self.assertNotIn(ecu[1], blacklisted_addrs, f'{car_model}: Blacklisted ecu: (Ecu.{ECU_NAME[ecu[0]]}, {hex(ecu[1])})') + + elif CP.carName == "chrysler": + # Some HD trucks have a combined TCM and ECM + if CP.carFingerprint.startswith("RAM HD"): + for ecu in ecus.keys(): + self.assertNotEqual(ecu[0], Ecu.transmission, f"{car_model}: Blacklisted ecu: (Ecu.{ECU_NAME[ecu[0]]}, {hex(ecu[1])})") + + def test_missing_versions_and_configs(self): + brand_versions = set(VERSIONS.keys()) + brand_configs = set(FW_QUERY_CONFIGS.keys()) + if len(brand_configs - brand_versions): + with self.subTest(): + self.fail(f"Brands do not implement FW_VERSIONS: {brand_configs - brand_versions}") + + if len(brand_versions - brand_configs): + with self.subTest(): + self.fail(f"Brands do not implement FW_QUERY_CONFIG: {brand_versions - brand_configs}") + + def test_fw_request_ecu_whitelist(self): + for brand, config in FW_QUERY_CONFIGS.items(): + with self.subTest(brand=brand): + whitelisted_ecus = {ecu for r in config.requests for ecu in r.whitelist_ecus} + brand_ecus = {fw[0] for car_fw in VERSIONS[brand].values() for fw in car_fw} + brand_ecus |= {ecu[0] for ecu in config.extra_ecus} + + # each ecu in brand's fw versions + extra ecus needs to be whitelisted at least once + ecus_not_whitelisted = brand_ecus - whitelisted_ecus + + ecu_strings = ", ".join([f'Ecu.{ECU_NAME[ecu]}' for ecu in ecus_not_whitelisted]) + self.assertFalse(len(whitelisted_ecus) and len(ecus_not_whitelisted), + f'{brand.title()}: FW query whitelist missing ecus: {ecu_strings}') - self.assertTrue(passed, "Duplicate FW versions found") if __name__ == "__main__": unittest.main() diff --git a/selfdrive/test/test_models.py b/selfdrive/car/tests/test_models.py similarity index 54% rename from selfdrive/test/test_models.py rename to selfdrive/car/tests/test_models.py index 3be0f96b37..641c109316 100755 --- a/selfdrive/test/test_models.py +++ b/selfdrive/car/tests/test_models.py @@ -8,32 +8,24 @@ from typing import List, Optional, Tuple from parameterized import parameterized_class from cereal import log, car -from common.params import Params from common.realtime import DT_CTRL -from selfdrive.boardd.boardd import can_capnp_to_can_list, can_list_to_can_capnp from selfdrive.car.fingerprints import all_known_cars from selfdrive.car.car_helpers import interfaces from selfdrive.car.gm.values import CAR as GM from selfdrive.car.honda.values import CAR as HONDA, HONDA_BOSCH from selfdrive.car.hyundai.values import CAR as HYUNDAI -from selfdrive.car.toyota.values import CAR as TOYOTA -from selfdrive.test.test_routes import routes, non_tested_cars +from selfdrive.car.tests.routes import non_tested_cars, routes, CarTestRoute from selfdrive.test.openpilotci import get_url from tools.lib.logreader import LogReader +from tools.lib.route import Route -from panda.tests.safety import libpandasafety_py -from panda.tests.safety.common import package_can_msg +from panda.tests.libpanda import libpanda_py PandaType = log.PandaState.PandaType NUM_JOBS = int(os.environ.get("NUM_JOBS", "1")) JOB_ID = int(os.environ.get("JOB_ID", "0")) -# TODO: get updated routes for these cars -ignore_can_valid = [ - HYUNDAI.SANTA_FE, -] - ignore_addr_checks_valid = [ GM.BUICK_REGAL, HYUNDAI.GENESIS_G70_2020, @@ -42,36 +34,54 @@ ignore_addr_checks_valid = [ # build list of test cases routes_by_car = defaultdict(set) for r in routes: - routes_by_car[r.car_fingerprint].add(r.route) + routes_by_car[r.car_model].add(r) -test_cases: List[Tuple[str, Optional[str]]] = [] +test_cases: List[Tuple[str, Optional[CarTestRoute]]] = [] for i, c in enumerate(sorted(all_known_cars())): if i % NUM_JOBS == JOB_ID: test_cases.extend((c, r) for r in routes_by_car.get(c, (None, ))) +SKIP_ENV_VAR = "SKIP_LONG_TESTS" + -@parameterized_class(('car_model', 'route'), test_cases) -class TestCarModel(unittest.TestCase): +class TestCarModelBase(unittest.TestCase): + car_model = None + test_route = None + ci = True + @unittest.skipIf(SKIP_ENV_VAR in os.environ, f"Long running test skipped. Unset {SKIP_ENV_VAR} to run") @classmethod def setUpClass(cls): - if cls.route is None: + if cls.__name__ == 'TestCarModel' or cls.__name__.endswith('Base'): + raise unittest.SkipTest + + if 'FILTER' in os.environ: + if not cls.car_model.startswith(tuple(os.environ.get('FILTER').split(','))): + raise unittest.SkipTest + + if cls.test_route is None: if cls.car_model in non_tested_cars: print(f"Skipping tests for {cls.car_model}: missing route") raise unittest.SkipTest raise Exception(f"missing test route for {cls.car_model}") - params = Params() - params.clear_all() + experimental_long = False + test_segs = (2, 1, 0) + if cls.test_route.segment is not None: + test_segs = (cls.test_route.segment,) - for seg in [2, 1, 0]: + for seg in test_segs: try: - lr = LogReader(get_url(cls.route, seg)) + if cls.ci: + lr = LogReader(get_url(cls.test_route.route, seg)) + else: + lr = LogReader(Route(cls.test_route.route).log_paths()[seg]) except Exception: continue + car_fw = [] can_msgs = [] - fingerprint = {i: dict() for i in range(3)} + fingerprint = defaultdict(dict) for msg in lr: if msg.which() == "can": for m in msg.can: @@ -79,29 +89,38 @@ class TestCarModel(unittest.TestCase): fingerprint[m.src][m.address] = len(m.dat) can_msgs.append(msg) elif msg.which() == "carParams": + car_fw = msg.carParams.carFw if msg.carParams.openpilotLongitudinalControl: - params.put_bool("DisableRadar", True) + experimental_long = True + if cls.car_model is None and not cls.ci: + cls.car_model = msg.carParams.carFingerprint if len(can_msgs) > int(50 / DT_CTRL): break else: - raise Exception(f"Route {repr(cls.route)} not found or no CAN msgs found. Is it uploaded?") + raise Exception(f"Route: {repr(cls.test_route.route)} with segments: {test_segs} not found or no CAN msgs found. Is it uploaded?") cls.can_msgs = sorted(can_msgs, key=lambda msg: msg.logMonoTime) cls.CarInterface, cls.CarController, cls.CarState = interfaces[cls.car_model] - cls.CP = cls.CarInterface.get_params(cls.car_model, fingerprint, []) + cls.CP = cls.CarInterface.get_params(cls.car_model, fingerprint, car_fw, experimental_long) assert cls.CP assert cls.CP.carFingerprint == cls.car_model + @classmethod + def tearDownClass(cls): + del cls.can_msgs + def setUp(self): self.CI = self.CarInterface(self.CP, self.CarController, self.CarState) assert self.CI # TODO: check safetyModel is in release panda build - self.safety = libpandasafety_py.libpandasafety - set_status = self.safety.set_safety_hooks(self.CP.safetyConfigs[0].safetyModel.raw, self.CP.safetyConfigs[0].safetyParam) - self.assertEqual(0, set_status, f"failed to set safetyModel {self.CP.safetyConfigs[0].safetyModel}") + self.safety = libpanda_py.libpanda + + cfg = self.CP.safetyConfigs[-1] + set_status = self.safety.set_safety_hooks(cfg.safetyModel.raw, cfg.safetyParam) + self.assertEqual(0, set_status, f"failed to set safetyModel {cfg}") self.safety.init_tests() def test_car_params(self): @@ -110,33 +129,36 @@ class TestCarModel(unittest.TestCase): # make sure car params are within a valid range self.assertGreater(self.CP.mass, 1) - self.assertGreater(self.CP.steerRateCost, 1e-3) if self.CP.steerControlType != car.CarParams.SteerControlType.angle: tuning = self.CP.lateralTuning.which() if tuning == 'pid': self.assertTrue(len(self.CP.lateralTuning.pid.kpV)) - elif tuning == 'lqr': - self.assertTrue(len(self.CP.lateralTuning.lqr.a)) + elif tuning == 'torque': + self.assertTrue(self.CP.lateralTuning.torque.kf > 0) elif tuning == 'indi': self.assertTrue(len(self.CP.lateralTuning.indi.outerLoopGainV)) else: - raise Exception("unkown tuning") + raise Exception("unknown tuning") def test_car_interface(self): - # TODO: also check for checkusm and counter violations from can parser + # TODO: also check for checksum violations from can parser can_invalid_cnt = 0 + can_valid = False CC = car.CarControl.new_message() + for i, msg in enumerate(self.can_msgs): CS = self.CI.update(CC, (msg.as_builder().to_bytes(),)) self.CI.apply(CC) - # wait 2s for low frequency msgs to be seen - if i > 200: + if CS.canValid: + can_valid = True + + # wait max of 2s for low frequency msgs to be seen + if i > 200 or can_valid: can_invalid_cnt += not CS.canValid - if self.car_model not in ignore_can_valid: - self.assertLess(can_invalid_cnt, 50) + self.assertEqual(can_invalid_cnt, 0) def test_radar_interface(self): os.environ['NO_RADAR_SLEEP'] = "1" @@ -145,11 +167,11 @@ class TestCarModel(unittest.TestCase): assert RI error_cnt = 0 - for msg in self.can_msgs: - radar_data = RI.update((msg.as_builder().to_bytes(),)) - if radar_data is not None: - error_cnt += car.RadarData.Error.canError in radar_data.errors - self.assertLess(error_cnt, 20) + for i, msg in enumerate(self.can_msgs): + rr = RI.update((msg.as_builder().to_bytes(),)) + if rr is not None and i > 50: + error_cnt += car.RadarData.Error.canError in rr.errors + self.assertEqual(error_cnt, 0) def test_panda_safety_rx_valid(self): if self.CP.dashcamOnly: @@ -168,7 +190,7 @@ class TestCarModel(unittest.TestCase): if msg.src >= 64: continue - to_send = package_can_msg([msg.address, 0, msg.dat, msg.src]) + to_send = libpanda_py.make_CANPacket(msg.address, msg.src % 4, msg.dat) if self.safety.safety_rx_hook(to_send) != 1: failed_addrs[hex(msg.address)] += 1 @@ -190,30 +212,35 @@ class TestCarModel(unittest.TestCase): # warm up pass, as initial states may be different for can in self.can_msgs[:300]: - for msg in can_capnp_to_can_list(can.can, src_filter=range(64)): - to_send = package_can_msg(msg) + self.CI.update(CC, (can.as_builder().to_bytes(), )) + for msg in filter(lambda m: m.src in range(64), can.can): + to_send = libpanda_py.make_CANPacket(msg.address, msg.src, msg.dat) self.safety.safety_rx_hook(to_send) - self.CI.update(CC, (can_list_to_can_capnp([msg, ]), )) + controls_allowed_prev = False + CS_prev = car.CarState.new_message() checks = defaultdict(lambda: 0) - for can in self.can_msgs: + for idx, can in enumerate(self.can_msgs): CS = self.CI.update(CC, (can.as_builder().to_bytes(), )) - for msg in can_capnp_to_can_list(can.can, src_filter=range(64)): - to_send = package_can_msg(msg) + for msg in filter(lambda m: m.src in range(64), can.can): + to_send = libpanda_py.make_CANPacket(msg.address, msg.src % 4, msg.dat) ret = self.safety.safety_rx_hook(to_send) self.assertEqual(1, ret, f"safety rx failed ({ret=}): {to_send}") + # Skip first frame so CS_prev is properly initialized + if idx == 0: + CS_prev = CS + # Button may be left pressed in warm up period + if not self.CP.pcmCruise: + self.safety.set_controls_allowed(0) + continue + # TODO: check rest of panda's carstate (steering, ACC main on, etc.) - # TODO: make the interceptor thresholds in openpilot and panda match, then remove this exception - gas_pressed = CS.gasPressed - if self.CP.enableGasInterceptor and gas_pressed and not self.safety.get_gas_pressed_prev(): - # panda intentionally has a higher threshold - if self.CP.carName == "toyota" and 15 < CS.gas < 15*1.5: - gas_pressed = False - if self.CP.carName == "honda": - gas_pressed = False - checks['gasPressed'] += gas_pressed != self.safety.get_gas_pressed_prev() + checks['gasPressed'] += CS.gasPressed != self.safety.get_gas_pressed_prev() + if self.CP.carName not in ("hyundai", "volkswagen", "body"): + # TODO: fix standstill mismatches for other makes + checks['standstill'] += CS.standstill == self.safety.get_vehicle_moving() # TODO: remove this exception once this mismatch is resolved brake_pressed = CS.brakePressed @@ -221,23 +248,40 @@ class TestCarModel(unittest.TestCase): if self.CP.carFingerprint in (HONDA.PILOT, HONDA.PASSPORT, HONDA.RIDGELINE) and CS.brake > 0.05: brake_pressed = False checks['brakePressed'] += brake_pressed != self.safety.get_brake_pressed_prev() + checks['regenBraking'] += CS.regenBraking != self.safety.get_regen_braking_prev() if self.CP.pcmCruise: - checks['controlsAllowed'] += not CS.cruiseState.enabled and self.safety.get_controls_allowed() + # On most pcmCruise cars, openpilot's state is always tied to the PCM's cruise state. + # On Honda Nidec, we always engage on the rising edge of the PCM cruise state, but + # openpilot brakes to zero even if the min ACC speed is non-zero (i.e. the PCM disengages). + if self.CP.carName == "honda" and self.CP.carFingerprint not in HONDA_BOSCH: + # only the rising edges are expected to match + if CS.cruiseState.enabled and not CS_prev.cruiseState.enabled: + checks['controlsAllowed'] += not self.safety.get_controls_allowed() + else: + checks['controlsAllowed'] += not CS.cruiseState.enabled and self.safety.get_controls_allowed() + else: + # Check for enable events on rising edge of controls allowed + button_enable = any(evt.enable for evt in CS.events) + mismatch = button_enable != (self.safety.get_controls_allowed() and not controls_allowed_prev) + checks['controlsAllowed'] += mismatch + controls_allowed_prev = self.safety.get_controls_allowed() + if button_enable and not mismatch: + self.safety.set_controls_allowed(False) if self.CP.carName == "honda": checks['mainOn'] += CS.cruiseState.available != self.safety.get_acc_main_on() - # TODO: add flag to toyota safety - if self.CP.carFingerprint == TOYOTA.SIENNA and checks['brakePressed'] < 25: - checks['brakePressed'] = 0 - - # Honda Nidec uses button enable in panda, but pcm enable in openpilot - if self.CP.carName == "honda" and self.CP.carFingerprint not in HONDA_BOSCH and checks['controlsAllowed'] < 25: - checks['controlsAllowed'] = 0 + CS_prev = CS failed_checks = {k: v for k, v in checks.items() if v > 0} self.assertFalse(len(failed_checks), f"panda safety doesn't agree with openpilot: {failed_checks}") + +@parameterized_class(('car_model', 'test_route'), test_cases) +class TestCarModel(TestCarModelBase): + pass + + if __name__ == "__main__": unittest.main() diff --git a/selfdrive/car/torque_data/override.yaml b/selfdrive/car/torque_data/override.yaml new file mode 100644 index 0000000000..1eda931e3e --- /dev/null +++ b/selfdrive/car/torque_data/override.yaml @@ -0,0 +1,43 @@ +legend: [LAT_ACCEL_FACTOR, MAX_LAT_ACCEL_MEASURED, FRICTION] +### angle control +# Nissan appears to have torque +NISSAN X-TRAIL 2017: [.nan, 1.5, .nan] +NISSAN ALTIMA 2020: [.nan, 1.5, .nan] +NISSAN LEAF 2018 Instrument Cluster: [.nan, 1.5, .nan] +NISSAN LEAF 2018: [.nan, 1.5, .nan] +NISSAN ROGUE 2019: [.nan, 1.5, .nan] + +# Tesla has high torque +TESLA AP1 MODEL S: [.nan, 2.5, .nan] +TESLA AP2 MODEL S: [.nan, 2.5, .nan] + +# Guess +FORD ESCAPE 4TH GEN: [.nan, 1.5, .nan] +FORD EXPLORER 6TH GEN: [.nan, 1.5, .nan] +FORD FOCUS 4TH GEN: [.nan, 1.5, .nan] +### + +# No steering wheel +COMMA BODY: [.nan, 1000, .nan] + +# Totally new cars +RAM 1500 5TH GEN: [2.0, 2.0, 0.0] +RAM HD 5TH GEN: [1.4, 1.4, 0.0] +SUBARU OUTBACK 6TH GEN: [2.3, 2.3, 0.11] +CHEVROLET BOLT EV 2022: [2.0, 2.0, 0.05] +CHEVROLET BOLT EUV 2022: [2.0, 2.0, 0.05] +CHEVROLET SILVERADO 1500 2020: [1.9, 1.9, 0.112] +CHEVROLET EQUINOX 2019: [2.0, 2.0, 0.05] +VOLKSWAGEN PASSAT NMS: [2.5, 2.5, 0.1] +VOLKSWAGEN SHARAN 2ND GEN: [2.5, 2.5, 0.1] +HYUNDAI SANTA CRUZ 1ST GEN: [2.7, 2.7, 0.1] +KIA SPORTAGE 5TH GEN: [2.7, 2.7, 0.1] +KIA SPORTAGE HYBRID 5TH GEN: [2.5, 2.5, 0.1] +GENESIS GV70 1ST GEN: [2.42, 2.42, 0.1] +KIA SORENTO PLUG-IN HYBRID 4TH GEN: [2.5, 2.5, 0.1] + +# Dashcam or fallback configured as ideal car +mock: [10.0, 10, 0.0] + +# Manually checked +HONDA CIVIC 2022: [2.5, 1.2, 0.15] diff --git a/selfdrive/car/torque_data/params.yaml b/selfdrive/car/torque_data/params.yaml new file mode 100644 index 0000000000..3b212c6507 --- /dev/null +++ b/selfdrive/car/torque_data/params.yaml @@ -0,0 +1,100 @@ +ACURA ILX 2016: [1.524988973896102, 0.519011053086259, 0.34236219253028] +ACURA RDX 2018: [0.9987728568686902, 0.5323765166196301, 0.303218805715844] +ACURA RDX 2020: [1.4314459806646749, 0.33874701282109954, 0.18048847083897598] +AUDI A3 3RD GEN: [1.5122414863077502, 1.7443517531719404, 0.15194151892450905] +AUDI Q3 2ND GEN: [1.4439223359448605, 1.2254955789112076, 0.1413798895978097] +CHEVROLET VOLT PREMIER 2017: [1.5961527626411784, 1.8422651988094612, 0.1572393918005158] +CHRYSLER PACIFICA 2018: [1.593387270257916, 1.3366521181047952, 0.13776367250652022] +CHRYSLER PACIFICA 2020: [1.4323553627965695, 1.509076559398423, 0.14328246159386085] +CHRYSLER PACIFICA HYBRID 2017: [1.3032470208409048, 1.06831764583744, 0.13287170990024627] +CHRYSLER PACIFICA HYBRID 2018: [1.6068280248761635, 1.2943025830995154, 0.1358557824293823] +CHRYSLER PACIFICA HYBRID 2019: [1.4624643614072217, 1.1958788168371808, 0.15748488008472716] +GENESIS G70 2018: [3.8520195946707947, 2.354697063349854, 0.06830285485626221] +GMC ACADIA DENALI 2018: [1.3181430320331884, 1.1853735340610179, 0.3450592280031644] +HONDA ACCORD 2018: [1.7135052593468778, 0.3461280068322071, 0.21579936052863807] +HONDA ACCORD HYBRID 2018: [1.6651615004829625, 0.30322180951193245, 0.2083000440586149] +HONDA CIVIC (BOSCH) 2019: [1.691708637466905, 0.40132900729454185, 0.25460295304024094] +HONDA CIVIC 2016: [1.6528895627785531, 0.4018518740819229, 0.25458812851328544] +HONDA CR-V 2016: [0.7667141440182675, 0.5927571534745969, 0.40909087636157127] +HONDA CR-V 2017: [2.01323205142022, 0.2700612209345081, 0.2238412881331528] +HONDA CR-V HYBRID 2019: [2.072034634644233, 0.7152085160516978, 0.20237105008376083] +HONDA FIT 2018: [1.5719981427109775, 0.5712761407108976, 0.110773383324281] +HONDA HRV 2019: [2.0661212805710205, 0.7521343418694775, 0.17760375789242094] +HONDA INSIGHT 2019: [1.5201671214069354, 0.5660229120683284, 0.25808042580281876] +HONDA ODYSSEY 2018: [1.8774809275211801, 0.8394431662987996, 0.2096978613792822] +HONDA PASSPORT 2021: [1.5305538930036766, 0.7956063674638759, 0.19599407381531284] +HONDA PILOT 2017: [1.7262026201812795, 0.9470005614967523, 0.21351430733218763] +HONDA RIDGELINE 2017: [1.4146525028237624, 0.7356572861629564, 0.23307177552211328] +HYUNDAI ELANTRA 2021: [3.169, 2.1259108157250735, 0.0819] +HYUNDAI GENESIS 2015-2016: [1.8466226943929824, 1.5552063647830634, 0.0984484465421171] +HYUNDAI IONIQ 5 2022: [3.172929, 3.0, 0.096019] +HYUNDAI IONIQ ELECTRIC LIMITED 2019: [1.7662975472852054, 1.613755614526594, 0.17087579756306276] +HYUNDAI IONIQ PHEV 2020: [3.2928700076638537, 2.1193482926455656, 0.12463700961468778] +HYUNDAI IONIQ PLUG-IN HYBRID 2019: [2.970807902012267, 1.6312321830002083, 0.1088964990357482] +HYUNDAI KONA ELECTRIC 2019: [3.078814714619148, 3.2961956260770484, 0.12359762054065548] +HYUNDAI PALISADE 2020: [2.544642494803999, 1.8721703683337008, 0.1301424599248651] +HYUNDAI SANTA FE 2019: [3.0787027729757632, 2.6173437483495565, 0.1207019341823945] +HYUNDAI SANTA FE HYBRID 2022: [3.501877602644835, 2.729064118456137, 0.10384068104538963] +HYUNDAI SANTA FE PlUG-IN HYBRID 2022: [1.6953050513611045, 1.5837614296206861, 0.12672855941458458] +HYUNDAI SONATA 2019: [2.2200457811703953, 1.2967330275895228, 0.14039920986586393] +HYUNDAI SONATA 2020: [2.9638737459977467, 2.1259108157250735, 0.07813665616927593] +HYUNDAI SONATA HYBRID 2021: [2.8990264092395734, 2.061410192222139, 0.0899805488717382] +HYUNDAI TUCSON HYBRID 4TH GEN: [2.035545, 2.035545, 0.110272] +JEEP GRAND CHEROKEE 2019: [1.7321233388827006, 1.289689569171081, 0.15046331002097185] +JEEP GRAND CHEROKEE V6 2018: [1.8776598027756923, 1.4057367824262523, 0.11725947414922003] +KIA EV6 2022: [3.2, 3.0, 0.05] +KIA K5 2021: [2.405339728085138, 1.460032270828705, 0.11650989850813716] +KIA NIRO EV 2020: [2.9215954981365337, 2.1500583840260044, 0.09236802474810267] +KIA SORENTO GT LINE 2018: [2.464854685101844, 1.5335274218367956, 0.12056170567599558] +KIA STINGER GT2 2018: [2.7499043387418967, 1.849652021986449, 0.12048334239559202] +LEXUS ES 2019: [1.935835, 2.134803912579666, 0.093439] +LEXUS ES HYBRID 2019: [2.135678, 1.863360677810788, 0.109627] +LEXUS NX 2018: [2.302625600642627, 2.1382378491466625, 0.14986840878892838] +LEXUS NX 2020: [2.4331999786982936, 2.1045680431705414, 0.14099899317761067] +LEXUS NX HYBRID 2018: [2.4025593501080955, 1.8080446063815507, 0.15349361249519017] +LEXUS RX 2016: [1.5876816543130423, 1.0427699298523752, 0.21334066732397142] +LEXUS RX 2020: [1.5228812994274734, 1.431102486563665, 0.164117] +LEXUS RX HYBRID 2017: [1.6984261557042386, 1.3211501880159107, 0.1820354534928893] +LEXUS RX HYBRID 2020: [1.5522309889823778, 1.255230465866663, 0.2220954003055114] +MAZDA CX-9 2021: [1.7601682915983443, 1.0889677335154337, 0.17713792194297195] +SKODA SUPERB 3RD GEN: [1.166437404652981, 1.1686163012668165, 0.12194533036948708] +SUBARU FORESTER 2019: [3.6617001649776793, 2.342197172531713, 0.11075960785398745] +SUBARU IMPREZA LIMITED 2019: [1.0670704910352047, 0.8234374840709592, 0.20986563268614938] +SUBARU IMPREZA SPORT 2020: [2.6068223389108303, 2.134872342760203, 0.15261513193561627] +TOYOTA AVALON 2016: [2.5185770183845646, 1.7153346784214922, 0.10603968787111022] +TOYOTA AVALON 2019: [1.7036141952825095, 1.239619084240008, 0.08459830394899492] +TOYOTA AVALON 2022: [2.3154403649717357, 2.7777922854327124, 0.11453999639164605] +TOYOTA C-HR 2018: [1.5591084333664578, 1.271271459066948, 0.20259087058453193] +TOYOTA C-HR 2021: [1.7678810166088303, 1.3742176337919942, 0.2319674583741509] +TOYOTA CAMRY 2018: [2.1172995371905015, 1.7156177222420887, 0.105192506] +TOYOTA CAMRY 2021: [2.446083, 2.3476510120007434, 0.121615] +TOYOTA CAMRY HYBRID 2018: [1.996333, 1.7996193116697359, 0.112565] +TOYOTA CAMRY HYBRID 2021: [2.263582, 2.3901492458927986, 0.115257] +TOYOTA COROLLA 2017: [3.117154369115421, 1.8438132575043773, 0.12289685869250652] +TOYOTA COROLLA HYBRID TSS2 2019: [1.9079729107361805, 1.8118712531729109, 0.22251440891543514] +TOYOTA COROLLA TSS2 2019: [2.0742917676766712, 1.9258612322678952, 0.16888685704519352] +TOYOTA HIGHLANDER 2017: [1.8696367437248915, 1.626293990451463, 0.17485372210240796] +TOYOTA HIGHLANDER 2020: [2.022340166827233, 1.6183134804881791, 0.14592306380054457] +TOYOTA HIGHLANDER HYBRID 2018: [1.752033, 1.6433903296845025, 0.144600] +TOYOTA HIGHLANDER HYBRID 2020: [1.901174, 2.104015182965606, 0.14447040132184993] +TOYOTA MIRAI 2021: [2.506899832157829, 1.7417213930750164, 0.20182618449440565] +TOYOTA PRIUS 2017: [1.60, 1.5023147650693636, 0.151515] +TOYOTA PRIUS TSS2 2021: [1.972600, 1.9104337425537743, 0.170968] +TOYOTA RAV4 2017: [2.085695074355425, 2.2142832316984733, 0.13339165270103975] +TOYOTA RAV4 2019: [2.331293, 2.0993589721530252, 0.129822] +TOYOTA RAV4 2019 8965: [2.5084506298290377, 2.4216520504763475, 0.11992835265067918] +TOYOTA RAV4 2019 x02: [2.7209621987605024, 2.2148637653781593, 0.10862567142268198] +TOYOTA RAV4 HYBRID 2017: [1.9796257271652042, 1.7503987331707576, 0.14628860048885406] +TOYOTA RAV4 HYBRID 2019: [2.2271858492309153, 2.074844961405639, 0.14382216826893632] +TOYOTA RAV4 HYBRID 2019 8965: [2.1077397198131336, 1.8162215166877735, 0.13891369391200137] +TOYOTA RAV4 HYBRID 2019 x02: [2.803624333289342, 2.272367966572498, 0.11364569214387774] +TOYOTA RAV4 HYBRID 2022: [2.241883248393209, 1.9304407208090029, 0.112174] +TOYOTA RAV4 HYBRID 2022 x02: [3.044930631831037, 2.3979189796380918, 0.14023209146703736] +TOYOTA SIENNA 2018: [1.689726, 1.3208264576110418, 0.140456] +VOLKSWAGEN ARTEON 1ST GEN: [1.45136518053819, 1.3639364049316804, 0.23806361745695032] +VOLKSWAGEN ATLAS 1ST GEN: [1.4677006726964945, 1.6733266634075656, 0.12959584092073367] +VOLKSWAGEN GOLF 7TH GEN: [1.3750394140491293, 1.5814743077200641, 0.2018321939386586] +VOLKSWAGEN JETTA 7TH GEN: [1.2271623034089392, 1.216955117387, 0.19437384688370712] +VOLKSWAGEN PASSAT 8TH GEN: [1.3432120736752917, 1.7087275587362314, 0.19444383787326647] +VOLKSWAGEN TIGUAN 2ND GEN: [0.9711965500094828, 1.0001565939459098, 0.1465626137072916] +legend: [LAT_ACCEL_FACTOR, MAX_LAT_ACCEL_MEASURED, FRICTION] diff --git a/selfdrive/car/torque_data/substitute.yaml b/selfdrive/car/torque_data/substitute.yaml new file mode 100644 index 0000000000..aeb2e6f280 --- /dev/null +++ b/selfdrive/car/torque_data/substitute.yaml @@ -0,0 +1,79 @@ +MAZDA 3: MAZDA CX-9 2021 +MAZDA 6: MAZDA CX-9 2021 +MAZDA CX-5: MAZDA CX-9 2021 +MAZDA CX-5 2022: MAZDA CX-9 2021 +MAZDA CX-9: MAZDA CX-9 2021 + +TOYOTA ALPHARD HYBRID 2021 : TOYOTA SIENNA 2018 +TOYOTA ALPHARD 2020: TOYOTA SIENNA 2018 +TOYOTA PRIUS v 2017 : TOYOTA PRIUS 2017 +TOYOTA RAV4 2022: TOYOTA RAV4 HYBRID 2022 +TOYOTA C-HR HYBRID 2018: TOYOTA C-HR 2018 +LEXUS IS 2018: LEXUS NX 2018 +LEXUS CT HYBRID 2018 : LEXUS NX 2018 +LEXUS ES HYBRID 2018: TOYOTA CAMRY HYBRID 2018 +LEXUS NX HYBRID 2020: LEXUS NX 2020 +LEXUS RC 2020: LEXUS NX 2020 +TOYOTA AVALON HYBRID 2019: TOYOTA AVALON 2019 +TOYOTA AVALON HYBRID 2022: TOYOTA AVALON 2022 + +KIA OPTIMA 4TH GEN: HYUNDAI SONATA 2020 +KIA OPTIMA 4TH GEN FACELIFT: HYUNDAI SONATA 2020 +KIA OPTIMA HYBRID 2017 & SPORTS 2019: HYUNDAI SONATA 2020 +KIA FORTE E 2018 & GT 2021: HYUNDAI SONATA 2020 +KIA CEED INTRO ED 2019: HYUNDAI SONATA 2020 +KIA SELTOS 2021: HYUNDAI SONATA 2020 +KIA NIRO HYBRID 2019: KIA NIRO EV 2020 +KIA NIRO HYBRID 2021: KIA NIRO EV 2020 +HYUNDAI VELOSTER 2019: HYUNDAI SONATA 2019 +HYUNDAI KONA 2020: HYUNDAI KONA ELECTRIC 2019 +HYUNDAI KONA HYBRID 2020: HYUNDAI KONA ELECTRIC 2019 +HYUNDAI KONA ELECTRIC 2022: HYUNDAI KONA ELECTRIC 2019 +HYUNDAI IONIQ HYBRID 2017-2019: HYUNDAI IONIQ PLUG-IN HYBRID 2019 +HYUNDAI IONIQ HYBRID 2020-2022: HYUNDAI IONIQ PLUG-IN HYBRID 2019 +HYUNDAI IONIQ ELECTRIC 2020: HYUNDAI IONIQ PLUG-IN HYBRID 2019 +HYUNDAI ELANTRA 2017: HYUNDAI SONATA 2019 +HYUNDAI ELANTRA HYBRID 2021: HYUNDAI SONATA 2020 +HYUNDAI TUCSON 2019: HYUNDAI SANTA FE 2019 +HYUNDAI TUCSON 4TH GEN: HYUNDAI TUCSON HYBRID 4TH GEN +HYUNDAI SANTA FE 2022: HYUNDAI SANTA FE HYBRID 2022 +KIA STINGER 2022: KIA STINGER GT2 2018 +GENESIS G90 2017: GENESIS G70 2018 +GENESIS G80 2017: GENESIS G70 2018 +GENESIS G70 2020: HYUNDAI SONATA 2020 + +HONDA FREED 2020: HONDA ODYSSEY 2018 +HONDA CR-V EU 2016: HONDA CR-V 2016 +HONDA CIVIC SEDAN 1.6 DIESEL 2019: HONDA CIVIC (BOSCH) 2019 +HONDA E 2020: HONDA CIVIC (BOSCH) 2019 +HONDA ODYSSEY CHN 2019: HONDA ODYSSEY 2018 + +BUICK REGAL ESSENCE 2018: CHEVROLET VOLT PREMIER 2017 +CADILLAC ESCALADE ESV 2016: CHEVROLET VOLT PREMIER 2017 +CADILLAC ATS Premium Performance 2018: CHEVROLET VOLT PREMIER 2017 +CHEVROLET MALIBU PREMIER 2017: CHEVROLET VOLT PREMIER 2017 +HOLDEN ASTRA RS-V BK 2017: CHEVROLET VOLT PREMIER 2017 + +SKODA OCTAVIA 3RD GEN: SKODA SUPERB 3RD GEN +SKODA SCALA 1ST GEN: SKODA SUPERB 3RD GEN +SKODA KODIAQ 1ST GEN: SKODA SUPERB 3RD GEN +SKODA KAROQ 1ST GEN: SKODA SUPERB 3RD GEN +SKODA KAMIQ 1ST GEN: SKODA SUPERB 3RD GEN +VOLKSWAGEN T-ROC 1ST GEN: VOLKSWAGEN TIGUAN 2ND GEN +VOLKSWAGEN T-CROSS 1ST GEN: VOLKSWAGEN TIGUAN 2ND GEN +VOLKSWAGEN TOURAN 2ND GEN: VOLKSWAGEN TIGUAN 2ND GEN +VOLKSWAGEN TRANSPORTER T6.1: VOLKSWAGEN TIGUAN 2ND GEN +AUDI Q2 1ST GEN: VOLKSWAGEN TIGUAN 2ND GEN +VOLKSWAGEN TAOS 1ST GEN: VOLKSWAGEN TIGUAN 2ND GEN +VOLKSWAGEN POLO 6TH GEN: VOLKSWAGEN GOLF 7TH GEN +SEAT LEON 3RD GEN: VOLKSWAGEN GOLF 7TH GEN +SEAT ATECA 1ST GEN: VOLKSWAGEN GOLF 7TH GEN + +SUBARU LEGACY 7TH GEN: SUBARU OUTBACK 6TH GEN + +# Old subarus don't have much data guessing it's like low torque impreza +SUBARU OUTBACK 2018 - 2019: SUBARU IMPREZA LIMITED 2019 +SUBARU OUTBACK 2015 - 2017: SUBARU IMPREZA LIMITED 2019 +SUBARU FORESTER 2017 - 2018: SUBARU IMPREZA LIMITED 2019 +SUBARU LEGACY 2015 - 2018: SUBARU IMPREZA LIMITED 2019 +SUBARU ASCENT LIMITED 2019: SUBARU FORESTER 2019 diff --git a/selfdrive/car/toyota/carcontroller.py b/selfdrive/car/toyota/carcontroller.py index 9062fea6c1..c5bfdc4b22 100644 --- a/selfdrive/car/toyota/carcontroller.py +++ b/selfdrive/car/toyota/carcontroller.py @@ -4,34 +4,49 @@ from selfdrive.car import apply_toyota_steer_torque_limits, create_gas_intercept from selfdrive.car.toyota.toyotacan import create_steer_command, create_ui_command, \ create_accel_command, create_acc_cancel_command, \ create_fcw_command, create_lta_steer_command -from selfdrive.car.toyota.values import CAR, STATIC_DSU_MSGS, NO_STOP_TIMER_CAR, \ - MIN_ACC_SPEED, PEDAL_TRANSITION, CarControllerParams +from selfdrive.car.toyota.values import CAR, STATIC_DSU_MSGS, NO_STOP_TIMER_CAR, TSS2_CAR, \ + MIN_ACC_SPEED, PEDAL_TRANSITION, CarControllerParams, \ + UNSUPPORTED_DSU_CAR from opendbc.can.packer import CANPacker + VisualAlert = car.CarControl.HUDControl.VisualAlert +# EPS faults if you apply torque while the steering rate is above 100 deg/s for too long +MAX_STEER_RATE = 100 # deg/s +MAX_STEER_RATE_FRAMES = 18 # tx control frames needed before torque can be cut + +# EPS allows user torque above threshold for 50 frames before permanently faulting +MAX_USER_TORQUE = 500 + -class CarController(): +class CarController: def __init__(self, dbc_name, CP, VM): + self.CP = CP + self.torque_rate_limits = CarControllerParams(self.CP) + self.frame = 0 self.last_steer = 0 self.alert_active = False self.last_standstill = False self.standstill_req = False - self.steer_rate_limited = False + self.steer_rate_counter = 0 self.packer = CANPacker(dbc_name) self.gas = 0 self.accel = 0 - def update(self, enabled, active, CS, frame, actuators, pcm_cancel_cmd, hud_alert, - left_line, right_line, lead, left_lane_depart, right_lane_depart): + def update(self, CC, CS): + actuators = CC.actuators + hud_control = CC.hudControl + pcm_cancel_cmd = CC.cruiseControl.cancel + lat_active = CC.latActive and abs(CS.out.steeringTorque) < MAX_USER_TORQUE # gas and brake - if CS.CP.enableGasInterceptor and active: + if self.CP.enableGasInterceptor and CC.longActive: MAX_INTERCEPTOR_GAS = 0.5 # RAV4 has very sensitive gas pedal - if CS.CP.carFingerprint in (CAR.RAV4, CAR.RAV4H, CAR.HIGHLANDER, CAR.HIGHLANDERH): + if self.CP.carFingerprint in (CAR.RAV4, CAR.RAV4H, CAR.HIGHLANDER, CAR.HIGHLANDERH): PEDAL_SCALE = interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED, MIN_ACC_SPEED + PEDAL_TRANSITION], [0.15, 0.3, 0.0]) - elif CS.CP.carFingerprint in (CAR.COROLLA,): + elif self.CP.carFingerprint in (CAR.COROLLA,): PEDAL_SCALE = interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED, MIN_ACC_SPEED + PEDAL_TRANSITION], [0.3, 0.4, 0.0]) else: PEDAL_SCALE = interp(CS.out.vEgo, [0.0, MIN_ACC_SPEED, MIN_ACC_SPEED + PEDAL_TRANSITION], [0.4, 0.5, 0.0]) @@ -45,23 +60,29 @@ class CarController(): # steer torque new_steer = int(round(actuators.steer * CarControllerParams.STEER_MAX)) - apply_steer = apply_toyota_steer_torque_limits(new_steer, self.last_steer, CS.out.steeringTorqueEps, CarControllerParams) - self.steer_rate_limited = new_steer != apply_steer + apply_steer = apply_toyota_steer_torque_limits(new_steer, self.last_steer, CS.out.steeringTorqueEps, self.torque_rate_limits) + + # Count up to MAX_STEER_RATE_FRAMES, at which point we need to cut torque to avoid a steering fault + if lat_active and abs(CS.out.steeringRateDeg) >= MAX_STEER_RATE: + self.steer_rate_counter += 1 + else: + self.steer_rate_counter = 0 - # Cut steering while we're in a known fault state (2s) - if not active or CS.steer_state in (9, 25): + apply_steer_req = 1 + if not lat_active: apply_steer = 0 apply_steer_req = 0 - else: - apply_steer_req = 1 + elif self.steer_rate_counter > MAX_STEER_RATE_FRAMES: + apply_steer_req = 0 + self.steer_rate_counter = 0 # TODO: probably can delete this. CS.pcm_acc_status uses a different signal # than CS.cruiseState.enabled. confirm they're not meaningfully different - if not enabled and CS.pcm_acc_status: + if not CC.enabled and CS.pcm_acc_status: pcm_cancel_cmd = 1 # on entering standstill, send standstill request - if CS.out.standstill and not self.last_standstill and CS.CP.carFingerprint not in NO_STOP_TIMER_CAR: + if CS.out.standstill and not self.last_standstill and (self.CP.carFingerprint not in NO_STOP_TIMER_CAR or self.CP.enableGasInterceptor): self.standstill_req = True if CS.pcm_acc_status != 8: # pcm entered standstill or it's disabled @@ -72,68 +93,73 @@ class CarController(): can_sends = [] - #*** control msgs *** - #print("steer {0} {1} {2} {3}".format(apply_steer, min_lim, max_lim, CS.steer_torque_motor) + # *** control msgs *** + # print("steer {0} {1} {2} {3}".format(apply_steer, min_lim, max_lim, CS.steer_torque_motor) # toyota can trace shows this message at 42Hz, with counter adding alternatively 1 and 2; # sending it at 100Hz seem to allow a higher rate limit, as the rate limit seems imposed # on consecutive messages - # can_sends.append(create_steer_command(self.packer, apply_steer, apply_steer_req, frame)) - # if frame % 2 == 0 and CS.CP.carFingerprint in TSS2_CAR: - # can_sends.append(create_lta_steer_command(self.packer, 0, 0, frame // 2)) + """ + can_sends.append(create_steer_command(self.packer, apply_steer, apply_steer_req)) + if self.frame % 2 == 0 and self.CP.carFingerprint in TSS2_CAR: + can_sends.append(create_lta_steer_command(self.packer, 0, 0, self.frame // 2)) + """ # LTA mode. Set ret.steerControlType = car.CarParams.SteerControlType.angle and whitelist 0x191 in the panda - can_sends.append(create_steer_command(self.packer, 0, 0, frame)) + can_sends.append(create_steer_command(self.packer, 0, 0)) # On TSS2 cars, the LTA and STEER_TORQUE_SENSOR messages use relative steering angle signals that start # at 0 degrees, so we need to offset the commanded angle as well. can_sends.append(create_lta_steer_command(self.packer, actuators.steeringAngleDeg + CS.out.steeringAngleOffsetDeg, CS.out.steeringAngleDeg + CS.out.steeringAngleOffsetDeg, CS.out.steeringTorque, - apply_steer_req, frame)) + apply_steer_req, self.frame)) # we can spam can to cancel the system even if we are using lat only control - if (frame % 3 == 0 and CS.CP.openpilotLongitudinalControl) or pcm_cancel_cmd: - lead = lead or CS.out.vEgo < 12. # at low speed we always assume the lead is present so ACC can be engaged + if (self.frame % 3 == 0 and self.CP.openpilotLongitudinalControl) or pcm_cancel_cmd: + lead = hud_control.leadVisible or CS.out.vEgo < 12. # at low speed we always assume the lead is present so ACC can be engaged # Lexus IS uses a different cancellation message - if pcm_cancel_cmd and CS.CP.carFingerprint in (CAR.LEXUS_IS, CAR.LEXUS_RC): + if pcm_cancel_cmd and self.CP.carFingerprint in UNSUPPORTED_DSU_CAR: can_sends.append(create_acc_cancel_command(self.packer)) - elif CS.CP.openpilotLongitudinalControl: + elif self.CP.openpilotLongitudinalControl: can_sends.append(create_accel_command(self.packer, pcm_accel_cmd, pcm_cancel_cmd, self.standstill_req, lead, CS.acc_type)) self.accel = pcm_accel_cmd else: can_sends.append(create_accel_command(self.packer, 0, pcm_cancel_cmd, False, lead, CS.acc_type)) - if frame % 2 == 0 and CS.CP.enableGasInterceptor and CS.CP.openpilotLongitudinalControl: + if self.frame % 2 == 0 and self.CP.enableGasInterceptor and self.CP.openpilotLongitudinalControl: # send exactly zero if gas cmd is zero. Interceptor will send the max between read value and gas cmd. # This prevents unexpected pedal range rescaling - can_sends.append(create_gas_interceptor_command(self.packer, interceptor_gas_cmd, frame // 2)) + can_sends.append(create_gas_interceptor_command(self.packer, interceptor_gas_cmd, self.frame // 2)) self.gas = interceptor_gas_cmd - # ui mesg is at 1Hz but we send asap if: - # - there is something to display - # - there is something to stop displaying - fcw_alert = hud_alert == VisualAlert.fcw - steer_alert = hud_alert in (VisualAlert.steerRequired, VisualAlert.ldw) - - send_ui = False - if ((fcw_alert or steer_alert) and not self.alert_active) or \ - (not (fcw_alert or steer_alert) and self.alert_active): - send_ui = True - self.alert_active = not self.alert_active - elif pcm_cancel_cmd: - # forcing the pcm to disengage causes a bad fault sound so play a good sound instead - send_ui = True - - if (frame % 100 == 0 or send_ui): - can_sends.append(create_ui_command(self.packer, steer_alert, pcm_cancel_cmd, left_line, right_line, left_lane_depart, right_lane_depart, enabled)) - - if frame % 100 == 0 and CS.CP.enableDsu: - can_sends.append(create_fcw_command(self.packer, fcw_alert)) + if self.CP.carFingerprint != CAR.PRIUS_V: + # ui mesg is at 1Hz but we send asap if: + # - there is something to display + # - there is something to stop displaying + fcw_alert = hud_control.visualAlert == VisualAlert.fcw + steer_alert = hud_control.visualAlert in (VisualAlert.steerRequired, VisualAlert.ldw) + + send_ui = False + if ((fcw_alert or steer_alert) and not self.alert_active) or \ + (not (fcw_alert or steer_alert) and self.alert_active): + send_ui = True + self.alert_active = not self.alert_active + elif pcm_cancel_cmd: + # forcing the pcm to disengage causes a bad fault sound so play a good sound instead + send_ui = True + + if self.frame % 100 == 0 or send_ui: + can_sends.append(create_ui_command(self.packer, steer_alert, pcm_cancel_cmd, hud_control.leftLaneVisible, + hud_control.rightLaneVisible, hud_control.leftLaneDepart, + hud_control.rightLaneDepart, CC.enabled)) + + if (self.frame % 100 == 0 or send_ui) and self.CP.enableDsu: + can_sends.append(create_fcw_command(self.packer, fcw_alert)) # *** static msgs *** - for (addr, cars, bus, fr_step, vl) in STATIC_DSU_MSGS: - if frame % fr_step == 0 and CS.CP.enableDsu and CS.CP.carFingerprint in cars: + for addr, cars, bus, fr_step, vl in STATIC_DSU_MSGS: + if self.frame % fr_step == 0 and self.CP.enableDsu and self.CP.carFingerprint in cars: can_sends.append(make_can_msg(addr, vl, bus)) new_actuators = actuators.copy() @@ -141,4 +167,5 @@ class CarController(): new_actuators.accel = self.accel new_actuators.gas = self.gas + self.frame += 1 return new_actuators, can_sends diff --git a/selfdrive/car/toyota/carstate.py b/selfdrive/car/toyota/carstate.py index 328dbdeef4..b31a6313f3 100644 --- a/selfdrive/car/toyota/carstate.py +++ b/selfdrive/car/toyota/carstate.py @@ -1,12 +1,12 @@ from cereal import car +from common.conversions import Conversions as CV from common.numpy_fast import mean from common.filter_simple import FirstOrderFilter from common.realtime import DT_CTRL from opendbc.can.can_define import CANDefine -from selfdrive.car.interfaces import CarStateBase from opendbc.can.parser import CANParser -from selfdrive.config import Conversions as CV -from selfdrive.car.toyota.values import ToyotaFlags, CAR, DBC, STEER_THRESHOLD, NO_STOP_TIMER_CAR, TSS2_CAR, EPS_SCALE +from selfdrive.car.interfaces import CarStateBase +from selfdrive.car.toyota.values import ToyotaFlags, DBC, STEER_THRESHOLD, TSS2_CAR, RADAR_ACC_CAR, EPS_SCALE, UNSUPPORTED_DSU_CAR class CarState(CarStateBase): @@ -15,11 +15,12 @@ class CarState(CarStateBase): can_define = CANDefine(DBC[CP.carFingerprint]["pt"]) self.shifter_values = can_define.dv["GEAR_PACKET"]["GEAR"] self.eps_torque_scale = EPS_SCALE[CP.carFingerprint] / 100. + self.cluster_speed_hyst_gap = CV.KPH_TO_MS / 2. + self.cluster_min_speed = CV.KPH_TO_MS / 2. # On cars with cp.vl["STEER_TORQUE_SENSOR"]["STEER_ANGLE"] # the signal is zeroed to where the steering angle is at start. # Need to apply an offset as soon as the steering angle measurements are both received - self.needs_angle_offset = True self.accurate_steer_angle_seen = False self.angle_offset = FirstOrderFilter(None, 60.0, DT_CTRL, initialized=False) @@ -33,12 +34,13 @@ class CarState(CarStateBase): ret.doorOpen = any([cp.vl["BODY_CONTROL_STATE"]["DOOR_OPEN_FL"], cp.vl["BODY_CONTROL_STATE"]["DOOR_OPEN_FR"], cp.vl["BODY_CONTROL_STATE"]["DOOR_OPEN_RL"], cp.vl["BODY_CONTROL_STATE"]["DOOR_OPEN_RR"]]) ret.seatbeltUnlatched = cp.vl["BODY_CONTROL_STATE"]["SEATBELT_DRIVER_UNLATCHED"] != 0 + ret.parkingBrake = cp.vl["BODY_CONTROL_STATE"]["PARKING_BRAKE"] == 1 ret.brakePressed = cp.vl["BRAKE_MODULE"]["BRAKE_PRESSED"] != 0 ret.brakeHoldActive = cp.vl["ESP_CONTROL"]["BRAKE_HOLD_ACTIVE"] == 1 if self.CP.enableGasInterceptor: - ret.gas = (cp.vl["GAS_SENSOR"]["INTERCEPTOR_GAS"] + cp.vl["GAS_SENSOR"]["INTERCEPTOR_GAS2"]) / 2. - ret.gasPressed = ret.gas > 15 + ret.gas = (cp.vl["GAS_SENSOR"]["INTERCEPTOR_GAS"] + cp.vl["GAS_SENSOR"]["INTERCEPTOR_GAS2"]) // 2 + ret.gasPressed = ret.gas > 805 else: # TODO: find a new, common signal msg = "GAS_PEDAL_HYBRID" if (self.CP.flags & ToyotaFlags.HYBRID) else "GAS_PEDAL" @@ -53,14 +55,15 @@ class CarState(CarStateBase): ) ret.vEgoRaw = mean([ret.wheelSpeeds.fl, ret.wheelSpeeds.fr, ret.wheelSpeeds.rl, ret.wheelSpeeds.rr]) ret.vEgo, ret.aEgo = self.update_speed_kf(ret.vEgoRaw) + ret.vEgoCluster = ret.vEgo * 1.015 # minimum of all the cars - ret.standstill = ret.vEgoRaw < 0.001 + ret.standstill = ret.vEgoRaw == 0 ret.steeringAngleDeg = cp.vl["STEER_ANGLE_SENSOR"]["STEER_ANGLE"] + cp.vl["STEER_ANGLE_SENSOR"]["STEER_FRACTION"] self.torque_sensor_angle_deg = cp.vl["STEER_TORQUE_SENSOR"]["STEER_ANGLE"] - # Some newer models have a more accurate angle measurement in the TORQUE_SENSOR message. Use if non-zero - if abs(self.torque_sensor_angle_deg) > 1e-3: + # On some cars, the angle measurement is non-zero while initializing + if abs(self.torque_sensor_angle_deg) > 1e-3 and not bool(cp.vl["STEER_TORQUE_SENSOR"]["STEER_ANGLE_INITIALIZING"]): self.accurate_steer_angle_seen = True if self.accurate_steer_angle_seen: @@ -83,42 +86,54 @@ class CarState(CarStateBase): ret.steeringTorqueEps = cp.vl["STEER_TORQUE_SENSOR"]["STEER_TORQUE_EPS"] * self.eps_torque_scale # we could use the override bit from dbc, but it's triggered at too high torque values ret.steeringPressed = abs(ret.steeringTorque) > STEER_THRESHOLD - ret.steerWarning = cp.vl["EPS_STATUS"]["LKA_STATE"] not in (1, 5) - - if self.CP.carFingerprint in (CAR.LEXUS_IS, CAR.LEXUS_RC): + # steer rate fault: goes to 21 or 25 for 1 frame, then 9 for 2 seconds + # lka msg drop out: goes to 9 then 11 for a combined total of 2 seconds + ret.steerFaultTemporary = cp.vl["EPS_STATUS"]["LKA_STATE"] in (0, 9, 11, 21, 25) + # 17 is a fault from a prolonged high torque delta between cmd and user + # 3 is a fault from the lka command message not being received by the EPS + ret.steerFaultPermanent = cp.vl["EPS_STATUS"]["LKA_STATE"] in (3, 17) + + if self.CP.carFingerprint in UNSUPPORTED_DSU_CAR: + # TODO: find the bit likely in DSU_CRUISE that describes an ACC fault. one may also exist in CLUTCH ret.cruiseState.available = cp.vl["DSU_CRUISE"]["MAIN_ON"] != 0 ret.cruiseState.speed = cp.vl["DSU_CRUISE"]["SET_SPEED"] * CV.KPH_TO_MS + cluster_set_speed = cp.vl["PCM_CRUISE_ALT"]["UI_SET_SPEED"] else: + ret.accFaulted = cp.vl["PCM_CRUISE_2"]["ACC_FAULTED"] != 0 ret.cruiseState.available = cp.vl["PCM_CRUISE_2"]["MAIN_ON"] != 0 ret.cruiseState.speed = cp.vl["PCM_CRUISE_2"]["SET_SPEED"] * CV.KPH_TO_MS + cluster_set_speed = cp.vl["PCM_CRUISE_SM"]["UI_SET_SPEED"] - if self.CP.carFingerprint in TSS2_CAR: - self.acc_type = cp_cam.vl["ACC_CONTROL"]["ACC_TYPE"] + # UI_SET_SPEED is always non-zero when main is on, hide until first enable + if ret.cruiseState.speed != 0: + is_metric = cp.vl["BODY_CONTROL_STATE_2"]["UNITS"] in (1, 2) + conversion_factor = CV.KPH_TO_MS if is_metric else CV.MPH_TO_MS + ret.cruiseState.speedCluster = cluster_set_speed * conversion_factor + + cp_acc = cp_cam if self.CP.carFingerprint in (TSS2_CAR - RADAR_ACC_CAR) else cp + + if self.CP.carFingerprint in (TSS2_CAR | RADAR_ACC_CAR): + self.acc_type = cp_acc.vl["ACC_CONTROL"]["ACC_TYPE"] + ret.stockFcw = bool(cp_acc.vl["ACC_HUD"]["FCW"]) # some TSS2 cars have low speed lockout permanently set, so ignore on those cars # these cars are identified by an ACC_TYPE value of 2. # TODO: it is possible to avoid the lockout and gain stop and go if you # send your own ACC_CONTROL msg on startup with ACC_TYPE set to 1 - if (self.CP.carFingerprint not in TSS2_CAR and self.CP.carFingerprint not in (CAR.LEXUS_IS, CAR.LEXUS_RC)) or \ + if (self.CP.carFingerprint not in TSS2_CAR and self.CP.carFingerprint not in UNSUPPORTED_DSU_CAR) or \ (self.CP.carFingerprint in TSS2_CAR and self.acc_type == 1): self.low_speed_lockout = cp.vl["PCM_CRUISE_2"]["LOW_SPEED_LOCKOUT"] == 2 self.pcm_acc_status = cp.vl["PCM_CRUISE"]["CRUISE_STATE"] - if self.CP.carFingerprint in NO_STOP_TIMER_CAR or self.CP.enableGasInterceptor: - # ignore standstill in hybrid vehicles, since pcm allows to restart without - # receiving any special command. Also if interceptor is detected - ret.cruiseState.standstill = False - else: - ret.cruiseState.standstill = self.pcm_acc_status == 7 + ret.cruiseState.standstill = self.pcm_acc_status == 7 ret.cruiseState.enabled = bool(cp.vl["PCM_CRUISE"]["CRUISE_ACTIVE"]) ret.cruiseState.nonAdaptive = cp.vl["PCM_CRUISE"]["CRUISE_STATE"] in (1, 2, 3, 4, 5, 6) ret.genericToggle = bool(cp.vl["LIGHT_STALK"]["AUTO_HIGH_BEAM"]) - ret.stockAeb = bool(cp_cam.vl["PRE_COLLISION"]["PRECOLLISION_ACTIVE"] and cp_cam.vl["PRE_COLLISION"]["FORCE"] < -1e-5) - ret.espDisabled = cp.vl["ESP_CONTROL"]["TC_DISABLED"] != 0 - # 2 is standby, 10 is active. TODO: check that everything else is really a faulty state - self.steer_state = cp.vl["EPS_STATUS"]["LKA_STATE"] + + if not self.CP.enableDsu: + ret.stockAeb = bool(cp_acc.vl["PRE_COLLISION"]["PRECOLLISION_ACTIVE"] and cp_acc.vl["PRE_COLLISION"]["FORCE"] < -1e-5) if self.CP.enableBsm: ret.leftBlindspot = (cp.vl["BSM"]["L_ADJACENT"] == 1) or (cp.vl["BSM"]["L_APPROACHING"] == 1) @@ -142,6 +157,8 @@ class CarState(CarStateBase): ("DOOR_OPEN_RL", "BODY_CONTROL_STATE"), ("DOOR_OPEN_RR", "BODY_CONTROL_STATE"), ("SEATBELT_DRIVER_UNLATCHED", "BODY_CONTROL_STATE"), + ("PARKING_BRAKE", "BODY_CONTROL_STATE"), + ("UNITS", "BODY_CONTROL_STATE_2"), ("TC_DISABLED", "ESP_CONTROL"), ("BRAKE_HOLD_ACTIVE", "ESP_CONTROL"), ("STEER_FRACTION", "STEER_ANGLE_SENSOR"), @@ -149,9 +166,11 @@ class CarState(CarStateBase): ("CRUISE_ACTIVE", "PCM_CRUISE"), ("CRUISE_STATE", "PCM_CRUISE"), ("GAS_RELEASED", "PCM_CRUISE"), + ("UI_SET_SPEED", "PCM_CRUISE_SM"), ("STEER_TORQUE_DRIVER", "STEER_TORQUE_SENSOR"), ("STEER_TORQUE_EPS", "STEER_TORQUE_SENSOR"), ("STEER_ANGLE", "STEER_TORQUE_SENSOR"), + ("STEER_ANGLE_INITIALIZING", "STEER_TORQUE_SENSOR"), ("TURN_SIGNALS", "BLINKERS_STATE"), ("LKA_STATE", "EPS_STATUS"), ("AUTO_HIGH_BEAM", "LIGHT_STALK"), @@ -162,12 +181,14 @@ class CarState(CarStateBase): ("LIGHT_STALK", 1), ("BLINKERS_STATE", 0.15), ("BODY_CONTROL_STATE", 3), + ("BODY_CONTROL_STATE_2", 2), ("ESP_CONTROL", 3), ("EPS_STATUS", 25), ("BRAKE_MODULE", 40), ("WHEEL_SPEEDS", 80), ("STEER_ANGLE_SENSOR", 80), ("PCM_CRUISE", 33), + ("PCM_CRUISE_SM", 1), ("STEER_TORQUE_SENSOR", 50), ] @@ -178,13 +199,16 @@ class CarState(CarStateBase): signals.append(("GAS_PEDAL", "GAS_PEDAL")) checks.append(("GAS_PEDAL", 33)) - if CP.carFingerprint in (CAR.LEXUS_IS, CAR.LEXUS_RC): + if CP.carFingerprint in UNSUPPORTED_DSU_CAR: signals.append(("MAIN_ON", "DSU_CRUISE")) signals.append(("SET_SPEED", "DSU_CRUISE")) + signals.append(("UI_SET_SPEED", "PCM_CRUISE_ALT")) checks.append(("DSU_CRUISE", 5)) + checks.append(("PCM_CRUISE_ALT", 1)) else: signals.append(("MAIN_ON", "PCM_CRUISE_2")) signals.append(("SET_SPEED", "PCM_CRUISE_2")) + signals.append(("ACC_FAULTED", "PCM_CRUISE_2")) signals.append(("LOW_SPEED_LOCKOUT", "PCM_CRUISE_2")) checks.append(("PCM_CRUISE_2", 33)) @@ -203,23 +227,43 @@ class CarState(CarStateBase): ] checks.append(("BSM", 1)) + if CP.carFingerprint in RADAR_ACC_CAR: + signals += [ + ("ACC_TYPE", "ACC_CONTROL"), + ("FCW", "ACC_HUD"), + ] + checks += [ + ("ACC_CONTROL", 33), + ("ACC_HUD", 1), + ] + + if CP.carFingerprint not in (TSS2_CAR - RADAR_ACC_CAR) and not CP.enableDsu: + signals += [ + ("FORCE", "PRE_COLLISION"), + ("PRECOLLISION_ACTIVE", "PRE_COLLISION"), + ] + checks += [ + ("PRE_COLLISION", 33), + ] + return CANParser(DBC[CP.carFingerprint]["pt"], signals, checks, 0) @staticmethod def get_cam_can_parser(CP): - signals = [ - ("FORCE", "PRE_COLLISION"), - ("PRECOLLISION_ACTIVE", "PRE_COLLISION"), - ] + signals = [] + checks = [] - # use steering message to check if panda is connected to frc - checks = [ - ("STEERING_LKA", 42), - ("PRE_COLLISION", 0), # TODO: figure out why freq is inconsistent - ] - - if CP.carFingerprint in TSS2_CAR: - signals.append(("ACC_TYPE", "ACC_CONTROL")) - checks.append(("ACC_CONTROL", 33)) + if CP.carFingerprint in (TSS2_CAR - RADAR_ACC_CAR): + signals += [ + ("PRECOLLISION_ACTIVE", "PRE_COLLISION"), + ("FORCE", "PRE_COLLISION"), + ("ACC_TYPE", "ACC_CONTROL"), + ("FCW", "ACC_HUD"), + ] + checks += [ + ("PRE_COLLISION", 33), + ("ACC_CONTROL", 33), + ("ACC_HUD", 1), + ] return CANParser(DBC[CP.carFingerprint]["pt"], signals, checks, 2) diff --git a/selfdrive/car/toyota/interface.py b/selfdrive/car/toyota/interface.py index 9d16d140c1..9b9b82292d 100644 --- a/selfdrive/car/toyota/interface.py +++ b/selfdrive/car/toyota/interface.py @@ -1,9 +1,9 @@ #!/usr/bin/env python3 from cereal import car -from selfdrive.config import Conversions as CV -from selfdrive.car.toyota.tunes import LatTunes, LongTunes, set_long_tune, set_lat_tune -from selfdrive.car.toyota.values import Ecu, CAR, ToyotaFlags, TSS2_CAR, NO_DSU_CAR, MIN_ACC_SPEED, EPS_SCALE, EV_HYBRID_CAR, CarControllerParams -from selfdrive.car import STD_CARGO_KG, scale_rot_inertia, scale_tire_stiffness, gen_empty_fingerprint, get_safety_config +from common.conversions import Conversions as CV +from panda import Panda +from selfdrive.car.toyota.values import Ecu, CAR, ToyotaFlags, TSS2_CAR, RADAR_ACC_CAR, NO_DSU_CAR, MIN_ACC_SPEED, EPS_SCALE, EV_HYBRID_CAR, UNSUPPORTED_DSU_CAR, CarControllerParams, NO_STOP_TIMER_CAR +from selfdrive.car import STD_CARGO_KG, scale_tire_stiffness, get_safety_config from selfdrive.car.interfaces import CarInterfaceBase EventName = car.CarEvent.EventName @@ -15,18 +15,21 @@ class CarInterface(CarInterfaceBase): return CarControllerParams.ACCEL_MIN, CarControllerParams.ACCEL_MAX @staticmethod - def get_params(candidate, fingerprint=gen_empty_fingerprint(), car_fw=[]): # pylint: disable=dangerous-default-value - ret = CarInterfaceBase.get_std_params(candidate, fingerprint) - + def _get_params(ret, candidate, fingerprint, car_fw, experimental_long): ret.carName = "toyota" ret.safetyConfigs = [get_safety_config(car.CarParams.SafetyModel.toyota)] ret.safetyConfigs[0].safetyParam = EPS_SCALE[candidate] + if candidate in (CAR.RAV4, CAR.PRIUS_V, CAR.COROLLA, CAR.LEXUS_ESH, CAR.LEXUS_CTH): + ret.safetyConfigs[0].safetyParam |= Panda.FLAG_TOYOTA_ALT_BRAKE + ret.steerActuatorDelay = 0.12 # Default delay, Prius has larger delay ret.steerLimitTimer = 0.4 ret.stoppingControl = False # Toyota starts braking more when it thinks you want to stop stop_and_go = False + steering_angle_deadzone_deg = 0.0 + CarInterfaceBase.configure_torque_tune(candidate, ret.lateralTuning, steering_angle_deadzone_deg) if candidate == CAR.PRIUS: stop_and_go = True @@ -34,17 +37,19 @@ class CarInterface(CarInterfaceBase): ret.steerRatio = 15.74 # unknown end-to-end spec tire_stiffness_factor = 0.6371 # hand-tune ret.mass = 3045. * CV.LB_TO_KG + STD_CARGO_KG - - set_lat_tune(ret.lateralTuning, LatTunes.INDI_PRIUS) - ret.steerActuatorDelay = 0.3 + # Only give steer angle deadzone to for bad angle sensor prius + for fw in car_fw: + if fw.ecu == "eps" and not fw.fwVersion == b'8965B47060\x00\x00\x00\x00\x00\x00': + steering_angle_deadzone_deg = 0.2 + ret.steerActuatorDelay = 0.25 + CarInterfaceBase.configure_torque_tune(candidate, ret.lateralTuning, steering_angle_deadzone_deg) elif candidate == CAR.PRIUS_V: stop_and_go = True ret.wheelbase = 2.78 ret.steerRatio = 17.4 tire_stiffness_factor = 0.5533 - ret.mass = 4387. * CV.LB_TO_KG + STD_CARGO_KG - set_lat_tune(ret.lateralTuning, LatTunes.LQR_RAV4) + ret.mass = 3340. * CV.LB_TO_KG + STD_CARGO_KG elif candidate in (CAR.RAV4, CAR.RAV4H): stop_and_go = True if (candidate in CAR.RAV4H) else False @@ -52,14 +57,12 @@ class CarInterface(CarInterfaceBase): ret.steerRatio = 16.88 # 14.5 is spec end-to-end tire_stiffness_factor = 0.5533 ret.mass = 3650. * CV.LB_TO_KG + STD_CARGO_KG # mean between normal and hybrid - set_lat_tune(ret.lateralTuning, LatTunes.LQR_RAV4) elif candidate == CAR.COROLLA: ret.wheelbase = 2.70 ret.steerRatio = 18.27 tire_stiffness_factor = 0.444 # not optimized yet ret.mass = 2860. * CV.LB_TO_KG + STD_CARGO_KG # mean between normal and hybrid - set_lat_tune(ret.lateralTuning, LatTunes.PID_A) elif candidate in (CAR.LEXUS_RX, CAR.LEXUS_RXH, CAR.LEXUS_RX_TSS2, CAR.LEXUS_RXH_TSS2): stop_and_go = True @@ -68,7 +71,6 @@ class CarInterface(CarInterfaceBase): ret.wheelSpeedFactor = 1.035 tire_stiffness_factor = 0.5533 ret.mass = 4481. * CV.LB_TO_KG + STD_CARGO_KG # mean between min and max - set_lat_tune(ret.lateralTuning, LatTunes.PID_C) elif candidate in (CAR.CHR, CAR.CHRH): stop_and_go = True @@ -76,7 +78,6 @@ class CarInterface(CarInterfaceBase): ret.steerRatio = 13.6 tire_stiffness_factor = 0.7933 ret.mass = 3300. * CV.LB_TO_KG + STD_CARGO_KG - set_lat_tune(ret.lateralTuning, LatTunes.PID_F) elif candidate in (CAR.CAMRY, CAR.CAMRYH, CAR.CAMRY_TSS2, CAR.CAMRYH_TSS2): stop_and_go = True @@ -84,44 +85,43 @@ class CarInterface(CarInterfaceBase): ret.steerRatio = 13.7 tire_stiffness_factor = 0.7933 ret.mass = 3400. * CV.LB_TO_KG + STD_CARGO_KG # mean between normal and hybrid - set_lat_tune(ret.lateralTuning, LatTunes.PID_C) - - elif candidate in (CAR.HIGHLANDER_TSS2, CAR.HIGHLANDERH_TSS2): - stop_and_go = True - ret.wheelbase = 2.84988 # 112.2 in = 2.84988 m - ret.steerRatio = 16.0 - tire_stiffness_factor = 0.8 - ret.mass = 4700. * CV.LB_TO_KG + STD_CARGO_KG # 4260 + 4-5 people - set_lat_tune(ret.lateralTuning, LatTunes.PID_G) - elif candidate in (CAR.HIGHLANDER, CAR.HIGHLANDERH): + elif candidate in (CAR.HIGHLANDER, CAR.HIGHLANDERH, CAR.HIGHLANDER_TSS2, CAR.HIGHLANDERH_TSS2): stop_and_go = True - ret.wheelbase = 2.78 + ret.wheelbase = 2.8194 # average of 109.8 and 112.2 in ret.steerRatio = 16.0 tire_stiffness_factor = 0.8 - ret.mass = 4607. * CV.LB_TO_KG + STD_CARGO_KG # mean between normal and hybrid limited - set_lat_tune(ret.lateralTuning, LatTunes.PID_G) + ret.mass = 4516. * CV.LB_TO_KG + STD_CARGO_KG # mean between normal and hybrid - elif candidate in (CAR.AVALON, CAR.AVALON_2019, CAR.AVALONH_2019, CAR.AVALON_TSS2): + elif candidate in (CAR.AVALON, CAR.AVALON_2019, CAR.AVALONH_2019, CAR.AVALON_TSS2, CAR.AVALONH_TSS2): + # starting from 2019, all Avalon variants have stop and go + # https://engage.toyota.com/static/images/toyota_safety_sense/TSS_Applicability_Chart.pdf + stop_and_go = candidate != CAR.AVALON 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_KG # mean between normal and hybrid - set_lat_tune(ret.lateralTuning, LatTunes.PID_H) - elif candidate in (CAR.RAV4_TSS2, CAR.RAV4H_TSS2): + elif candidate in (CAR.RAV4_TSS2, CAR.RAV4_TSS2_2022, CAR.RAV4H_TSS2, CAR.RAV4H_TSS2_2022): stop_and_go = True ret.wheelbase = 2.68986 ret.steerRatio = 14.3 tire_stiffness_factor = 0.7933 ret.mass = 3585. * CV.LB_TO_KG + STD_CARGO_KG # Average between ICE and Hybrid - set_lat_tune(ret.lateralTuning, LatTunes.PID_D) - - # 2019+ Rav4 TSS2 uses two different steering racks and specific tuning seems to be necessary. + ret.lateralTuning.init('pid') + ret.lateralTuning.pid.kiBP = [0.0] + ret.lateralTuning.pid.kpBP = [0.0] + ret.lateralTuning.pid.kpV = [0.6] + ret.lateralTuning.pid.kiV = [0.1] + ret.lateralTuning.pid.kf = 0.00007818594 + + # 2019+ RAV4 TSS2 uses two different steering racks and specific tuning seems to be necessary. # See https://github.com/commaai/openpilot/pull/21429#issuecomment-873652891 for fw in car_fw: if fw.ecu == "eps" and (fw.fwVersion.startswith(b'\x02') or fw.fwVersion in [b'8965B42181\x00\x00\x00\x00\x00\x00']): - set_lat_tune(ret.lateralTuning, LatTunes.PID_I) + ret.lateralTuning.pid.kpV = [0.15] + ret.lateralTuning.pid.kiV = [0.05] + ret.lateralTuning.pid.kf = 0.00004 break elif candidate in (CAR.COROLLA_TSS2, CAR.COROLLAH_TSS2): @@ -131,7 +131,6 @@ class CarInterface(CarInterfaceBase): tire_stiffness_factor = 0.444 # not optimized yet ret.mass = 3060. * CV.LB_TO_KG + STD_CARGO_KG ret.steerControlType = car.CarParams.SteerControlType.angle - # set_lat_tune(ret.lateralTuning, LatTunes.PID_D) elif candidate in (CAR.LEXUS_ES_TSS2, CAR.LEXUS_ESH_TSS2, CAR.LEXUS_ESH): stop_and_go = True @@ -139,7 +138,6 @@ class CarInterface(CarInterfaceBase): ret.steerRatio = 16.0 # not optimized tire_stiffness_factor = 0.444 # not optimized yet ret.mass = 3677. * CV.LB_TO_KG + STD_CARGO_KG # mean between min and max - set_lat_tune(ret.lateralTuning, LatTunes.PID_D) elif candidate == CAR.SIENNA: stop_and_go = True @@ -147,14 +145,12 @@ class CarInterface(CarInterfaceBase): ret.steerRatio = 15.5 tire_stiffness_factor = 0.444 ret.mass = 4590. * CV.LB_TO_KG + STD_CARGO_KG - set_lat_tune(ret.lateralTuning, LatTunes.PID_J) elif candidate in (CAR.LEXUS_IS, CAR.LEXUS_RC): ret.wheelbase = 2.79908 ret.steerRatio = 13.3 tire_stiffness_factor = 0.444 ret.mass = 3736.8 * CV.LB_TO_KG + STD_CARGO_KG - set_lat_tune(ret.lateralTuning, LatTunes.PID_L) elif candidate == CAR.LEXUS_CTH: stop_and_go = True @@ -162,15 +158,13 @@ class CarInterface(CarInterfaceBase): ret.steerRatio = 18.6 tire_stiffness_factor = 0.517 ret.mass = 3108 * CV.LB_TO_KG + STD_CARGO_KG # mean between min and max - set_lat_tune(ret.lateralTuning, LatTunes.PID_M) - elif candidate in (CAR.LEXUS_NXH, CAR.LEXUS_NX, CAR.LEXUS_NX_TSS2): + elif candidate in (CAR.LEXUS_NX, CAR.LEXUS_NXH, CAR.LEXUS_NX_TSS2, CAR.LEXUS_NXH_TSS2): stop_and_go = True ret.wheelbase = 2.66 ret.steerRatio = 14.7 tire_stiffness_factor = 0.444 # not optimized yet ret.mass = 4070 * CV.LB_TO_KG + STD_CARGO_KG - set_lat_tune(ret.lateralTuning, LatTunes.PID_C) elif candidate == CAR.PRIUS_TSS2: stop_and_go = True @@ -178,7 +172,6 @@ class CarInterface(CarInterfaceBase): ret.steerRatio = 13.4 # True steerRatio from older prius tire_stiffness_factor = 0.6371 # hand-tune ret.mass = 3115. * CV.LB_TO_KG + STD_CARGO_KG - set_lat_tune(ret.lateralTuning, LatTunes.PID_N) elif candidate == CAR.MIRAI: stop_and_go = True @@ -186,23 +179,16 @@ class CarInterface(CarInterfaceBase): ret.steerRatio = 14.8 tire_stiffness_factor = 0.8 ret.mass = 4300. * CV.LB_TO_KG + STD_CARGO_KG - set_lat_tune(ret.lateralTuning, LatTunes.PID_C) - elif candidate == CAR.ALPHARD_TSS2: + elif candidate in (CAR.ALPHARD_TSS2, CAR.ALPHARDH_TSS2): stop_and_go = True ret.wheelbase = 3.00 ret.steerRatio = 14.2 tire_stiffness_factor = 0.444 ret.mass = 4305. * CV.LB_TO_KG + STD_CARGO_KG - set_lat_tune(ret.lateralTuning, LatTunes.PID_J) - ret.steerRateCost = 1. ret.centerToFront = ret.wheelbase * 0.44 - # TODO: get actual value, for now starting with reasonable value for - # civic and scaling by mass and wheelbase - ret.rotationalInertia = scale_rot_inertia(ret.mass, ret.wheelbase) - # TODO: start from empirically derived lateral slip stiffness for the civic and scale by # mass and CG position, so all cars will have approximately similar dyn behaviors ret.tireStiffnessFront, ret.tireStiffnessRear = scale_tire_stiffness(ret.mass, ret.wheelbase, ret.centerToFront, @@ -213,10 +199,14 @@ class CarInterface(CarInterfaceBase): smartDsu = 0x2FF in fingerprint[0] # In TSS2 cars the camera does long control found_ecus = [fw.ecu for fw in car_fw] - ret.enableDsu = (len(found_ecus) > 0) and (Ecu.dsu not in found_ecus) and (candidate not in NO_DSU_CAR) and (not smartDsu) + ret.enableDsu = len(found_ecus) > 0 and Ecu.dsu not in found_ecus and candidate not in (NO_DSU_CAR | UNSUPPORTED_DSU_CAR) and not smartDsu ret.enableGasInterceptor = 0x201 in fingerprint[0] # if the smartDSU is detected, openpilot can send ACC_CMD (and the smartDSU will block it from the DSU) or not (the DSU is "connected") - ret.openpilotLongitudinalControl = smartDsu or ret.enableDsu or candidate in TSS2_CAR + ret.openpilotLongitudinalControl = smartDsu or ret.enableDsu or candidate in (TSS2_CAR - RADAR_ACC_CAR) + ret.autoResumeSng = ret.openpilotLongitudinalControl and candidate in NO_STOP_TIMER_CAR + + if not ret.openpilotLongitudinalControl: + ret.safetyConfigs[0].safetyParam |= Panda.FLAG_TOYOTA_STOCK_LONGITUDINAL # we can't use the fingerprint to detect this reliably, since # the EV gas pedal signal can take a couple seconds to appear @@ -227,55 +217,50 @@ class CarInterface(CarInterfaceBase): # to a negative value, so it won't matter. ret.minEnableSpeed = -1. if (stop_and_go or ret.enableGasInterceptor) else MIN_ACC_SPEED - if ret.enableGasInterceptor: - set_long_tune(ret.longitudinalTuning, LongTunes.PEDAL) - elif candidate in TSS2_CAR: - set_long_tune(ret.longitudinalTuning, LongTunes.TSS2) - ret.stoppingDecelRate = 0.3 # reach stopping target smoothly + tune = ret.longitudinalTuning + tune.deadzoneBP = [0., 9.] + tune.deadzoneV = [.0, .15] + if candidate in TSS2_CAR or ret.enableGasInterceptor: + tune.kpBP = [0., 5., 20.] + tune.kpV = [1.3, 1.0, 0.7] + tune.kiBP = [0., 5., 12., 20., 27.] + tune.kiV = [.35, .23, .20, .17, .1] + if candidate in TSS2_CAR: + ret.stoppingDecelRate = 0.3 # reach stopping target smoothly else: - set_long_tune(ret.longitudinalTuning, LongTunes.TSS) + tune.kpBP = [0., 5., 35.] + tune.kiBP = [0., 35.] + tune.kpV = [3.6, 2.4, 1.5] + tune.kiV = [0.54, 0.36] return ret # returns a car.CarState - def update(self, c, can_strings): - # ******************* do can recv ******************* - self.cp.update_strings(can_strings) - self.cp_cam.update_strings(can_strings) - + def _update(self, c): ret = self.CS.update(self.cp, self.cp_cam) - ret.canValid = self.cp.can_valid and self.cp_cam.can_valid - ret.steeringRateLimited = self.CC.steer_rate_limited if self.CC is not None else False - # events events = self.create_common_events(ret) - if self.CS.low_speed_lockout and self.CP.openpilotLongitudinalControl: - events.add(EventName.lowSpeedLockout) - if ret.vEgo < self.CP.minEnableSpeed and self.CP.openpilotLongitudinalControl: - events.add(EventName.belowEngageSpeed) - if c.actuators.accel > 0.3: - # some margin on the actuator to not false trigger cancellation while stopping - events.add(EventName.speedTooLow) - if ret.vEgo < 0.001: - # while in standstill, send a user alert - events.add(EventName.manualRestart) + if self.CP.openpilotLongitudinalControl: + if ret.cruiseState.standstill and not ret.brakePressed and not self.CP.enableGasInterceptor: + events.add(EventName.resumeRequired) + if self.CS.low_speed_lockout: + events.add(EventName.lowSpeedLockout) + if ret.vEgo < self.CP.minEnableSpeed: + events.add(EventName.belowEngageSpeed) + if c.actuators.accel > 0.3: + # some margin on the actuator to not false trigger cancellation while stopping + events.add(EventName.speedTooLow) + if ret.vEgo < 0.001: + # while in standstill, send a user alert + events.add(EventName.manualRestart) ret.events = events.to_msg() - self.CS.out = ret.as_reader() - return self.CS.out + return ret # pass in a car.CarControl # to be called @ 100hz def apply(self, c): - hud_control = c.hudControl - ret = self.CC.update(c.enabled, c.active, self.CS, self.frame, - c.actuators, c.cruiseControl.cancel, - hud_control.visualAlert, hud_control.leftLaneVisible, - hud_control.rightLaneVisible, hud_control.leadVisible, - hud_control.leftLaneDepart, hud_control.rightLaneDepart) - - self.frame += 1 - return ret + return self.CC.update(c, self.CS) diff --git a/selfdrive/car/toyota/radar_interface.py b/selfdrive/car/toyota/radar_interface.py index 590840851d..8c87704ff2 100755 --- a/selfdrive/car/toyota/radar_interface.py +++ b/selfdrive/car/toyota/radar_interface.py @@ -6,6 +6,9 @@ from selfdrive.car.interfaces import RadarInterfaceBase def _create_radar_can_parser(car_fingerprint): + if DBC[car_fingerprint]['radar'] is None: + return None + if car_fingerprint in TSS2_CAR: RADAR_A_MSGS = list(range(0x180, 0x190)) RADAR_B_MSGS = list(range(0x190, 0x1a0)) @@ -48,7 +51,7 @@ class RadarInterface(RadarInterfaceBase): self.no_radar = CP.carFingerprint in NO_DSU_CAR and CP.carFingerprint not in TSS2_CAR def update(self, can_strings): - if self.no_radar: + if self.no_radar or self.rcp is None: return super().update(None) vls = self.rcp.update_strings(can_strings) diff --git a/selfdrive/car/toyota/toyotacan.py b/selfdrive/car/toyota/toyotacan.py index e22f8ba610..36e6f5aa4d 100644 --- a/selfdrive/car/toyota/toyotacan.py +++ b/selfdrive/car/toyota/toyotacan.py @@ -1,12 +1,12 @@ from common.numpy_fast import interp -def create_steer_command(packer, steer, steer_req, raw_cnt): + +def create_steer_command(packer, steer, steer_req): """Creates a CAN message for the Toyota Steer Command.""" values = { "STEER_REQUEST": steer_req, "STEER_TORQUE_CMD": steer, - "COUNTER": raw_cnt, "SET_ME_1": 1, } return packer.make_can_msg("STEERING_LKA", 0, values) diff --git a/selfdrive/car/toyota/tunes.py b/selfdrive/car/toyota/tunes.py deleted file mode 100644 index f26fc72a09..0000000000 --- a/selfdrive/car/toyota/tunes.py +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/env python3 -from enum import Enum - - -class LongTunes(Enum): - PEDAL = 0 - TSS2 = 1 - TSS = 2 - -class LatTunes(Enum): - INDI_PRIUS = 0 - LQR_RAV4 = 1 - PID_A = 2 - PID_B = 3 - PID_C = 4 - PID_D = 5 - PID_E = 6 - PID_F = 7 - PID_G = 8 - PID_I = 9 - PID_H = 10 - PID_J = 11 - PID_K = 12 - PID_L = 13 - PID_M = 14 - PID_N = 15 - - -###### LONG ###### -def set_long_tune(tune, name): - # Improved longitudinal tune - if name == LongTunes.TSS2 or name == LongTunes.PEDAL: - tune.deadzoneBP = [0., 8.05] - tune.deadzoneV = [.0, .14] - tune.kpBP = [0., 5., 20.] - tune.kpV = [1.3, 1.0, 0.7] - tune.kiBP = [0., 5., 12., 20., 27.] - tune.kiV = [.35, .23, .20, .17, .1] - # Default longitudinal tune - elif name == LongTunes.TSS: - tune.deadzoneBP = [0., 9.] - tune.deadzoneV = [0., .15] - tune.kpBP = [0., 5., 35.] - tune.kiBP = [0., 35.] - tune.kpV = [3.6, 2.4, 1.5] - tune.kiV = [0.54, 0.36] - else: - raise NotImplementedError('This longitudinal tune does not exist') - - -###### LAT ###### -def set_lat_tune(tune, name): - if name == LatTunes.INDI_PRIUS: - tune.init('indi') - tune.indi.innerLoopGainBP = [0.] - tune.indi.innerLoopGainV = [4.0] - tune.indi.outerLoopGainBP = [0.] - tune.indi.outerLoopGainV = [3.0] - tune.indi.timeConstantBP = [0.] - tune.indi.timeConstantV = [1.0] - tune.indi.actuatorEffectivenessBP = [0.] - tune.indi.actuatorEffectivenessV = [1.0] - - elif name == LatTunes.LQR_RAV4: - tune.init('lqr') - tune.lqr.scale = 1500.0 - tune.lqr.ki = 0.05 - tune.lqr.a = [0., 1., -0.22619643, 1.21822268] - tune.lqr.b = [-1.92006585e-04, 3.95603032e-05] - tune.lqr.c = [1., 0.] - tune.lqr.k = [-110.73572306, 451.22718255] - tune.lqr.l = [0.3233671, 0.3185757] - tune.lqr.dcGain = 0.002237852961363602 - - elif 'PID' in str(name): - tune.init('pid') - tune.pid.kiBP = [0.0] - tune.pid.kpBP = [0.0] - if name == LatTunes.PID_A: - tune.pid.kpV = [0.2] - tune.pid.kiV = [0.05] - tune.pid.kf = 0.00003 - elif name == LatTunes.PID_C: - tune.pid.kpV = [0.6] - tune.pid.kiV = [0.1] - tune.pid.kf = 0.00006 - elif name == LatTunes.PID_D: - tune.pid.kpV = [0.6] - tune.pid.kiV = [0.1] - tune.pid.kf = 0.00007818594 - elif name == LatTunes.PID_F: - tune.pid.kpV = [0.723] - tune.pid.kiV = [0.0428] - tune.pid.kf = 0.00006 - elif name == LatTunes.PID_G: - tune.pid.kpV = [0.18] - tune.pid.kiV = [0.015] - tune.pid.kf = 0.00012 - elif name == LatTunes.PID_H: - tune.pid.kpV = [0.17] - tune.pid.kiV = [0.03] - tune.pid.kf = 0.00006 - elif name == LatTunes.PID_I: - tune.pid.kpV = [0.15] - tune.pid.kiV = [0.05] - tune.pid.kf = 0.00004 - elif name == LatTunes.PID_J: - tune.pid.kpV = [0.19] - tune.pid.kiV = [0.02] - tune.pid.kf = 0.00007818594 - elif name == LatTunes.PID_L: - tune.pid.kpV = [0.3] - tune.pid.kiV = [0.05] - tune.pid.kf = 0.00006 - elif name == LatTunes.PID_M: - tune.pid.kpV = [0.3] - tune.pid.kiV = [0.05] - tune.pid.kf = 0.00007 - elif name == LatTunes.PID_N: - tune.pid.kpV = [0.35] - tune.pid.kiV = [0.15] - tune.pid.kf = 0.00007818594 - else: - raise NotImplementedError('This PID tune does not exist') - else: - raise NotImplementedError('This lateral tune does not exist') diff --git a/selfdrive/car/toyota/values.py b/selfdrive/car/toyota/values.py index b8a6ae7e0d..56bb2697c7 100644 --- a/selfdrive/car/toyota/values.py +++ b/selfdrive/car/toyota/values.py @@ -1,9 +1,13 @@ from collections import defaultdict -from enum import IntFlag +from dataclasses import dataclass +from enum import Enum, IntFlag +from typing import Dict, List, Union from cereal import car +from common.conversions import Conversions as CV from selfdrive.car import dbc_dict -from selfdrive.config import Conversions as CV +from selfdrive.car.docs_definitions import CarFootnote, CarInfo, Column, Harness +from selfdrive.car.fw_query_definitions import FwQueryConfig, Request, StdQueries Ecu = car.CarParams.Ecu MIN_ACC_SPEED = 19. * CV.MPH_TO_MS @@ -15,10 +19,16 @@ class CarControllerParams: ACCEL_MIN = -3.5 # m/s2 STEER_MAX = 1500 - STEER_DELTA_UP = 10 # 1.5s time to peak torque - STEER_DELTA_DOWN = 25 # always lower than 45 otherwise the Rav4 faults (Prius seems ok with 50) STEER_ERROR_MAX = 350 # max delta between torque cmd and torque motor + def __init__(self, CP): + if CP.lateralTuning.which == 'torque': + self.STEER_DELTA_UP = 15 # 1.0s time to peak torque + self.STEER_DELTA_DOWN = 25 # always lower than 45 otherwise the Rav4 faults (Prius seems ok with 50) + else: + self.STEER_DELTA_UP = 10 # 1.5s time to peak torque + self.STEER_DELTA_DOWN = 25 # always lower than 45 otherwise the Rav4 faults (Prius seems ok with 50) + class ToyotaFlags(IntFlag): HYBRID = 1 @@ -27,10 +37,12 @@ class ToyotaFlags(IntFlag): class CAR: # Toyota ALPHARD_TSS2 = "TOYOTA ALPHARD 2020" + ALPHARDH_TSS2 = "TOYOTA ALPHARD HYBRID 2021" AVALON = "TOYOTA AVALON 2016" AVALON_2019 = "TOYOTA AVALON 2019" AVALONH_2019 = "TOYOTA AVALON HYBRID 2019" - AVALON_TSS2 = "TOYOTA AVALON 2022" + AVALON_TSS2 = "TOYOTA AVALON 2022" # TSS 2.5 + AVALONH_TSS2 = "TOYOTA AVALON HYBRID 2022" CAMRY = "TOYOTA CAMRY 2018" CAMRYH = "TOYOTA CAMRY HYBRID 2018" CAMRY_TSS2 = "TOYOTA CAMRY 2021" # TSS 2.5 @@ -51,8 +63,10 @@ class CAR: RAV4 = "TOYOTA RAV4 2017" RAV4H = "TOYOTA RAV4 HYBRID 2017" RAV4_TSS2 = "TOYOTA RAV4 2019" + RAV4_TSS2_2022 = "TOYOTA RAV4 2022" RAV4H_TSS2 = "TOYOTA RAV4 HYBRID 2019" - MIRAI = "TOYOTA MIRAI 2021" # TSS 2.5 + RAV4H_TSS2_2022 = "TOYOTA RAV4 HYBRID 2022" + MIRAI = "TOYOTA MIRAI 2021" # TSS 2.5 SIENNA = "TOYOTA SIENNA 2018" # Lexus @@ -64,12 +78,107 @@ class CAR: LEXUS_NX = "LEXUS NX 2018" LEXUS_NXH = "LEXUS NX HYBRID 2018" LEXUS_NX_TSS2 = "LEXUS NX 2020" + LEXUS_NXH_TSS2 = "LEXUS NX HYBRID 2020" LEXUS_RC = "LEXUS RC 2020" LEXUS_RX = "LEXUS RX 2016" LEXUS_RXH = "LEXUS RX HYBRID 2017" LEXUS_RX_TSS2 = "LEXUS RX 2020" LEXUS_RXH_TSS2 = "LEXUS RX HYBRID 2020" + +class Footnote(Enum): + CAMRY = CarFootnote( + "openpilot operates above 28mph for Camry 4CYL L, 4CYL LE and 4CYL SE which don't have Full-Speed Range Dynamic Radar Cruise Control.", + Column.FSR_LONGITUDINAL) + + +@dataclass +class ToyotaCarInfo(CarInfo): + package: str = "All" + harness: Enum = Harness.toyota + + +CAR_INFO: Dict[str, Union[ToyotaCarInfo, List[ToyotaCarInfo]]] = { + # Toyota + CAR.ALPHARD_TSS2: ToyotaCarInfo("Toyota Alphard 2019-20"), + CAR.ALPHARDH_TSS2: ToyotaCarInfo("Toyota Alphard Hybrid 2021"), + CAR.AVALON: [ + ToyotaCarInfo("Toyota Avalon 2016", "Toyota Safety Sense P"), + ToyotaCarInfo("Toyota Avalon 2017-18"), + ], + CAR.AVALON_2019: ToyotaCarInfo("Toyota Avalon 2019-21"), + CAR.AVALONH_2019: ToyotaCarInfo("Toyota Avalon Hybrid 2019-21"), + CAR.AVALON_TSS2: ToyotaCarInfo("Toyota Avalon 2022"), + CAR.AVALONH_TSS2: ToyotaCarInfo("Toyota Avalon Hybrid 2022"), + CAR.CAMRY: ToyotaCarInfo("Toyota Camry 2018-20", video_link="https://www.youtube.com/watch?v=fkcjviZY9CM", footnotes=[Footnote.CAMRY]), + CAR.CAMRYH: ToyotaCarInfo("Toyota Camry Hybrid 2018-20", video_link="https://www.youtube.com/watch?v=Q2DYY0AWKgk"), + CAR.CAMRY_TSS2: ToyotaCarInfo("Toyota Camry 2021-22", footnotes=[Footnote.CAMRY]), + CAR.CAMRYH_TSS2: ToyotaCarInfo("Toyota Camry Hybrid 2021-23"), + CAR.CHR: ToyotaCarInfo("Toyota C-HR 2017-21"), + CAR.CHRH: ToyotaCarInfo("Toyota C-HR Hybrid 2017-19"), + CAR.COROLLA: ToyotaCarInfo("Toyota Corolla 2017-19"), + CAR.COROLLA_TSS2: [ + ToyotaCarInfo("Toyota Corolla 2020-22", video_link="https://www.youtube.com/watch?v=_66pXk0CBYA"), + ToyotaCarInfo("Toyota Corolla Cross (Non-US only) 2020-23", min_enable_speed=7.5), + ToyotaCarInfo("Toyota Corolla Hatchback 2019-22", video_link="https://www.youtube.com/watch?v=_66pXk0CBYA"), + ], + CAR.COROLLAH_TSS2: [ + ToyotaCarInfo("Toyota Corolla Hybrid 2020-22"), + ToyotaCarInfo("Toyota Corolla Cross Hybrid (Non-US only) 2020-22", min_enable_speed=7.5), + ToyotaCarInfo("Lexus UX Hybrid 2019-22"), + ], + CAR.HIGHLANDER: ToyotaCarInfo("Toyota Highlander 2017-19", video_link="https://www.youtube.com/watch?v=0wS0wXSLzoo"), + CAR.HIGHLANDER_TSS2: ToyotaCarInfo("Toyota Highlander 2020-22"), + CAR.HIGHLANDERH: ToyotaCarInfo("Toyota Highlander Hybrid 2017-19"), + CAR.HIGHLANDERH_TSS2: ToyotaCarInfo("Toyota Highlander Hybrid 2020-22"), + CAR.PRIUS: [ + ToyotaCarInfo("Toyota Prius 2016", "Toyota Safety Sense P", "https://www.youtube.com/watch?v=8zopPJI8XQ0"), + ToyotaCarInfo("Toyota Prius 2017-20", video_link="https://www.youtube.com/watch?v=8zopPJI8XQ0"), + ToyotaCarInfo("Toyota Prius Prime 2017-20", video_link="https://www.youtube.com/watch?v=8zopPJI8XQ0"), + ], + CAR.PRIUS_V: ToyotaCarInfo("Toyota Prius v 2017", "Toyota Safety Sense P", min_enable_speed=MIN_ACC_SPEED), + CAR.PRIUS_TSS2: [ + ToyotaCarInfo("Toyota Prius 2021-22", video_link="https://www.youtube.com/watch?v=J58TvCpUd4U"), + ToyotaCarInfo("Toyota Prius Prime 2021-22", video_link="https://www.youtube.com/watch?v=J58TvCpUd4U"), + ], + CAR.RAV4: [ + ToyotaCarInfo("Toyota RAV4 2016", "Toyota Safety Sense P"), + ToyotaCarInfo("Toyota RAV4 2017-18") + ], + CAR.RAV4H: [ + ToyotaCarInfo("Toyota RAV4 Hybrid 2016", "Toyota Safety Sense P", "https://youtu.be/LhT5VzJVfNI?t=26"), + ToyotaCarInfo("Toyota RAV4 Hybrid 2017-18", video_link="https://youtu.be/LhT5VzJVfNI?t=26") + ], + CAR.RAV4_TSS2: ToyotaCarInfo("Toyota RAV4 2019-21", video_link="https://www.youtube.com/watch?v=wJxjDd42gGA"), + CAR.RAV4_TSS2_2022: ToyotaCarInfo("Toyota RAV4 2022"), + CAR.RAV4H_TSS2: ToyotaCarInfo("Toyota RAV4 Hybrid 2019-21"), + CAR.RAV4H_TSS2_2022: ToyotaCarInfo("Toyota RAV4 Hybrid 2022", video_link="https://youtu.be/U0nH9cnrFB0"), + CAR.MIRAI: ToyotaCarInfo("Toyota Mirai 2021"), + CAR.SIENNA: ToyotaCarInfo("Toyota Sienna 2018-20", video_link="https://www.youtube.com/watch?v=q1UPOo4Sh68", min_enable_speed=MIN_ACC_SPEED), + + # Lexus + CAR.LEXUS_CTH: ToyotaCarInfo("Lexus CT Hybrid 2017-18", "Lexus Safety System+"), + CAR.LEXUS_ESH: ToyotaCarInfo("Lexus ES Hybrid 2017-18", "Lexus Safety System+"), + CAR.LEXUS_ES_TSS2: ToyotaCarInfo("Lexus ES 2019-22"), + CAR.LEXUS_ESH_TSS2: ToyotaCarInfo("Lexus ES Hybrid 2019-22", video_link="https://youtu.be/BZ29osRVJeg?t=12"), + CAR.LEXUS_IS: ToyotaCarInfo("Lexus IS 2017-19"), + CAR.LEXUS_NX: ToyotaCarInfo("Lexus NX 2018-19"), + CAR.LEXUS_NXH: ToyotaCarInfo("Lexus NX Hybrid 2018-19"), + CAR.LEXUS_NX_TSS2: ToyotaCarInfo("Lexus NX 2020-21"), + CAR.LEXUS_NXH_TSS2: ToyotaCarInfo("Lexus NX Hybrid 2020-21"), + CAR.LEXUS_RC: ToyotaCarInfo("Lexus RC 2017-20"), + CAR.LEXUS_RX: [ + ToyotaCarInfo("Lexus RX 2016", "Lexus Safety System+"), + ToyotaCarInfo("Lexus RX 2017-19"), + ], + CAR.LEXUS_RXH: [ + ToyotaCarInfo("Lexus RX Hybrid 2016", "Lexus Safety System+"), + ToyotaCarInfo("Lexus RX Hybrid 2017-19"), + ], + CAR.LEXUS_RX_TSS2: ToyotaCarInfo("Lexus RX 2020-22"), + CAR.LEXUS_RXH_TSS2: ToyotaCarInfo("Lexus RX Hybrid 2020-21"), +} + # (addr, cars, bus, 1/freq*100, vl) STATIC_DSU_MSGS = [ (0x128, (CAR.PRIUS, CAR.RAV4H, CAR.LEXUS_RXH, CAR.LEXUS_NXH, CAR.LEXUS_NX, CAR.RAV4, CAR.COROLLA, CAR.AVALON), 1, 3, b'\xf4\x01\x90\x83\x00\x37'), @@ -92,9 +201,41 @@ STATIC_DSU_MSGS = [ (0x4CB, (CAR.PRIUS, CAR.RAV4H, CAR.LEXUS_RXH, CAR.LEXUS_NXH, CAR.LEXUS_NX, CAR.RAV4, CAR.COROLLA, CAR.HIGHLANDERH, CAR.HIGHLANDER, CAR.AVALON, CAR.SIENNA, CAR.LEXUS_CTH, CAR.LEXUS_ESH, CAR.LEXUS_RX, CAR.PRIUS_V), 0, 100, b'\x0c\x00\x00\x00\x00\x00\x00\x00'), ] +TOYOTA_VERSION_REQUEST = b'\x1a\x88\x01' +TOYOTA_VERSION_RESPONSE = b'\x5a\x88\x01' + +FW_QUERY_CONFIG = FwQueryConfig( + requests=[ + Request( + [StdQueries.SHORT_TESTER_PRESENT_REQUEST, TOYOTA_VERSION_REQUEST], + [StdQueries.SHORT_TESTER_PRESENT_RESPONSE, TOYOTA_VERSION_RESPONSE], + whitelist_ecus=[Ecu.fwdCamera, Ecu.fwdRadar, Ecu.dsu, Ecu.abs, Ecu.eps], + bus=0, + ), + Request( + [StdQueries.SHORT_TESTER_PRESENT_REQUEST, StdQueries.OBD_VERSION_REQUEST], + [StdQueries.SHORT_TESTER_PRESENT_RESPONSE, StdQueries.OBD_VERSION_RESPONSE], + whitelist_ecus=[Ecu.engine], + bus=0, + ), + Request( + [StdQueries.TESTER_PRESENT_REQUEST, StdQueries.DEFAULT_DIAGNOSTIC_REQUEST, StdQueries.EXTENDED_DIAGNOSTIC_REQUEST, StdQueries.UDS_VERSION_REQUEST], + [StdQueries.TESTER_PRESENT_RESPONSE, StdQueries.DEFAULT_DIAGNOSTIC_RESPONSE, StdQueries.EXTENDED_DIAGNOSTIC_RESPONSE, StdQueries.UDS_VERSION_RESPONSE], + whitelist_ecus=[Ecu.engine, Ecu.fwdRadar, Ecu.fwdCamera, Ecu.abs, Ecu.eps], + bus=0, + ), + ], + non_essential_ecus={ + # FIXME: On some models, abs can sometimes be missing + Ecu.abs: [CAR.RAV4, CAR.COROLLA, CAR.HIGHLANDER, CAR.SIENNA, CAR.LEXUS_IS], + # On some models, the engine can show on two different addresses + Ecu.engine: [CAR.CAMRY, CAR.COROLLA_TSS2, CAR.CHR, CAR.LEXUS_IS], + } +) + FW_VERSIONS = { CAR.AVALON: { - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152607060\x00\x00\x00\x00\x00\x00', ], (Ecu.dsu, 0x791, None): [ @@ -119,7 +260,7 @@ FW_VERSIONS = { ], }, CAR.AVALON_2019: { - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152607140\x00\x00\x00\x00\x00\x00', b'F152607171\x00\x00\x00\x00\x00\x00', b'F152607110\x00\x00\x00\x00\x00\x00', @@ -147,7 +288,7 @@ FW_VERSIONS = { ], }, CAR.AVALONH_2019: { - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152641040\x00\x00\x00\x00\x00\x00', b'F152641061\x00\x00\x00\x00\x00\x00', b'F152641050\x00\x00\x00\x00\x00\x00', @@ -174,7 +315,8 @@ FW_VERSIONS = { ], }, CAR.AVALON_TSS2: { - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ + b'\x01F152607240\x00\x00\x00\x00\x00\x00', b'\x01F152607280\x00\x00\x00\x00\x00\x00', ], (Ecu.eps, 0x7a1, None): [ @@ -183,11 +325,31 @@ FW_VERSIONS = { (Ecu.engine, 0x700, None): [ b'\x01896630742000\x00\x00\x00\x00', ], + (Ecu.fwdRadar, 0x750, 0xf): [ + b'\x018821F6201200\x00\x00\x00\x00', + b'\x018821F6201300\x00\x00\x00\x00', + ], + (Ecu.fwdCamera, 0x750, 0x6d): [ + b'\x028646F4104100\x00\x00\x00\x008646G5301200\x00\x00\x00\x00', + b'\x028646F4104100\x00\x00\x00\x008646G3304000\x00\x00\x00\x00', + ], + }, + CAR.AVALONH_TSS2: { + (Ecu.abs, 0x7b0, None): [ + b'F152641080\x00\x00\x00\x00\x00\x00', + ], + (Ecu.eps, 0x7a1, None): [ + b'8965B41110\x00\x00\x00\x00\x00\x00', + ], + (Ecu.engine, 0x700, None): [ + b'\x018966306Q6000\x00\x00\x00\x00', + ], (Ecu.fwdRadar, 0x750, 0xf): [ b'\x018821F6201200\x00\x00\x00\x00', ], (Ecu.fwdCamera, 0x750, 0x6d): [ b'\x028646F4104100\x00\x00\x00\x008646G5301200\x00\x00\x00\x00', + b'\x028646F4104100\x00\x00\x00\x008646G3304000\x00\x00\x00\x00', ], }, CAR.CAMRY: { @@ -229,7 +391,7 @@ FW_VERSIONS = { b'8821F0608200 ', b'8821F0609100 ', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152606210\x00\x00\x00\x00\x00\x00', b'F152606230\x00\x00\x00\x00\x00\x00', b'F152606270\x00\x00\x00\x00\x00\x00', @@ -293,7 +455,7 @@ FW_VERSIONS = { b'\x028966306S0100\x00\x00\x00\x00897CF3305001\x00\x00\x00\x00', b'\x028966306S1100\x00\x00\x00\x00897CF3305001\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152633214\x00\x00\x00\x00\x00\x00', b'F152633660\x00\x00\x00\x00\x00\x00', b'F152633712\x00\x00\x00\x00\x00\x00', @@ -359,7 +521,7 @@ FW_VERSIONS = { (Ecu.eps, 0x7a1, None): [ b'8965B33630\x00\x00\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'\x01F152606370\x00\x00\x00\x00\x00\x00', b'\x01F152606390\x00\x00\x00\x00\x00\x00', b'\x01F152606400\x00\x00\x00\x00\x00\x00', @@ -384,21 +546,28 @@ FW_VERSIONS = { CAR.CAMRYH_TSS2: { (Ecu.eps, 0x7a1, None): [ b'8965B33630\x00\x00\x00\x00\x00\x00', + b'8965B33650\x00\x00\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152633D00\x00\x00\x00\x00\x00\x00', + b'F152633D60\x00\x00\x00\x00\x00\x00', + b'F152633310\x00\x00\x00\x00\x00\x00', ], (Ecu.engine, 0x700, None): [ b'\x018966306Q6000\x00\x00\x00\x00', b'\x018966306Q7000\x00\x00\x00\x00', + b'\x018966306V1000\x00\x00\x00\x00', + b'\x01896633T20000\x00\x00\x00\x00', ], (Ecu.fwdRadar, 0x750, 15): [ b'\x018821F6201200\x00\x00\x00\x00', + b'\x018821F6201300\x00\x00\x00\x00', ], (Ecu.fwdCamera, 0x750, 109): [ b'\x028646F3305200\x00\x00\x00\x008646G5301200\x00\x00\x00\x00', b'\x028646F3305300\x00\x00\x00\x008646G5301200\x00\x00\x00\x00', b'\x028646F3305300\x00\x00\x00\x008646G3304000\x00\x00\x00\x00', + b'\x028646F3305500\x00\x00\x00\x008646G3304000\x00\x00\x00\x00', ], }, CAR.CHR: { @@ -419,7 +588,7 @@ FW_VERSIONS = { b'8821FF406000 ', b'8821FF407100 ', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152610020\x00\x00\x00\x00\x00\x00', b'F152610153\x00\x00\x00\x00\x00\x00', b'F152610210\x00\x00\x00\x00\x00\x00', @@ -441,6 +610,7 @@ FW_VERSIONS = { b'\x033F401100\x00\x00\x00\x00\x00\x00\x00\x00A0202000\x00\x00\x00\x00\x00\x00\x00\x00895231203102\x00\x00\x00\x00', b'\x033F401200\x00\x00\x00\x00\x00\x00\x00\x00A0202000\x00\x00\x00\x00\x00\x00\x00\x00895231203202\x00\x00\x00\x00', b'\x033F424000\x00\x00\x00\x00\x00\x00\x00\x00A0202000\x00\x00\x00\x00\x00\x00\x00\x00895231203202\x00\x00\x00\x00', + b'\x033F424000\x00\x00\x00\x00\x00\x00\x00\x00A0202000\x00\x00\x00\x00\x00\x00\x00\x00895231203302\x00\x00\x00\x00', ], (Ecu.fwdRadar, 0x750, 0xf): [ b'8821F0W01000 ', @@ -470,7 +640,7 @@ FW_VERSIONS = { b'\x0289663F431000\x00\x00\x00\x008966A4703000\x00\x00\x00\x00', b'\x0189663F438000\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152610012\x00\x00\x00\x00\x00\x00', b'F152610013\x00\x00\x00\x00\x00\x00', b'F152610014\x00\x00\x00\x00\x00\x00', @@ -529,7 +699,7 @@ FW_VERSIONS = { b'881510201100\x00\x00\x00\x00', b'881510201200\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152602190\x00\x00\x00\x00\x00\x00', b'F152602191\x00\x00\x00\x00\x00\x00', ], @@ -549,6 +719,7 @@ FW_VERSIONS = { }, CAR.COROLLA_TSS2: { (Ecu.engine, 0x700, None): [ + b'\x01896630A22000\x00\x00\x00\x00', b'\x01896630ZG2000\x00\x00\x00\x00', b'\x01896630ZG5000\x00\x00\x00\x00', b'\x01896630ZG5100\x00\x00\x00\x00', @@ -557,6 +728,8 @@ FW_VERSIONS = { b'\x01896630ZP1000\x00\x00\x00\x00', b'\x01896630ZP2000\x00\x00\x00\x00', b'\x01896630ZQ5000\x00\x00\x00\x00', + b'\x01896630ZU9000\x00\x00\x00\x00', + b'\x01896630ZX4000\x00\x00\x00\x00', b'\x018966312L8000\x00\x00\x00\x00', b'\x018966312M0000\x00\x00\x00\x00', b'\x018966312M9000\x00\x00\x00\x00', @@ -575,6 +748,7 @@ FW_VERSIONS = { b'\x018966312S7000\x00\x00\x00\x00', b'\x018966312W3000\x00\x00\x00\x00', b'\x018966312W9000\x00\x00\x00\x00', + b'\x01896637644000\x00\x00\x00\x00', ], (Ecu.engine, 0x7e0, None): [ b'\x0230A10000\x00\x00\x00\x00\x00\x00\x00\x00A0202000\x00\x00\x00\x00\x00\x00\x00\x00', @@ -587,7 +761,10 @@ FW_VERSIONS = { b'\x03312N6000\x00\x00\x00\x00\x00\x00\x00\x00A0202000\x00\x00\x00\x00\x00\x00\x00\x00895231203402\x00\x00\x00\x00', b'\x03312N6100\x00\x00\x00\x00\x00\x00\x00\x00A0202000\x00\x00\x00\x00\x00\x00\x00\x00895231203302\x00\x00\x00\x00', b'\x03312N6100\x00\x00\x00\x00\x00\x00\x00\x00A0202000\x00\x00\x00\x00\x00\x00\x00\x00895231203402\x00\x00\x00\x00', + b'\x03312N6200\x00\x00\x00\x00\x00\x00\x00\x00A0202000\x00\x00\x00\x00\x00\x00\x00\x00895231203202\x00\x00\x00\x00', + b'\x03312N6200\x00\x00\x00\x00\x00\x00\x00\x00A0202000\x00\x00\x00\x00\x00\x00\x00\x00895231203302\x00\x00\x00\x00', b'\x02312K4000\x00\x00\x00\x00\x00\x00\x00\x00A0202000\x00\x00\x00\x00\x00\x00\x00\x00', + b'\x02312U5000\x00\x00\x00\x00\x00\x00\x00\x00A0202000\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.eps, 0x7a1, None): [ b'\x018965B12350\x00\x00\x00\x00\x00\x00', @@ -599,9 +776,11 @@ FW_VERSIONS = { b'\x018965B1255000\x00\x00\x00\x00', b'8965B12361\x00\x00\x00\x00\x00\x00', b'8965B16011\x00\x00\x00\x00\x00\x00', - b'\x018965B12510\x00\x00\x00\x00\x00\x00' + b'8965B76012\x00\x00\x00\x00\x00\x00', + b'\x018965B12510\x00\x00\x00\x00\x00\x00', + b'\x018965B1256000\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'\x01F152602280\x00\x00\x00\x00\x00\x00', b'\x01F152602560\x00\x00\x00\x00\x00\x00', b'\x01F152602590\x00\x00\x00\x00\x00\x00', @@ -621,6 +800,9 @@ FW_VERSIONS = { b'\x01F152612C00\x00\x00\x00\x00\x00\x00', b'F152602191\x00\x00\x00\x00\x00\x00', b'\x01F152612862\x00\x00\x00\x00\x00\x00', + b'\x01F152612B91\x00\x00\x00\x00\x00\x00', + b'\x01F15260A070\x00\x00\x00\x00\x00\x00', + b'\x01F152676250\x00\x00\x00\x00\x00\x00', ], (Ecu.fwdRadar, 0x750, 0xf): [ b'\x018821F3301100\x00\x00\x00\x00', @@ -638,6 +820,7 @@ FW_VERSIONS = { b'\x028646F1202100\x00\x00\x00\x008646G2601400\x00\x00\x00\x00', b'\x028646F1202200\x00\x00\x00\x008646G2601500\x00\x00\x00\x00', b'\x028646F1601100\x00\x00\x00\x008646G2601400\x00\x00\x00\x00', + b'\x028646F1601300\x00\x00\x00\x008646G2601400\x00\x00\x00\x00', ], }, CAR.COROLLAH_TSS2: { @@ -647,8 +830,11 @@ FW_VERSIONS = { b'\x01896637621000\x00\x00\x00\x00', b'\x01896637624000\x00\x00\x00\x00', b'\x01896637626000\x00\x00\x00\x00', + b'\x01896637639000\x00\x00\x00\x00', b'\x01896637648000\x00\x00\x00\x00', b'\x01896637643000\x00\x00\x00\x00', + b'\x02896630A07000\x00\x00\x00\x008966A4703000\x00\x00\x00\x00', + b'\x02896630A21000\x00\x00\x00\x008966A4703000\x00\x00\x00\x00', b'\x02896630ZJ5000\x00\x00\x00\x008966A4703000\x00\x00\x00\x00', b'\x02896630ZN8000\x00\x00\x00\x008966A4703000\x00\x00\x00\x00', b'\x02896630ZQ3000\x00\x00\x00\x008966A4703000\x00\x00\x00\x00', @@ -666,6 +852,7 @@ FW_VERSIONS = { (Ecu.eps, 0x7a1, None): [ b'8965B12361\x00\x00\x00\x00\x00\x00', b'8965B12451\x00\x00\x00\x00\x00\x00', + b'8965B16011\x00\x00\x00\x00\x00\x00', b'8965B76012\x00\x00\x00\x00\x00\x00', b'8965B76050\x00\x00\x00\x00\x00\x00', b'\x018965B12350\x00\x00\x00\x00\x00\x00', @@ -676,7 +863,7 @@ FW_VERSIONS = { b'\x018965B12520\x00\x00\x00\x00\x00\x00', b'\x018965B12530\x00\x00\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152612590\x00\x00\x00\x00\x00\x00', b'F152612691\x00\x00\x00\x00\x00\x00', b'F152612692\x00\x00\x00\x00\x00\x00', @@ -686,14 +873,17 @@ FW_VERSIONS = { b'F152612800\x00\x00\x00\x00\x00\x00', b'F152612820\x00\x00\x00\x00\x00\x00', b'F152612840\x00\x00\x00\x00\x00\x00', + b'F152612842\x00\x00\x00\x00\x00\x00', b'F152612890\x00\x00\x00\x00\x00\x00', b'F152612A00\x00\x00\x00\x00\x00\x00', b'F152612A10\x00\x00\x00\x00\x00\x00', + b'F152612D00\x00\x00\x00\x00\x00\x00', + b'F152616011\x00\x00\x00\x00\x00\x00', + b'F152616060\x00\x00\x00\x00\x00\x00', b'F152642540\x00\x00\x00\x00\x00\x00', b'F152676293\x00\x00\x00\x00\x00\x00', b'F152676303\x00\x00\x00\x00\x00\x00', b'F152676304\x00\x00\x00\x00\x00\x00', - b'F152612D00\x00\x00\x00\x00\x00\x00', ], (Ecu.fwdRadar, 0x750, 0xf): [ b'\x018821F3301100\x00\x00\x00\x00', @@ -709,6 +899,7 @@ FW_VERSIONS = { b'\x028646F1202000\x00\x00\x00\x008646G2601200\x00\x00\x00\x00', b'\x028646F1202100\x00\x00\x00\x008646G2601400\x00\x00\x00\x00', b'\x028646F1202200\x00\x00\x00\x008646G2601500\x00\x00\x00\x00', + b'\x028646F1601100\x00\x00\x00\x008646G2601400\x00\x00\x00\x00', b"\x028646F1601300\x00\x00\x00\x008646G2601400\x00\x00\x00\x00", b'\x028646F4203400\x00\x00\x00\x008646G2601200\x00\x00\x00\x00', b'\x028646F76020C0\x00\x00\x00\x008646G26011A0\x00\x00\x00\x00', @@ -744,7 +935,7 @@ FW_VERSIONS = { b'8965B48150\x00\x00\x00\x00\x00\x00', b'8965B48210\x00\x00\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [b'F15260E011\x00\x00\x00\x00\x00\x00'], + (Ecu.abs, 0x7b0, None): [b'F15260E011\x00\x00\x00\x00\x00\x00'], (Ecu.dsu, 0x791, None): [ b'881510E01100\x00\x00\x00\x00', b'881510E01200\x00\x00\x00\x00', @@ -762,7 +953,7 @@ FW_VERSIONS = { (Ecu.eps, 0x7a1, None): [ b'8965B48160\x00\x00\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152648541\x00\x00\x00\x00\x00\x00', b'F152648542\x00\x00\x00\x00\x00\x00', ], @@ -787,10 +978,11 @@ FW_VERSIONS = { b'8965B48310\x00\x00\x00\x00\x00\x00', b'8965B48320\x00\x00\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'\x01F15260E051\x00\x00\x00\x00\x00\x00', b'\x01F15260E061\x00\x00\x00\x00\x00\x00', b'\x01F15260E110\x00\x00\x00\x00\x00\x00', + b'\x01F15260E170\x00\x00\x00\x00\x00\x00', ], (Ecu.engine, 0x700, None): [ b'\x01896630E62100\x00\x00\x00\x00', @@ -805,15 +997,19 @@ FW_VERSIONS = { b'\x01896630EB2200\x00\x00\x00\x00', b'\x01896630EC4000\x00\x00\x00\x00', b'\x01896630ED9000\x00\x00\x00\x00', + b'\x01896630ED9100\x00\x00\x00\x00', b'\x01896630EE1000\x00\x00\x00\x00', + b'\x01896630EE1100\x00\x00\x00\x00', ], (Ecu.fwdRadar, 0x750, 0xf): [ b'\x018821F3301400\x00\x00\x00\x00', b'\x018821F6201200\x00\x00\x00\x00', + b'\x018821F6201300\x00\x00\x00\x00', ], (Ecu.fwdCamera, 0x750, 0x6d): [ b'\x028646F0E02100\x00\x00\x00\x008646G2601200\x00\x00\x00\x00', b'\x028646F4803000\x00\x00\x00\x008646G5301200\x00\x00\x00\x00', + b'\x028646F4803000\x00\x00\x00\x008646G3304000\x00\x00\x00\x00', ], }, CAR.HIGHLANDERH_TSS2: { @@ -821,30 +1017,38 @@ FW_VERSIONS = { b'8965B48241\x00\x00\x00\x00\x00\x00', b'8965B48310\x00\x00\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'\x01F15264872300\x00\x00\x00\x00', b'\x01F15264872400\x00\x00\x00\x00', b'\x01F15264872500\x00\x00\x00\x00', b'\x01F15264873500\x00\x00\x00\x00', b'\x01F152648C6300\x00\x00\x00\x00', + b'\x01F152648J4000\x00\x00\x00\x00', + b'\x01F152648J5000\x00\x00\x00\x00', + b'\x01F152648J6000\x00\x00\x00\x00', ], (Ecu.engine, 0x700, None): [ b'\x01896630E67000\x00\x00\x00\x00', b'\x01896630EA1000\x00\x00\x00\x00', b'\x01896630EE4000\x00\x00\x00\x00', - b'\x01896630EA1000\x00\x00\x00\x00897CF4801001\x00\x00\x00\x00', + b'\x01896630EE4100\x00\x00\x00\x00', + b'\x01896630EE5000\x00\x00\x00\x00', + b'\x01896630EE6000\x00\x00\x00\x00', b'\x02896630E66000\x00\x00\x00\x00897CF4801001\x00\x00\x00\x00', + b'\x02896630E66100\x00\x00\x00\x00897CF4801001\x00\x00\x00\x00', + b'\x01896630EA1000\x00\x00\x00\x00897CF4801001\x00\x00\x00\x00', b'\x02896630EB3000\x00\x00\x00\x00897CF4801001\x00\x00\x00\x00', b'\x02896630EB3100\x00\x00\x00\x00897CF4801001\x00\x00\x00\x00', - b'\x02896630E66100\x00\x00\x00\x00897CF4801001\x00\x00\x00\x00', ], (Ecu.fwdRadar, 0x750, 0xf): [ b'\x018821F3301400\x00\x00\x00\x00', b'\x018821F6201200\x00\x00\x00\x00', + b'\x018821F6201300\x00\x00\x00\x00', ], (Ecu.fwdCamera, 0x750, 0x6d): [ b'\x028646F0E02100\x00\x00\x00\x008646G2601200\x00\x00\x00\x00', b'\x028646F4803000\x00\x00\x00\x008646G5301200\x00\x00\x00\x00', + b'\x028646F4803000\x00\x00\x00\x008646G3304000\x00\x00\x00\x00', ], }, CAR.LEXUS_IS: { @@ -863,7 +1067,7 @@ FW_VERSIONS = { b'\x02353P7000\x00\x00\x00\x00\x00\x00\x00\x00530J5000\x00\x00\x00\x00\x00\x00\x00\x00', b'\x02353P9000\x00\x00\x00\x00\x00\x00\x00\x00553C1000\x00\x00\x00\x00\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152653300\x00\x00\x00\x00\x00\x00', b'F152653301\x00\x00\x00\x00\x00\x00', b'F152653310\x00\x00\x00\x00\x00\x00', @@ -947,7 +1151,7 @@ FW_VERSIONS = { b'8965B47050\x00\x00\x00\x00\x00\x00', b'8965B47060\x00\x00\x00\x00\x00\x00', # This is the EPS with good angle sensor ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152647290\x00\x00\x00\x00\x00\x00', b'F152647300\x00\x00\x00\x00\x00\x00', b'F152647310\x00\x00\x00\x00\x00\x00', @@ -988,7 +1192,7 @@ FW_VERSIONS = { ], }, CAR.PRIUS_V: { - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152647280\x00\x00\x00\x00\x00\x00', ], (Ecu.engine, 0x7e0, None): [ @@ -1021,7 +1225,7 @@ FW_VERSIONS = { b'8965B42082\x00\x00\x00\x00\x00\x00', b'8965B42083\x00\x00\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F15260R102\x00\x00\x00\x00\x00\x00', b'F15260R103\x00\x00\x00\x00\x00\x00', b'F152642493\x00\x00\x00\x00\x00\x00', @@ -1058,7 +1262,7 @@ FW_VERSIONS = { b'8965B42162\x00\x00\x00\x00\x00\x00', b'8965B42163\x00\x00\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152642090\x00\x00\x00\x00\x00\x00', b'F152642110\x00\x00\x00\x00\x00\x00', b'F152642120\x00\x00\x00\x00\x00\x00', @@ -1118,20 +1322,24 @@ FW_VERSIONS = { b'\x02896634A18100\x00\x00\x00\x00897CF1201001\x00\x00\x00\x00', b'\x02896634A43000\x00\x00\x00\x00897CF4201001\x00\x00\x00\x00', b'\x02896634A47000\x00\x00\x00\x00897CF4201001\x00\x00\x00\x00', + b'\x028966342Z8000\x00\x00\x00\x00897CF1201001\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'\x01F15260R210\x00\x00\x00\x00\x00\x00', b'\x01F15260R220\x00\x00\x00\x00\x00\x00', b'\x01F15260R290\x00\x00\x00\x00\x00\x00', b'\x01F15260R300\x00\x00\x00\x00\x00\x00', + b'\x01F15260R302\x00\x00\x00\x00\x00\x00', b'\x01F152642551\x00\x00\x00\x00\x00\x00', b'\x01F152642561\x00\x00\x00\x00\x00\x00', + b'\x01F152642601\x00\x00\x00\x00\x00\x00', b'\x01F152642700\x00\x00\x00\x00\x00\x00', b'\x01F152642701\x00\x00\x00\x00\x00\x00', b'\x01F152642710\x00\x00\x00\x00\x00\x00', b'\x01F152642711\x00\x00\x00\x00\x00\x00', b'\x01F152642750\x00\x00\x00\x00\x00\x00', b'\x01F152642751\x00\x00\x00\x00\x00\x00', + b'\x01F15260R292\x00\x00\x00\x00\x00\x00', ], (Ecu.eps, 0x7a1, None): [ b'8965B42170\x00\x00\x00\x00\x00\x00', @@ -1157,6 +1365,29 @@ FW_VERSIONS = { b'\x028646F4203800\x00\x00\x00\x008646G2601500\x00\x00\x00\x00', ], }, + CAR.RAV4_TSS2_2022: { + (Ecu.abs, 0x7b0, None): [ + b'\x01F15260R350\x00\x00\x00\x00\x00\x00', + b'\x01F15260R361\x00\x00\x00\x00\x00\x00', + ], + (Ecu.eps, 0x7a1, None): [ + b'\x028965B0R01500\x00\x00\x00\x008965B0R02500\x00\x00\x00\x00', + ], + (Ecu.engine, 0x700, None): [ + b'\x01896634AA0000\x00\x00\x00\x00', + b'\x01896634AA0100\x00\x00\x00\x00', + b'\x01896634AA1000\x00\x00\x00\x00', + b'\x01896634A88000\x00\x00\x00\x00', + b'\x01896634A89000\x00\x00\x00\x00', + b'\x01896634A89100\x00\x00\x00\x00', + ], + (Ecu.fwdRadar, 0x750, 0xf): [ + b'\x018821F0R01100\x00\x00\x00\x00', + ], + (Ecu.fwdCamera, 0x750, 0x6d): [ + b'\x028646F0R02100\x00\x00\x00\x008646G0R01100\x00\x00\x00\x00', + ], + }, CAR.RAV4H_TSS2: { (Ecu.engine, 0x700, None): [ b'\x01896634A15000\x00\x00\x00\x00', @@ -1166,6 +1397,7 @@ FW_VERSIONS = { b'\x018966342X6000\x00\x00\x00\x00', b'\x01896634A25000\x00\x00\x00\x00', b'\x018966342W5000\x00\x00\x00\x00', + b'\x018966342W7000\x00\x00\x00\x00', b'\x028966342W4001\x00\x00\x00\x00897CF1203001\x00\x00\x00\x00', b'\x02896634A13000\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'\x02896634A13001\x00\x00\x00\x00897CF4801001\x00\x00\x00\x00', @@ -1173,10 +1405,11 @@ FW_VERSIONS = { b'\x02896634A14001\x00\x00\x00\x00897CF1203001\x00\x00\x00\x00', b'\x02896634A23000\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'\x02896634A23001\x00\x00\x00\x00897CF1203001\x00\x00\x00\x00', + b'\x02896634A23101\x00\x00\x00\x00897CF1203001\x00\x00\x00\x00', b'\x02896634A14001\x00\x00\x00\x00897CF4801001\x00\x00\x00\x00', b'\x02896634A14101\x00\x00\x00\x00897CF4801001\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152642291\x00\x00\x00\x00\x00\x00', b'F152642290\x00\x00\x00\x00\x00\x00', b'F152642322\x00\x00\x00\x00\x00\x00', @@ -1214,6 +1447,34 @@ FW_VERSIONS = { b'\x028646F4203800\x00\x00\x00\x008646G2601500\x00\x00\x00\x00', ], }, + CAR.RAV4H_TSS2_2022: { + (Ecu.abs, 0x7b0, None): [ + b'\x01F15264283100\x00\x00\x00\x00', + b'\x01F15264286200\x00\x00\x00\x00', + b'\x01F15264286100\x00\x00\x00\x00', + b'\x01F15264283200\x00\x00\x00\x00', + ], + (Ecu.eps, 0x7a1, None): [ + b'\x028965B0R01500\x00\x00\x00\x008965B0R02500\x00\x00\x00\x00', + b'8965B42182\x00\x00\x00\x00\x00\x00', + b'8965B42172\x00\x00\x00\x00\x00\x00', + ], + (Ecu.engine, 0x700, None): [ + b'\x01896634A02001\x00\x00\x00\x00', + b'\x01896634A03000\x00\x00\x00\x00', + b'\x01896634A08000\x00\x00\x00\x00', + b'\x01896634A61000\x00\x00\x00\x00', + b'\x01896634A62000\x00\x00\x00\x00', + b'\x01896634A62100\x00\x00\x00\x00', + b'\x01896634A63000\x00\x00\x00\x00', + ], + (Ecu.fwdRadar, 0x750, 0xf): [ + b'\x018821F0R01100\x00\x00\x00\x00', + ], + (Ecu.fwdCamera, 0x750, 0x6d): [ + b'\x028646F0R02100\x00\x00\x00\x008646G0R01100\x00\x00\x00\x00', + ], + }, CAR.SIENNA: { (Ecu.engine, 0x700, None): [ b'\x01896630832100\x00\x00\x00\x00', @@ -1235,7 +1496,7 @@ FW_VERSIONS = { b'8965B45080\x00\x00\x00\x00\x00\x00', b'8965B45082\x00\x00\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152608130\x00\x00\x00\x00\x00\x00', ], (Ecu.dsu, 0x791, None): [ @@ -1254,7 +1515,7 @@ FW_VERSIONS = { (Ecu.dsu, 0x791, None): [ b'881517601100\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152676144\x00\x00\x00\x00\x00\x00', ], (Ecu.engine, 0x7e0, None): [ @@ -1269,13 +1530,14 @@ FW_VERSIONS = { }, CAR.LEXUS_ES_TSS2: { (Ecu.engine, 0x700, None): [ + b'\x018966306U6000\x00\x00\x00\x00', b'\x01896630EC9100\x00\x00\x00\x00', b'\x018966333T5000\x00\x00\x00\x00', b'\x018966333T5100\x00\x00\x00\x00', b'\x018966333X6000\x00\x00\x00\x00', b'\x01896633T07000\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'\x01F152606281\x00\x00\x00\x00\x00\x00', b'\x01F152606340\x00\x00\x00\x00\x00\x00', b'\x01F152606461\x00\x00\x00\x00\x00\x00', @@ -1285,18 +1547,21 @@ FW_VERSIONS = { b'8965B33252\x00\x00\x00\x00\x00\x00', b'8965B33590\x00\x00\x00\x00\x00\x00', b'8965B33690\x00\x00\x00\x00\x00\x00', + b'8965B33721\x00\x00\x00\x00\x00\x00', b'8965B48271\x00\x00\x00\x00\x00\x00', ], (Ecu.fwdRadar, 0x750, 0xf): [ b'\x018821F3301100\x00\x00\x00\x00', b'\x018821F3301200\x00\x00\x00\x00', b'\x018821F3301400\x00\x00\x00\x00', + b'\x018821F6201300\x00\x00\x00\x00', ], (Ecu.fwdCamera, 0x750, 0x6d): [ b'\x028646F33030D0\x00\x00\x00\x008646G26011A0\x00\x00\x00\x00', b'\x028646F3303200\x00\x00\x00\x008646G26011A0\x00\x00\x00\x00', b'\x028646F3304100\x00\x00\x00\x008646G2601200\x00\x00\x00\x00', b'\x028646F3304300\x00\x00\x00\x008646G2601500\x00\x00\x00\x00', + b'\x028646F3309100\x00\x00\x00\x008646G3304000\x00\x00\x00\x00', b'\x028646F4810200\x00\x00\x00\x008646G2601400\x00\x00\x00\x00', ], }, @@ -1307,22 +1572,26 @@ FW_VERSIONS = { b'\x028966333T0100\x00\x00\x00\x00897CF3305001\x00\x00\x00\x00', b'\x028966333V4000\x00\x00\x00\x00897CF3305001\x00\x00\x00\x00', b'\x02896633T09000\x00\x00\x00\x00897CF3307001\x00\x00\x00\x00', + b'\x01896633T38000\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152633423\x00\x00\x00\x00\x00\x00', b'F152633680\x00\x00\x00\x00\x00\x00', b'F152633681\x00\x00\x00\x00\x00\x00', + b'F152633F50\x00\x00\x00\x00\x00\x00', ], (Ecu.eps, 0x7a1, None): [ b'8965B33252\x00\x00\x00\x00\x00\x00', b'8965B33590\x00\x00\x00\x00\x00\x00', b'8965B33690\x00\x00\x00\x00\x00\x00', + b'8965B33721\x00\x00\x00\x00\x00\x00', ], (Ecu.fwdRadar, 0x750, 0xf): [ b'\x018821F3301100\x00\x00\x00\x00', b'\x018821F3301200\x00\x00\x00\x00', b'\x018821F3301300\x00\x00\x00\x00', b'\x018821F3301400\x00\x00\x00\x00', + b'\x018821F6201300\x00\x00\x00\x00', ], (Ecu.fwdCamera, 0x750, 0x6d): [ b'\x028646F33030D0\x00\x00\x00\x008646G26011A0\x00\x00\x00\x00', @@ -1331,13 +1600,14 @@ FW_VERSIONS = { b'\x028646F3304100\x00\x00\x00\x008646G2601200\x00\x00\x00\x00', b'\x028646F3304200\x00\x00\x00\x008646G2601400\x00\x00\x00\x00', b'\x028646F3304300\x00\x00\x00\x008646G2601500\x00\x00\x00\x00', + b'\x028646F3309100\x00\x00\x00\x008646G3304000\x00\x00\x00\x00', ], }, CAR.LEXUS_ESH: { (Ecu.engine, 0x7e0, None): [ b'\x02333M4200\x00\x00\x00\x00\x00\x00\x00\x00A4701000\x00\x00\x00\x00\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152633171\x00\x00\x00\x00\x00\x00', ], (Ecu.dsu, 0x791, None): [ @@ -1363,7 +1633,7 @@ FW_VERSIONS = { b'\x01896637854000\x00\x00\x00\x00', b'\x01896637878000\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152678130\x00\x00\x00\x00\x00\x00', b'F152678140\x00\x00\x00\x00\x00\x00', ], @@ -1387,9 +1657,10 @@ FW_VERSIONS = { CAR.LEXUS_NX_TSS2: { (Ecu.engine, 0x700, None): [ b'\x018966378B2100\x00\x00\x00\x00', + b'\x018966378B3000\x00\x00\x00\x00', b'\x018966378G3000\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'\x01F152678221\x00\x00\x00\x00\x00\x00', ], (Ecu.eps, 0x7a1, None): [ @@ -1397,12 +1668,31 @@ FW_VERSIONS = { ], (Ecu.fwdRadar, 0x750, 0xf): [ b"\x018821F3301400\x00\x00\x00\x00", + b'\x018821F3301200\x00\x00\x00\x00', + b'\x018821F3301300\x00\x00\x00\x00', ], (Ecu.fwdCamera, 0x750, 0x6d): [ b'\x028646F78030A0\x00\x00\x00\x008646G2601200\x00\x00\x00\x00', b'\x028646F7803100\x00\x00\x00\x008646G2601400\x00\x00\x00\x00', ], }, + CAR.LEXUS_NXH_TSS2: { + (Ecu.engine, 0x7e0, None): [ + b'\x0237887000\x00\x00\x00\x00\x00\x00\x00\x00A4701000\x00\x00\x00\x00\x00\x00\x00\x00', + ], + (Ecu.abs, 0x7b0, None): [ + b'F152678210\x00\x00\x00\x00\x00\x00', + ], + (Ecu.eps, 0x7a1, None): [ + b'8965B78120\x00\x00\x00\x00\x00\x00', + ], + (Ecu.fwdRadar, 0x750, 0xf): [ + b'\x018821F3301400\x00\x00\x00\x00', + ], + (Ecu.fwdCamera, 0x750, 0x6d): [ + b'\x028646F78030A0\x00\x00\x00\x008646G2601200\x00\x00\x00\x00', + ], + }, CAR.LEXUS_NXH: { (Ecu.engine, 0x7e0, None): [ b'\x0237841000\x00\x00\x00\x00\x00\x00\x00\x00A4701000\x00\x00\x00\x00\x00\x00\x00\x00', @@ -1411,7 +1701,7 @@ FW_VERSIONS = { b'\x0237882000\x00\x00\x00\x00\x00\x00\x00\x00A4701000\x00\x00\x00\x00\x00\x00\x00\x00', b'\x0237886000\x00\x00\x00\x00\x00\x00\x00\x00A4701000\x00\x00\x00\x00\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152678160\x00\x00\x00\x00\x00\x00', b'F152678170\x00\x00\x00\x00\x00\x00', b'F152678171\x00\x00\x00\x00\x00\x00', @@ -1438,7 +1728,7 @@ FW_VERSIONS = { (Ecu.engine, 0x7e0, None): [ b'\x0232484000\x00\x00\x00\x00\x00\x00\x00\x0052422000\x00\x00\x00\x00\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152624221\x00\x00\x00\x00\x00\x00', ], (Ecu.dsu, 0x791, None): [ @@ -1474,7 +1764,7 @@ FW_VERSIONS = { b'\x018966348R8500\x00\x00\x00\x00', b'\x018966348W1300\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152648472\x00\x00\x00\x00\x00\x00', b'F152648473\x00\x00\x00\x00\x00\x00', b'F152648492\x00\x00\x00\x00\x00\x00', @@ -1521,7 +1811,7 @@ FW_VERSIONS = { b'\x02348V6000\x00\x00\x00\x00\x00\x00\x00\x00A4802000\x00\x00\x00\x00\x00\x00\x00\x00', b'\x02348Z3000\x00\x00\x00\x00\x00\x00\x00\x00A4802000\x00\x00\x00\x00\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152648361\x00\x00\x00\x00\x00\x00', b'F152648501\x00\x00\x00\x00\x00\x00', b'F152648502\x00\x00\x00\x00\x00\x00', @@ -1560,13 +1850,16 @@ FW_VERSIONS = { b'\x01896630EB0000\x00\x00\x00\x00', b'\x01896630EC9000\x00\x00\x00\x00', b'\x01896630ED0000\x00\x00\x00\x00', + b'\x01896630ED0100\x00\x00\x00\x00', b'\x01896630ED6000\x00\x00\x00\x00', b'\x018966348W5100\x00\x00\x00\x00', b'\x018966348W9000\x00\x00\x00\x00', b'\x01896634D12000\x00\x00\x00\x00', b'\x01896634D12100\x00\x00\x00\x00', + b'\x01896634D43000\x00\x00\x00\x00', + b'\x01896634D44000\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'\x01F15260E031\x00\x00\x00\x00\x00\x00', b'\x01F15260E041\x00\x00\x00\x00\x00\x00', b'\x01F152648781\x00\x00\x00\x00\x00\x00', @@ -1585,21 +1878,27 @@ FW_VERSIONS = { b'\x028646F4810100\x00\x00\x00\x008646G2601200\x00\x00\x00\x00', b'\x028646F4810200\x00\x00\x00\x008646G2601400\x00\x00\x00\x00', b'\x028646F4810300\x00\x00\x00\x008646G2601400\x00\x00\x00\x00', + b'\x028646F4810400\x00\x00\x00\x008646G2601400\x00\x00\x00\x00', ], }, CAR.LEXUS_RXH_TSS2: { (Ecu.engine, 0x7e0, None): [ b'\x02348X8000\x00\x00\x00\x00\x00\x00\x00\x00A4802000\x00\x00\x00\x00\x00\x00\x00\x00', + b'\x02348Y3000\x00\x00\x00\x00\x00\x00\x00\x00A4802000\x00\x00\x00\x00\x00\x00\x00\x00', b'\x0234D14000\x00\x00\x00\x00\x00\x00\x00\x00A4802000\x00\x00\x00\x00\x00\x00\x00\x00', b'\x0234D16000\x00\x00\x00\x00\x00\x00\x00\x00A4802000\x00\x00\x00\x00\x00\x00\x00\x00', + b'\x02348X4000\x00\x00\x00\x00\x00\x00\x00\x00A4802000\x00\x00\x00\x00\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152648831\x00\x00\x00\x00\x00\x00', + b'F152648891\x00\x00\x00\x00\x00\x00', b'F152648D00\x00\x00\x00\x00\x00\x00', b'F152648D60\x00\x00\x00\x00\x00\x00', + b'F152648811\x00\x00\x00\x00\x00\x00', ], (Ecu.eps, 0x7a1, None): [ b'8965B48271\x00\x00\x00\x00\x00\x00', + b'8965B48261\x00\x00\x00\x00\x00\x00', ], (Ecu.fwdRadar, 0x750, 0xf): [ b'\x018821F3301400\x00\x00\x00\x00', @@ -1612,6 +1911,7 @@ FW_VERSIONS = { CAR.PRIUS_TSS2: { (Ecu.engine, 0x700, None): [ b'\x028966347B1000\x00\x00\x00\x008966A4703000\x00\x00\x00\x00', + b'\x028966347C4000\x00\x00\x00\x008966A4703000\x00\x00\x00\x00', b'\x028966347C6000\x00\x00\x00\x008966A4703000\x00\x00\x00\x00', b'\x028966347C8000\x00\x00\x00\x008966A4703000\x00\x00\x00\x00', b'\x038966347C0000\x00\x00\x00\x008966A4703000\x00\x00\x00\x00897CF4710101\x00\x00\x00\x00', @@ -1619,7 +1919,7 @@ FW_VERSIONS = { b'\x038966347C5000\x00\x00\x00\x008966A4703000\x00\x00\x00\x00897CF4707101\x00\x00\x00\x00', b'\x038966347C5100\x00\x00\x00\x008966A4703000\x00\x00\x00\x00897CF4707101\x00\x00\x00\x00', ], - (Ecu.esp, 0x7b0, None): [ + (Ecu.abs, 0x7b0, None): [ b'F152647500\x00\x00\x00\x00\x00\x00', b'F152647510\x00\x00\x00\x00\x00\x00', b'F152647520\x00\x00\x00\x00\x00\x00', @@ -1635,11 +1935,15 @@ FW_VERSIONS = { (Ecu.fwdCamera, 0x750, 0x6d): [ b'\x028646F4707000\x00\x00\x00\x008646G2601400\x00\x00\x00\x00', b'\x028646F4710000\x00\x00\x00\x008646G2601500\x00\x00\x00\x00', + b'\x028646F4712000\x00\x00\x00\x008646G2601500\x00\x00\x00\x00', ], }, CAR.MIRAI: { - (Ecu.esp, 0x7D1, None): [b'\x01898A36203000\x00\x00\x00\x00',], - (Ecu.esp, 0x7B0, None): [b'\x01F15266203200\x00\x00\x00\x00',], # a second ESP ECU + (Ecu.abs, 0x7D1, None): [b'\x01898A36203000\x00\x00\x00\x00',], + (Ecu.abs, 0x7B0, None): [ # a second ABS ECU + b'\x01F15266203200\x00\x00\x00\x00', + b'\x01F15266203500\x00\x00\x00\x00', + ], (Ecu.eps, 0x7A1, None): [b'\x028965B6204100\x00\x00\x00\x008965B6203100\x00\x00\x00\x00',], (Ecu.fwdRadar, 0x750, 0xf): [b'\x018821F6201200\x00\x00\x00\x00',], (Ecu.fwdCamera, 0x750, 0x6d): [b'\x028646F6201400\x00\x00\x00\x008646G5301200\x00\x00\x00\x00',], @@ -1662,6 +1966,23 @@ FW_VERSIONS = { b'\x028646F5803200\x00\x00\x00\x008646G2601400\x00\x00\x00\x00', ], }, + CAR.ALPHARDH_TSS2: { + (Ecu.engine, 0x7e0, None): [ + b'\x0235879000\x00\x00\x00\x00\x00\x00\x00\x00A4701000\x00\x00\x00\x00\x00\x00\x00\x00', + ], + (Ecu.eps, 0x7a1, None): [ + b'8965B58040\x00\x00\x00\x00\x00\x00', + ], + (Ecu.abs, 0x7b0, None): [ + b'F152658341\x00\x00\x00\x00\x00\x00' + ], + (Ecu.fwdRadar, 0x750, 0xf): [ + b'\x018821F3301400\x00\x00\x00\x00', + ], + (Ecu.fwdCamera, 0x750, 0x6d): [ + b'\x028646FV201000\x00\x00\x00\x008646G2601400\x00\x00\x00\x00', + ], + }, } STEER_THRESHOLD = 100 @@ -1691,7 +2012,9 @@ DBC = { CAR.AVALON_2019: dbc_dict('toyota_nodsu_pt_generated', 'toyota_adas'), CAR.AVALONH_2019: dbc_dict('toyota_nodsu_pt_generated', 'toyota_adas'), CAR.AVALON_TSS2: dbc_dict('toyota_nodsu_pt_generated', 'toyota_tss2_adas'), + CAR.AVALONH_TSS2: dbc_dict('toyota_nodsu_pt_generated', 'toyota_tss2_adas'), CAR.RAV4_TSS2: dbc_dict('toyota_nodsu_pt_generated', 'toyota_tss2_adas'), + CAR.RAV4_TSS2_2022: dbc_dict('toyota_nodsu_pt_generated', None), CAR.COROLLA_TSS2: dbc_dict('toyota_nodsu_pt_generated', 'toyota_tss2_adas'), CAR.COROLLAH_TSS2: dbc_dict('toyota_nodsu_pt_generated', 'toyota_tss2_adas'), CAR.LEXUS_ES_TSS2: dbc_dict('toyota_nodsu_pt_generated', 'toyota_tss2_adas'), @@ -1701,27 +2024,36 @@ DBC = { CAR.LEXUS_IS: dbc_dict('toyota_tnga_k_pt_generated', 'toyota_adas'), CAR.LEXUS_CTH: dbc_dict('toyota_new_mc_pt_generated', 'toyota_adas'), CAR.RAV4H_TSS2: dbc_dict('toyota_nodsu_pt_generated', 'toyota_tss2_adas'), + CAR.RAV4H_TSS2_2022: dbc_dict('toyota_nodsu_pt_generated', None), CAR.LEXUS_NXH: dbc_dict('toyota_tnga_k_pt_generated', 'toyota_adas'), CAR.LEXUS_NX: dbc_dict('toyota_tnga_k_pt_generated', 'toyota_adas'), CAR.LEXUS_NX_TSS2: dbc_dict('toyota_nodsu_pt_generated', 'toyota_tss2_adas'), + CAR.LEXUS_NXH_TSS2: dbc_dict('toyota_nodsu_pt_generated', 'toyota_tss2_adas'), CAR.PRIUS_TSS2: dbc_dict('toyota_nodsu_pt_generated', 'toyota_tss2_adas'), CAR.MIRAI: dbc_dict('toyota_nodsu_pt_generated', 'toyota_tss2_adas'), CAR.ALPHARD_TSS2: dbc_dict('toyota_nodsu_pt_generated', 'toyota_tss2_adas'), + CAR.ALPHARDH_TSS2: dbc_dict('toyota_nodsu_pt_generated', 'toyota_tss2_adas'), } # These cars have non-standard EPS torque scale factors. All others are 73 EPS_SCALE = defaultdict(lambda: 73, {CAR.PRIUS: 66, CAR.COROLLA: 88, CAR.LEXUS_IS: 77, CAR.LEXUS_RC: 77, CAR.LEXUS_CTH: 100, CAR.PRIUS_V: 100}) # Toyota/Lexus Safety Sense 2.0 and 2.5 -TSS2_CAR = {CAR.RAV4_TSS2, CAR.COROLLA_TSS2, CAR.COROLLAH_TSS2, CAR.LEXUS_ES_TSS2, CAR.LEXUS_ESH_TSS2, CAR.RAV4H_TSS2, +TSS2_CAR = {CAR.RAV4_TSS2, CAR.RAV4_TSS2_2022, CAR.COROLLA_TSS2, CAR.COROLLAH_TSS2, CAR.LEXUS_ES_TSS2, CAR.LEXUS_ESH_TSS2, CAR.RAV4H_TSS2, CAR.RAV4H_TSS2_2022, CAR.LEXUS_RX_TSS2, CAR.LEXUS_RXH_TSS2, CAR.HIGHLANDER_TSS2, CAR.HIGHLANDERH_TSS2, CAR.PRIUS_TSS2, CAR.CAMRY_TSS2, CAR.CAMRYH_TSS2, - CAR.MIRAI, CAR.LEXUS_NX_TSS2, CAR.ALPHARD_TSS2, CAR.AVALON_TSS2} + CAR.MIRAI, CAR.LEXUS_NX_TSS2, CAR.LEXUS_NXH_TSS2, CAR.ALPHARD_TSS2, CAR.AVALON_TSS2, CAR.AVALONH_TSS2, CAR.ALPHARDH_TSS2} NO_DSU_CAR = TSS2_CAR | {CAR.CHR, CAR.CHRH, CAR.CAMRY, CAR.CAMRYH} -EV_HYBRID_CAR = {CAR.AVALONH_2019, CAR.CAMRYH, CAR.CAMRYH_TSS2, CAR.CHRH, CAR.COROLLAH_TSS2, CAR.HIGHLANDERH, CAR.HIGHLANDERH_TSS2, CAR.PRIUS, - CAR.PRIUS_V, CAR.RAV4H, CAR.RAV4H_TSS2, CAR.LEXUS_CTH, CAR.MIRAI, CAR.LEXUS_ESH, CAR.LEXUS_ESH_TSS2, CAR.LEXUS_NXH, CAR.LEXUS_RXH, - CAR.LEXUS_RXH_TSS2, CAR.PRIUS_TSS2} +# the DSU uses the AEB message for longitudinal on these cars +UNSUPPORTED_DSU_CAR = {CAR.LEXUS_IS, CAR.LEXUS_RC} + +# these cars have a radar which sends ACC messages instead of the camera +RADAR_ACC_CAR = {CAR.RAV4H_TSS2_2022, CAR.RAV4_TSS2_2022} + +EV_HYBRID_CAR = {CAR.AVALONH_2019, CAR.AVALONH_TSS2, CAR.CAMRYH, CAR.CAMRYH_TSS2, CAR.CHRH, CAR.COROLLAH_TSS2, CAR.HIGHLANDERH, CAR.HIGHLANDERH_TSS2, CAR.PRIUS, + CAR.PRIUS_V, CAR.RAV4H, CAR.RAV4H_TSS2, CAR.RAV4H_TSS2_2022, CAR.LEXUS_CTH, CAR.MIRAI, CAR.LEXUS_ESH, CAR.LEXUS_ESH_TSS2, CAR.LEXUS_NXH, CAR.LEXUS_RXH, + CAR.LEXUS_RXH_TSS2, CAR.LEXUS_NXH_TSS2, CAR.PRIUS_TSS2, CAR.ALPHARDH_TSS2} # no resume button press required NO_STOP_TIMER_CAR = TSS2_CAR | {CAR.PRIUS_V, CAR.RAV4H, CAR.HIGHLANDERH, CAR.HIGHLANDER, CAR.SIENNA, CAR.LEXUS_ESH} diff --git a/selfdrive/car/vin.py b/selfdrive/car/vin.py index 648f416511..cf1c25e851 100755 --- a/selfdrive/car/vin.py +++ b/selfdrive/car/vin.py @@ -1,33 +1,63 @@ #!/usr/bin/env python3 -import traceback +import re import cereal.messaging as messaging -from panda.python.uds import FUNCTIONAL_ADDRS +from panda.python.uds import get_rx_addr_for_tx_addr, FUNCTIONAL_ADDRS from selfdrive.car.isotp_parallel_query import IsoTpParallelQuery -from selfdrive.swaglog import cloudlog +from selfdrive.car.fw_query_definitions import StdQueries +from system.swaglog import cloudlog -VIN_REQUEST = b'\x09\x02' -VIN_RESPONSE = b'\x49\x02\x01' VIN_UNKNOWN = "0" * 17 +VIN_RE = "[A-HJ-NPR-Z0-9]{17}" + + +def is_valid_vin(vin: str): + return re.fullmatch(VIN_RE, vin) is not None def get_vin(logcan, sendcan, bus, timeout=0.1, retry=5, debug=False): + addrs = list(range(0x7e0, 0x7e8)) + list(range(0x18DA00F1, 0x18DB00F1, 0x100)) # addrs to process/wait for + valid_vin_addrs = [0x7e0, 0x7e2, 0x18da10f1, 0x18da0ef1] # engine, VMCU, 29-bit engine, PGM-FI for i in range(retry): - try: - query = IsoTpParallelQuery(sendcan, logcan, bus, FUNCTIONAL_ADDRS, [VIN_REQUEST], [VIN_RESPONSE], functional_addr=True, debug=debug) - for addr, vin in query.get_data(timeout).items(): - return addr[0], vin.decode() - print(f"vin query retry ({i+1}) ...") - except Exception: - cloudlog.warning(f"VIN query exception: {traceback.format_exc()}") + for request, response in ((StdQueries.UDS_VIN_REQUEST, StdQueries.UDS_VIN_RESPONSE), (StdQueries.OBD_VIN_REQUEST, StdQueries.OBD_VIN_RESPONSE)): + try: + query = IsoTpParallelQuery(sendcan, logcan, bus, addrs, [request, ], [response, ], functional_addrs=FUNCTIONAL_ADDRS, debug=debug) + results = query.get_data(timeout) + + for addr in valid_vin_addrs: + vin = results.get((addr, None)) + if vin is not None: + # Ford pads with null bytes + if len(vin) == 24: + vin = re.sub(b'\x00*$', b'', vin) + + # Honda Bosch response starts with a length, trim to correct length + if vin.startswith(b'\x11'): + vin = vin[1:18] + + return get_rx_addr_for_tx_addr(addr), vin.decode() + + cloudlog.error(f"vin query retry ({i+1}) ...") + except Exception: + cloudlog.exception("VIN query exception") return 0, VIN_UNKNOWN if __name__ == "__main__": + import argparse import time + + parser = argparse.ArgumentParser(description='Get VIN of the car') + parser.add_argument('--debug', action='store_true') + parser.add_argument('--bus', type=int, default=1) + parser.add_argument('--timeout', type=float, default=0.1) + parser.add_argument('--retry', type=int, default=5) + args = parser.parse_args() + sendcan = messaging.pub_sock('sendcan') logcan = messaging.sub_sock('can') time.sleep(1) - addr, vin = get_vin(logcan, sendcan, 1, debug=False) - print(hex(addr), vin) + + vin_rx_addr, vin = get_vin(logcan, sendcan, args.bus, args.timeout, args.retry, debug=args.debug) + print(f'RX: {hex(vin_rx_addr)}, VIN: {vin}') diff --git a/selfdrive/car/volkswagen/carcontroller.py b/selfdrive/car/volkswagen/carcontroller.py index f85a81a538..fff5548671 100644 --- a/selfdrive/car/volkswagen/carcontroller.py +++ b/selfdrive/car/volkswagen/carcontroller.py @@ -1,34 +1,36 @@ from cereal import car -from selfdrive.car import apply_std_steer_torque_limits -from selfdrive.car.volkswagen import volkswagencan -from selfdrive.car.volkswagen.values import DBC_FILES, CANBUS, MQB_LDW_MESSAGES, BUTTON_STATES, CarControllerParams as P from opendbc.can.packer import CANPacker +from common.numpy_fast import clip +from common.conversions import Conversions as CV +from selfdrive.car import apply_std_steer_torque_limits +from selfdrive.car.volkswagen import mqbcan, pqcan +from selfdrive.car.volkswagen.values import CANBUS, PQ_CARS, CarControllerParams VisualAlert = car.CarControl.HUDControl.VisualAlert +LongCtrlState = car.CarControl.Actuators.LongControlState -class CarController(): - def __init__(self, dbc_name, CP, VM): - self.apply_steer_last = 0 - self.packer_pt = CANPacker(DBC_FILES.mqb) +class CarController: + def __init__(self, dbc_name, CP, VM): + self.CP = CP + self.CCP = CarControllerParams(CP) + self.CCS = pqcan if CP.carFingerprint in PQ_CARS else mqbcan + self.packer_pt = CANPacker(dbc_name) + self.apply_steer_last = 0 + self.gra_acc_counter_last = None + self.frame = 0 self.hcaSameTorqueCount = 0 self.hcaEnabledFrameCount = 0 - self.graButtonStatesToSend = None - self.graMsgSentCount = 0 - self.graMsgStartFramePrev = 0 - self.graMsgBusCounterPrev = 0 - - self.steer_rate_limited = False - - def update(self, c, enabled, CS, frame, ext_bus, actuators, visual_alert, left_lane_visible, right_lane_visible, left_lane_depart, right_lane_depart): - """ Controls thread """ + def update(self, CC, CS, ext_bus): + actuators = CC.actuators + hud_control = CC.hudControl can_sends = [] # **** Steering Controls ************************************************ # - if frame % P.HCA_STEP == 0: + if self.frame % self.CCP.HCA_STEP == 0: # Logic to avoid HCA state 4 "refused": # * Don't steer unless HCA is in state 3 "ready" or 5 "active" # * Don't steer at standstill @@ -39,23 +41,22 @@ class CarController(): # torque value. Do that anytime we happen to have 0 torque, or failing that, # when exceeding ~1/3 the 360 second timer. - if c.active and CS.out.vEgo > CS.CP.minSteerSpeed and not (CS.out.standstill or CS.out.steerError or CS.out.steerWarning): - new_steer = int(round(actuators.steer * P.STEER_MAX)) - apply_steer = apply_std_steer_torque_limits(new_steer, self.apply_steer_last, CS.out.steeringTorque, P) - self.steer_rate_limited = new_steer != apply_steer + if CC.latActive: + new_steer = int(round(actuators.steer * self.CCP.STEER_MAX)) + apply_steer = apply_std_steer_torque_limits(new_steer, self.apply_steer_last, CS.out.steeringTorque, self.CCP) if apply_steer == 0: hcaEnabled = False self.hcaEnabledFrameCount = 0 else: self.hcaEnabledFrameCount += 1 - if self.hcaEnabledFrameCount >= 118 * (100 / P.HCA_STEP): # 118s + if self.hcaEnabledFrameCount >= 118 * (100 / self.CCP.HCA_STEP): # 118s hcaEnabled = False self.hcaEnabledFrameCount = 0 else: hcaEnabled = True if self.apply_steer_last == apply_steer: self.hcaSameTorqueCount += 1 - if self.hcaSameTorqueCount > 1.9 * (100 / P.HCA_STEP): # 1.9s + if self.hcaSameTorqueCount > 1.9 * (100 / self.CCP.HCA_STEP): # 1.9s apply_steer -= (1, -1)[apply_steer < 0] self.hcaSameTorqueCount = 0 else: @@ -65,52 +66,44 @@ class CarController(): apply_steer = 0 self.apply_steer_last = apply_steer - idx = (frame / P.HCA_STEP) % 16 - can_sends.append(volkswagencan.create_mqb_steering_control(self.packer_pt, CANBUS.pt, apply_steer, - idx, hcaEnabled)) + can_sends.append(self.CCS.create_steering_control(self.packer_pt, CANBUS.pt, apply_steer, hcaEnabled)) + + # **** Acceleration Controls ******************************************** # + + if self.frame % self.CCP.ACC_CONTROL_STEP == 0 and self.CP.openpilotLongitudinalControl: + acc_control = self.CCS.acc_control_value(CS.out.cruiseState.available, CS.out.accFaulted, CC.longActive) + accel = clip(actuators.accel, self.CCP.ACCEL_MIN, self.CCP.ACCEL_MAX) if CC.longActive else 0 + stopping = actuators.longControlState == LongCtrlState.stopping + starting = actuators.longControlState == LongCtrlState.starting + can_sends.extend(self.CCS.create_acc_accel_control(self.packer_pt, CANBUS.pt, CS.acc_type, CC.longActive, accel, + acc_control, stopping, starting, CS.esp_hold_confirmation)) # **** HUD Controls ***************************************************** # - if frame % P.LDW_STEP == 0: - if visual_alert in (VisualAlert.steerRequired, VisualAlert.ldw): - hud_alert = MQB_LDW_MESSAGES["laneAssistTakeOverSilent"] - else: - hud_alert = MQB_LDW_MESSAGES["none"] - - can_sends.append(volkswagencan.create_mqb_hud_control(self.packer_pt, CANBUS.pt, enabled, - CS.out.steeringPressed, hud_alert, left_lane_visible, - right_lane_visible, CS.ldw_stock_values, - left_lane_depart, right_lane_depart)) - - # **** ACC Button Controls ********************************************** # - - # FIXME: this entire section is in desperate need of refactoring - - if CS.CP.pcmCruise: - if frame > self.graMsgStartFramePrev + P.GRA_VBP_STEP: - if not enabled and CS.out.cruiseState.enabled: - # Cancel ACC if it's engaged with OP disengaged. - self.graButtonStatesToSend = BUTTON_STATES.copy() - self.graButtonStatesToSend["cancel"] = True - elif enabled and CS.esp_hold_confirmation: - # Blip the Resume button if we're engaged at standstill. - # FIXME: This is a naive implementation, improve with visiond or radar input. - self.graButtonStatesToSend = BUTTON_STATES.copy() - self.graButtonStatesToSend["resumeCruise"] = True - - if CS.graMsgBusCounter != self.graMsgBusCounterPrev: - self.graMsgBusCounterPrev = CS.graMsgBusCounter - if self.graButtonStatesToSend is not None: - if self.graMsgSentCount == 0: - self.graMsgStartFramePrev = frame - idx = (CS.graMsgBusCounter + 1) % 16 - can_sends.append(volkswagencan.create_mqb_acc_buttons_control(self.packer_pt, ext_bus, self.graButtonStatesToSend, CS, idx)) - self.graMsgSentCount += 1 - if self.graMsgSentCount >= P.GRA_VBP_COUNT: - self.graButtonStatesToSend = None - self.graMsgSentCount = 0 + if self.frame % self.CCP.LDW_STEP == 0: + hud_alert = 0 + if hud_control.visualAlert in (VisualAlert.steerRequired, VisualAlert.ldw): + hud_alert = self.CCP.LDW_MESSAGES["laneAssistTakeOver"] + can_sends.append(self.CCS.create_lka_hud_control(self.packer_pt, CANBUS.pt, CS.ldw_stock_values, CC.enabled, + CS.out.steeringPressed, hud_alert, hud_control)) + + if self.frame % self.CCP.ACC_HUD_STEP == 0 and self.CP.openpilotLongitudinalControl: + acc_hud_status = self.CCS.acc_hud_status_value(CS.out.cruiseState.available, CS.out.accFaulted, CC.longActive) + set_speed = hud_control.setSpeed * CV.MS_TO_KPH # FIXME: follow the recent displayed-speed updates, also use mph_kmh toggle to fix display rounding problem? + can_sends.append(self.CCS.create_acc_hud_control(self.packer_pt, CANBUS.pt, acc_hud_status, set_speed, + hud_control.leadVisible)) + + # **** Stock ACC Button Controls **************************************** # + + gra_send_ready = self.CP.pcmCruise and CS.gra_stock_values["COUNTER"] != self.gra_acc_counter_last + if gra_send_ready and (CC.cruiseControl.cancel or CC.cruiseControl.resume): + counter = (CS.gra_stock_values["COUNTER"] + 1) % 16 + can_sends.append(self.CCS.create_acc_buttons_control(self.packer_pt, ext_bus, CS.gra_stock_values, counter, + cancel=CC.cruiseControl.cancel, resume=CC.cruiseControl.resume)) new_actuators = actuators.copy() - new_actuators.steer = self.apply_steer_last / P.STEER_MAX + new_actuators.steer = self.apply_steer_last / self.CCP.STEER_MAX + self.gra_acc_counter_last = CS.gra_stock_values["COUNTER"] + self.frame += 1 return new_actuators, can_sends diff --git a/selfdrive/car/volkswagen/carstate.py b/selfdrive/car/volkswagen/carstate.py index 1fe8b56b90..263edbfc9d 100644 --- a/selfdrive/car/volkswagen/carstate.py +++ b/selfdrive/car/volkswagen/carstate.py @@ -1,23 +1,37 @@ import numpy as np from cereal import car -from selfdrive.config import Conversions as CV +from common.conversions import Conversions as CV from selfdrive.car.interfaces import CarStateBase from opendbc.can.parser import CANParser -from opendbc.can.can_define import CANDefine -from selfdrive.car.volkswagen.values import DBC_FILES, CANBUS, NetworkLocation, TransmissionType, GearShifter, BUTTON_STATES, CarControllerParams +from selfdrive.car.volkswagen.values import DBC, CANBUS, PQ_CARS, NetworkLocation, TransmissionType, GearShifter, \ + CarControllerParams + class CarState(CarStateBase): def __init__(self, CP): super().__init__(CP) - can_define = CANDefine(DBC_FILES.mqb) - if CP.transmissionType == TransmissionType.automatic: - self.shifter_values = can_define.dv["Getriebe_11"]["GE_Fahrstufe"] - elif CP.transmissionType == TransmissionType.direct: - self.shifter_values = can_define.dv["EV_Gearshift"]["GearPosition"] - self.hca_status_values = can_define.dv["LH_EPS_03"]["EPS_HCA_Status"] - self.buttonStates = BUTTON_STATES.copy() + self.CCP = CarControllerParams(CP) + self.button_states = {button.event_type: False for button in self.CCP.BUTTONS} + self.esp_hold_confirmation = False + + def create_button_events(self, pt_cp, buttons): + button_events = [] + + for button in buttons: + state = pt_cp.vl[button.can_addr][button.can_msg] in button.values + if self.button_states[button.event_type] != state: + event = car.CarState.ButtonEvent.new_message() + event.type = button.event_type + event.pressed = state + button_events.append(event) + self.button_states[button.event_type] = state + + return button_events def update(self, pt_cp, cam_cp, ext_cp, trans_type): + if self.CP.carFingerprint in PQ_CARS: + return self.update_pq(pt_cp, cam_cp, ext_cp, trans_type) + ret = car.CarState.new_message() # Update vehicle speed and acceleration from ABS wheel speeds. ret.wheelSpeeds = self.get_wheel_speeds( @@ -36,26 +50,28 @@ class CarState(CarStateBase): ret.steeringAngleDeg = pt_cp.vl["LWI_01"]["LWI_Lenkradwinkel"] * (1, -1)[int(pt_cp.vl["LWI_01"]["LWI_VZ_Lenkradwinkel"])] ret.steeringRateDeg = pt_cp.vl["LWI_01"]["LWI_Lenkradw_Geschw"] * (1, -1)[int(pt_cp.vl["LWI_01"]["LWI_VZ_Lenkradw_Geschw"])] ret.steeringTorque = pt_cp.vl["LH_EPS_03"]["EPS_Lenkmoment"] * (1, -1)[int(pt_cp.vl["LH_EPS_03"]["EPS_VZ_Lenkmoment"])] - ret.steeringPressed = abs(ret.steeringTorque) > CarControllerParams.STEER_DRIVER_ALLOWANCE + ret.steeringPressed = abs(ret.steeringTorque) > self.CCP.STEER_DRIVER_ALLOWANCE ret.yawRate = pt_cp.vl["ESP_02"]["ESP_Gierrate"] * (1, -1)[int(pt_cp.vl["ESP_02"]["ESP_VZ_Gierrate"])] * CV.DEG_TO_RAD # Verify EPS readiness to accept steering commands - hca_status = self.hca_status_values.get(pt_cp.vl["LH_EPS_03"]["EPS_HCA_Status"]) - ret.steerError = hca_status in ("DISABLED", "FAULT") - ret.steerWarning = hca_status in ("INITIALIZING", "REJECTED") + hca_status = self.CCP.hca_status_values.get(pt_cp.vl["LH_EPS_03"]["EPS_HCA_Status"]) + ret.steerFaultPermanent = hca_status in ("DISABLED", "FAULT") + ret.steerFaultTemporary = hca_status in ("INITIALIZING", "REJECTED") # Update gas, brakes, and gearshift. ret.gas = pt_cp.vl["Motor_20"]["MO_Fahrpedalrohwert_01"] / 100.0 ret.gasPressed = ret.gas > 0 ret.brake = pt_cp.vl["ESP_05"]["ESP_Bremsdruck"] / 250.0 # FIXME: this is pressure in Bar, not sure what OP expects - ret.brakePressed = bool(pt_cp.vl["ESP_05"]["ESP_Fahrer_bremst"]) - self.esp_hold_confirmation = pt_cp.vl["ESP_21"]["ESP_Haltebestaetigung"] + brake_pedal_pressed = bool(pt_cp.vl["Motor_14"]["MO_Fahrer_bremst"]) + brake_pressure_detected = bool(pt_cp.vl["ESP_05"]["ESP_Fahrer_bremst"]) + ret.brakePressed = brake_pedal_pressed or brake_pressure_detected + ret.parkingBrake = bool(pt_cp.vl["Kombi_01"]["KBI_Handbremse"]) # FIXME: need to include an EPB check as well # Update gear and/or clutch position data. if trans_type == TransmissionType.automatic: - ret.gearShifter = self.parse_gear_shifter(self.shifter_values.get(pt_cp.vl["Getriebe_11"]["GE_Fahrstufe"], None)) + ret.gearShifter = self.parse_gear_shifter(self.CCP.shifter_values.get(pt_cp.vl["Getriebe_11"]["GE_Fahrstufe"], None)) elif trans_type == TransmissionType.direct: - ret.gearShifter = self.parse_gear_shifter(self.shifter_values.get(pt_cp.vl["EV_Gearshift"]["GearPosition"], None)) + ret.gearShifter = self.parse_gear_shifter(self.CCP.shifter_values.get(pt_cp.vl["EV_Gearshift"]["GearPosition"], None)) elif trans_type == TransmissionType.manual: ret.clutchPressed = not pt_cp.vl["Motor_14"]["MO_Kuppl_schalter"] if bool(pt_cp.vl["Gateway_72"]["BCM1_Rueckfahrlicht_Schalter"]): @@ -73,11 +89,6 @@ class CarState(CarStateBase): # Update seatbelt fastened status. ret.seatbeltUnlatched = pt_cp.vl["Airbag_02"]["AB_Gurtschloss_FA"] != 3 - # Update driver preference for metric. VW stores many different unit - # preferences, including separate units for for distance vs. speed. - # We use the speed preference for OP. - self.displayMetricUnits = not pt_cp.vl["Einheiten_01"]["KBI_MFA_v_Einheit_02"] - # Consume blind-spot monitoring info/warning LED states, if available. # Infostufe: BSM LED on, Warnung: BSM LED flashing if self.CP.enableBsm: @@ -97,56 +108,148 @@ class CarState(CarStateBase): ret.stockAeb = bool(ext_cp.vl["ACC_10"]["ANB_Teilbremsung_Freigabe"]) or bool(ext_cp.vl["ACC_10"]["ANB_Zielbremsung_Freigabe"]) # Update ACC radar status. - self.tsk_status = pt_cp.vl["TSK_06"]["TSK_Status"] - if self.tsk_status == 2: + self.acc_type = ext_cp.vl["ACC_06"]["ACC_Typ"] + if pt_cp.vl["TSK_06"]["TSK_Status"] == 2: # ACC okay and enabled, but not currently engaged ret.cruiseState.available = True ret.cruiseState.enabled = False - elif self.tsk_status in (3, 4, 5): - # ACC okay and enabled, currently regulating speed (3) or driver accel override (4) or overrun coast-down (5) + elif pt_cp.vl["TSK_06"]["TSK_Status"] in (3, 4, 5): + # ACC okay and enabled, currently regulating speed (3) or driver accel override (4) or brake only (5) ret.cruiseState.available = True ret.cruiseState.enabled = True else: # ACC okay but disabled (1), or a radar visibility or other fault/disruption (6 or 7) ret.cruiseState.available = False ret.cruiseState.enabled = False + self.esp_hold_confirmation = bool(pt_cp.vl["ESP_21"]["ESP_Haltebestaetigung"]) + ret.cruiseState.standstill = self.CP.pcmCruise and self.esp_hold_confirmation + ret.accFaulted = pt_cp.vl["TSK_06"]["TSK_Status"] in (6, 7) # Update ACC setpoint. When the setpoint is zero or there's an error, the # radar sends a set-speed of ~90.69 m/s / 203mph. if self.CP.pcmCruise: - ret.cruiseState.speed = ext_cp.vl["ACC_02"]["ACC_Wunschgeschw"] * CV.KPH_TO_MS + ret.cruiseState.speed = ext_cp.vl["ACC_02"]["ACC_Wunschgeschw_02"] * CV.KPH_TO_MS if ret.cruiseState.speed > 90: ret.cruiseState.speed = 0 - # Update control button states for turn signals and ACC controls. - self.buttonStates["accelCruise"] = bool(pt_cp.vl["GRA_ACC_01"]["GRA_Tip_Hoch"]) - self.buttonStates["decelCruise"] = bool(pt_cp.vl["GRA_ACC_01"]["GRA_Tip_Runter"]) - self.buttonStates["cancel"] = bool(pt_cp.vl["GRA_ACC_01"]["GRA_Abbrechen"]) - self.buttonStates["setCruise"] = bool(pt_cp.vl["GRA_ACC_01"]["GRA_Tip_Setzen"]) - self.buttonStates["resumeCruise"] = bool(pt_cp.vl["GRA_ACC_01"]["GRA_Tip_Wiederaufnahme"]) - self.buttonStates["gapAdjustCruise"] = bool(pt_cp.vl["GRA_ACC_01"]["GRA_Verstellung_Zeitluecke"]) + # Update button states for turn signals and ACC controls, capture all ACC button state/config for passthrough ret.leftBlinker = bool(pt_cp.vl["Blinkmodi_02"]["Comfort_Signal_Left"]) ret.rightBlinker = bool(pt_cp.vl["Blinkmodi_02"]["Comfort_Signal_Right"]) - - # Read ACC hardware button type configuration info that has to pass thru - # to the radar. Ends up being different for steering wheel buttons vs - # third stalk type controls. - self.graHauptschalter = pt_cp.vl["GRA_ACC_01"]["GRA_Hauptschalter"] - self.graTypHauptschalter = pt_cp.vl["GRA_ACC_01"]["GRA_Typ_Hauptschalter"] - self.graButtonTypeInfo = pt_cp.vl["GRA_ACC_01"]["GRA_ButtonTypeInfo"] - self.graTipStufe2 = pt_cp.vl["GRA_ACC_01"]["GRA_Tip_Stufe_2"] - # Pick up the GRA_ACC_01 CAN message counter so we can sync to it for - # later cruise-control button spamming. - self.graMsgBusCounter = pt_cp.vl["GRA_ACC_01"]["COUNTER"] + ret.buttonEvents = self.create_button_events(pt_cp, self.CCP.BUTTONS) + self.gra_stock_values = pt_cp.vl["GRA_ACC_01"] # Additional safety checks performed in CarInterface. - self.parkingBrakeSet = bool(pt_cp.vl["Kombi_01"]["KBI_Handbremse"]) # FIXME: need to include an EPB check as well ret.espDisabled = pt_cp.vl["ESP_21"]["ESP_Tastung_passiv"] != 0 return ret + def update_pq(self, pt_cp, cam_cp, ext_cp, trans_type): + ret = car.CarState.new_message() + # Update vehicle speed and acceleration from ABS wheel speeds. + ret.wheelSpeeds = self.get_wheel_speeds( + pt_cp.vl["Bremse_3"]["Radgeschw__VL_4_1"], + pt_cp.vl["Bremse_3"]["Radgeschw__VR_4_1"], + pt_cp.vl["Bremse_3"]["Radgeschw__HL_4_1"], + pt_cp.vl["Bremse_3"]["Radgeschw__HR_4_1"], + ) + + # vEgo obtained from Bremse_1 vehicle speed rather than Bremse_3 wheel speeds because Bremse_3 isn't present on NSF + ret.vEgoRaw = pt_cp.vl["Bremse_1"]["Geschwindigkeit_neu__Bremse_1_"] * CV.KPH_TO_MS + ret.vEgo, ret.aEgo = self.update_speed_kf(ret.vEgoRaw) + ret.standstill = ret.vEgo < 0.1 + + # Update steering angle, rate, yaw rate, and driver input torque. VW send + # the sign/direction in a separate signal so they must be recombined. + ret.steeringAngleDeg = pt_cp.vl["Lenkhilfe_3"]["LH3_BLW"] * (1, -1)[int(pt_cp.vl["Lenkhilfe_3"]["LH3_BLWSign"])] + ret.steeringRateDeg = pt_cp.vl["Lenkwinkel_1"]["Lenkradwinkel_Geschwindigkeit"] * (1, -1)[int(pt_cp.vl["Lenkwinkel_1"]["Lenkradwinkel_Geschwindigkeit_S"])] + ret.steeringTorque = pt_cp.vl["Lenkhilfe_3"]["LH3_LM"] * (1, -1)[int(pt_cp.vl["Lenkhilfe_3"]["LH3_LMSign"])] + ret.steeringPressed = abs(ret.steeringTorque) > self.CCP.STEER_DRIVER_ALLOWANCE + ret.yawRate = pt_cp.vl["Bremse_5"]["Giergeschwindigkeit"] * (1, -1)[int(pt_cp.vl["Bremse_5"]["Vorzeichen_der_Giergeschwindigk"])] * CV.DEG_TO_RAD + + # Verify EPS readiness to accept steering commands + hca_status = self.CCP.hca_status_values.get(pt_cp.vl["Lenkhilfe_2"]["LH2_Sta_HCA"]) + ret.steerFaultPermanent = hca_status in ("DISABLED", "FAULT") + ret.steerFaultTemporary = hca_status in ("INITIALIZING", "REJECTED") + + # Update gas, brakes, and gearshift. + ret.gas = pt_cp.vl["Motor_3"]["Fahrpedal_Rohsignal"] / 100.0 + ret.gasPressed = ret.gas > 0 + ret.brake = pt_cp.vl["Bremse_5"]["Bremsdruck"] / 250.0 # FIXME: this is pressure in Bar, not sure what OP expects + ret.brakePressed = bool(pt_cp.vl["Motor_2"]["Bremslichtschalter"]) + ret.parkingBrake = bool(pt_cp.vl["Kombi_1"]["Bremsinfo"]) + + # Update gear and/or clutch position data. + if trans_type == TransmissionType.automatic: + ret.gearShifter = self.parse_gear_shifter(self.CCP.shifter_values.get(pt_cp.vl["Getriebe_1"]["Waehlhebelposition__Getriebe_1_"], None)) + elif trans_type == TransmissionType.manual: + ret.clutchPressed = not pt_cp.vl["Motor_1"]["Kupplungsschalter"] + reverse_light = bool(pt_cp.vl["Gate_Komf_1"]["GK1_Rueckfahr"]) + if reverse_light: + ret.gearShifter = GearShifter.reverse + else: + ret.gearShifter = GearShifter.drive + + # Update door and trunk/hatch lid open status. + ret.doorOpen = any([pt_cp.vl["Gate_Komf_1"]["GK1_Fa_Tuerkont"], + pt_cp.vl["Gate_Komf_1"]["BSK_BT_geoeffnet"], + pt_cp.vl["Gate_Komf_1"]["BSK_HL_geoeffnet"], + pt_cp.vl["Gate_Komf_1"]["BSK_HR_geoeffnet"], + pt_cp.vl["Gate_Komf_1"]["BSK_HD_Hauptraste"]]) + + # Update seatbelt fastened status. + ret.seatbeltUnlatched = not bool(pt_cp.vl["Airbag_1"]["Gurtschalter_Fahrer"]) + + # Consume blind-spot monitoring info/warning LED states, if available. + # Infostufe: BSM LED on, Warnung: BSM LED flashing + if self.CP.enableBsm: + ret.leftBlindspot = bool(ext_cp.vl["SWA_1"]["SWA_Infostufe_SWA_li"]) or bool(ext_cp.vl["SWA_1"]["SWA_Warnung_SWA_li"]) + ret.rightBlindspot = bool(ext_cp.vl["SWA_1"]["SWA_Infostufe_SWA_re"]) or bool(ext_cp.vl["SWA_1"]["SWA_Warnung_SWA_re"]) + + # Consume factory LDW data relevant for factory SWA (Lane Change Assist) + # and capture it for forwarding to the blind spot radar controller + self.ldw_stock_values = cam_cp.vl["LDW_Status"] if self.CP.networkLocation == NetworkLocation.fwdCamera else {} + + # Stock FCW is considered active if the release bit for brake-jerk warning + # is set. Stock AEB considered active if the partial braking or target + # braking release bits are set. + # Refer to VW Self Study Program 890253: Volkswagen Driver Assistance + # Systems, chapters on Front Assist with Braking and City Emergency + # Braking for the 2016 Passat NMS + # TODO: deferred until we can collect data on pre-MY2016 behavior, AWV message may be shorter with fewer signals + ret.stockFcw = False + ret.stockAeb = False + + # Update ACC radar status. + self.acc_type = ext_cp.vl["ACC_System"]["ACS_Typ_ACC"] + ret.cruiseState.available = bool(pt_cp.vl["Motor_5"]["GRA_Hauptschalter"]) + ret.cruiseState.enabled = pt_cp.vl["Motor_2"]["GRA_Status"] in (1, 2) + if self.CP.pcmCruise: + ret.accFaulted = ext_cp.vl["ACC_GRA_Anziege"]["ACA_StaACC"] in (6, 7) + else: + ret.accFaulted = pt_cp.vl["Motor_2"]["GRA_Status"] == 3 + + # Update ACC setpoint. When the setpoint reads as 255, the driver has not + # yet established an ACC setpoint, so treat it as zero. + ret.cruiseState.speed = ext_cp.vl["ACC_GRA_Anziege"]["ACA_V_Wunsch"] * CV.KPH_TO_MS + if ret.cruiseState.speed > 70: # 255 kph in m/s == no current setpoint + ret.cruiseState.speed = 0 + + # Update button states for turn signals and ACC controls, capture all ACC button state/config for passthrough + ret.leftBlinker, ret.rightBlinker = self.update_blinker_from_stalk(300, pt_cp.vl["Gate_Komf_1"]["GK1_Blinker_li"], + pt_cp.vl["Gate_Komf_1"]["GK1_Blinker_re"]) + ret.buttonEvents = self.create_button_events(pt_cp, self.CCP.BUTTONS) + self.gra_stock_values = pt_cp.vl["GRA_Neu"] + + # Additional safety checks performed in CarInterface. + ret.espDisabled = bool(pt_cp.vl["Bremse_1"]["ESP_Passiv_getastet"]) + + return ret + @staticmethod def get_can_parser(CP): + if CP.carFingerprint in PQ_CARS: + return CarState.get_can_parser_pq(CP) + signals = [ # sig_name, sig_address ("LWI_Lenkradwinkel", "LWI_01"), # Absolute steering angle @@ -168,15 +271,15 @@ class CarState(CarStateBase): ("Comfort_Signal_Right", "Blinkmodi_02"), # Right turn signal including comfort blink interval ("AB_Gurtschloss_FA", "Airbag_02"), # Seatbelt status, driver ("AB_Gurtschloss_BF", "Airbag_02"), # Seatbelt status, passenger - ("ESP_Fahrer_bremst", "ESP_05"), # Brake pedal pressed - ("ESP_Bremsdruck", "ESP_05"), # Brake pressure applied + ("ESP_Fahrer_bremst", "ESP_05"), # Driver applied brake pressure over threshold + ("MO_Fahrer_bremst", "Motor_14"), # Brake pedal switch + ("ESP_Bremsdruck", "ESP_05"), # Brake pressure ("MO_Fahrpedalrohwert_01", "Motor_20"), # Accelerator pedal value ("EPS_Lenkmoment", "LH_EPS_03"), # Absolute driver torque input ("EPS_VZ_Lenkmoment", "LH_EPS_03"), # Driver torque input sign ("EPS_HCA_Status", "LH_EPS_03"), # EPS HCA control status ("ESP_Tastung_passiv", "ESP_21"), # Stability control disabled ("ESP_Haltebestaetigung", "ESP_21"), # ESP hold confirmation - ("KBI_MFA_v_Einheit_02", "Einheiten_01"), # MPH vs KMH speed display ("KBI_Handbremse", "Kombi_01"), # Manual handbrake applied ("TSK_Status", "TSK_06"), # ACC engagement status from drivetrain coordinator ("GRA_Hauptschalter", "GRA_ACC_01"), # ACC button, on/off @@ -187,6 +290,7 @@ class CarState(CarStateBase): ("GRA_Tip_Wiederaufnahme", "GRA_ACC_01"), # ACC button, resume ("GRA_Verstellung_Zeitluecke", "GRA_ACC_01"), # ACC button, time gap adj ("GRA_Typ_Hauptschalter", "GRA_ACC_01"), # ACC main button type + ("GRA_Codierung", "GRA_ACC_01"), # ACC button configuration/coding ("GRA_Tip_Stufe_2", "GRA_ACC_01"), # unknown related to stalk type ("GRA_ButtonTypeInfo", "GRA_ACC_01"), # unknown related to stalk type ("COUNTER", "GRA_ACC_01"), # GRA_ACC_01 CAN message counter @@ -204,10 +308,10 @@ class CarState(CarStateBase): ("ESP_02", 50), # From J104 ABS/ESP controller ("GRA_ACC_01", 33), # From J533 CAN gateway (via LIN from steering wheel controls) ("Gateway_72", 10), # From J533 CAN gateway (aggregated data) + ("Motor_14", 10), # From J623 Engine control module ("Airbag_02", 5), # From J234 Airbag control module ("Kombi_01", 2), # From J285 Instrument cluster ("Blinkmodi_02", 1), # From J519 BCM (sent at 1Hz when no lights active, 50Hz when active) - ("Einheiten_01", 1), # From J??? not known if gateway, cluster, or BCM ] if CP.transmissionType == TransmissionType.automatic: @@ -219,7 +323,6 @@ class CarState(CarStateBase): elif CP.transmissionType == TransmissionType.manual: signals += [("MO_Kuppl_schalter", "Motor_14"), # Clutch switch ("BCM1_Rueckfahrlicht_Schalter", "Gateway_72")] # Reverse light from BCM - checks.append(("Motor_14", 10)) # From J623 Engine control module if CP.networkLocation == NetworkLocation.fwdCamera: # Radars are here on CANBUS.pt @@ -229,10 +332,13 @@ class CarState(CarStateBase): signals += MqbExtraSignals.bsm_radar_signals checks += MqbExtraSignals.bsm_radar_checks - return CANParser(DBC_FILES.mqb, signals, checks, CANBUS.pt) + return CANParser(DBC[CP.carFingerprint]["pt"], signals, checks, CANBUS.pt) @staticmethod def get_cam_can_parser(CP): + if CP.carFingerprint in PQ_CARS: + return CarState.get_cam_can_parser_pq(CP) + signals = [] checks = [] @@ -257,19 +363,138 @@ class CarState(CarStateBase): signals += MqbExtraSignals.bsm_radar_signals checks += MqbExtraSignals.bsm_radar_checks - return CANParser(DBC_FILES.mqb, signals, checks, CANBUS.cam) + return CANParser(DBC[CP.carFingerprint]["pt"], signals, checks, CANBUS.cam) + + @staticmethod + def get_can_parser_pq(CP): + signals = [ + # sig_name, sig_address, default + ("LH3_BLW", "Lenkhilfe_3"), # Absolute steering angle + ("LH3_BLWSign", "Lenkhilfe_3"), # Steering angle sign + ("LH3_LM", "Lenkhilfe_3"), # Absolute driver torque input + ("LH3_LMSign", "Lenkhilfe_3"), # Driver torque input sign + ("LH2_Sta_HCA", "Lenkhilfe_2"), # Steering rack HCA status + ("Lenkradwinkel_Geschwindigkeit", "Lenkwinkel_1"), # Absolute steering rate + ("Lenkradwinkel_Geschwindigkeit_S", "Lenkwinkel_1"), # Steering rate sign + ("Geschwindigkeit_neu__Bremse_1_", "Bremse_1"), # Vehicle speed from ABS + ("Radgeschw__VL_4_1", "Bremse_3"), # ABS wheel speed, front left + ("Radgeschw__VR_4_1", "Bremse_3"), # ABS wheel speed, front right + ("Radgeschw__HL_4_1", "Bremse_3"), # ABS wheel speed, rear left + ("Radgeschw__HR_4_1", "Bremse_3"), # ABS wheel speed, rear right + ("Giergeschwindigkeit", "Bremse_5"), # Absolute yaw rate + ("Vorzeichen_der_Giergeschwindigk", "Bremse_5"), # Yaw rate sign + ("Gurtschalter_Fahrer", "Airbag_1"), # Seatbelt status, driver + ("Gurtschalter_Beifahrer", "Airbag_1"), # Seatbelt status, passenger + ("Bremstestschalter", "Motor_2"), # Brake pedal pressed (brake light test switch) + ("Bremslichtschalter", "Motor_2"), # Brakes applied (brake light switch) + ("Bremsdruck", "Bremse_5"), # Brake pressure applied + ("Vorzeichen_Bremsdruck", "Bremse_5"), # Brake pressure applied sign (???) + ("Fahrpedal_Rohsignal", "Motor_3"), # Accelerator pedal value + ("ESP_Passiv_getastet", "Bremse_1"), # Stability control disabled + ("GRA_Hauptschalter", "Motor_5"), # ACC main switch + ("GRA_Status", "Motor_2"), # ACC engagement status + ("GK1_Fa_Tuerkont", "Gate_Komf_1"), # Door open, driver + ("BSK_BT_geoeffnet", "Gate_Komf_1"), # Door open, passenger + ("BSK_HL_geoeffnet", "Gate_Komf_1"), # Door open, rear left + ("BSK_HR_geoeffnet", "Gate_Komf_1"), # Door open, rear right + ("BSK_HD_Hauptraste", "Gate_Komf_1"), # Trunk or hatch open + ("GK1_Blinker_li", "Gate_Komf_1"), # Left turn signal on + ("GK1_Blinker_re", "Gate_Komf_1"), # Right turn signal on + ("Bremsinfo", "Kombi_1"), # Manual handbrake applied + ("GRA_Hauptschalt", "GRA_Neu"), # ACC button, on/off + ("GRA_Typ_Hauptschalt", "GRA_Neu"), # ACC button, momentary vs latching + ("GRA_Kodierinfo", "GRA_Neu"), # ACC button, configuration + ("GRA_Abbrechen", "GRA_Neu"), # ACC button, cancel + ("GRA_Neu_Setzen", "GRA_Neu"), # ACC button, set + ("GRA_Up_lang", "GRA_Neu"), # ACC button, increase or accel, long press + ("GRA_Down_lang", "GRA_Neu"), # ACC button, decrease or decel, long press + ("GRA_Up_kurz", "GRA_Neu"), # ACC button, increase or accel, short press + ("GRA_Down_kurz", "GRA_Neu"), # ACC button, decrease or decel, short press + ("GRA_Recall", "GRA_Neu"), # ACC button, resume + ("GRA_Zeitluecke", "GRA_Neu"), # ACC button, time gap adj + ("COUNTER", "GRA_Neu"), # ACC button, message counter + ("GRA_Sender", "GRA_Neu"), # ACC button, CAN message originator + ] + + checks = [ + # sig_address, frequency + ("Bremse_1", 100), # From J104 ABS/ESP controller + ("Bremse_3", 100), # From J104 ABS/ESP controller + ("Lenkhilfe_3", 100), # From J500 Steering Assist with integrated sensors + ("Lenkwinkel_1", 100), # From J500 Steering Assist with integrated sensors + ("Motor_3", 100), # From J623 Engine control module + ("Airbag_1", 50), # From J234 Airbag control module + ("Bremse_5", 50), # From J104 ABS/ESP controller + ("GRA_Neu", 50), # From J??? steering wheel control buttons + ("Kombi_1", 50), # From J285 Instrument cluster + ("Motor_2", 50), # From J623 Engine control module + ("Motor_5", 50), # From J623 Engine control module + ("Lenkhilfe_2", 20), # From J500 Steering Assist with integrated sensors + ("Gate_Komf_1", 10), # From J533 CAN gateway + ] + + if CP.transmissionType == TransmissionType.automatic: + signals += [("Waehlhebelposition__Getriebe_1_", "Getriebe_1", 0)] # Auto trans gear selector position + checks += [("Getriebe_1", 100)] # From J743 Auto transmission control module + elif CP.transmissionType == TransmissionType.manual: + signals += [("Kupplungsschalter", "Motor_1", 0), # Clutch switch + ("GK1_Rueckfahr", "Gate_Komf_1", 0)] # Reverse light from BCM + checks += [("Motor_1", 100)] # From J623 Engine control module + + if CP.networkLocation == NetworkLocation.fwdCamera: + # Extended CAN devices other than the camera are here on CANBUS.pt + signals += PqExtraSignals.fwd_radar_signals + checks += PqExtraSignals.fwd_radar_checks + if CP.enableBsm: + signals += PqExtraSignals.bsm_radar_signals + checks += PqExtraSignals.bsm_radar_checks + + return CANParser(DBC[CP.carFingerprint]["pt"], signals, checks, CANBUS.pt) + + @staticmethod + def get_cam_can_parser_pq(CP): + + signals = [] + checks = [] + + if CP.networkLocation == NetworkLocation.fwdCamera: + signals += [ + # sig_name, sig_address + ("LDW_SW_Warnung_links", "LDW_Status"), # Blind spot in warning mode on left side due to lane departure + ("LDW_SW_Warnung_rechts", "LDW_Status"), # Blind spot in warning mode on right side due to lane departure + ("LDW_Seite_DLCTLC", "LDW_Status"), # Direction of most likely lane departure (left or right) + ("LDW_DLC", "LDW_Status"), # Lane departure, distance to line crossing + ("LDW_TLC", "LDW_Status"), # Lane departure, time to line crossing + ] + checks += [ + # sig_address, frequency + ("LDW_Status", 10) # From R242 Driver assistance camera + ] + + if CP.networkLocation == NetworkLocation.gateway: + # Radars are here on CANBUS.cam + signals += PqExtraSignals.fwd_radar_signals + checks += PqExtraSignals.fwd_radar_checks + if CP.enableBsm: + signals += PqExtraSignals.bsm_radar_signals + checks += PqExtraSignals.bsm_radar_checks + + return CANParser(DBC[CP.carFingerprint]["pt"], signals, checks, CANBUS.cam) + class MqbExtraSignals: # Additional signal and message lists for optional or bus-portable controllers fwd_radar_signals = [ - ("ACC_Wunschgeschw", "ACC_02"), # ACC set speed + ("ACC_Wunschgeschw_02", "ACC_02"), # ACC set speed + ("ACC_Typ", "ACC_06"), # Basic vs FtS vs SnG ("AWV2_Freigabe", "ACC_10"), # FCW brake jerk release ("ANB_Teilbremsung_Freigabe", "ACC_10"), # AEB partial braking release ("ANB_Zielbremsung_Freigabe", "ACC_10"), # AEB target braking release ] fwd_radar_checks = [ - ("ACC_10", 50), # From J428 ACC radar control module - ("ACC_02", 17), # From J428 ACC radar control module + ("ACC_06", 50), # From J428 ACC radar control module + ("ACC_10", 50), # From J428 ACC radar control module + ("ACC_02", 17), # From J428 ACC radar control module ] bsm_radar_signals = [ ("SWA_Infostufe_SWA_li", "SWA_01"), # Blind spot object info, left @@ -278,5 +503,26 @@ class MqbExtraSignals: ("SWA_Warnung_SWA_re", "SWA_01"), # Blind spot object warning, right ] bsm_radar_checks = [ - ("SWA_01", 20), # From J1086 Lane Change Assist + ("SWA_01", 20), # From J1086 Lane Change Assist + ] + +class PqExtraSignals: + # Additional signal and message lists for optional or bus-portable controllers + fwd_radar_signals = [ + ("ACS_Typ_ACC", "ACC_System"), # Basic vs FtS (no SnG support on PQ) + ("ACA_StaACC", "ACC_GRA_Anziege"), # ACC drivetrain coordinator status + ("ACA_V_Wunsch", "ACC_GRA_Anziege"), # ACC set speed + ] + fwd_radar_checks = [ + ("ACC_System", 50), # From J428 ACC radar control module + ("ACC_GRA_Anziege", 25), # From J428 ACC radar control module + ] + bsm_radar_signals = [ + ("SWA_Infostufe_SWA_li", "SWA_1"), # Blind spot object info, left + ("SWA_Warnung_SWA_li", "SWA_1"), # Blind spot object warning, left + ("SWA_Infostufe_SWA_re", "SWA_1"), # Blind spot object info, right + ("SWA_Warnung_SWA_re", "SWA_1"), # Blind spot object warning, right + ] + bsm_radar_checks = [ + ("SWA_1", 20), # From J1086 Lane Change Assist ] diff --git a/selfdrive/car/volkswagen/interface.py b/selfdrive/car/volkswagen/interface.py index 961cfed7fe..da0ce25afa 100644 --- a/selfdrive/car/volkswagen/interface.py +++ b/selfdrive/car/volkswagen/interface.py @@ -1,8 +1,11 @@ from cereal import car -from selfdrive.car.volkswagen.values import CAR, BUTTON_STATES, CANBUS, NetworkLocation, TransmissionType, GearShifter -from selfdrive.car import STD_CARGO_KG, scale_rot_inertia, scale_tire_stiffness, gen_empty_fingerprint, get_safety_config +from panda import Panda +from common.conversions import Conversions as CV +from selfdrive.car import STD_CARGO_KG, get_safety_config from selfdrive.car.interfaces import CarInterfaceBase +from selfdrive.car.volkswagen.values import CAR, PQ_CARS, CANBUS, NetworkLocation, TransmissionType, GearShifter +ButtonType = car.CarState.ButtonEvent.Type EventName = car.CarEvent.EventName @@ -10,9 +13,6 @@ class CarInterface(CarInterfaceBase): def __init__(self, CP, CarController, CarState): super().__init__(CP, CarController, CarState) - self.displayMetricUnitsPrev = None - self.buttonStatesPrev = BUTTON_STATES.copy() - if CP.networkLocation == NetworkLocation.fwdCamera: self.ext_bus = CANBUS.pt self.cp_ext = self.cp @@ -21,17 +21,41 @@ class CarInterface(CarInterfaceBase): self.cp_ext = self.cp_cam @staticmethod - def get_params(candidate, fingerprint=gen_empty_fingerprint(), car_fw=None): - ret = CarInterfaceBase.get_std_params(candidate, fingerprint) + def _get_params(ret, candidate, fingerprint, car_fw, experimental_long): ret.carName = "volkswagen" ret.radarOffCan = True - if True: # pylint: disable=using-constant-test + use_off_car_defaults = len(fingerprint[0]) == 0 # Pick sensible carParams during offline doc generation/CI jobs + + if candidate in PQ_CARS: + # Set global PQ35/PQ46/NMS parameters + ret.safetyConfigs = [get_safety_config(car.CarParams.SafetyModel.volkswagenPq)] + ret.enableBsm = 0x3BA in fingerprint[0] # SWA_1 + + if 0x440 in fingerprint[0] or use_off_car_defaults: # Getriebe_1 + ret.transmissionType = TransmissionType.automatic + else: + ret.transmissionType = TransmissionType.manual + + if any(msg in fingerprint[1] for msg in (0x1A0, 0xC2)): # Bremse_1, Lenkwinkel_1 + ret.networkLocation = NetworkLocation.gateway + else: + ret.networkLocation = NetworkLocation.fwdCamera + + # The PQ port is in dashcam-only mode due to a fixed six-minute maximum timer on HCA steering. An unsupported + # EPS flash update to work around this timer, and enable steering down to zero, is available from: + # https://github.com/pd0wm/pq-flasher + # It is documented in a four-part blog series: + # https://blog.willemmelching.nl/carhacking/2022/01/02/vw-part1/ + # Panda ALLOW_DEBUG firmware required. + ret.dashcamOnly = True + + else: # Set global MQB parameters ret.safetyConfigs = [get_safety_config(car.CarParams.SafetyModel.volkswagen)] ret.enableBsm = 0x30F in fingerprint[0] # SWA_01 - if 0xAD in fingerprint[0]: # Getriebe_11 + if 0xAD in fingerprint[0] or use_off_car_defaults: # Getriebe_11 ret.transmissionType = TransmissionType.automatic elif 0x187 in fingerprint[0]: # EV_Gearshift ret.transmissionType = TransmissionType.direct @@ -46,16 +70,33 @@ class CarInterface(CarInterfaceBase): # Global lateral tuning defaults, can be overridden per-vehicle ret.steerActuatorDelay = 0.1 - ret.steerRateCost = 1.0 ret.steerLimitTimer = 0.4 ret.steerRatio = 15.6 # Let the params learner figure this out - tire_stiffness_factor = 1.0 # Let the params learner figure this out ret.lateralTuning.pid.kpBP = [0.] ret.lateralTuning.pid.kiBP = [0.] ret.lateralTuning.pid.kf = 0.00006 ret.lateralTuning.pid.kpV = [0.6] ret.lateralTuning.pid.kiV = [0.2] + # Global longitudinal tuning defaults, can be overridden per-vehicle + + ret.experimentalLongitudinalAvailable = ret.networkLocation == NetworkLocation.gateway or use_off_car_defaults + if experimental_long: + # Proof-of-concept, prep for E2E only. No radar points available. Panda ALLOW_DEBUG firmware required. + ret.openpilotLongitudinalControl = True + ret.safetyConfigs[0].safetyParam |= Panda.FLAG_VOLKSWAGEN_LONG_CONTROL + if ret.transmissionType == TransmissionType.manual: + ret.minEnableSpeed = 4.5 + + ret.pcmCruise = not ret.openpilotLongitudinalControl + ret.stoppingControl = True + ret.startingState = True + ret.startAccel = 1.0 + ret.vEgoStarting = 1.0 + ret.vEgoStopping = 1.0 + ret.longitudinalTuning.kpV = [0.1] + ret.longitudinalTuning.kiV = [0.0] + # Per-chassis tuning values, override tuning defaults here if desired if candidate == CAR.ARTEON_MK1: @@ -78,10 +119,24 @@ class CarInterface(CarInterfaceBase): ret.mass = 1551 + STD_CARGO_KG ret.wheelbase = 2.79 + elif candidate == CAR.PASSAT_NMS: + ret.mass = 1503 + STD_CARGO_KG + ret.wheelbase = 2.80 + ret.minEnableSpeed = 20 * CV.KPH_TO_MS # ACC "basic", no FtS + ret.minSteerSpeed = 50 * CV.KPH_TO_MS + ret.steerActuatorDelay = 0.2 + CarInterfaceBase.configure_torque_tune(candidate, ret.lateralTuning) + elif candidate == CAR.POLO_MK6: ret.mass = 1230 + STD_CARGO_KG ret.wheelbase = 2.55 + elif candidate == CAR.SHARAN_MK2: + ret.mass = 1639 + STD_CARGO_KG + ret.wheelbase = 2.92 + ret.minSteerSpeed = 50 * CV.KPH_TO_MS + ret.steerActuatorDelay = 0.2 + elif candidate == CAR.TAOS_MK1: ret.mass = 1498 + STD_CARGO_KG ret.wheelbase = 2.69 @@ -154,42 +209,17 @@ class CarInterface(CarInterfaceBase): else: raise ValueError(f"unsupported car {candidate}") - ret.rotationalInertia = scale_rot_inertia(ret.mass, ret.wheelbase) + ret.autoResumeSng = ret.minEnableSpeed == -1 ret.centerToFront = ret.wheelbase * 0.45 - ret.tireStiffnessFront, ret.tireStiffnessRear = scale_tire_stiffness(ret.mass, ret.wheelbase, ret.centerToFront, - tire_stiffness_factor=tire_stiffness_factor) return ret # returns a car.CarState - def update(self, c, can_strings): - buttonEvents = [] - - # Process the most recent CAN message traffic, and check for validity - # The camera CAN has no signals we use at this time, but we process it - # anyway so we can test connectivity with can_valid - self.cp.update_strings(can_strings) - self.cp_cam.update_strings(can_strings) - + def _update(self, c): ret = self.CS.update(self.cp, self.cp_cam, self.cp_ext, self.CP.transmissionType) - ret.canValid = self.cp.can_valid and self.cp_cam.can_valid - ret.steeringRateLimited = self.CC.steer_rate_limited if self.CC is not None else False - - # Check for and process state-change events (button press or release) from - # the turn stalk switch or ACC steering wheel/control stalk buttons. - for button in self.CS.buttonStates: - if self.CS.buttonStates[button] != self.buttonStatesPrev[button]: - be = car.CarState.ButtonEvent.new_message() - be.type = button - be.pressed = self.CS.buttonStates[button] - buttonEvents.append(be) - - events = self.create_common_events(ret, extra_gears=[GearShifter.eco, GearShifter.sport, GearShifter.manumatic]) - - # Vehicle health and operation safety checks - if self.CS.parkingBrakeSet: - events.add(EventName.parkBrake) - if self.CS.tsk_status in (6, 7): - events.add(EventName.accFaulted) + + events = self.create_common_events(ret, extra_gears=[GearShifter.eco, GearShifter.sport, GearShifter.manumatic], + pcm_enable=not self.CS.CP.openpilotLongitudinalControl, + enable_buttons=(ButtonType.setCruise, ButtonType.resumeCruise)) # Low speed steer alert hysteresis logic if self.CP.minSteerSpeed > 0. and ret.vEgo < (self.CP.minSteerSpeed + 1.): @@ -199,23 +229,15 @@ class CarInterface(CarInterfaceBase): if self.low_speed_alert: events.add(EventName.belowSteerSpeed) - ret.events = events.to_msg() - ret.buttonEvents = buttonEvents + if self.CS.CP.openpilotLongitudinalControl: + if ret.vEgo < self.CP.minEnableSpeed + 0.5: + events.add(EventName.belowEngageSpeed) + if c.enabled and ret.vEgo < self.CP.minEnableSpeed: + events.add(EventName.speedTooLow) - # update previous car states - self.displayMetricUnitsPrev = self.CS.displayMetricUnits - self.buttonStatesPrev = self.CS.buttonStates.copy() + ret.events = events.to_msg() - self.CS.out = ret.as_reader() - return self.CS.out + return ret def apply(self, c): - hud_control = c.hudControl - ret = self.CC.update(c, c.enabled, self.CS, self.frame, self.ext_bus, c.actuators, - hud_control.visualAlert, - hud_control.leftLaneVisible, - hud_control.rightLaneVisible, - hud_control.leftLaneDepart, - hud_control.rightLaneDepart) - self.frame += 1 - return ret + return self.CC.update(c, self.CS, self.ext_bus) diff --git a/selfdrive/car/volkswagen/mqbcan.py b/selfdrive/car/volkswagen/mqbcan.py new file mode 100644 index 0000000000..25a710dbb8 --- /dev/null +++ b/selfdrive/car/volkswagen/mqbcan.py @@ -0,0 +1,108 @@ +def create_steering_control(packer, bus, apply_steer, lkas_enabled): + values = { + "SET_ME_0X3": 0x3, + "Assist_Torque": abs(apply_steer), + "Assist_Requested": lkas_enabled, + "Assist_VZ": 1 if apply_steer < 0 else 0, + "HCA_Available": 1, + "HCA_Standby": not lkas_enabled, + "HCA_Active": lkas_enabled, + "SET_ME_0XFE": 0xFE, + "SET_ME_0X07": 0x07, + } + return packer.make_can_msg("HCA_01", bus, values) + + +def create_lka_hud_control(packer, bus, ldw_stock_values, enabled, steering_pressed, hud_alert, hud_control): + values = ldw_stock_values.copy() + + values.update({ + "LDW_Status_LED_gelb": 1 if enabled and steering_pressed else 0, + "LDW_Status_LED_gruen": 1 if enabled and not steering_pressed else 0, + "LDW_Lernmodus_links": 3 if hud_control.leftLaneDepart else 1 + hud_control.leftLaneVisible, + "LDW_Lernmodus_rechts": 3 if hud_control.rightLaneDepart else 1 + hud_control.rightLaneVisible, + "LDW_Texte": hud_alert, + }) + return packer.make_can_msg("LDW_02", bus, values) + + +def create_acc_buttons_control(packer, bus, gra_stock_values, counter, cancel=False, resume=False): + values = gra_stock_values.copy() + + values.update({ + "COUNTER": counter, + "GRA_Abbrechen": cancel, + "GRA_Tip_Wiederaufnahme": resume, + }) + + return packer.make_can_msg("GRA_ACC_01", bus, values) + + +def acc_control_value(main_switch_on, acc_faulted, long_active): + if acc_faulted: + acc_control = 6 + elif long_active: + acc_control = 3 + elif main_switch_on: + acc_control = 2 + else: + acc_control = 0 + + return acc_control + + +def acc_hud_status_value(main_switch_on, acc_faulted, long_active): + # TODO: happens to resemble the ACC control value for now, but extend this for init/gas override later + return acc_control_value(main_switch_on, acc_faulted, long_active) + + +def create_acc_accel_control(packer, bus, acc_type, enabled, accel, acc_control, stopping, starting, esp_hold): + commands = [] + + acc_06_values = { + "ACC_Typ": acc_type, + "ACC_Status_ACC": acc_control, + "ACC_StartStopp_Info": enabled, + "ACC_Sollbeschleunigung_02": accel if enabled else 3.01, + "ACC_zul_Regelabw_unten": 0.2, # TODO: dynamic adjustment of comfort-band + "ACC_zul_Regelabw_oben": 0.2, # TODO: dynamic adjustment of comfort-band + "ACC_neg_Sollbeschl_Grad_02": 4.0 if enabled else 0, # TODO: dynamic adjustment of jerk limits + "ACC_pos_Sollbeschl_Grad_02": 4.0 if enabled else 0, # TODO: dynamic adjustment of jerk limits + "ACC_Anfahren": starting, + "ACC_Anhalten": stopping, + } + commands.append(packer.make_can_msg("ACC_06", bus, acc_06_values)) + + if starting: + acc_hold_type = 4 # hold release / startup + elif esp_hold: + acc_hold_type = 3 # hold standby + elif stopping: + acc_hold_type = 1 # hold request + else: + acc_hold_type = 0 + + acc_07_values = { + "ACC_Anhalteweg": 0.75 if stopping else 20.46, # Distance to stop (stopping coordinator handles terminal roll-out) + "ACC_Freilauf_Info": 2 if enabled else 0, + "ACC_Folgebeschl": 3.02, # Not using secondary controller accel unless and until we understand its impact + "ACC_Sollbeschleunigung_02": accel if enabled else 3.01, + "ACC_Anforderung_HMS": acc_hold_type, + "ACC_Anfahren": starting, + "ACC_Anhalten": stopping, + } + commands.append(packer.make_can_msg("ACC_07", bus, acc_07_values)) + + return commands + + +def create_acc_hud_control(packer, bus, acc_hud_status, set_speed, lead_visible): + values = { + "ACC_Status_Anzeige": acc_hud_status, + "ACC_Wunschgeschw_02": set_speed if set_speed < 250 else 327.36, + "ACC_Gesetzte_Zeitluecke": 3, + "ACC_Display_Prio": 3, + # TODO: ACC_Abstandsindex for lead car distance, must determine analog vs digital cluster for scaling + } + + return packer.make_can_msg("ACC_02", bus, values) diff --git a/selfdrive/car/volkswagen/pqcan.py b/selfdrive/car/volkswagen/pqcan.py new file mode 100644 index 0000000000..6beb90c092 --- /dev/null +++ b/selfdrive/car/volkswagen/pqcan.py @@ -0,0 +1,91 @@ +def create_steering_control(packer, bus, apply_steer, lkas_enabled): + values = { + "LM_Offset": abs(apply_steer), + "LM_OffSign": 1 if apply_steer < 0 else 0, + "HCA_Status": 5 if (lkas_enabled and apply_steer != 0) else 3, + "Vib_Freq": 16, + } + + return packer.make_can_msg("HCA_1", bus, values) + + +def create_lka_hud_control(packer, bus, ldw_stock_values, enabled, steering_pressed, hud_alert, hud_control): + values = ldw_stock_values.copy() + + values.update({ + "LDW_Lampe_gelb": 1 if enabled and steering_pressed else 0, + "LDW_Lampe_gruen": 1 if enabled and not steering_pressed else 0, + "LDW_Lernmodus_links": 3 if hud_control.leftLaneDepart else 1 + hud_control.leftLaneVisible, + "LDW_Lernmodus_rechts": 3 if hud_control.rightLaneDepart else 1 + hud_control.rightLaneVisible, + "LDW_Textbits": hud_alert, + }) + + return packer.make_can_msg("LDW_Status", bus, values) + + +def create_acc_buttons_control(packer, bus, gra_stock_values, counter, cancel=False, resume=False): + values = gra_stock_values.copy() + + values.update({ + "COUNTER": counter, + "GRA_Abbrechen": cancel, + "GRA_Recall": resume, + }) + + return packer.make_can_msg("GRA_Neu", bus, values) + + +def acc_control_value(main_switch_on, acc_faulted, long_active): + if long_active: + acc_control = 1 + elif main_switch_on: + acc_control = 2 + else: + acc_control = 0 + + return acc_control + + +def acc_hud_status_value(main_switch_on, acc_faulted, long_active): + if acc_faulted: + hud_status = 6 + elif long_active: + hud_status = 3 + elif main_switch_on: + hud_status = 2 + else: + hud_status = 0 + + return hud_status + + +def create_acc_accel_control(packer, bus, acc_type, enabled, accel, acc_control, stopping, starting, esp_hold): + commands = [] + + values = { + "ACS_Sta_ADR": acc_control, + "ACS_StSt_Info": acc_control != 1, + "ACS_Typ_ACC": acc_type, + "ACS_Anhaltewunsch": acc_type == 1 and stopping, + "ACS_Sollbeschl": accel if acc_control == 1 else 3.01, + "ACS_zul_Regelabw": 0.2 if acc_control == 1 else 1.27, + "ACS_max_AendGrad": 3.0 if acc_control == 1 else 5.08, + } + + commands.append(packer.make_can_msg("ACC_System", bus, values)) + + return commands + + +def create_acc_hud_control(packer, bus, acc_hud_status, set_speed, lead_visible): + values = { + "ACA_StaACC": acc_hud_status, + "ACA_Zeitluecke": 2, + "ACA_V_Wunsch": set_speed, + "ACA_gemZeitl": 8 if lead_visible else 0, + # TODO: ACA_ID_StaACC, ACA_AnzDisplay, ACA_kmh_mph, ACA_PrioDisp, ACA_Aend_Zeitluecke + # display/display-prio handling probably needed to stop confusing the instrument cluster + # kmh_mph handling probably needed to resolve rounding errors in displayed setpoint + } + + return packer.make_can_msg("ACC_GRA_Anziege", bus, values) diff --git a/selfdrive/car/volkswagen/values.py b/selfdrive/car/volkswagen/values.py index 241338c2c5..18a444bf7c 100755 --- a/selfdrive/car/volkswagen/values.py +++ b/selfdrive/car/volkswagen/values.py @@ -1,61 +1,107 @@ -from collections import defaultdict -from typing import Dict +from collections import defaultdict, namedtuple +from dataclasses import dataclass +from enum import Enum +from typing import Dict, List, Union from cereal import car +from panda.python import uds +from opendbc.can.can_define import CANDefine from selfdrive.car import dbc_dict +from selfdrive.car.docs_definitions import CarFootnote, CarInfo, Column, Harness +from selfdrive.car.fw_query_definitions import FwQueryConfig, Request, p16 Ecu = car.CarParams.Ecu NetworkLocation = car.CarParams.NetworkLocation TransmissionType = car.CarParams.TransmissionType GearShifter = car.CarState.GearShifter +Button = namedtuple('Button', ['event_type', 'can_addr', 'can_msg', 'values']) + class CarControllerParams: - HCA_STEP = 2 # HCA_01 message frequency 50Hz - LDW_STEP = 10 # LDW_02 message frequency 10Hz - GRA_ACC_STEP = 3 # GRA_ACC_01 message frequency 33Hz - - GRA_VBP_STEP = 100 # Send ACC virtual button presses once a second - GRA_VBP_COUNT = 16 # Send VBP messages for ~0.5s (GRA_ACC_STEP * 16) - - # Observed documented MQB limits: 3.00 Nm max, rate of change 5.00 Nm/sec. - # Limiting rate-of-change based on real-world testing and Comma's safety - # requirements for minimum time to lane departure. - STEER_MAX = 300 # Max heading control assist torque 3.00 Nm - STEER_DELTA_UP = 4 # Max HCA reached in 1.50s (STEER_MAX / (50Hz * 1.50)) - STEER_DELTA_DOWN = 10 # Min HCA reached in 0.60s (STEER_MAX / (50Hz * 0.60)) - STEER_DRIVER_ALLOWANCE = 80 - STEER_DRIVER_MULTIPLIER = 3 # weight driver torque heavily - STEER_DRIVER_FACTOR = 1 # from dbc + HCA_STEP = 2 # HCA_01/HCA_1 message frequency 50Hz + ACC_CONTROL_STEP = 2 # ACC_06/ACC_07/ACC_System frequency 50Hz -class CANBUS: - pt = 0 - cam = 2 + ACCEL_MAX = 2.0 # 2.0 m/s max acceleration + ACCEL_MIN = -3.5 # 3.5 m/s max deceleration -class DBC_FILES: - mqb = "vw_mqb_2010" # Used for all cars with MQB-style CAN messaging + def __init__(self, CP): + # Documented lateral limits: 3.00 Nm max, rate of change 5.00 Nm/sec. + # MQB vs PQ maximums are shared, but rate-of-change limited differently + # based on safety requirements driven by lateral accel testing. + self.STEER_MAX = 300 # Max heading control assist torque 3.00 Nm + self.STEER_DRIVER_MULTIPLIER = 3 # weight driver torque heavily + self.STEER_DRIVER_FACTOR = 1 # from dbc -DBC = defaultdict(lambda: dbc_dict(DBC_FILES.mqb, None)) # type: Dict[str, Dict[str, str]] + can_define = CANDefine(DBC[CP.carFingerprint]["pt"]) -BUTTON_STATES = { - "accelCruise": False, - "decelCruise": False, - "cancel": False, - "setCruise": False, - "resumeCruise": False, - "gapAdjustCruise": False -} + if CP.carFingerprint in PQ_CARS: + self.LDW_STEP = 5 # LDW_1 message frequency 20Hz + self.ACC_HUD_STEP = 4 # ACC_GRA_Anziege frequency 25Hz + self.STEER_DRIVER_ALLOWANCE = 80 # Driver intervention threshold 0.8 Nm + self.STEER_DELTA_UP = 6 # Max HCA reached in 1.00s (STEER_MAX / (50Hz * 1.00)) + self.STEER_DELTA_DOWN = 10 # Min HCA reached in 0.60s (STEER_MAX / (50Hz * 0.60)) + + if CP.transmissionType == TransmissionType.automatic: + self.shifter_values = can_define.dv["Getriebe_1"]["Waehlhebelposition__Getriebe_1_"] + self.hca_status_values = can_define.dv["Lenkhilfe_2"]["LH2_Sta_HCA"] + + self.BUTTONS = [ + Button(car.CarState.ButtonEvent.Type.setCruise, "GRA_Neu", "GRA_Neu_Setzen", [1]), + Button(car.CarState.ButtonEvent.Type.resumeCruise, "GRA_Neu", "GRA_Recall", [1]), + Button(car.CarState.ButtonEvent.Type.accelCruise, "GRA_Neu", "GRA_Up_kurz", [1]), + Button(car.CarState.ButtonEvent.Type.decelCruise, "GRA_Neu", "GRA_Down_kurz", [1]), + Button(car.CarState.ButtonEvent.Type.cancel, "GRA_Neu", "GRA_Abbrechen", [1]), + Button(car.CarState.ButtonEvent.Type.gapAdjustCruise, "GRA_Neu", "GRA_Zeitluecke", [1]), + ] + + self.LDW_MESSAGES = { + "none": 0, # Nothing to display + "laneAssistUnavail": 1, # "Lane Assist currently not available." + "laneAssistUnavailSysError": 2, # "Lane Assist system error" + "laneAssistUnavailNoSensorView": 3, # "Lane Assist not available. No sensor view." + "laneAssistTakeOver": 4, # "Lane Assist: Please Take Over Steering" + "laneAssistDeactivTrailer": 5, # "Lane Assist: no function with trailer" + } + + else: + self.LDW_STEP = 10 # LDW_02 message frequency 10Hz + self.ACC_HUD_STEP = 6 # ACC_02 message frequency 16Hz + self.STEER_DRIVER_ALLOWANCE = 80 # Driver intervention threshold 0.8 Nm + self.STEER_DELTA_UP = 4 # Max HCA reached in 1.50s (STEER_MAX / (50Hz * 1.50)) + self.STEER_DELTA_DOWN = 10 # Min HCA reached in 0.60s (STEER_MAX / (50Hz * 0.60)) + + if CP.transmissionType == TransmissionType.automatic: + self.shifter_values = can_define.dv["Getriebe_11"]["GE_Fahrstufe"] + elif CP.transmissionType == TransmissionType.direct: + self.shifter_values = can_define.dv["EV_Gearshift"]["GearPosition"] + self.hca_status_values = can_define.dv["LH_EPS_03"]["EPS_HCA_Status"] + + self.BUTTONS = [ + Button(car.CarState.ButtonEvent.Type.setCruise, "GRA_ACC_01", "GRA_Tip_Setzen", [1]), + Button(car.CarState.ButtonEvent.Type.resumeCruise, "GRA_ACC_01", "GRA_Tip_Wiederaufnahme", [1]), + Button(car.CarState.ButtonEvent.Type.accelCruise, "GRA_ACC_01", "GRA_Tip_Hoch", [1]), + Button(car.CarState.ButtonEvent.Type.decelCruise, "GRA_ACC_01", "GRA_Tip_Runter", [1]), + Button(car.CarState.ButtonEvent.Type.cancel, "GRA_ACC_01", "GRA_Abbrechen", [1]), + Button(car.CarState.ButtonEvent.Type.gapAdjustCruise, "GRA_ACC_01", "GRA_Verstellung_Zeitluecke", [1]), + ] + + self.LDW_MESSAGES = { + "none": 0, # Nothing to display + "laneAssistUnavailChime": 1, # "Lane Assist currently not available." with chime + "laneAssistUnavailNoSensorChime": 3, # "Lane Assist not available. No sensor view." with chime + "laneAssistTakeOverUrgent": 4, # "Lane Assist: Please Take Over Steering" with urgent beep + "emergencyAssistUrgent": 6, # "Emergency Assist: Please Take Over Steering" with urgent beep + "laneAssistTakeOverChime": 7, # "Lane Assist: Please Take Over Steering" with chime + "laneAssistTakeOver": 8, # "Lane Assist: Please Take Over Steering" silent + "emergencyAssistChangingLanes": 9, # "Emergency Assist: Changing lanes..." with urgent beep + "laneAssistDeactivated": 10, # "Lane Assist deactivated." silent with persistent icon afterward + } + + +class CANBUS: + pt = 0 + cam = 2 -MQB_LDW_MESSAGES = { - "none": 0, # Nothing to display - "laneAssistUnavailChime": 1, # "Lane Assist currently not available." with chime - "laneAssistUnavailNoSensorChime": 3, # "Lane Assist not available. No sensor view." with chime - "laneAssistTakeOverUrgent": 4, # "Lane Assist: Please Take Over Steering" with urgent beep - "emergencyAssistUrgent": 6, # "Emergency Assist: Please Take Over Steering" with urgent beep - "laneAssistTakeOverChime": 7, # "Lane Assist: Please Take Over Steering" with chime - "laneAssistTakeOverSilent": 8, # "Lane Assist: Please Take Over Steering" silent - "emergencyAssistChangingLanes": 9, # "Emergency Assist: Changing lanes..." with urgent beep - "laneAssistDeactivated": 10, # "Lane Assist deactivated." silent with persistent icon afterward -} # Check the 7th and 8th characters of the VIN before adding a new CAR. If the # chassis code is already listed below, don't add a new CAR, just add to the @@ -68,7 +114,9 @@ class CAR: GOLF_MK7 = "VOLKSWAGEN GOLF 7TH GEN" # Chassis 5G/AU/BA/BE, Mk7 VW Golf and variants JETTA_MK7 = "VOLKSWAGEN JETTA 7TH GEN" # Chassis BU, Mk7 VW Jetta PASSAT_MK8 = "VOLKSWAGEN PASSAT 8TH GEN" # Chassis 3G, Mk8 VW Passat and variants + PASSAT_NMS = "VOLKSWAGEN PASSAT NMS" # Chassis A3, North America/China/Mideast NMS Passat, incl. facelift POLO_MK6 = "VOLKSWAGEN POLO 6TH GEN" # Chassis AW, Mk6 VW Polo + SHARAN_MK2 = "VOLKSWAGEN SHARAN 2ND GEN" # Chassis 7N, Mk2 Volkswagen Sharan and SEAT Alhambra TAOS_MK1 = "VOLKSWAGEN TAOS 1ST GEN" # Chassis B2, Mk1 VW Taos and Tharu TCROSS_MK1 = "VOLKSWAGEN T-CROSS 1ST GEN" # Chassis C1, Mk1 VW T-Cross SWB and LWB variants TIGUAN_MK2 = "VOLKSWAGEN TIGUAN 2ND GEN" # Chassis AD/BW, Mk2 VW Tiguan and variants @@ -87,6 +135,114 @@ class CAR: SKODA_SUPERB_MK3 = "SKODA SUPERB 3RD GEN" # Chassis 3V/NP, Mk3 Skoda Superb and variants SKODA_OCTAVIA_MK3 = "SKODA OCTAVIA 3RD GEN" # Chassis NE, Mk3 Skoda Octavia and variants + +PQ_CARS = {CAR.PASSAT_NMS, CAR.SHARAN_MK2} + + +DBC: Dict[str, Dict[str, str]] = defaultdict(lambda: dbc_dict("vw_mqb_2010", None)) +for car_type in PQ_CARS: + DBC[car_type] = dbc_dict("vw_golf_mk4", None) + + +class Footnote(Enum): + KAMIQ = CarFootnote( + "Not including the China market Kamiq, which is based on the (currently) unsupported PQ34 platform.", + Column.MODEL) + PASSAT = CarFootnote( + "Refers only to the MQB-based European B8 Passat, not the NMS Passat in the USA/China/Mideast markets.", + Column.MODEL) + VW_EXP_LONG = CarFootnote ( + "Only available for vehicles using a gateway (J533) harness. At this time, vehicles using a camera harness " + + "are limited to using stock ACC.", + Column.LONGITUDINAL) + VW_MQB_A0 = CarFootnote( + "Model-years 2022 and beyond may have a combined CAN gateway and BCM, which is supported by openpilot " + + "in software, but doesn't yet have a harness available from the comma store.", + Column.HARNESS) + + +@dataclass +class VWCarInfo(CarInfo): + package: str = "Adaptive Cruise Control (ACC) & Lane Assist" + harness: Enum = Harness.j533 + + def init_make(self, CP: car.CarParams): + self.footnotes.insert(0, Footnote.VW_EXP_LONG) + + +CAR_INFO: Dict[str, Union[VWCarInfo, List[VWCarInfo]]] = { + CAR.ARTEON_MK1: [ + VWCarInfo("Volkswagen Arteon 2018-22", video_link="https://youtu.be/FAomFKPFlDA"), + VWCarInfo("Volkswagen Arteon R 2020-22", video_link="https://youtu.be/FAomFKPFlDA"), + VWCarInfo("Volkswagen Arteon eHybrid 2020-22", video_link="https://youtu.be/FAomFKPFlDA"), + VWCarInfo("Volkswagen CC 2018-22", video_link="https://youtu.be/FAomFKPFlDA"), + ], + CAR.ATLAS_MK1: [ + VWCarInfo("Volkswagen Atlas 2018-23"), + VWCarInfo("Volkswagen Atlas Cross Sport 2021-22"), + VWCarInfo("Volkswagen Teramont 2018-22"), + VWCarInfo("Volkswagen Teramont Cross Sport 2021-22"), + VWCarInfo("Volkswagen Teramont X 2021-22"), + ], + CAR.GOLF_MK7: [ + VWCarInfo("Volkswagen e-Golf 2014-20"), + VWCarInfo("Volkswagen Golf 2015-20"), + VWCarInfo("Volkswagen Golf Alltrack 2015-19"), + VWCarInfo("Volkswagen Golf GTD 2015-20"), + VWCarInfo("Volkswagen Golf GTE 2015-20"), + VWCarInfo("Volkswagen Golf GTI 2015-21"), + VWCarInfo("Volkswagen Golf R 2015-19"), + VWCarInfo("Volkswagen Golf SportsVan 2015-20"), + ], + CAR.JETTA_MK7: [ + VWCarInfo("Volkswagen Jetta 2018-22"), + VWCarInfo("Volkswagen Jetta GLI 2021-22"), + ], + CAR.PASSAT_MK8: [ + VWCarInfo("Volkswagen Passat 2015-22", footnotes=[Footnote.PASSAT]), + VWCarInfo("Volkswagen Passat Alltrack 2015-22"), + VWCarInfo("Volkswagen Passat GTE 2015-22"), + ], + CAR.PASSAT_NMS: VWCarInfo("Volkswagen Passat NMS 2017-22"), + CAR.POLO_MK6: [ + VWCarInfo("Volkswagen Polo 2020-22", footnotes=[Footnote.VW_MQB_A0]), + VWCarInfo("Volkswagen Polo GTI 2020-22", footnotes=[Footnote.VW_MQB_A0]), + ], + CAR.SHARAN_MK2: [ + VWCarInfo("Volkswagen Sharan 2018-22"), + VWCarInfo("SEAT Alhambra 2018-20"), + ], + CAR.TAOS_MK1: VWCarInfo("Volkswagen Taos 2022"), + CAR.TCROSS_MK1: VWCarInfo("Volkswagen T-Cross 2021", footnotes=[Footnote.VW_MQB_A0]), + CAR.TIGUAN_MK2: VWCarInfo("Volkswagen Tiguan 2019-22"), + CAR.TOURAN_MK2: VWCarInfo("Volkswagen Touran 2017"), + CAR.TRANSPORTER_T61: [ + VWCarInfo("Volkswagen Caravelle 2020"), + VWCarInfo("Volkswagen California 2021"), + ], + CAR.TROC_MK1: VWCarInfo("Volkswagen T-Roc 2021", footnotes=[Footnote.VW_MQB_A0]), + CAR.AUDI_A3_MK3: [ + VWCarInfo("Audi A3 2014-19"), + VWCarInfo("Audi A3 Sportback e-tron 2017-18"), + VWCarInfo("Audi RS3 2018"), + VWCarInfo("Audi S3 2015-17"), + ], + CAR.AUDI_Q2_MK1: VWCarInfo("Audi Q2 2018"), + CAR.AUDI_Q3_MK2: VWCarInfo("Audi Q3 2019-23"), + CAR.SEAT_ATECA_MK1: VWCarInfo("SEAT Ateca 2018"), + CAR.SEAT_LEON_MK3: VWCarInfo("SEAT Leon 2014-20"), + CAR.SKODA_KAMIQ_MK1: VWCarInfo("Škoda Kamiq 2021", footnotes=[Footnote.VW_MQB_A0, Footnote.KAMIQ]), + CAR.SKODA_KAROQ_MK1: VWCarInfo("Škoda Karoq 2019-21"), + CAR.SKODA_KODIAQ_MK1: VWCarInfo("Škoda Kodiaq 2018-19"), + CAR.SKODA_SCALA_MK1: VWCarInfo("Škoda Scala 2020", footnotes=[Footnote.VW_MQB_A0]), + CAR.SKODA_SUPERB_MK3: VWCarInfo("Škoda Superb 2015-22"), + CAR.SKODA_OCTAVIA_MK3: [ + VWCarInfo("Škoda Octavia 2015, 2018-19"), + VWCarInfo("Škoda Octavia RS 2016"), + ], +} + + # All supported cars should return FW from the engine, srs, eps, and fwdRadar. Cars # with a manual trans won't return transmission firmware, but all other cars will. # @@ -96,25 +252,57 @@ class CAR: # ECU SW part numbers are invalid for vehicle ID and compatibility checks. Try to have # them repaired by the tuner before including them in openpilot. +VOLKSWAGEN_VERSION_REQUEST_MULTI = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER]) + \ + p16(uds.DATA_IDENTIFIER_TYPE.VEHICLE_MANUFACTURER_SPARE_PART_NUMBER) + \ + p16(uds.DATA_IDENTIFIER_TYPE.VEHICLE_MANUFACTURER_ECU_SOFTWARE_VERSION_NUMBER) + \ + p16(uds.DATA_IDENTIFIER_TYPE.APPLICATION_DATA_IDENTIFICATION) +VOLKSWAGEN_VERSION_RESPONSE = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER + 0x40]) + +VOLKSWAGEN_RX_OFFSET = 0x6a + +FW_QUERY_CONFIG = FwQueryConfig( + requests=[ + Request( + [VOLKSWAGEN_VERSION_REQUEST_MULTI], + [VOLKSWAGEN_VERSION_RESPONSE], + whitelist_ecus=[Ecu.srs, Ecu.eps, Ecu.fwdRadar], + rx_offset=VOLKSWAGEN_RX_OFFSET, + ), + Request( + [VOLKSWAGEN_VERSION_REQUEST_MULTI], + [VOLKSWAGEN_VERSION_RESPONSE], + whitelist_ecus=[Ecu.engine, Ecu.transmission], + ), + ], +) + FW_VERSIONS = { CAR.ARTEON_MK1: { (Ecu.engine, 0x7e0, None): [ b'\xf1\x873G0906259F \xf1\x890004', + b'\xf1\x873G0906259N \xf1\x890004', b'\xf1\x873G0906259P \xf1\x890001', + b'\xf1\x875NA907115H \xf1\x890002', ], (Ecu.transmission, 0x7e1, None): [ b'\xf1\x8709G927158L \xf1\x893611', b'\xf1\x870GC300011L \xf1\x891401', + b'\xf1\x870GC300014M \xf1\x892802', + b'\xf1\x870GC300040P \xf1\x891401', ], (Ecu.srs, 0x715, None): [ + b'\xf1\x873Q0959655BK\xf1\x890703\xf1\x82\x0e1616001613121157161111572900', b'\xf1\x873Q0959655BK\xf1\x890703\xf1\x82\x0e1616001613121177161113772900', b'\xf1\x873Q0959655DL\xf1\x890732\xf1\x82\0161812141812171105141123052J00', ], (Ecu.eps, 0x712, None): [ b'\xf1\x873Q0909144K \xf1\x895072\xf1\x82\x0571B41815A1', + b'\xf1\x873Q0909144L \xf1\x895081\xf1\x82\x0571B00817A1', b'\xf1\x875Q0910143C \xf1\x892211\xf1\x82\00567B0020800', + b'\xf1\x875WA907145M \xf1\x891051\xf1\x82\x002MB4092M7N', ], (Ecu.fwdRadar, 0x757, None): [ + b'\xf1\x872Q0907572AA\xf1\x890396', b'\xf1\x872Q0907572T \xf1\x890383', b'\xf1\x875Q0907572J \xf1\x890654', ], @@ -122,31 +310,42 @@ FW_VERSIONS = { CAR.ATLAS_MK1: { (Ecu.engine, 0x7e0, None): [ b'\xf1\x8703H906026AA\xf1\x899970', + b'\xf1\x8703H906026AJ\xf1\x890638', + b'\xf1\x8703H906026AJ\xf1\x891017', b'\xf1\x8703H906026AT\xf1\x891922', + b'\xf1\x8703H906026BC\xf1\x892664', b'\xf1\x8703H906026F \xf1\x896696', b'\xf1\x8703H906026F \xf1\x899970', b'\xf1\x8703H906026J \xf1\x896026', b'\xf1\x8703H906026J \xf1\x899971', b'\xf1\x8703H906026S \xf1\x896693', b'\xf1\x8703H906026S \xf1\x899970', + b'\xf1\x873CN906259 \xf1\x890005', ], (Ecu.transmission, 0x7e1, None): [ b'\xf1\x8709G927158A \xf1\x893387', b'\xf1\x8709G927158DR\xf1\x893536', + b'\xf1\x8709G927158DR\xf1\x893742', + b'\xf1\x8709G927158F \xf1\x893489', b'\xf1\x8709G927158FT\xf1\x893835', + b'\xf1\x8709G927158GL\xf1\x893939', ], (Ecu.srs, 0x715, None): [ b'\xf1\x873Q0959655BC\xf1\x890503\xf1\x82\0161914151912001103111122031200', b'\xf1\x873Q0959655BN\xf1\x890713\xf1\x82\0162214152212001105141122052900', b'\xf1\x873Q0959655DB\xf1\x890720\xf1\x82\0162214152212001105141122052900', b'\xf1\x873Q0959655DM\xf1\x890732\xf1\x82\x0e1114151112001105161122052J00', + b'\xf1\x873Q0959655DM\xf1\x890732\xf1\x82\x0e1115151112001105171122052J00', ], (Ecu.eps, 0x712, None): [ b'\xf1\x873QF909144B \xf1\x891582\xf1\x82\00571B60924A1', b'\xf1\x873QF909144B \xf1\x891582\xf1\x82\x0571B6G920A1', + b'\xf1\x875Q0909143P \xf1\x892051\xf1\x820528B6080105', b'\xf1\x875Q0909143P \xf1\x892051\xf1\x820528B6090105', ], (Ecu.fwdRadar, 0x757, None): [ + b'\xf1\x872Q0907572AA\xf1\x890396', + b'\xf1\x872Q0907572R \xf1\x890372', b'\xf1\x872Q0907572T \xf1\x890383', b'\xf1\x875Q0907572H \xf1\x890620', b'\xf1\x875Q0907572J \xf1\x890654', @@ -162,6 +361,7 @@ FW_VERSIONS = { b'\xf1\x8704E906023BN\xf1\x894518', b'\xf1\x8704E906024K \xf1\x896811', b'\xf1\x8704E906027GR\xf1\x892394', + b'\xf1\x8704E906027HD\xf1\x892603', b'\xf1\x8704E906027HD\xf1\x893742', b'\xf1\x8704E906027MA\xf1\x894958', b'\xf1\x8704L906021DT\xf1\x895520', @@ -172,16 +372,21 @@ FW_VERSIONS = { b'\xf1\x8704L906056CL\xf1\x893823', b'\xf1\x8704L906056CR\xf1\x895813', b'\xf1\x8704L906056HE\xf1\x893758', + b'\xf1\x8704L906056HN\xf1\x896590', b'\xf1\x870EA906016A \xf1\x898343', b'\xf1\x870EA906016E \xf1\x894219', + b'\xf1\x870EA906016F \xf1\x894238', b'\xf1\x870EA906016F \xf1\x895002', + b'\xf1\x870EA906016Q \xf1\x895993', b'\xf1\x870EA906016S \xf1\x897207', b'\xf1\x875G0906259 \xf1\x890007', + b'\xf1\x875G0906259D \xf1\x890002', b'\xf1\x875G0906259J \xf1\x890002', b'\xf1\x875G0906259L \xf1\x890002', b'\xf1\x875G0906259N \xf1\x890003', b'\xf1\x875G0906259Q \xf1\x890002', b'\xf1\x875G0906259Q \xf1\x892313', + b'\xf1\x875G0906259T \xf1\x890003', b'\xf1\x878V0906259H \xf1\x890002', b'\xf1\x878V0906259J \xf1\x890003', b'\xf1\x878V0906259K \xf1\x890001', @@ -191,10 +396,12 @@ FW_VERSIONS = { b'\xf1\x878V0906264L \xf1\x890002', b'\xf1\x878V0906264M \xf1\x890001', b'\xf1\x878V09C0BB01 \xf1\x890001', + b'\xf1\x8704E906024K \xf1\x899970', ], (Ecu.transmission, 0x7e1, None): [ b'\xf1\x8709G927749AP\xf1\x892943', b'\xf1\x8709S927158A \xf1\x893585', + b'\xf1\x870CW300040H \xf1\x890606', b'\xf1\x870CW300041H \xf1\x891010', b'\xf1\x870CW300042F \xf1\x891604', b'\xf1\x870CW300043B \xf1\x891601', @@ -208,6 +415,9 @@ FW_VERSIONS = { b'\xf1\x870D9300012 \xf1\x894937', b'\xf1\x870D9300012 \xf1\x895045', b'\xf1\x870D9300014M \xf1\x895004', + b'\xf1\x870D9300014Q \xf1\x895006', + b'\xf1\x870D9300020J \xf1\x894902', + b'\xf1\x870D9300020Q \xf1\x895201', b'\xf1\x870D9300020S \xf1\x895201', b'\xf1\x870D9300040A \xf1\x893613', b'\xf1\x870D9300040S \xf1\x894311', @@ -221,86 +431,96 @@ FW_VERSIONS = { b'\xf1\x870GC300020G \xf1\x892401', b'\xf1\x870GC300020G \xf1\x892403', b'\xf1\x870GC300020G \xf1\x892404', + b'\xf1\x870GC300020N \xf1\x892804', b'\xf1\x870GC300043T \xf1\x899999', ], (Ecu.srs, 0x715, None): [ - b'\xf1\x875Q0959655AA\xf1\x890386\xf1\x82\0211413001113120043114317121C111C9113', - b'\xf1\x875Q0959655AA\xf1\x890386\xf1\x82\0211413001113120053114317121C111C9113', - b'\xf1\x875Q0959655AA\xf1\x890388\xf1\x82\0211413001113120043114317121C111C9113', - b'\xf1\x875Q0959655AA\xf1\x890388\xf1\x82\0211413001113120043114417121411149113', - b'\xf1\x875Q0959655AA\xf1\x890388\xf1\x82\0211413001113120053114317121C111C9113', - b'\xf1\x875Q0959655BH\xf1\x890336\xf1\x82\02314160011123300314211012230229333463100', - b'\xf1\x875Q0959655BT\xf1\x890403\xf1\x82\023141600111233003142404A2252229333463100', - b'\xf1\x875Q0959655BT\xf1\x890403\xf1\x82\023141600111233003142405A2252229333463100', - b'\xf1\x875Q0959655C \xf1\x890361\xf1\x82\0211413001112120004110415121610169112', - b'\xf1\x875Q0959655D \xf1\x890388\xf1\x82\0211413001113120006110417121A101A9113', - b'\xf1\x875Q0959655J \xf1\x890830\xf1\x82\023271112111312--071104171825102591131211', - b'\xf1\x875Q0959655J \xf1\x890830\xf1\x82\023271212111312--071104171838103891131211', - b'\xf1\x875Q0959655J \xf1\x890830\xf1\x82\023341512112212--071104172328102891131211', + b'\xf1\x875Q0959655AA\xf1\x890386\xf1\x82\x111413001113120043114317121C111C9113', + b'\xf1\x875Q0959655AA\xf1\x890386\xf1\x82\x111413001113120053114317121C111C9113', + b'\xf1\x875Q0959655AA\xf1\x890388\xf1\x82\x111413001113120043114317121C111C9113', + b'\xf1\x875Q0959655AA\xf1\x890388\xf1\x82\x111413001113120043114417121411149113', + b'\xf1\x875Q0959655AA\xf1\x890388\xf1\x82\x111413001113120053114317121C111C9113', + b'\xf1\x875Q0959655BH\xf1\x890336\xf1\x82\x1314160011123300314211012230229333463100', + b'\xf1\x875Q0959655BS\xf1\x890403\xf1\x82\x1314160011123300314240012250229333463100', + b'\xf1\x875Q0959655BT\xf1\x890403\xf1\x82\x13141600111233003142404A2252229333463100', + b'\xf1\x875Q0959655BT\xf1\x890403\xf1\x82\x13141600111233003142405A2252229333463100', + b'\xf1\x875Q0959655C \xf1\x890361\xf1\x82\x111413001112120004110415121610169112', + b'\xf1\x875Q0959655D \xf1\x890388\xf1\x82\x111413001113120006110417121A101A9113', + b'\xf1\x875Q0959655J \xf1\x890830\xf1\x82\x13271112111312--071104171825102591131211', + b'\xf1\x875Q0959655J \xf1\x890830\xf1\x82\x13271212111312--071104171838103891131211', + b'\xf1\x875Q0959655J \xf1\x890830\xf1\x82\x13341512112212--071104172328102891131211', b'\xf1\x875Q0959655J \xf1\x890830\xf1\x82\x13272512111312--07110417182C102C91131211', - b'\xf1\x875Q0959655M \xf1\x890361\xf1\x82\0211413001112120041114115121611169112', - b'\xf1\x875Q0959655S \xf1\x890870\xf1\x82\02315120011211200621143171717111791132111', - b'\xf1\x875Q0959655S \xf1\x890870\xf1\x82\02324230011211200061104171724102491132111', - b'\xf1\x875Q0959655S \xf1\x890870\xf1\x82\02324230011211200621143171724112491132111', + b'\xf1\x875Q0959655M \xf1\x890361\xf1\x82\x111413001112120041114115121611169112', + b'\xf1\x875Q0959655S \xf1\x890870\xf1\x82\x1315120011211200621143171717111791132111', + b'\xf1\x875Q0959655S \xf1\x890870\xf1\x82\x1324230011211200061104171724102491132111', + b'\xf1\x875Q0959655S \xf1\x890870\xf1\x82\x1324230011211200621143171724112491132111', b'\xf1\x875Q0959655S \xf1\x890870\xf1\x82\x1315120011211200061104171717101791132111', b'\xf1\x875Q0959655S \xf1\x890870\xf1\x82\x1324230011211200631143171724122491132111', - b'\xf1\x875Q0959655T \xf1\x890825\xf1\x82\023271200111312--071104171837103791132111', + b'\xf1\x875Q0959655T \xf1\x890825\xf1\x82\x13271200111312--071104171837103791132111', b'\xf1\x875Q0959655T \xf1\x890830\xf1\x82\x13271100111312--071104171826102691131211', b'\xf1\x875QD959655 \xf1\x890388\xf1\x82\x111413001113120006110417121D101D9112', ], (Ecu.eps, 0x712, None): [ - b'\xf1\x873Q0909144F \xf1\x895043\xf1\x82\00561A01612A0', - b'\xf1\x873Q0909144H \xf1\x895061\xf1\x82\00566A0J612A1', - b'\xf1\x873Q0909144J \xf1\x895063\xf1\x82\00566A00514A1', - b'\xf1\x873Q0909144J \xf1\x895063\xf1\x82\00566A0J712A1', - b'\xf1\x873Q0909144K \xf1\x895072\xf1\x82\00571A0J714A1', + b'\xf1\x873Q0909144F \xf1\x895043\xf1\x82\x0561A01612A0', + b'\xf1\x873Q0909144H \xf1\x895061\xf1\x82\x0566A0J612A1', + b'\xf1\x873Q0909144J \xf1\x895063\xf1\x82\x0566A00514A1', + b'\xf1\x873Q0909144J \xf1\x895063\xf1\x82\x0566A01613A1', + b'\xf1\x873Q0909144J \xf1\x895063\xf1\x82\x0566A0J712A1', + b'\xf1\x873Q0909144K \xf1\x895072\xf1\x82\x0571A0J714A1', b'\xf1\x873Q0909144L \xf1\x895081\xf1\x82\x0571A0JA15A1', - b'\xf1\x873Q0909144M \xf1\x895082\xf1\x82\00571A01A18A1', - b'\xf1\x873Q0909144M \xf1\x895082\xf1\x82\00571A0JA16A1', + b'\xf1\x873Q0909144M \xf1\x895082\xf1\x82\x0571A01A18A1', + b'\xf1\x873Q0909144M \xf1\x895082\xf1\x82\x0571A0JA16A1', + b'\xf1\x873QM909144 \xf1\x895072\xf1\x82\x0571A01714A1', b'\xf1\x875Q0909143K \xf1\x892033\xf1\x820519A9040203', - b'\xf1\x875Q0909144AA\xf1\x891081\xf1\x82\00521A00441A1', + b'\xf1\x875Q0909144AA\xf1\x891081\xf1\x82\x0521A00441A1', + b'\xf1\x875Q0909144AA\xf1\x891081\xf1\x82\x0521A00608A1', b'\xf1\x875Q0909144AA\xf1\x891081\xf1\x82\x0521A00641A1', - b'\xf1\x875Q0909144AB\xf1\x891082\xf1\x82\00521A00442A1', - b'\xf1\x875Q0909144AB\xf1\x891082\xf1\x82\00521A00642A1', - b'\xf1\x875Q0909144AB\xf1\x891082\xf1\x82\00521A07B05A1', - b'\xf1\x875Q0909144L \xf1\x891021\xf1\x82\00521A00602A0', - b'\xf1\x875Q0909144L \xf1\x891021\xf1\x82\00522A00402A0', + b'\xf1\x875Q0909144AB\xf1\x891082\xf1\x82\x0521A00442A1', + b'\xf1\x875Q0909144AB\xf1\x891082\xf1\x82\x0521A00642A1', + b'\xf1\x875Q0909144AB\xf1\x891082\xf1\x82\x0521A07B05A1', + b'\xf1\x875Q0909144L \xf1\x891021\xf1\x82\x0521A00602A0', + b'\xf1\x875Q0909144L \xf1\x891021\xf1\x82\x0522A00402A0', b'\xf1\x875Q0909144L \xf1\x891021\xf1\x82\x0521A00502A0', - b'\xf1\x875Q0909144P \xf1\x891043\xf1\x82\00511A00403A0', - b'\xf1\x875Q0909144R \xf1\x891061\xf1\x82\00516A00604A1', - b'\xf1\x875Q0909144S \xf1\x891063\xf1\x82\00516A00604A1', - b'\xf1\x875Q0909144S \xf1\x891063\xf1\x82\00516A07A02A1', - b'\xf1\x875Q0909144T \xf1\x891072\xf1\x82\00521A00507A1', + b'\xf1\x875Q0909144P \xf1\x891043\xf1\x82\x0511A00403A0', + b'\xf1\x875Q0909144R \xf1\x891061\xf1\x82\x0516A00604A1', + b'\xf1\x875Q0909144S \xf1\x891063\xf1\x82\x0516A00404A1', + b'\xf1\x875Q0909144S \xf1\x891063\xf1\x82\x0516A00604A1', + b'\xf1\x875Q0909144S \xf1\x891063\xf1\x82\x0516A07A02A1', + b'\xf1\x875Q0909144T \xf1\x891072\xf1\x82\x0521A00507A1', b'\xf1\x875Q0909144T \xf1\x891072\xf1\x82\x0521A07B04A1', - b'\xf1\x875Q0909144T \xf1\x891072\xf1\x82\00521A20B03A1', + b'\xf1\x875Q0909144T \xf1\x891072\xf1\x82\x0521A20B03A1', b'\xf1\x875QD909144B \xf1\x891072\xf1\x82\x0521A00507A1', b'\xf1\x875QM909144A \xf1\x891072\xf1\x82\x0521A20B03A1', - b'\xf1\x875QM909144B \xf1\x891081\xf1\x82\00521A00442A1', - b'\xf1\x875QN909144A \xf1\x895081\xf1\x82\00571A01A16A1', - b'\xf1\x875QN909144A \xf1\x895081\xf1\x82\00571A01A18A1', + b'\xf1\x875QM909144B \xf1\x891081\xf1\x82\x0521A00442A1', + b'\xf1\x875QN909144A \xf1\x895081\xf1\x82\x0571A01A16A1', + b'\xf1\x875QN909144A \xf1\x895081\xf1\x82\x0571A01A18A1', b'\xf1\x875QN909144A \xf1\x895081\xf1\x82\x0571A01A17A1', - b'\xf1\x875QN909144B \xf1\x895082\xf1\x82\00571A01A18A1', + b'\xf1\x875QN909144B \xf1\x895082\xf1\x82\x0571A01A18A1', + b'\xf1\x875Q0910143C \xf1\x892211\xf1\x82\x0567A2000400', ], (Ecu.fwdRadar, 0x757, None): [ - b'\xf1\x875Q0907567G \xf1\x890390\xf1\x82\00101', + b'\xf1\x875Q0907567G \xf1\x890390\xf1\x82\x0101', b'\xf1\x875Q0907567J \xf1\x890396\xf1\x82\x0101', - b'\xf1\x875Q0907572A \xf1\x890141\xf1\x82\00101', - b'\xf1\x875Q0907572B \xf1\x890200\xf1\x82\00101', - b'\xf1\x875Q0907572C \xf1\x890210\xf1\x82\00101', - b'\xf1\x875Q0907572D \xf1\x890304\xf1\x82\00101', - b'\xf1\x875Q0907572E \xf1\x89X310\xf1\x82\00101', - b'\xf1\x875Q0907572F \xf1\x890400\xf1\x82\00101', + b'\xf1\x875Q0907572A \xf1\x890141\xf1\x82\x0101', + b'\xf1\x875Q0907572B \xf1\x890200\xf1\x82\x0101', + b'\xf1\x875Q0907572C \xf1\x890210\xf1\x82\x0101', + b'\xf1\x875Q0907572D \xf1\x890304\xf1\x82\x0101', + b'\xf1\x875Q0907572E \xf1\x89X310\xf1\x82\x0101', + b'\xf1\x875Q0907572F \xf1\x890400\xf1\x82\x0101', b'\xf1\x875Q0907572G \xf1\x890571', b'\xf1\x875Q0907572H \xf1\x890620', b'\xf1\x875Q0907572J \xf1\x890654', b'\xf1\x875Q0907572P \xf1\x890682', b'\xf1\x875Q0907572R \xf1\x890771', + b'\xf1\x875Q0907572S \xf1\x890780', ], }, CAR.JETTA_MK7: { (Ecu.engine, 0x7e0, None): [ b'\xf1\x8704E906024AK\xf1\x899937', b'\xf1\x8704E906024AS\xf1\x899912', + b'\xf1\x8704E906024BC\xf1\x899971', + b'\xf1\x8704E906024BG\xf1\x891057', b'\xf1\x8704E906024B \xf1\x895594', b'\xf1\x8704E906024C \xf1\x899970', b'\xf1\x8704E906024L \xf1\x895595', @@ -311,6 +531,8 @@ FW_VERSIONS = { (Ecu.transmission, 0x7e1, None): [ b'\xf1\x8709G927158BQ\xf1\x893545', b'\xf1\x8709S927158BS\xf1\x893642', + b'\xf1\x8709S927158BS\xf1\x893694', + b'\xf1\x8709S927158CK\xf1\x893770', b'\xf1\x8709S927158R \xf1\x893552', b'\xf1\x8709S927158R \xf1\x893587', b'\xf1\x870GC300020N \xf1\x892803', @@ -323,6 +545,7 @@ FW_VERSIONS = { b'\xf1\x875Q0959655BR\xf1\x890403\xf1\x82\02311170031313300314240011150119333433100', b'\xf1\x875Q0959655BR\xf1\x890403\xf1\x82\02319170031313300314240011550159333463100', b'\xf1\x875Q0959655CB\xf1\x890421\xf1\x82\x1314171231313500314643021650169333613100', + b'\xf1\x875Q0959655CB\xf1\x890421\xf1\x82\x1314171231313500314642021650169333613100', ], (Ecu.eps, 0x712, None): [ b'\xf1\x873Q0909144M \xf1\x895082\xf1\x82\x0571A10A11A1', @@ -340,67 +563,119 @@ FW_VERSIONS = { }, CAR.PASSAT_MK8: { (Ecu.engine, 0x7e0, None): [ + b'\xf1\x8703N906026E \xf1\x892114', b'\xf1\x8704E906023AH\xf1\x893379', + b'\xf1\x8704L906026ET\xf1\x891990', + b'\xf1\x8704L906026FP\xf1\x892012', b'\xf1\x8704L906026GA\xf1\x892013', b'\xf1\x8704L906026KD\xf1\x894798', b'\xf1\x873G0906264 \xf1\x890004', ], (Ecu.transmission, 0x7e1, None): [ + b'\xf1\x870CW300043H \xf1\x891601', b'\xf1\x870CW300048R \xf1\x890610', + b'\xf1\x870D9300013A \xf1\x894905', b'\xf1\x870D9300014L \xf1\x895002', + b'\xf1\x870D9300041A \xf1\x894801', b'\xf1\x870DD300045T \xf1\x891601', + b'\xf1\x870DL300011H \xf1\x895201', b'\xf1\x870GC300042H \xf1\x891404', ], (Ecu.srs, 0x715, None): [ + b'\xf1\x873Q0959655AE\xf1\x890195\xf1\x82\r56140056130012416612124111', b'\xf1\x873Q0959655AN\xf1\x890306\xf1\x82\r58160058140013036914110311', + b'\xf1\x873Q0959655BA\xf1\x890195\xf1\x82\r56140056130012516612125111', b'\xf1\x873Q0959655BB\xf1\x890195\xf1\x82\r56140056130012026612120211', b'\xf1\x873Q0959655BK\xf1\x890703\xf1\x82\0165915005914001344701311442900', + b'\xf1\x873Q0959655CN\xf1\x890720\xf1\x82\x0e5915005914001305701311052900', b'\xf1\x875Q0959655S \xf1\x890870\xf1\x82\02315120011111200631145171716121691132111', ], (Ecu.eps, 0x712, None): [ + b'\xf1\x873Q0909144J \xf1\x895063\xf1\x82\x0566B00611A1', + b'\xf1\x873Q0909144J \xf1\x895063\xf1\x82\x0566B00711A1', + b'\xf1\x875Q0909143M \xf1\x892041\xf1\x820522B0060803', b'\xf1\x875Q0909143M \xf1\x892041\xf1\x820522B0080803', b'\xf1\x875Q0909144AB\xf1\x891082\xf1\x82\00521B00606A1', b'\xf1\x875Q0909144S \xf1\x891063\xf1\x82\00516B00501A1', b'\xf1\x875Q0909144T \xf1\x891072\xf1\x82\00521B00703A1', + b'\xf1\x875Q0910143C \xf1\x892211\xf1\x82\x0567B0020600', ], (Ecu.fwdRadar, 0x757, None): [ + b'\xf1\x873Q0907572A \xf1\x890130', b'\xf1\x873Q0907572B \xf1\x890192', b'\xf1\x873Q0907572C \xf1\x890195', + b'\xf1\x873Q0907572C \xf1\x890196', b'\xf1\x875Q0907572R \xf1\x890771', ], }, + CAR.PASSAT_NMS: { + (Ecu.engine, 0x7e0, None): [ + b'\xf1\x8706K906016C \xf1\x899609', + b'\xf1\x8706K906016G \xf1\x891124', + b'\xf1\x8706K906071BJ\xf1\x894891', + ], + (Ecu.transmission, 0x7e1, None): [ + b'\xf1\x8709G927158AB\xf1\x893318', + b'\xf1\x8709G927158BD\xf1\x893121', + b'\xf1\x8709G927158FQ\xf1\x893745', + ], + (Ecu.srs, 0x715, None): [ + b'\xf1\x87561959655 \xf1\x890210\xf1\x82\02212121111113000102011--121012--101312', + b'\xf1\x87561959655C \xf1\x890508\xf1\x82\02215141111121100314919--153015--304831', + ], + (Ecu.fwdRadar, 0x757, None): [ + b'\xf1\x87561907567A \xf1\x890132', + b'\xf1\x877N0907572C \xf1\x890211\xf1\x82\00152', + ], + }, CAR.POLO_MK6: { (Ecu.engine, 0x7e0, None): [ - b'\xf1\x8704C906025H \xf1\x895177', + b'\xf1\x8704C906025H \xf1\x895177', ], (Ecu.transmission, 0x7e1, None): [ - b'\xf1\x870CW300050D \xf1\x891908', + b'\xf1\x870CW300050D \xf1\x891908', ], (Ecu.srs, 0x715, None): [ b'\xf1\x872Q0959655AJ\xf1\x890250\xf1\x82\x1248130411110416--04040404784811152H14', ], (Ecu.eps, 0x712, None): [ - b'\xf1\x872Q1909144M \xf1\x896041', + b'\xf1\x872Q1909144M \xf1\x896041', ], (Ecu.fwdRadar, 0x757, None): [ b'\xf1\x872Q0907572R \xf1\x890372', ], }, - CAR.TAOS_MK1: { + CAR.SHARAN_MK2: { + # TODO: Sharan Mk2 EPS and DQ250 auto trans both require KWP2000 support for fingerprinting (Ecu.engine, 0x7e0, None): [ - b'\xf1\x8705E906013E \xf1\x891624', + b'\xf1\x8704L906016HE\xf1\x894635', ], - (Ecu.transmission, 0x7e1, None): [ - b'\xf1\x8709S927158BL\xf1\x893791', + (Ecu.srs, 0x715, None): [ + b'\xf1\x877N0959655D \xf1\x890016\xf1\x82\x0801100705----10--', ], (Ecu.fwdRadar, 0x757, None): [ - b'\xf1\x872Q0907572T \xf1\x890383', + b'\xf1\x877N0907572C \xf1\x890211\xf1\x82\x0153', ], - (Ecu.eps, 0x712, None): [ - b'\xf1\x875QM909144C \xf1\x891082\xf1\x82\x0521060605A1', + }, + CAR.TAOS_MK1: { + (Ecu.engine, 0x7e0, None): [ + b'\xf1\x8704E906027NJ\xf1\x891445', + b'\xf1\x8705E906013E \xf1\x891624', + ], + (Ecu.transmission, 0x7e1, None): [ + b'\xf1\x8709S927158BL\xf1\x893791', + b'\xf1\x8709S927158FF\xf1\x893876', ], (Ecu.srs, 0x715, None): [ b'\xf1\x875Q0959655CB\xf1\x890421\xf1\x82\x1311111111333500314646021450149333613100', + b'\xf1\x875Q0959655CE\xf1\x890421\xf1\x82\x1311110011333300314240021350139333613100', + ], + (Ecu.eps, 0x712, None): [ + b'\xf1\x875QM909144C \xf1\x891082\xf1\x82\x0521060405A1', + b'\xf1\x875QM909144C \xf1\x891082\xf1\x82\x0521060605A1', + ], + (Ecu.fwdRadar, 0x757, None): [ + b'\xf1\x872Q0907572T \xf1\x890383', ], }, CAR.TCROSS_MK1: { @@ -422,16 +697,23 @@ FW_VERSIONS = { }, CAR.TIGUAN_MK2: { (Ecu.engine, 0x7e0, None): [ + b'\xf1\x8704E906027NB\xf1\x899504', b'\xf1\x8704L906026EJ\xf1\x893661', b'\xf1\x8704L906027G \xf1\x899893', b'\xf1\x875N0906259 \xf1\x890002', + b'\xf1\x875NA907115E \xf1\x890005', b'\xf1\x8783A907115B \xf1\x890005', + b'\xf1\x8783A907115G \xf1\x890001', ], (Ecu.transmission, 0x7e1, None): [ b'\xf1\x8709G927158DT\xf1\x893698', + b'\xf1\x8709G927158GC\xf1\x893821', + b'\xf1\x8709G927158GD\xf1\x893820', + b'\xf1\x870D9300043 \xf1\x895202', b'\xf1\x870DL300011N \xf1\x892001', b'\xf1\x870DL300011N \xf1\x892012', b'\xf1\x870DL300013A \xf1\x893005', + b'\xf1\x870DL300013G \xf1\x892119', b'\xf1\x870DL300013G \xf1\x892120', ], (Ecu.srs, 0x715, None): [ @@ -439,17 +721,25 @@ FW_VERSIONS = { b'\xf1\x875Q0959655BM\xf1\x890403\xf1\x82\02316143231313500314641011750179333423100', b'\xf1\x875Q0959655BT\xf1\x890403\xf1\x82\02312110031333300314240583752379333423100', b'\xf1\x875Q0959655BT\xf1\x890403\xf1\x82\02331310031333336313140013950399333423100', + b'\xf1\x875Q0959655BT\xf1\x890403\xf1\x82\x1331310031333334313140013750379333423100', + b'\xf1\x875Q0959655BT\xf1\x890403\xf1\x82\x1331310031333334313140573752379333423100', + b'\xf1\x875Q0959655CB\xf1\x890421\xf1\x82\x1316143231313500314647021750179333613100', ], (Ecu.eps, 0x712, None): [ b'\xf1\x875Q0909143M \xf1\x892041\xf1\x820529A6060603', + b'\xf1\x875Q0909144AB\xf1\x891082\xf1\x82\x0521A60604A1', + b'\xf1\x875Q0910143C \xf1\x892211\xf1\x82\x0567A6000600', b'\xf1\x875QF909144B \xf1\x895582\xf1\x82\00571A60634A1', b'\xf1\x875QM909144B \xf1\x891081\xf1\x82\x0521A60604A1', + b'\xf1\x875QM909144C \xf1\x891082\xf1\x82\x0521A60604A1', b'\xf1\x875QM909144C \xf1\x891082\xf1\x82\00521A60804A1', ], (Ecu.fwdRadar, 0x757, None): [ + b'\xf1\x872Q0907572AA\xf1\x890396', b'\xf1\x872Q0907572J \xf1\x890156', b'\xf1\x872Q0907572Q \xf1\x890342', b'\xf1\x872Q0907572R \xf1\x890372', + b'\xf1\x872Q0907572T \xf1\x890383', ], }, CAR.TOURAN_MK2: { @@ -513,27 +803,40 @@ FW_VERSIONS = { b'\xf1\x8704E906023BL\xf1\x895190', b'\xf1\x8704E906027CJ\xf1\x897798', b'\xf1\x8704L997022N \xf1\x899459', + b'\xf1\x875G0906259A \xf1\x890004', b'\xf1\x875G0906259L \xf1\x890002', b'\xf1\x875G0906259Q \xf1\x890002', b'\xf1\x878V0906259F \xf1\x890002', + b'\xf1\x878V0906259J \xf1\x890002', + b'\xf1\x878V0906259K \xf1\x890001', b'\xf1\x878V0906264B \xf1\x890003', b'\xf1\x878V0907115B \xf1\x890007', + b'\xf1\x878V0907404A \xf1\x890005', ], (Ecu.transmission, 0x7e1, None): [ b'\xf1\x870CW300044T \xf1\x895245', b'\xf1\x870CW300048 \xf1\x895201', b'\xf1\x870D9300012 \xf1\x894912', + b'\xf1\x870D9300012K \xf1\x894513', b'\xf1\x870D9300013B \xf1\x894931', b'\xf1\x870D9300041N \xf1\x894512', + b'\xf1\x870D9300043T \xf1\x899699', + b'\xf1\x870DD300046 \xf1\x891604', b'\xf1\x870DD300046A \xf1\x891602', b'\xf1\x870DD300046F \xf1\x891602', b'\xf1\x870DD300046G \xf1\x891601', + b'\xf1\x870DL300012E \xf1\x892012', + b'\xf1\x870GC300011 \xf1\x890403', b'\xf1\x870GC300013M \xf1\x892402', b'\xf1\x870GC300042J \xf1\x891402', ], (Ecu.srs, 0x715, None): [ b'\xf1\x875Q0959655AB\xf1\x890388\xf1\x82\0211111001111111206110412111321139114', b'\xf1\x875Q0959655AM\xf1\x890315\xf1\x82\x1311111111111111311411011231129321212100', + b'\xf1\x875Q0959655AM\xf1\x890318\xf1\x82\x1311111111111112311411011531159321212100', + b'\xf1\x875Q0959655AR\xf1\x890315\xf1\x82\x1311110011131115311211012331239321212100', + b'\xf1\x875Q0959655BJ\xf1\x890339\xf1\x82\x1311110011131100311111011731179321342100', + b'\xf1\x875Q0959655J \xf1\x890825\xf1\x82\x13111112111111--241115141112221291163221', b'\xf1\x875Q0959655J \xf1\x890825\xf1\x82\023111112111111--171115141112221291163221', b'\xf1\x875Q0959655J \xf1\x890830\xf1\x82\023121111111211--261117141112231291163221', b'\xf1\x875Q0959655J \xf1\x890830\xf1\x82\x13121111111111--341117141212231291163221', @@ -542,9 +845,13 @@ FW_VERSIONS = { ], (Ecu.eps, 0x712, None): [ b'\xf1\x873Q0909144H \xf1\x895061\xf1\x82\00566G0HA14A1', + b'\xf1\x873Q0909144K \xf1\x895072\xf1\x82\x0571G01A16A1', + b'\xf1\x873Q0909144K \xf1\x895072\xf1\x82\x0571G0HA16A1', + b'\xf1\x873Q0909144L \xf1\x895081\xf1\x82\x0571G0JA14A1', b'\xf1\x875Q0909144AB\xf1\x891082\xf1\x82\00521G0G809A1', b'\xf1\x875Q0909144P \xf1\x891043\xf1\x82\00503G00303A0', b'\xf1\x875Q0909144P \xf1\x891043\xf1\x82\00503G00803A0', + b'\xf1\x875Q0909144P \xf1\x891043\xf1\x82\x0503G0G803A0', b'\xf1\x875Q0909144R \xf1\x891061\xf1\x82\00516G00804A1', b'\xf1\x875Q0909144T \xf1\x891072\xf1\x82\00521G00807A1', ], @@ -576,20 +883,24 @@ FW_VERSIONS = { CAR.AUDI_Q3_MK2: { (Ecu.engine, 0x7e0, None): [ b'\xf1\x8705E906018N \xf1\x899970', + b'\xf1\x8705L906022M \xf1\x890901', b'\xf1\x8783A906259 \xf1\x890001', b'\xf1\x8783A906259 \xf1\x890005', ], (Ecu.transmission, 0x7e1, None): [ b'\xf1\x8709G927158CN\xf1\x893608', + b'\xf1\x870GC300045D \xf1\x892802', b'\xf1\x870GC300046F \xf1\x892701', ], (Ecu.srs, 0x715, None): [ b'\xf1\x875Q0959655BF\xf1\x890403\xf1\x82\x1321211111211200311121232152219321422111', + b'\xf1\x875Q0959655CC\xf1\x890421\xf1\x82\x131111111111120031111224118A119321532111', b'\xf1\x875Q0959655CC\xf1\x890421\xf1\x82\x131111111111120031111237116A119321532111', ], (Ecu.eps, 0x712, None): [ b'\xf1\x875Q0910143C \xf1\x892211\xf1\x82\x0567G6000300', b'\xf1\x875Q0910143C \xf1\x892211\xf1\x82\x0567G6000800', + b'\xf1\x875QF909144B \xf1\x895582\xf1\x82\x0571G60533A1', ], (Ecu.fwdRadar, 0x757, None): [ b'\xf1\x872Q0907572R \xf1\x890372', @@ -660,18 +971,23 @@ FW_VERSIONS = { CAR.SKODA_KAROQ_MK1: { (Ecu.engine, 0x7e0, None): [ b'\xf1\x8705E906018P \xf1\x896020', + b'\xf1\x8705L906022BS\xf1\x890913', ], (Ecu.transmission, 0x7e1, None): [ b'\xf1\x870CW300041S \xf1\x891615', + b'\xf1\x870GC300014L \xf1\x892802', ], (Ecu.srs, 0x715, None): [ b'\xf1\x873Q0959655BH\xf1\x890712\xf1\x82\0161213001211001101131122012100', + b'\xf1\x873Q0959655DE\xf1\x890731\xf1\x82\x0e1213001211001101131121012J00', ], (Ecu.eps, 0x712, None): [ b'\xf1\x875Q0910143C \xf1\x892211\xf1\x82\00567T6100500', + b'\xf1\x875Q0910143C \xf1\x892211\xf1\x82\x0567T6100700', ], (Ecu.fwdRadar, 0x757, None): [ b'\xf1\x872Q0907572M \xf1\x890233', + b'\xf1\x872Q0907572T \xf1\x890383', ], }, CAR.SKODA_KODIAQ_MK1: { @@ -705,11 +1021,13 @@ FW_VERSIONS = { (Ecu.engine, 0x7e0, None): [ b'\xf1\x8704E906016ER\xf1\x895823', b'\xf1\x8704E906027HD\xf1\x893742', + b'\xf1\x8704E906027MH\xf1\x894786', b'\xf1\x8704L906021DT\xf1\x898127', b'\xf1\x8704L906026BS\xf1\x891541', b'\xf1\x875G0906259C \xf1\x890002', ], (Ecu.transmission, 0x7e1, None): [ + b'\xf1\x870CW300041L \xf1\x891601', b'\xf1\x870CW300041N \xf1\x891605', b'\xf1\x870CW300043B \xf1\x891601', b'\xf1\x870D9300041C \xf1\x894936', @@ -722,11 +1040,13 @@ FW_VERSIONS = { b'\xf1\x873Q0959655AS\xf1\x890200\xf1\x82\r11120011100010022212110200', b'\xf1\x873Q0959655BH\xf1\x890703\xf1\x82\0163221003221002105755331052100', b'\xf1\x873Q0959655CN\xf1\x890720\xf1\x82\x0e3221003221002105755331052100', + b'\xf1\x875QD959655 \xf1\x890388\xf1\x82\x111101000011110006110411111111119111', ], (Ecu.eps, 0x712, None): [ b'\xf1\x873Q0909144J \xf1\x895063\xf1\x82\00566A01513A1', b'\xf1\x875Q0909144AA\xf1\x891081\xf1\x82\00521T00403A1', b'\xf1\x875Q0909144AB\xf1\x891082\xf1\x82\x0521T00403A1', + b'\xf1\x875QD909144E \xf1\x891081\xf1\x82\x0521T00503A1', b'\xf1\x875Q0909144R \xf1\x891061\xf1\x82\x0516A00604A1', ], (Ecu.fwdRadar, 0x757, None): [ @@ -734,6 +1054,7 @@ FW_VERSIONS = { b'\xf1\x875Q0907572F \xf1\x890400\xf1\x82\00101', b'\xf1\x875Q0907572J \xf1\x890654', b'\xf1\x875Q0907572P \xf1\x890682', + b'\xf1\x875Q0907572R \xf1\x890771', ], }, CAR.SKODA_SCALA_MK1: { @@ -755,6 +1076,7 @@ FW_VERSIONS = { }, CAR.SKODA_SUPERB_MK3: { (Ecu.engine, 0x7e0, None): [ + b'\xf1\x8704L906026ET\xf1\x891343', b'\xf1\x8704L906026FP\xf1\x891196', b'\xf1\x8704L906026KB\xf1\x894071', b'\xf1\x8704L906026KD\xf1\x894798', @@ -765,9 +1087,11 @@ FW_VERSIONS = { b'\xf1\x870CW300042H \xf1\x891601', b'\xf1\x870D9300011T \xf1\x894801', b'\xf1\x870D9300012 \xf1\x894940', + b'\xf1\x870D9300041H \xf1\x894905', b'\xf1\x870GC300043 \xf1\x892301', ], (Ecu.srs, 0x715, None): [ + b'\xf1\x875Q0959655AE\xf1\x890130\xf1\x82\x12111200111121001121110012211292221111', b'\xf1\x875Q0959655AE\xf1\x890130\xf1\x82\022111200111121001121118112231292221111', b'\xf1\x875Q0959655AK\xf1\x890130\xf1\x82\022111200111121001121110012211292221111', b'\xf1\x875Q0959655BH\xf1\x890336\xf1\x82\02331310031313100313131013141319331413100', diff --git a/selfdrive/car/volkswagen/volkswagencan.py b/selfdrive/car/volkswagen/volkswagencan.py deleted file mode 100644 index 10e0054c79..0000000000 --- a/selfdrive/car/volkswagen/volkswagencan.py +++ /dev/null @@ -1,49 +0,0 @@ -# CAN controls for MQB platform Volkswagen, Audi, Skoda and SEAT. -# PQ35/PQ46/NMS, and any future MLB, to come later. - -def create_mqb_steering_control(packer, bus, apply_steer, idx, lkas_enabled): - values = { - "SET_ME_0X3": 0x3, - "Assist_Torque": abs(apply_steer), - "Assist_Requested": lkas_enabled, - "Assist_VZ": 1 if apply_steer < 0 else 0, - "HCA_Available": 1, - "HCA_Standby": not lkas_enabled, - "HCA_Active": lkas_enabled, - "SET_ME_0XFE": 0xFE, - "SET_ME_0X07": 0x07, - } - return packer.make_can_msg("HCA_01", bus, values, idx) - -def create_mqb_hud_control(packer, bus, enabled, steering_pressed, hud_alert, left_lane_visible, right_lane_visible, - ldw_stock_values, left_lane_depart, right_lane_depart): - # Lane color reference: - # 0 (LKAS disabled) - off - # 1 (LKAS enabled, no lane detected) - dark gray - # 2 (LKAS enabled, lane detected) - light gray on VW, green or white on Audi depending on year or virtual cockpit. On a color MFD on a 2015 A3 TDI it is white, virtual cockpit on a 2018 A3 e-Tron its green. - # 3 (LKAS enabled, lane departure detected) - white on VW, red on Audi - values = ldw_stock_values.copy() - values.update({ - "LDW_Status_LED_gelb": 1 if enabled and steering_pressed else 0, - "LDW_Status_LED_gruen": 1 if enabled and not steering_pressed else 0, - "LDW_Lernmodus_links": 3 if left_lane_depart else 1 + left_lane_visible, - "LDW_Lernmodus_rechts": 3 if right_lane_depart else 1 + right_lane_visible, - "LDW_Texte": hud_alert, - }) - return packer.make_can_msg("LDW_02", bus, values) - -def create_mqb_acc_buttons_control(packer, bus, buttonStatesToSend, CS, idx): - values = { - "GRA_Hauptschalter": CS.graHauptschalter, - "GRA_Abbrechen": buttonStatesToSend["cancel"], - "GRA_Tip_Setzen": buttonStatesToSend["setCruise"], - "GRA_Tip_Hoch": buttonStatesToSend["accelCruise"], - "GRA_Tip_Runter": buttonStatesToSend["decelCruise"], - "GRA_Tip_Wiederaufnahme": buttonStatesToSend["resumeCruise"], - "GRA_Verstellung_Zeitluecke": 3 if buttonStatesToSend["gapAdjustCruise"] else 0, - "GRA_Typ_Hauptschalter": CS.graTypHauptschalter, - "GRA_Codierung": 2, - "GRA_Tip_Stufe_2": CS.graTipStufe2, - "GRA_ButtonTypeInfo": CS.graButtonTypeInfo - } - return packer.make_can_msg("GRA_ACC_01", bus, values, idx) diff --git a/selfdrive/common/SConscript b/selfdrive/common/SConscript deleted file mode 100644 index 8dfeecbdd7..0000000000 --- a/selfdrive/common/SConscript +++ /dev/null @@ -1,37 +0,0 @@ -Import('env', 'arch', 'SHARED') - -if SHARED: - fxn = env.SharedLibrary -else: - fxn = env.Library - -common_libs = [ - 'params.cc', - 'statlog.cc', - 'swaglog.cc', - 'util.cc', - 'gpio.cc', - 'i2c.cc', - 'watchdog.cc', -] - -_common = fxn('common', common_libs, LIBS="json11") - -files = [ - 'clutil.cc', - 'visionimg.cc', -] - -if arch == "aarch64": - _gpu_libs = ['gui', 'adreno_utils'] -elif arch == "larch64": - _gpu_libs = ["GLESv2"] -else: - _gpu_libs = ["GL"] - -_gpucommon = fxn('gpucommon', files, LIBS=_gpu_libs) -Export('_common', '_gpucommon', '_gpu_libs') - -if GetOption('test'): - env.Program('tests/test_util', ['tests/test_util.cc'], LIBS=[_common]) - env.Program('tests/test_swaglog', ['tests/test_swaglog.cc'], LIBS=[_common, 'json11', 'zmq', 'pthread']) diff --git a/selfdrive/common/gpio.cc b/selfdrive/common/gpio.cc deleted file mode 100644 index 033d6da4f7..0000000000 --- a/selfdrive/common/gpio.cc +++ /dev/null @@ -1,32 +0,0 @@ -#include "selfdrive/common/gpio.h" - -#include -#include - -#include - -#include "selfdrive/common/util.h" - -// We assume that all pins have already been exported on boot, -// and that we have permission to write to them. - -int gpio_init(int pin_nr, bool output) { - char pin_dir_path[50]; - int pin_dir_path_len = snprintf(pin_dir_path, sizeof(pin_dir_path), - "/sys/class/gpio/gpio%d/direction", pin_nr); - if(pin_dir_path_len <= 0) { - return -1; - } - const char *value = output ? "out" : "in"; - return util::write_file(pin_dir_path, (void*)value, strlen(value)); -} - -int gpio_set(int pin_nr, bool high) { - char pin_val_path[50]; - int pin_val_path_len = snprintf(pin_val_path, sizeof(pin_val_path), - "/sys/class/gpio/gpio%d/value", pin_nr); - if(pin_val_path_len <= 0) { - return -1; - } - return util::write_file(pin_val_path, (void*)(high ? "1" : "0"), 1); -} diff --git a/selfdrive/common/version.h b/selfdrive/common/version.h deleted file mode 100644 index 1fcbdac271..0000000000 --- a/selfdrive/common/version.h +++ /dev/null @@ -1 +0,0 @@ -#define COMMA_VERSION "0.8.14" diff --git a/selfdrive/common/visionimg.cc b/selfdrive/common/visionimg.cc deleted file mode 100644 index a98aabc36c..0000000000 --- a/selfdrive/common/visionimg.cc +++ /dev/null @@ -1,63 +0,0 @@ -#include "selfdrive/common/visionimg.h" - -#include - -#ifdef QCOM -#include -#include -#include -#include -#define GL_GLEXT_PROTOTYPES -#include -using namespace android; - -EGLImageTexture::EGLImageTexture(const VisionBuf *buf) { - const int bpp = 3; - assert((buf->len % buf->stride) == 0); - assert((buf->stride % bpp) == 0); - - const int format = HAL_PIXEL_FORMAT_RGB_888; - private_handle = new private_handle_t(buf->fd, buf->len, - private_handle_t::PRIV_FLAGS_USES_ION|private_handle_t::PRIV_FLAGS_FRAMEBUFFER, - 0, format, - buf->stride/bpp, buf->len/buf->stride, - buf->width, buf->height); - - // GraphicBuffer is ref counted by EGLClientBuffer(ANativeWindowBuffer), no need and not possible to release. - GraphicBuffer* gb = new GraphicBuffer(buf->width, buf->height, (PixelFormat)format, - GraphicBuffer::USAGE_HW_TEXTURE, buf->stride/bpp, (private_handle_t*)private_handle, false); - - EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); - assert(display != EGL_NO_DISPLAY); - - EGLint img_attrs[] = {EGL_IMAGE_PRESERVED_KHR, EGL_TRUE, EGL_NONE}; - img_khr = eglCreateImageKHR(display, EGL_NO_CONTEXT, - EGL_NATIVE_BUFFER_ANDROID, gb->getNativeBuffer(), img_attrs); - assert(img_khr != EGL_NO_IMAGE_KHR); - - glGenTextures(1, &frame_tex); - glBindTexture(GL_TEXTURE_2D, frame_tex); - glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, img_khr); -} - -EGLImageTexture::~EGLImageTexture() { - glDeleteTextures(1, &frame_tex); - EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); - assert(display != EGL_NO_DISPLAY); - eglDestroyImageKHR(display, img_khr); - delete (private_handle_t*)private_handle; -} - -#else // ifdef QCOM - -EGLImageTexture::EGLImageTexture(const VisionBuf *buf) { - glGenTextures(1, &frame_tex); - glBindTexture(GL_TEXTURE_2D, frame_tex); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, buf->width, buf->height, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr); - glGenerateMipmap(GL_TEXTURE_2D); -} - -EGLImageTexture::~EGLImageTexture() { - glDeleteTextures(1, &frame_tex); -} -#endif // ifdef QCOM diff --git a/selfdrive/common/visionimg.h b/selfdrive/common/visionimg.h deleted file mode 100644 index e8917f3bd6..0000000000 --- a/selfdrive/common/visionimg.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once - -#include "cereal/visionipc/visionbuf.h" - -#ifdef __APPLE__ -#include -#else -#include -#endif - -#ifdef QCOM -#include -#define EGL_EGLEXT_PROTOTYPES -#include -#undef Status -#endif - -class EGLImageTexture { - public: - EGLImageTexture(const VisionBuf *buf); - ~EGLImageTexture(); - GLuint frame_tex = 0; -#ifdef QCOM - void *private_handle = nullptr; - EGLImageKHR img_khr = 0; -#endif -}; diff --git a/selfdrive/common/watchdog.h b/selfdrive/common/watchdog.h deleted file mode 100644 index 7ed23aa0d9..0000000000 --- a/selfdrive/common/watchdog.h +++ /dev/null @@ -1,3 +0,0 @@ -#pragma once - -bool watchdog_kick(); diff --git a/selfdrive/config.py b/selfdrive/config.py deleted file mode 100644 index 511f6126c4..0000000000 --- a/selfdrive/config.py +++ /dev/null @@ -1,29 +0,0 @@ -import numpy as np - -class Conversions: - #Speed - MPH_TO_KPH = 1.609344 - KPH_TO_MPH = 1. / MPH_TO_KPH - MS_TO_KPH = 3.6 - KPH_TO_MS = 1. / MS_TO_KPH - MS_TO_MPH = MS_TO_KPH * KPH_TO_MPH - MPH_TO_MS = MPH_TO_KPH * KPH_TO_MS - MS_TO_KNOTS = 1.9438 - KNOTS_TO_MS = 1. / MS_TO_KNOTS - #Angle - DEG_TO_RAD = np.pi / 180. - RAD_TO_DEG = 1. / DEG_TO_RAD - #Mass - LB_TO_KG = 0.453592 - - -RADAR_TO_CENTER = 2.7 # (deprecated) RADAR is ~ 2.7m ahead from center of car -RADAR_TO_CAMERA = 1.52 # RADAR is ~ 1.5m ahead from center of mesh frame - -class UIParams: - lidar_x, lidar_y, lidar_zoom = 384, 960, 6 - lidar_car_x, lidar_car_y = lidar_x / 2., lidar_y / 1.1 - car_hwidth = 1.7272 / 2 * lidar_zoom - car_front = 2.6924 * lidar_zoom - car_back = 1.8796 * lidar_zoom - car_color = 110 diff --git a/selfdrive/controls/controlsd.py b/selfdrive/controls/controlsd.py index 1a34d31311..342ecc52fe 100755 --- a/selfdrive/controls/controlsd.py +++ b/selfdrive/controls/controlsd.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 import os import math -from numbers import Number +from typing import SupportsFloat from cereal import car, log from common.numpy_fast import clip @@ -9,23 +9,25 @@ from common.realtime import sec_since_boot, config_realtime_process, Priority, R from common.profiler import Profiler from common.params import Params, put_nonblocking import cereal.messaging as messaging -from selfdrive.config import Conversions as CV -from selfdrive.swaglog import cloudlog +from common.conversions import Conversions as CV +from panda import ALTERNATIVE_EXPERIENCE +from system.swaglog import cloudlog +from system.version import is_release_branch, get_short_branch from selfdrive.boardd.boardd import can_list_to_can_capnp from selfdrive.car.car_helpers import get_car, get_startup_event, get_one_can -from selfdrive.controls.lib.lane_planner import CAMERA_OFFSET -from selfdrive.controls.lib.drive_helpers import update_v_cruise, initialize_v_cruise -from selfdrive.controls.lib.drive_helpers import get_lag_adjusted_curvature +from selfdrive.controls.lib.lateral_planner import CAMERA_OFFSET +from selfdrive.controls.lib.drive_helpers import VCruiseHelper, get_lag_adjusted_curvature +from selfdrive.controls.lib.latcontrol import LatControl from selfdrive.controls.lib.longcontrol import LongControl from selfdrive.controls.lib.latcontrol_pid import LatControlPID from selfdrive.controls.lib.latcontrol_indi import LatControlINDI -from selfdrive.controls.lib.latcontrol_lqr import LatControlLQR from selfdrive.controls.lib.latcontrol_angle import LatControlAngle +from selfdrive.controls.lib.latcontrol_torque import LatControlTorque from selfdrive.controls.lib.events import Events, ET from selfdrive.controls.lib.alertmanager import AlertManager, set_offroad_alert from selfdrive.controls.lib.vehicle_model import VehicleModel from selfdrive.locationd.calibrationd import Calibration -from selfdrive.hardware import HARDWARE, TICI, EON +from system.hardware import HARDWARE from selfdrive.manager.process_config import managed_processes SOFT_DISABLE_TIME = 3 # seconds @@ -35,12 +37,9 @@ LANE_DEPARTURE_THRESHOLD = 0.1 REPLAY = "REPLAY" in os.environ SIMULATION = "SIMULATION" in os.environ NOSENSOR = "NOSENSOR" in os.environ -IGNORE_PROCESSES = {"rtshield", "uploader", "deleter", "loggerd", "logmessaged", "tombstoned", - "logcatd", "proclogd", "clocksd", "updated", "timezoned", "manage_athenad", - "statsd", "shutdownd"} | \ - {k for k, v in managed_processes.items() if not v.enabled} - -ACTUATOR_FIELDS = set(car.CarControl.Actuators.schema.fields.keys()) +IGNORE_PROCESSES = {"uploader", "deleter", "loggerd", "logmessaged", "tombstoned", "statsd", + "logcatd", "proclogd", "clocksd", "updated", "timezoned", "manage_athenad", "laikad"} | \ + {k for k, v in managed_processes.items() if not v.enabled} ThermalStatus = log.DeviceState.ThermalStatus State = log.ControlsState.OpenpilotState @@ -49,15 +48,22 @@ Desire = log.LateralPlan.Desire LaneChangeState = log.LateralPlan.LaneChangeState LaneChangeDirection = log.LateralPlan.LaneChangeDirection EventName = car.CarEvent.EventName -ButtonEvent = car.CarState.ButtonEvent +ButtonType = car.CarState.ButtonEvent.Type SafetyModel = car.CarParams.SafetyModel -IGNORED_SAFETY_MODES = [SafetyModel.silent, SafetyModel.noOutput] -CSID_MAP = {"0": EventName.roadCameraError, "1": EventName.wideRoadCameraError, "2": EventName.driverCameraError} +IGNORED_SAFETY_MODES = (SafetyModel.silent, SafetyModel.noOutput) +CSID_MAP = {"1": EventName.roadCameraError, "2": EventName.wideRoadCameraError, "0": EventName.driverCameraError} +ACTUATOR_FIELDS = tuple(car.CarControl.Actuators.schema.fields.keys()) +ACTIVE_STATES = (State.enabled, State.softDisabling, State.overriding) +ENABLED_STATES = (State.preEnabled, *ACTIVE_STATES) + class Controls: - def __init__(self, sm=None, pm=None, can_sock=None): - config_realtime_process(4 if TICI else 3, Priority.CTRL_HIGH) + def __init__(self, sm=None, pm=None, can_sock=None, CI=None): + config_realtime_process(4, Priority.CTRL_HIGH) + + # Ensure the current branch is cached, otherwise the first iteration of controlsd lags + self.branch = get_short_branch("") # Setup sockets self.pm = pm @@ -65,41 +71,54 @@ class Controls: self.pm = messaging.PubMaster(['sendcan', 'controlsState', 'carState', 'carControl', 'carEvents', 'carParams']) - self.camera_packets = ["roadCameraState", "driverCameraState"] - if TICI: - self.camera_packets.append("wideRoadCameraState") + self.camera_packets = ["roadCameraState", "driverCameraState", "wideRoadCameraState"] + + self.can_sock = can_sock + if can_sock is None: + can_timeout = None if os.environ.get('NO_CAN_TIMEOUT', False) else 20 + self.can_sock = messaging.sub_sock('can', timeout=can_timeout) - params = Params() - self.joystick_mode = params.get_bool("JoystickDebugMode") - joystick_packet = ['testJoystick'] if self.joystick_mode else [] + self.log_sock = messaging.sub_sock('androidLog') + self.params = Params() self.sm = sm if self.sm is None: - ignore = ['driverCameraState', 'managerState'] if SIMULATION else None + ignore = ['testJoystick'] + if SIMULATION: + ignore += ['driverCameraState', 'managerState'] + if self.params.get_bool('WideCameraOnly'): + ignore += ['roadCameraState'] self.sm = messaging.SubMaster(['deviceState', 'pandaStates', 'peripheralState', 'modelV2', 'liveCalibration', 'driverMonitoringState', 'longitudinalPlan', 'lateralPlan', 'liveLocationKalman', - 'managerState', 'liveParameters', 'radarState'] + self.camera_packets + joystick_packet, - ignore_alive=ignore, ignore_avg_freq=['radarState', 'longitudinalPlan']) + 'managerState', 'liveParameters', 'radarState', 'liveTorqueParameters', 'testJoystick'] + self.camera_packets, + ignore_alive=ignore, ignore_avg_freq=['radarState', 'longitudinalPlan', 'testJoystick']) - self.can_sock = can_sock - if can_sock is None: - can_timeout = None if os.environ.get('NO_CAN_TIMEOUT', False) else 100 - self.can_sock = messaging.sub_sock('can', timeout=can_timeout) + if CI is None: + # wait for one pandaState and one CAN packet + print("Waiting for CAN messages...") + get_one_can(self.can_sock) + + num_pandas = len(messaging.recv_one_retry(self.sm.sock['pandaStates']).pandaStates) + self.CI, self.CP = get_car(self.can_sock, self.pm.sock['sendcan'], num_pandas) + else: + self.CI, self.CP = CI, CI.CP - if TICI: - self.log_sock = messaging.sub_sock('androidLog') + self.joystick_mode = self.params.get_bool("JoystickDebugMode") or (self.CP.notCar and sm is None) - # wait for one pandaState and one CAN packet - print("Waiting for CAN messages...") - get_one_can(self.can_sock) + # set alternative experiences from parameters + self.disengage_on_accelerator = self.params.get_bool("DisengageOnAccelerator") + self.CP.alternativeExperience = 0 + if not self.disengage_on_accelerator: + self.CP.alternativeExperience |= ALTERNATIVE_EXPERIENCE.DISABLE_DISENGAGE_ON_GAS - self.CI, self.CP = get_car(self.can_sock, self.pm.sock['sendcan']) + if self.CP.dashcamOnly and self.params.get_bool("DashcamOverride"): + self.CP.dashcamOnly = False # read params - self.is_metric = params.get_bool("IsMetric") - self.is_ldw_enabled = params.get_bool("IsLdwEnabled") - openpilot_enabled_toggle = params.get_bool("OpenpilotEnabledToggle") - passive = params.get_bool("Passive") or not openpilot_enabled_toggle + self.is_metric = self.params.get_bool("IsMetric") + self.is_ldw_enabled = self.params.get_bool("IsLdwEnabled") + openpilot_enabled_toggle = self.params.get_bool("OpenpilotEnabledToggle") + passive = self.params.get_bool("Passive") or not openpilot_enabled_toggle # detect sound card presence and ensure successful init sounds_available = HARDWARE.get_sound_card_online() @@ -113,46 +132,59 @@ class Controls: safety_config.safetyModel = car.CarParams.SafetyModel.noOutput self.CP.safetyConfigs = [safety_config] + if is_release_branch(): + self.CP.experimentalLongitudinalAvailable = False + # Write CarParams for radard cp_bytes = self.CP.to_bytes() - params.put("CarParams", cp_bytes) + self.params.put("CarParams", cp_bytes) put_nonblocking("CarParamsCache", cp_bytes) + put_nonblocking("CarParamsPersistent", cp_bytes) + + # cleanup old params + if not self.CP.experimentalLongitudinalAvailable: + self.params.remove("ExperimentalLongitudinalEnabled") + if not self.CP.openpilotLongitudinalControl: + self.params.remove("ExperimentalMode") self.CC = car.CarControl.new_message() + self.CS_prev = car.CarState.new_message() self.AM = AlertManager() self.events = Events() self.LoC = LongControl(self.CP) self.VM = VehicleModel(self.CP) + self.LaC: LatControl if self.CP.steerControlType == car.CarParams.SteerControlType.angle: self.LaC = LatControlAngle(self.CP, self.CI) elif self.CP.lateralTuning.which() == 'pid': self.LaC = LatControlPID(self.CP, self.CI) elif self.CP.lateralTuning.which() == 'indi': self.LaC = LatControlINDI(self.CP, self.CI) - elif self.CP.lateralTuning.which() == 'lqr': - self.LaC = LatControlLQR(self.CP, self.CI) + elif self.CP.lateralTuning.which() == 'torque': + self.LaC = LatControlTorque(self.CP, self.CI) self.initialized = False self.state = State.disabled self.enabled = False self.active = False - self.can_rcv_error = False + self.can_rcv_timeout = False self.soft_disable_timer = 0 - self.v_cruise_kph = 255 - self.v_cruise_kph_last = 0 self.mismatch_counter = 0 self.cruise_mismatch_counter = 0 - self.can_rcv_error_counter = 0 + self.can_rcv_timeout_counter = 0 self.last_blinker_frame = 0 self.distance_traveled = 0 self.last_functional_fan_frame = 0 self.events_prev = [] self.current_alert_types = [ET.PERMANENT] - self.logged_comm_issue = False - self.button_timers = {ButtonEvent.Type.decelCruise: 0, ButtonEvent.Type.accelCruise: 0} + self.logged_comm_issue = None self.last_actuators = car.CarControl.Actuators.new_message() + self.steer_limited = False + self.desired_curvature = 0.0 + self.desired_curvature_rate = 0.0 + self.v_cruise_helper = VCruiseHelper(self.CP) # TODO: no longer necessary, aside from process replay self.sm['liveParameters'].valid = True @@ -177,6 +209,16 @@ class Controls: self.rk = Ratekeeper(100, print_delay_threshold=None) self.prof = Profiler(False) # off by default + def set_initial_state(self): + if REPLAY: + controls_state = Params().get("ReplayControlsState") + if controls_state is not None: + controls_state = log.ControlsState.from_bytes(controls_state) + self.v_cruise_helper.v_cruise_kph = controls_state.vCruise + + if any(ps.controlsAllowed for ps in self.sm['pandaStates']): + self.state = State.enabled + def update_events(self, CS): """Compute carEvents from carState""" @@ -192,30 +234,51 @@ class Controls: self.events.add(EventName.controlsInitializing) return - self.events.add_from_msg(CS.events) - self.events.add_from_msg(self.sm['driverMonitoringState'].events) + # no more events while in dashcam mode + if self.read_only: + return + + # Block resume if cruise never previously enabled + resume_pressed = any(be.type in (ButtonType.accelCruise, ButtonType.resumeCruise) for be in CS.buttonEvents) + if not self.CP.pcmCruise and not self.v_cruise_helper.v_cruise_initialized and resume_pressed: + self.events.add(EventName.resumeBlocked) + + # Disable on rising edge of accelerator or brake. Also disable on brake when speed > 0 + if (CS.gasPressed and not self.CS_prev.gasPressed and self.disengage_on_accelerator) or \ + (CS.brakePressed and (not self.CS_prev.brakePressed or not CS.standstill)) or \ + (CS.regenBraking and (not self.CS_prev.regenBraking or not CS.standstill)): + self.events.add(EventName.pedalPressed) + + if CS.brakePressed and CS.standstill: + self.events.add(EventName.preEnableStandstill) + + if CS.gasPressed: + self.events.add(EventName.gasPressedOverride) + + if not self.CP.notCar: + self.events.add_from_msg(self.sm['driverMonitoringState'].events) + + # Add car events, ignore if CAN isn't valid + if CS.canValid: + self.events.add_from_msg(CS.events) - # Create events for battery, temperature, disk space, and memory - if EON and (self.sm['peripheralState'].pandaType != PandaType.uno) and \ - self.sm['deviceState'].batteryPercent < 1 and self.sm['deviceState'].chargingError: - # at zero percent battery, while discharging, OP should not allowed - self.events.add(EventName.lowBattery) + # Create events for temperature, disk space, and memory if self.sm['deviceState'].thermalStatus >= ThermalStatus.red: self.events.add(EventName.overheat) if self.sm['deviceState'].freeSpacePercent < 7 and not SIMULATION: # under 7% of space free no enable allowed self.events.add(EventName.outOfSpace) # TODO: make tici threshold the same - if self.sm['deviceState'].memoryUsagePercent > (90 if TICI else 65) and not SIMULATION: + if self.sm['deviceState'].memoryUsagePercent > 90 and not SIMULATION: self.events.add(EventName.lowMemory) # TODO: enable this once loggerd CPU usage is more reasonable - #cpus = list(self.sm['deviceState'].cpuUsagePercent)[:(-1 if EON else None)] + #cpus = list(self.sm['deviceState'].cpuUsagePercent) #if max(cpus, default=0) > 95 and not SIMULATION: # self.events.add(EventName.highCpuUsage) # Alert if fan isn't spinning for 5 seconds - if self.sm['peripheralState'].pandaType in (PandaType.uno, PandaType.dos): + if self.sm['peripheralState'].pandaType != log.PandaState.PandaType.unknown: if self.sm['peripheralState'].fanSpeedRpm == 0 and self.sm['deviceState'].fanSpeedPercentDesired > 50: if (self.sm.frame - self.last_functional_fan_frame) * DT_CTRL > 5.0: self.events.add(EventName.fanMalfunction) @@ -245,44 +308,74 @@ class Controls: LaneChangeState.laneChangeFinishing): self.events.add(EventName.laneChange) - if not CS.canValid: - self.events.add(EventName.canError) - for i, pandaState in enumerate(self.sm['pandaStates']): # All pandas must match the list of safetyConfigs, and if outside this list, must be silent or noOutput if i < len(self.CP.safetyConfigs): safety_mismatch = pandaState.safetyModel != self.CP.safetyConfigs[i].safetyModel or \ pandaState.safetyParam != self.CP.safetyConfigs[i].safetyParam or \ - pandaState.unsafeMode != self.CP.unsafeMode + pandaState.alternativeExperience != self.CP.alternativeExperience else: safety_mismatch = pandaState.safetyModel not in IGNORED_SAFETY_MODES - if safety_mismatch or self.mismatch_counter >= 200: + if safety_mismatch or pandaState.safetyRxChecksInvalid or self.mismatch_counter >= 200: self.events.add(EventName.controlsMismatch) if log.PandaState.FaultType.relayMalfunction in pandaState.faults: self.events.add(EventName.relayMalfunction) - # Check for HW or system issues - if len(self.sm['radarState'].radarErrors): + # Handle HW and system malfunctions + # Order is very intentional here. Be careful when modifying this. + # All events here should at least have NO_ENTRY and SOFT_DISABLE. + num_events = len(self.events) + + not_running = {p.name for p in self.sm['managerState'].processes if not p.running and p.shouldBeRunning} + if self.sm.rcv_frame['managerState'] and (not_running - IGNORE_PROCESSES): + self.events.add(EventName.processNotRunning) + else: + if not SIMULATION and not self.rk.lagging: + if not self.sm.all_alive(self.camera_packets): + self.events.add(EventName.cameraMalfunction) + elif not self.sm.all_freq_ok(self.camera_packets): + self.events.add(EventName.cameraFrameRate) + if self.rk.lagging: + self.events.add(EventName.controlsdLagging) + if len(self.sm['radarState'].radarErrors) or not self.sm.all_checks(['radarState']): self.events.add(EventName.radarFault) - elif not self.sm.valid["pandaStates"]: + if not self.sm.valid['pandaStates']: self.events.add(EventName.usbError) - elif not self.sm.all_alive_and_valid() or self.can_rcv_error: - self.events.add(EventName.commIssue) - if not self.logged_comm_issue: - invalid = [s for s, valid in self.sm.valid.items() if not valid] - not_alive = [s for s, alive in self.sm.alive.items() if not alive] - cloudlog.event("commIssue", invalid=invalid, not_alive=not_alive, can_error=self.can_rcv_error, error=True) - self.logged_comm_issue = True + if CS.canTimeout: + self.events.add(EventName.canBusMissing) + elif not CS.canValid: + self.events.add(EventName.canError) + + # generic catch-all. ideally, a more specific event should be added above instead + has_disable_events = self.events.any(ET.NO_ENTRY) and (self.events.any(ET.SOFT_DISABLE) or self.events.any(ET.IMMEDIATE_DISABLE)) + no_system_errors = (not has_disable_events) or (len(self.events) == num_events) + if (not self.sm.all_checks() or self.can_rcv_timeout) and no_system_errors: + if not self.sm.all_alive(): + self.events.add(EventName.commIssue) + elif not self.sm.all_freq_ok(): + self.events.add(EventName.commIssueAvgFreq) + else: # invalid or can_rcv_timeout. + self.events.add(EventName.commIssue) + + logs = { + 'invalid': [s for s, valid in self.sm.valid.items() if not valid], + 'not_alive': [s for s, alive in self.sm.alive.items() if not alive], + 'not_freq_ok': [s for s, freq_ok in self.sm.freq_ok.items() if not freq_ok], + 'can_rcv_timeout': self.can_rcv_timeout, + } + if logs != self.logged_comm_issue: + cloudlog.event("commIssue", error=True, **logs) + self.logged_comm_issue = logs else: - self.logged_comm_issue = False + self.logged_comm_issue = None if not self.sm['liveParameters'].valid: self.events.add(EventName.vehicleModelInvalid) if not self.sm['lateralPlan'].mpcSolutionValid: self.events.add(EventName.plannerError) - if not self.sm['liveLocationKalman'].sensorsOK and not NOSENSOR: + if not (self.sm['liveParameters'].sensorValid or self.sm['liveLocationKalman'].sensorsOK) and not NOSENSOR: if self.sm.frame > 5 / DT_CTRL: # Give locationd some time to receive all the inputs self.events.add(EventName.sensorDataInvalid) if not self.sm['liveLocationKalman'].posenetOK: @@ -294,27 +387,26 @@ class Controls: # Check for mismatch between openpilot and car's PCM cruise_mismatch = CS.cruiseState.enabled and (not self.enabled or not self.CP.pcmCruise) self.cruise_mismatch_counter = self.cruise_mismatch_counter + 1 if cruise_mismatch else 0 - if self.cruise_mismatch_counter > int(3. / DT_CTRL): + if self.cruise_mismatch_counter > int(6. / DT_CTRL): self.events.add(EventName.cruiseMismatch) # Check for FCW - stock_long_is_braking = self.enabled and not self.CP.openpilotLongitudinalControl and CS.aEgo < -1.5 + stock_long_is_braking = self.enabled and not self.CP.openpilotLongitudinalControl and CS.aEgo < -1.25 model_fcw = self.sm['modelV2'].meta.hardBrakePredicted and not CS.brakePressed and not stock_long_is_braking planner_fcw = self.sm['longitudinalPlan'].fcw and self.enabled if planner_fcw or model_fcw: self.events.add(EventName.fcw) - if TICI: - for m in messaging.drain_sock(self.log_sock, wait_for_one=False): - try: - msg = m.androidLog.message - if any(err in msg for err in ("ERROR_CRC", "ERROR_ECC", "ERROR_STREAM_UNDERFLOW", "APPLY FAILED")): - csid = msg.split("CSID:")[-1].split(" ")[0] - evt = CSID_MAP.get(csid, None) - if evt is not None: - self.events.add(evt) - except UnicodeDecodeError: - pass + for m in messaging.drain_sock(self.log_sock, wait_for_one=False): + try: + msg = m.androidLog.message + if any(err in msg for err in ("ERROR_CRC", "ERROR_ECC", "ERROR_STREAM_UNDERFLOW", "APPLY FAILED")): + csid = msg.split("CSID:")[-1].split(" ")[0] + evt = CSID_MAP.get(csid, None) + if evt is not None: + self.events.add(evt) + except UnicodeDecodeError: + pass # TODO: fix simulator if not SIMULATION: @@ -322,28 +414,12 @@ class Controls: if not self.sm['liveLocationKalman'].gpsOK and (self.distance_traveled > 1000): # Not show in first 1 km to allow for driving out of garage. This event shows after 5 minutes self.events.add(EventName.noGps) - if not self.sm.all_alive(self.camera_packets): - self.events.add(EventName.cameraMalfunction) + if self.sm['modelV2'].frameDropPerc > 20: self.events.add(EventName.modeldLagging) if self.sm['liveLocationKalman'].excessiveResets: self.events.add(EventName.localizerMalfunction) - # Check if all manager processes are running - not_running = {p.name for p in self.sm['managerState'].processes if not p.running} - if self.sm.rcv_frame['managerState'] and (not_running - IGNORE_PROCESSES): - self.events.add(EventName.processNotRunning) - - # Only allow engagement with brake pressed when stopped behind another stopped car - speeds = self.sm['longitudinalPlan'].speeds - if len(speeds) > 1: - v_future = speeds[-1] - else: - v_future = 100.0 - if CS.brakePressed and v_future >= self.CP.vEgoStarting \ - and self.CP.openpilotLongitudinalControl and CS.vEgo < 0.3: - self.events.add(EventName.noTarget) - def data_sample(self): """Receive data from sockets and update carState""" @@ -354,23 +430,22 @@ class Controls: self.sm.update(0) if not self.initialized: - all_valid = CS.canValid and self.sm.all_alive_and_valid() - if all_valid or self.sm.frame * DT_CTRL > 3.5 or SIMULATION: + all_valid = CS.canValid and self.sm.all_checks() + timed_out = self.sm.frame * DT_CTRL > (6. if REPLAY else 3.5) + if all_valid or timed_out or SIMULATION: if not self.read_only: self.CI.init(self.CP, self.can_sock, self.pm.sock['sendcan']) - self.initialized = True - - if REPLAY and self.sm['pandaStates'][0].controlsAllowed: - self.state = State.enabled + self.initialized = True + self.set_initial_state() Params().put_bool("ControlsReady", True) # Check for CAN timeout if not can_strs: - self.can_rcv_error_counter += 1 - self.can_rcv_error = True + self.can_rcv_timeout_counter += 1 + self.can_rcv_timeout = True else: - self.can_rcv_error = False + self.can_rcv_timeout = False # When the panda and controlsd do not agree on controls_allowed # we want to disengage openpilot. However the status from the panda goes through @@ -391,13 +466,7 @@ class Controls: def state_transition(self, CS): """Compute conditional state transitions and execute actions on state transitions""" - self.v_cruise_kph_last = self.v_cruise_kph - - # if stock cruise is completely disabled, then we can use our own set speed logic - if not self.CP.pcmCruise: - self.v_cruise_kph = update_v_cruise(self.v_cruise_kph, CS.buttonEvents, self.button_timers, self.enabled, self.is_metric) - elif CS.cruiseState.enabled: - self.v_cruise_kph = CS.cruiseState.speed * CV.MS_TO_KPH + self.v_cruise_helper.update_v_cruise(CS, self.enabled, self.is_metric) # decrement the soft disable timer at every step, as it's reset on # entrance in SOFT_DISABLING state @@ -405,7 +474,7 @@ class Controls: self.current_alert_types = [ET.PERMANENT] - # ENABLED, PRE ENABLING, SOFT DISABLING + # ENABLED, SOFT DISABLING, PRE ENABLING, OVERRIDING if self.state != State.disabled: # user and immediate disable always have priority in a non-disabled state if self.events.any(ET.USER_DISABLE): @@ -424,6 +493,10 @@ class Controls: self.soft_disable_timer = int(SOFT_DISABLE_TIME / DT_CTRL) self.current_alert_types.append(ET.SOFT_DISABLE) + elif self.events.any(ET.OVERRIDE_LATERAL) or self.events.any(ET.OVERRIDE_LONGITUDINAL): + self.state = State.overriding + self.current_alert_types += [ET.OVERRIDE_LATERAL, ET.OVERRIDE_LONGITUDINAL] + # SOFT DISABLING elif self.state == State.softDisabling: if not self.events.any(ET.SOFT_DISABLE): @@ -443,6 +516,17 @@ class Controls: else: self.current_alert_types.append(ET.PRE_ENABLE) + # OVERRIDING + elif self.state == State.overriding: + if self.events.any(ET.SOFT_DISABLE): + self.state = State.softDisabling + self.soft_disable_timer = int(SOFT_DISABLE_TIME / DT_CTRL) + self.current_alert_types.append(ET.SOFT_DISABLE) + elif not (self.events.any(ET.OVERRIDE_LATERAL) or self.events.any(ET.OVERRIDE_LONGITUDINAL)): + self.state = State.enabled + else: + self.current_alert_types += [ET.OVERRIDE_LATERAL, ET.OVERRIDE_LONGITUDINAL] + # DISABLED elif self.state == State.disabled: if self.events.any(ET.ENABLE): @@ -452,32 +536,45 @@ class Controls: else: if self.events.any(ET.PRE_ENABLE): self.state = State.preEnabled + elif self.events.any(ET.OVERRIDE_LATERAL) or self.events.any(ET.OVERRIDE_LONGITUDINAL): + self.state = State.overriding else: self.state = State.enabled self.current_alert_types.append(ET.ENABLE) - self.v_cruise_kph = initialize_v_cruise(CS.vEgo, CS.buttonEvents, self.v_cruise_kph_last) + self.v_cruise_helper.initialize_v_cruise(CS) - # Check if actuators are enabled - self.active = self.state == State.enabled or self.state == State.softDisabling + # Check if openpilot is engaged and actuators are enabled + self.enabled = self.state in ENABLED_STATES + self.active = self.state in ACTIVE_STATES if self.active: self.current_alert_types.append(ET.WARNING) - # Check if openpilot is engaged - self.enabled = self.active or self.state == State.preEnabled - def state_control(self, CS): - """Given the state, this function returns an actuators packet""" + """Given the state, this function returns a CarControl packet""" # Update VehicleModel - params = self.sm['liveParameters'] - x = max(params.stiffnessFactor, 0.1) - sr = max(params.steerRatio, 0.1) + lp = self.sm['liveParameters'] + x = max(lp.stiffnessFactor, 0.1) + sr = max(lp.steerRatio, 0.1) self.VM.update_params(x, sr) + # Update Torque Params + if self.CP.lateralTuning.which() == 'torque': + torque_params = self.sm['liveTorqueParameters'] + if self.sm.all_checks(['liveTorqueParameters']) and torque_params.useParams: + self.LaC.update_live_torque_params(torque_params.latAccelFactorFiltered, torque_params.latAccelOffsetFiltered, torque_params.frictionCoefficientFiltered) + lat_plan = self.sm['lateralPlan'] long_plan = self.sm['longitudinalPlan'] - actuators = car.CarControl.Actuators.new_message() + CC = car.CarControl.new_message() + CC.enabled = self.enabled + # Check which actuators can be enabled + CC.latActive = self.active and not CS.steerFaultTemporary and not CS.steerFaultPermanent and \ + CS.vEgo > self.CP.minSteerSpeed and not CS.standstill + CC.longActive = self.enabled and not self.events.any(ET.OVERRIDE_LONGITUDINAL) and self.CP.openpilotLongitudinalControl + + actuators = CC.actuators actuators.longControlState = self.LoC.long_control_state if CS.leftBlinker or CS.rightBlinker: @@ -485,46 +582,61 @@ class Controls: # State specific actions - if not self.active: + if not CC.latActive: self.LaC.reset() + if not CC.longActive: self.LoC.reset(v_pid=CS.vEgo) if not self.joystick_mode: # accel PID loop - pid_accel_limits = self.CI.get_pid_accel_limits(self.CP, CS.vEgo, self.v_cruise_kph * CV.KPH_TO_MS) + pid_accel_limits = self.CI.get_pid_accel_limits(self.CP, CS.vEgo, self.v_cruise_helper.v_cruise_kph * CV.KPH_TO_MS) t_since_plan = (self.sm.frame - self.sm.rcv_frame['longitudinalPlan']) * DT_CTRL - actuators.accel = self.LoC.update(self.active, CS, self.CP, long_plan, pid_accel_limits, t_since_plan) + actuators.accel = self.LoC.update(CC.longActive, CS, long_plan, pid_accel_limits, t_since_plan) # Steering PID loop and lateral MPC - lat_active = self.active and not CS.steerWarning and not CS.steerError and CS.vEgo > self.CP.minSteerSpeed - desired_curvature, desired_curvature_rate = get_lag_adjusted_curvature(self.CP, CS.vEgo, - lat_plan.psis, - lat_plan.curvatures, - lat_plan.curvatureRates) - actuators.steer, actuators.steeringAngleDeg, lac_log = self.LaC.update(lat_active, CS, self.CP, self.VM, params, self.last_actuators, - desired_curvature, desired_curvature_rate) + self.desired_curvature, self.desired_curvature_rate = get_lag_adjusted_curvature(self.CP, CS.vEgo, + lat_plan.psis, + lat_plan.curvatures, + lat_plan.curvatureRates) + actuators.steer, actuators.steeringAngleDeg, lac_log = self.LaC.update(CC.latActive, CS, self.VM, lp, + self.last_actuators, self.steer_limited, self.desired_curvature, + self.desired_curvature_rate, self.sm['liveLocationKalman']) else: lac_log = log.ControlsState.LateralDebugState.new_message() - if self.sm.rcv_frame['testJoystick'] > 0 and self.active: - actuators.accel = 4.0*clip(self.sm['testJoystick'].axes[0], -1, 1) + if self.sm.rcv_frame['testJoystick'] > 0: + if CC.longActive: + actuators.accel = 4.0*clip(self.sm['testJoystick'].axes[0], -1, 1) - steer = clip(self.sm['testJoystick'].axes[1], -1, 1) - # max angle is 45 for angle-based cars - actuators.steer, actuators.steeringAngleDeg = steer, steer * 45. + if CC.latActive: + steer = clip(self.sm['testJoystick'].axes[1], -1, 1) + # max angle is 45 for angle-based cars + actuators.steer, actuators.steeringAngleDeg = steer, steer * 45. - lac_log.active = True + lac_log.active = self.active lac_log.steeringAngleDeg = CS.steeringAngleDeg - lac_log.output = steer - lac_log.saturated = abs(steer) >= 0.9 + lac_log.output = actuators.steer + lac_log.saturated = abs(actuators.steer) >= 0.9 # Send a "steering required alert" if saturation count has reached the limit - if lac_log.active and lac_log.saturated and not CS.steeringPressed: + if lac_log.active and not CS.steeringPressed and self.CP.lateralTuning.which() == 'torque' and not self.joystick_mode: + undershooting = abs(lac_log.desiredLateralAccel) / abs(1e-3 + lac_log.actualLateralAccel) > 1.2 + turning = abs(lac_log.desiredLateralAccel) > 1.0 + good_speed = CS.vEgo > 5 + max_torque = abs(self.last_actuators.steer) > 0.99 + if undershooting and turning and good_speed and max_torque: + self.events.add(EventName.steerSaturated) + elif lac_log.active and not CS.steeringPressed and lac_log.saturated: dpath_points = lat_plan.dPathPoints if len(dpath_points): # Check if we deviated from the path # TODO use desired vs actual curvature - left_deviation = actuators.steer > 0 and dpath_points[0] < -0.20 - right_deviation = actuators.steer < 0 and dpath_points[0] > 0.20 + if self.CP.steerControlType == car.CarParams.SteerControlType.angle: + steering_value = actuators.steeringAngleDeg + else: + steering_value = actuators.steer + + left_deviation = steering_value > 0 and dpath_points[0] < -0.20 + right_deviation = steering_value < 0 and dpath_points[0] > 0.20 if left_deviation or right_deviation: self.events.add(EventName.steerSaturated) @@ -532,44 +644,38 @@ class Controls: # Ensure no NaNs/Infs for p in ACTUATOR_FIELDS: attr = getattr(actuators, p) - if not isinstance(attr, Number): + if not isinstance(attr, SupportsFloat): continue if not math.isfinite(attr): cloudlog.error(f"actuators.{p} not finite {actuators.to_dict()}") setattr(actuators, p, 0.0) - return actuators, lac_log - - def update_button_timers(self, buttonEvents): - # increment timer for buttons still pressed - for k in self.button_timers: - if self.button_timers[k] > 0: - self.button_timers[k] += 1 - - for b in buttonEvents: - if b.type.raw in self.button_timers: - self.button_timers[b.type.raw] = 1 if b.pressed else 0 + return CC, lac_log - def publish_logs(self, CS, start_time, actuators, lac_log): + def publish_logs(self, CS, start_time, CC, lac_log): """Send actuators and hud commands to the car, send controlsstate and MPC logging""" - CC = car.CarControl.new_message() - CC.enabled = self.enabled - CC.active = self.active - CC.actuators = actuators - - orientation_value = self.sm['liveLocationKalman'].orientationNED.value + # Orientation and angle rates can be useful for carcontroller + # Only calibrated (car) frame is relevant for the carcontroller + orientation_value = list(self.sm['liveLocationKalman'].calibratedOrientationNED.value) if len(orientation_value) > 2: - CC.roll = orientation_value[0] - CC.pitch = orientation_value[1] + CC.orientationNED = orientation_value + angular_rate_value = list(self.sm['liveLocationKalman'].angularVelocityCalibrated.value) + if len(angular_rate_value) > 2: + CC.angularVelocity = angular_rate_value + CC.cruiseControl.override = self.enabled and not CC.longActive and self.CP.openpilotLongitudinalControl CC.cruiseControl.cancel = CS.cruiseState.enabled and (not self.enabled or not self.CP.pcmCruise) if self.joystick_mode and self.sm.rcv_frame['testJoystick'] > 0 and self.sm['testJoystick'].buttons[0]: CC.cruiseControl.cancel = True + speeds = self.sm['longitudinalPlan'].speeds + if len(speeds): + CC.cruiseControl.resume = self.enabled and CS.cruiseState.standstill and speeds[-1] > 0.1 + hudControl = CC.hudControl - hudControl.setSpeed = float(self.v_cruise_kph * CV.KPH_TO_MS) + hudControl.setSpeed = float(self.v_cruise_helper.v_cruise_cluster_kph * CV.KPH_TO_MS) hudControl.speedVisible = self.enabled hudControl.lanesVisible = self.enabled hudControl.leadVisible = self.sm['longitudinalPlan'].hasLead @@ -579,13 +685,13 @@ class Controls: recent_blinker = (self.sm.frame - self.last_blinker_frame) * DT_CTRL < 5.0 # 5s blinker cooldown ldw_allowed = self.is_ldw_enabled and CS.vEgo > LDW_MIN_SPEED and not recent_blinker \ - and not self.active and self.sm['liveCalibration'].calStatus == Calibration.CALIBRATED + and not CC.latActive and self.sm['liveCalibration'].calStatus == Calibration.CALIBRATED model_v2 = self.sm['modelV2'] desire_prediction = model_v2.meta.desirePrediction if len(desire_prediction) and ldw_allowed: - right_lane_visible = self.sm['lateralPlan'].rProb > 0.5 - left_lane_visible = self.sm['lateralPlan'].lProb > 0.5 + right_lane_visible = model_v2.laneLineProbs[2] > 0.5 + left_lane_visible = model_v2.laneLineProbs[1] > 0.5 l_lane_change_prob = desire_prediction[Desire.laneChangeLeft - 1] r_lane_change_prob = desire_prediction[Desire.laneChangeRight - 1] @@ -605,7 +711,7 @@ class Controls: if self.enabled: clear_event_types.add(ET.NO_ENTRY) - alerts = self.events.create_alerts(self.current_alert_types, [self.CP, self.sm, self.is_metric, self.soft_disable_timer]) + alerts = self.events.create_alerts(self.current_alert_types, [self.CP, CS, self.sm, self.is_metric, self.soft_disable_timer]) self.AM.add_many(self.sm.frame, alerts) current_alert = self.AM.process_alerts(self.sm.frame, clear_event_types) if current_alert: @@ -616,15 +722,16 @@ class Controls: self.last_actuators, can_sends = self.CI.apply(CC) self.pm.send('sendcan', can_list_to_can_capnp(can_sends, msgtype='sendcan', valid=CS.canValid)) CC.actuatorsOutput = self.last_actuators + self.steer_limited = abs(CC.actuators.steer - CC.actuatorsOutput.steer) > 1e-2 force_decel = (self.sm['driverMonitoringState'].awarenessStatus < 0.) or \ (self.state == State.softDisabling) # Curvature & Steering angle - params = self.sm['liveParameters'] + lp = self.sm['liveParameters'] - steer_angle_without_offset = math.radians(CS.steeringAngleDeg - params.angleOffsetDeg) - curvature = -self.VM.calc_curvature(steer_angle_without_offset, CS.vEgo, params.roll) + steer_angle_without_offset = math.radians(CS.steeringAngleDeg - lp.angleOffsetDeg) + curvature = -self.VM.calc_curvature(steer_angle_without_offset, CS.vEgo, lp.roll) # controlsState dat = messaging.new_message('controlsState') @@ -645,18 +752,22 @@ class Controls: controlsState.enabled = self.enabled controlsState.active = self.active controlsState.curvature = curvature + controlsState.desiredCurvature = self.desired_curvature + controlsState.desiredCurvatureRate = self.desired_curvature_rate controlsState.state = self.state controlsState.engageable = not self.events.any(ET.NO_ENTRY) controlsState.longControlState = self.LoC.long_control_state controlsState.vPid = float(self.LoC.v_pid) - controlsState.vCruise = float(self.v_cruise_kph) + controlsState.vCruise = float(self.v_cruise_helper.v_cruise_kph) + controlsState.vCruiseCluster = float(self.v_cruise_helper.v_cruise_cluster_kph) controlsState.upAccelCmd = float(self.LoC.pid.p) controlsState.uiAccelCmd = float(self.LoC.pid.i) controlsState.ufAccelCmd = float(self.LoC.pid.f) controlsState.cumLagMs = -self.rk.remaining * 1000. controlsState.startMonoTime = int(start_time * 1e9) controlsState.forceDecel = bool(force_decel) - controlsState.canErrorCounter = self.can_rcv_error_counter + controlsState.canErrorCounter = self.can_rcv_timeout_counter + controlsState.experimentalMode = self.params.get_bool("ExperimentalMode") and self.CP.openpilotLongitudinalControl lat_tuning = self.CP.lateralTuning.which() if self.joystick_mode: @@ -665,8 +776,8 @@ class Controls: controlsState.lateralControlState.angleState = lac_log elif lat_tuning == 'pid': controlsState.lateralControlState.pidState = lac_log - elif lat_tuning == 'lqr': - controlsState.lateralControlState.lqrState = lac_log + elif lat_tuning == 'torque': + controlsState.lateralControlState.torqueState = lac_log elif lat_tuning == 'indi': controlsState.lateralControlState.indiState = lac_log @@ -706,11 +817,15 @@ class Controls: start_time = sec_since_boot() self.prof.checkpoint("Ratekeeper", ignore=True) + self.is_metric = self.params.get_bool("IsMetric") + # Sample data from sockets and get a carState CS = self.data_sample() + cloudlog.timestamp("Data sampled") self.prof.checkpoint("Sample") self.update_events(CS) + cloudlog.timestamp("Events updated") if not self.read_only and self.initialized: # Update control state @@ -718,15 +833,15 @@ class Controls: self.prof.checkpoint("State transition") # Compute actuators (runs PID loops and lateral MPC) - actuators, lac_log = self.state_control(CS) + CC, lac_log = self.state_control(CS) self.prof.checkpoint("State Control") # Publish data - self.publish_logs(CS, start_time, actuators, lac_log) + self.publish_logs(CS, start_time, CC, lac_log) self.prof.checkpoint("Sent") - self.update_button_timers(CS.buttonEvents) + self.CS_prev = CS def controlsd_thread(self): while True: @@ -734,6 +849,7 @@ class Controls: self.rk.monitor_time() self.prof.display() + def main(sm=None, pm=None, logcan=None): controls = Controls(sm, pm, logcan) controls.controlsd_thread() diff --git a/selfdrive/controls/lib/alertmanager.py b/selfdrive/controls/lib/alertmanager.py index 2dad05e214..cb878483de 100644 --- a/selfdrive/controls/lib/alertmanager.py +++ b/selfdrive/controls/lib/alertmanager.py @@ -22,7 +22,7 @@ def set_offroad_alert(alert: str, show_alert: bool, extra_text: Optional[str] = a['text'] += extra_text Params().put(alert, json.dumps(a)) else: - Params().delete(alert) + Params().remove(alert) @dataclass diff --git a/selfdrive/controls/lib/alerts_offroad.json b/selfdrive/controls/lib/alerts_offroad.json index aa54f582f6..2f85ea917a 100644 --- a/selfdrive/controls/lib/alerts_offroad.json +++ b/selfdrive/controls/lib/alerts_offroad.json @@ -1,8 +1,4 @@ { - "Offroad_ChargeDisabled": { - "text": "EON charging disabled after car being off for more than 30 hours. Turn ignition on to start charging again.", - "severity": 0 - }, "Offroad_TemperatureTooHigh": { "text": "Device temperature too high. System won't start.", "severity": 1 @@ -41,6 +37,10 @@ "text": "NVMe drive not mounted.", "severity": 1 }, + "Offroad_BadNvme": { + "text": "Unsupported NVMe drive detected. Device may draw significantly more power and overheat due to the unsupported NVMe.", + "severity": 1 + }, "Offroad_CarUnrecognized": { "text": "openpilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai.", "severity": 0 diff --git a/selfdrive/controls/lib/desire_helper.py b/selfdrive/controls/lib/desire_helper.py index c34d143a5a..4790b8f0eb 100644 --- a/selfdrive/controls/lib/desire_helper.py +++ b/selfdrive/controls/lib/desire_helper.py @@ -1,11 +1,11 @@ from cereal import log +from common.conversions import Conversions as CV from common.realtime import DT_MDL -from selfdrive.config import Conversions as CV LaneChangeState = log.LateralPlan.LaneChangeState LaneChangeDirection = log.LateralPlan.LaneChangeDirection -LANE_CHANGE_SPEED_MIN = 30 * CV.MPH_TO_MS +LANE_CHANGE_SPEED_MIN = 20 * CV.MPH_TO_MS LANE_CHANGE_TIME_MAX = 10. DESIRES = { @@ -40,12 +40,12 @@ class DesireHelper: self.prev_one_blinker = False self.desire = log.LateralPlan.Desire.none - def update(self, carstate, active, lane_change_prob): + def update(self, carstate, lateral_active, lane_change_prob): v_ego = carstate.vEgo one_blinker = carstate.leftBlinker != carstate.rightBlinker below_lane_change_speed = v_ego < LANE_CHANGE_SPEED_MIN - if not active or self.lane_change_timer > LANE_CHANGE_TIME_MAX: + if not lateral_active or self.lane_change_timer > LANE_CHANGE_TIME_MAX: self.lane_change_state = LaneChangeState.off self.lane_change_direction = LaneChangeDirection.none else: diff --git a/selfdrive/controls/lib/drive_helpers.py b/selfdrive/controls/lib/drive_helpers.py index 14be3d5ed8..3d5ec8ac1d 100644 --- a/selfdrive/controls/lib/drive_helpers.py +++ b/selfdrive/controls/lib/drive_helpers.py @@ -1,8 +1,9 @@ import math + from cereal import car +from common.conversions import Conversions as CV from common.numpy_fast import clip, interp from common.realtime import DT_MDL -from selfdrive.config import Conversions as CV from selfdrive.modeld.constants import T_IDXS # WARNING: this value was determined based on the model's training distribution, @@ -10,115 +11,180 @@ from selfdrive.modeld.constants import T_IDXS V_CRUISE_MAX = 145 # kph V_CRUISE_MIN = 8 # kph V_CRUISE_ENABLE_MIN = 40 # kph +V_CRUISE_INITIAL = 255 # kph +IMPERIAL_INCREMENT = 1.6 # should be CV.MPH_TO_KPH, but this causes rounding errors +MIN_SPEED = 1.0 LAT_MPC_N = 16 LON_MPC_N = 32 CONTROL_N = 17 CAR_ROTATION_RADIUS = 0.0 -# this corresponds to 80deg/s and 20deg/s steering angle in a toyota corolla -MAX_CURVATURE_RATES = [0.03762194918267951, 0.003441203371932992] -MAX_CURVATURE_RATE_SPEEDS = [0, 35] +# EU guidelines +MAX_LATERAL_JERK = 5.0 +ButtonEvent = car.CarState.ButtonEvent +ButtonType = car.CarState.ButtonEvent.Type CRUISE_LONG_PRESS = 50 CRUISE_NEAREST_FUNC = { - car.CarState.ButtonEvent.Type.accelCruise: math.ceil, - car.CarState.ButtonEvent.Type.decelCruise: math.floor, + ButtonType.accelCruise: math.ceil, + ButtonType.decelCruise: math.floor, } CRUISE_INTERVAL_SIGN = { - car.CarState.ButtonEvent.Type.accelCruise: +1, - car.CarState.ButtonEvent.Type.decelCruise: -1, + ButtonType.accelCruise: +1, + ButtonType.decelCruise: -1, } -class MPC_COST_LAT: - PATH = 1.0 - HEADING = 1.0 - STEER_RATE = 1.0 +class VCruiseHelper: + def __init__(self, CP): + self.CP = CP + self.v_cruise_kph = V_CRUISE_INITIAL + self.v_cruise_cluster_kph = V_CRUISE_INITIAL + self.v_cruise_kph_last = 0 + self.button_timers = {ButtonType.decelCruise: 0, ButtonType.accelCruise: 0} + self.button_change_states = {btn: {"standstill": False, "enabled": False} for btn in self.button_timers} + + @property + def v_cruise_initialized(self): + return self.v_cruise_kph != V_CRUISE_INITIAL + + def update_v_cruise(self, CS, enabled, is_metric): + self.v_cruise_kph_last = self.v_cruise_kph + + if CS.cruiseState.available: + if not self.CP.pcmCruise: + # if stock cruise is completely disabled, then we can use our own set speed logic + self._update_v_cruise_non_pcm(CS, enabled, is_metric) + self.v_cruise_cluster_kph = self.v_cruise_kph + self.update_button_timers(CS, enabled) + else: + self.v_cruise_kph = CS.cruiseState.speed * CV.MS_TO_KPH + self.v_cruise_cluster_kph = CS.cruiseState.speedCluster * CV.MS_TO_KPH + else: + self.v_cruise_kph = V_CRUISE_INITIAL + self.v_cruise_cluster_kph = V_CRUISE_INITIAL + def _update_v_cruise_non_pcm(self, CS, enabled, is_metric): + # handle button presses. TODO: this should be in state_control, but a decelCruise press + # would have the effect of both enabling and changing speed is checked after the state transition + if not enabled: + return -class MPC_COST_LONG: - TTC = 5.0 - DISTANCE = 0.1 - ACCELERATION = 10.0 - JERK = 20.0 + long_press = False + button_type = None + v_cruise_delta = 1. if is_metric else IMPERIAL_INCREMENT -def rate_limit(new_value, last_value, dw_step, up_step): - return clip(new_value, last_value + dw_step, last_value + up_step) + for b in CS.buttonEvents: + if b.type.raw in self.button_timers and not b.pressed: + if self.button_timers[b.type.raw] > CRUISE_LONG_PRESS: + return # end long press + button_type = b.type.raw + break + else: + for k in self.button_timers.keys(): + if self.button_timers[k] and self.button_timers[k] % CRUISE_LONG_PRESS == 0: + button_type = k + long_press = True + break + if button_type is None: + return -def get_steer_max(CP, v_ego): - return interp(v_ego, CP.steerMaxBP, CP.steerMaxV) + # Don't adjust speed when pressing resume to exit standstill + cruise_standstill = self.button_change_states[button_type]["standstill"] or CS.cruiseState.standstill + if button_type == ButtonType.accelCruise and cruise_standstill: + return + # Don't adjust speed if we've enabled since the button was depressed (some ports enable on rising edge) + if not self.button_change_states[button_type]["enabled"]: + return -def update_v_cruise(v_cruise_kph, buttonEvents, button_timers, enabled, metric): - # handle button presses. TODO: this should be in state_control, but a decelCruise press - # would have the effect of both enabling and changing speed is checked after the state transition - if not enabled: - return v_cruise_kph + v_cruise_delta = v_cruise_delta * (5 if long_press else 1) + if long_press and self.v_cruise_kph % v_cruise_delta != 0: # partial interval + self.v_cruise_kph = CRUISE_NEAREST_FUNC[button_type](self.v_cruise_kph / v_cruise_delta) * v_cruise_delta + else: + self.v_cruise_kph += v_cruise_delta * CRUISE_INTERVAL_SIGN[button_type] - long_press = False - button_type = None + # If set is pressed while overriding, clip cruise speed to minimum of vEgo + if CS.gasPressed and button_type in (ButtonType.decelCruise, ButtonType.setCruise): + self.v_cruise_kph = max(self.v_cruise_kph, CS.vEgo * CV.MS_TO_KPH) - v_cruise_delta = 1 if metric else 1.6 + self.v_cruise_kph = clip(round(self.v_cruise_kph, 1), V_CRUISE_MIN, V_CRUISE_MAX) - for b in buttonEvents: - if b.type.raw in button_timers and not b.pressed: - if button_timers[b.type.raw] > CRUISE_LONG_PRESS: - return v_cruise_kph # end long press - button_type = b.type.raw - break - else: - for k in button_timers.keys(): - if button_timers[k] and button_timers[k] % CRUISE_LONG_PRESS == 0: - button_type = k - long_press = True - break + def update_button_timers(self, CS, enabled): + # increment timer for buttons still pressed + for k in self.button_timers: + if self.button_timers[k] > 0: + self.button_timers[k] += 1 - if button_type: - v_cruise_delta = v_cruise_delta * (5 if long_press else 1) - if long_press and v_cruise_kph % v_cruise_delta != 0: # partial interval - v_cruise_kph = CRUISE_NEAREST_FUNC[button_type](v_cruise_kph / v_cruise_delta) * v_cruise_delta + for b in CS.buttonEvents: + if b.type.raw in self.button_timers: + # Start/end timer and store current state on change of button pressed + self.button_timers[b.type.raw] = 1 if b.pressed else 0 + self.button_change_states[b.type.raw] = {"standstill": CS.cruiseState.standstill, "enabled": enabled} + + def initialize_v_cruise(self, CS): + # initializing is handled by the PCM + if self.CP.pcmCruise: + return + + # 250kph or above probably means we never had a set speed + if any(b.type in (ButtonType.accelCruise, ButtonType.resumeCruise) for b in CS.buttonEvents) and self.v_cruise_kph_last < 250: + self.v_cruise_kph = self.v_cruise_kph_last else: - v_cruise_kph += v_cruise_delta * CRUISE_INTERVAL_SIGN[button_type] - v_cruise_kph = clip(round(v_cruise_kph, 1), V_CRUISE_MIN, V_CRUISE_MAX) + self.v_cruise_kph = int(round(clip(CS.vEgo * CV.MS_TO_KPH, V_CRUISE_ENABLE_MIN, V_CRUISE_MAX))) - return v_cruise_kph + self.v_cruise_cluster_kph = self.v_cruise_kph -def initialize_v_cruise(v_ego, buttonEvents, v_cruise_last): - for b in buttonEvents: - # 250kph or above probably means we never had a set speed - if b.type == car.CarState.ButtonEvent.Type.accelCruise and v_cruise_last < 250: - return v_cruise_last +def apply_deadzone(error, deadzone): + if error > deadzone: + error -= deadzone + elif error < - deadzone: + error += deadzone + else: + error = 0. + return error + - return int(round(clip(v_ego * CV.MS_TO_KPH, V_CRUISE_ENABLE_MIN, V_CRUISE_MAX))) +def apply_center_deadzone(error, deadzone): + if (error > - deadzone) and (error < deadzone): + error = 0. + return error + + +def rate_limit(new_value, last_value, dw_step, up_step): + return clip(new_value, last_value + dw_step, last_value + up_step) def get_lag_adjusted_curvature(CP, v_ego, psis, curvatures, curvature_rates): if len(psis) != CONTROL_N: - psis = [0.0 for i in range(CONTROL_N)] - curvatures = [0.0 for i in range(CONTROL_N)] - curvature_rates = [0.0 for i in range(CONTROL_N)] + psis = [0.0]*CONTROL_N + curvatures = [0.0]*CONTROL_N + curvature_rates = [0.0]*CONTROL_N + v_ego = max(MIN_SPEED, v_ego) # TODO this needs more thought, use .2s extra for now to estimate other delays delay = CP.steerActuatorDelay + .2 - current_curvature = curvatures[0] - psi = interp(delay, T_IDXS[:CONTROL_N], psis) - desired_curvature_rate = curvature_rates[0] # MPC can plan to turn the wheel and turn back before t_delay. This means # in high delay cases some corrections never even get commanded. So just use # psi to calculate a simple linearization of desired curvature - curvature_diff_from_psi = psi / (max(v_ego, 1e-1) * delay) - current_curvature - desired_curvature = current_curvature + 2 * curvature_diff_from_psi + current_curvature_desired = curvatures[0] + psi = interp(delay, T_IDXS[:CONTROL_N], psis) + average_curvature_desired = psi / (v_ego * delay) + desired_curvature = 2 * average_curvature_desired - current_curvature_desired - max_curvature_rate = interp(v_ego, MAX_CURVATURE_RATE_SPEEDS, MAX_CURVATURE_RATES) + # This is the "desired rate of the setpoint" not an actual desired rate + desired_curvature_rate = curvature_rates[0] + max_curvature_rate = MAX_LATERAL_JERK / (v_ego**2) # inexact calculation, check https://github.com/commaai/openpilot/pull/24755 safe_desired_curvature_rate = clip(desired_curvature_rate, - -max_curvature_rate, - max_curvature_rate) + -max_curvature_rate, + max_curvature_rate) safe_desired_curvature = clip(desired_curvature, - current_curvature - max_curvature_rate * DT_MDL, - current_curvature + max_curvature_rate * DT_MDL) + current_curvature_desired - max_curvature_rate * DT_MDL, + current_curvature_desired + max_curvature_rate * DT_MDL) + return safe_desired_curvature, safe_desired_curvature_rate diff --git a/selfdrive/controls/lib/events.py b/selfdrive/controls/lib/events.py index 931932cc0d..5578a83a23 100644 --- a/selfdrive/controls/lib/events.py +++ b/selfdrive/controls/lib/events.py @@ -1,13 +1,14 @@ +import math import os from enum import IntEnum from typing import Dict, Union, Callable, List, Optional from cereal import log, car import cereal.messaging as messaging +from common.conversions import Conversions as CV from common.realtime import DT_CTRL -from selfdrive.config import Conversions as CV from selfdrive.locationd.calibrationd import MIN_SPEED_FILTER -from selfdrive.version import get_short_branch +from system.version import get_short_branch AlertSize = log.ControlsState.AlertSize AlertStatus = log.ControlsState.AlertStatus @@ -30,6 +31,8 @@ class Priority(IntEnum): class ET: ENABLE = 'enable' PRE_ENABLE = 'preEnable' + OVERRIDE_LATERAL = 'overrideLateral' + OVERRIDE_LONGITUDINAL = 'overrideLongitudinal' NO_ENTRY = 'noEntry' WARNING = 'warning' USER_DISABLE = 'userDisable' @@ -134,12 +137,16 @@ class Alert: return f"{self.alert_text_1}/{self.alert_text_2} {self.priority} {self.visual_alert} {self.audible_alert}" def __gt__(self, alert2) -> bool: + if not isinstance(alert2, Alert): + return False return self.priority > alert2.priority class NoEntryAlert(Alert): - def __init__(self, alert_text_2: str, visual_alert: car.CarControl.HUDControl.VisualAlert=VisualAlert.none): - super().__init__("openpilot Unavailable", alert_text_2, AlertStatus.normal, + def __init__(self, alert_text_2: str, + alert_text_1: str = "openpilot Unavailable", + visual_alert: car.CarControl.HUDControl.VisualAlert=VisualAlert.none): + super().__init__(alert_text_1, alert_text_2, AlertStatus.normal, AlertSize.mid, Priority.LOW, visual_alert, AudibleAlert.refuse, 3.) @@ -198,35 +205,35 @@ def get_display_speed(speed_ms: float, metric: bool) -> str: # ********** alert callback functions ********** -AlertCallbackType = Callable[[car.CarParams, messaging.SubMaster, bool, int], Alert] +AlertCallbackType = Callable[[car.CarParams, car.CarState, messaging.SubMaster, bool, int], Alert] def soft_disable_alert(alert_text_2: str) -> AlertCallbackType: - def func(CP: car.CarParams, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: + def func(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: if soft_disable_time < int(0.5 / DT_CTRL): return ImmediateDisableAlert(alert_text_2) return SoftDisableAlert(alert_text_2) return func def user_soft_disable_alert(alert_text_2: str) -> AlertCallbackType: - def func(CP: car.CarParams, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: + def func(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: if soft_disable_time < int(0.5 / DT_CTRL): return ImmediateDisableAlert(alert_text_2) return UserSoftDisableAlert(alert_text_2) return func -def startup_master_alert(CP: car.CarParams, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: - branch = get_short_branch("") +def startup_master_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: + branch = get_short_branch("") # Ensure get_short_branch is cached to avoid lags on startup if "REPLAY" in os.environ: branch = "replay" return StartupAlert("WARNING: This branch is not tested", branch, alert_status=AlertStatus.userPrompt) -def below_engage_speed_alert(CP: car.CarParams, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: +def below_engage_speed_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: return NoEntryAlert(f"Speed Below {get_display_speed(CP.minEnableSpeed, metric)}") -def below_steer_speed_alert(CP: car.CarParams, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: +def below_steer_speed_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: return Alert( f"Steer Unavailable Below {get_display_speed(CP.minSteerSpeed, metric)}", "", @@ -234,7 +241,7 @@ def below_steer_speed_alert(CP: car.CarParams, sm: messaging.SubMaster, metric: Priority.MID, VisualAlert.steerRequired, AudibleAlert.prompt, 0.4) -def calibration_incomplete_alert(CP: car.CarParams, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: +def calibration_incomplete_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: return Alert( "Calibration in Progress: %d%%" % sm['liveCalibration'].calPerc, f"Drive Above {get_display_speed(MIN_SPEED_FILTER, metric)}", @@ -242,23 +249,81 @@ def calibration_incomplete_alert(CP: car.CarParams, sm: messaging.SubMaster, met Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .2) -def no_gps_alert(CP: car.CarParams, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: - gps_integrated = sm['peripheralState'].pandaType in (log.PandaState.PandaType.uno, log.PandaState.PandaType.dos) +def no_gps_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: return Alert( "Poor GPS reception", - "If sky is visible, contact support" if gps_integrated else "Check GPS antenna placement", + "Hardware malfunctioning if sky is visible", AlertStatus.normal, AlertSize.mid, Priority.LOWER, VisualAlert.none, AudibleAlert.none, .2, creation_delay=300.) +# *** debug alerts *** -def wrong_car_mode_alert(CP: car.CarParams, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: +def out_of_space_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: + full_perc = round(100. - sm['deviceState'].freeSpacePercent) + return NormalPermanentAlert("Out of Storage", f"{full_perc}% full") + + +def posenet_invalid_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: + mdl = sm['modelV2'].velocity.x[0] if len(sm['modelV2'].velocity.x) else math.nan + err = CS.vEgo - mdl + msg = f"Speed Error: {err:.1f} m/s" + return NoEntryAlert(msg, alert_text_1="Posenet Speed Invalid") + + +def process_not_running_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: + not_running = [p.name for p in sm['managerState'].processes if not p.running and p.shouldBeRunning] + msg = ', '.join(not_running) + return NoEntryAlert(msg, alert_text_1="Process Not Running") + + +def comm_issue_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: + bs = [s for s in sm.data.keys() if not sm.all_checks([s, ])] + msg = ', '.join(bs[:4]) # can't fit too many on one line + return NoEntryAlert(msg, alert_text_1="Communication Issue Between Processes") + + +def camera_malfunction_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: + all_cams = ('roadCameraState', 'driverCameraState', 'wideRoadCameraState') + bad_cams = [s.replace('State', '') for s in all_cams if s in sm.data.keys() and not sm.all_checks([s, ])] + return NormalPermanentAlert("Camera Malfunction", ', '.join(bad_cams)) + + +def calibration_invalid_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: + rpy = sm['liveCalibration'].rpyCalib + yaw = math.degrees(rpy[2] if len(rpy) == 3 else math.nan) + pitch = math.degrees(rpy[1] if len(rpy) == 3 else math.nan) + angles = f"Pitch: {pitch:.1f}°, Yaw: {yaw:.1f}°" + return NormalPermanentAlert("Calibration Invalid", angles) + + +def overheat_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: + cpu = max(sm['deviceState'].cpuTempC, default=0.) + gpu = max(sm['deviceState'].gpuTempC, default=0.) + temp = max((cpu, gpu, sm['deviceState'].memoryTempC)) + return NormalPermanentAlert("System Overheated", f"{temp:.0f} °C") + + +def low_memory_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: + return NormalPermanentAlert("Low Memory", f"{sm['deviceState'].memoryUsagePercent}% used") + + +def high_cpu_usage_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: + x = max(sm['deviceState'].cpuUsagePercent, default=0.) + return NormalPermanentAlert("High CPU Usage", f"{x}% used") + + +def modeld_lagging_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: + return NormalPermanentAlert("Driving Model Lagging", f"{sm['modelV2'].frameDropPerc:.1f}% frames dropped") + + +def wrong_car_mode_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: text = "Cruise Mode Disabled" if CP.carName == "honda": text = "Main Switch Off" return NoEntryAlert(text) -def joystick_alert(CP: car.CarParams, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: +def joystick_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: axes = sm['testJoystick'].axes gb, steer = list(axes)[:2] if len(axes) else (0., 0.) vals = f"Gas: {round(gb * 100.)}%, Steer: {round(steer * 100.)}%" @@ -356,14 +421,6 @@ EVENTS: Dict[int, Dict[str, Union[Alert, AlertCallbackType]]] = { # ********** events only containing alerts that display while engaged ********** - EventName.gasPressed: { - ET.PRE_ENABLE: Alert( - "Release Gas Pedal to Engage", - "", - AlertStatus.normal, AlertSize.small, - Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .1, creation_delay=1.), - }, - # openpilot tries to learn certain parameters about your car by observing # how the car behaves to steering inputs from both human and openpilot driving. # This includes: @@ -382,7 +439,7 @@ EVENTS: Dict[int, Dict[str, Union[Alert, AlertCallbackType]]] = { "Steering Temporarily Unavailable", "", AlertStatus.userPrompt, AlertSize.small, - Priority.LOW, VisualAlert.steerRequired, AudibleAlert.prompt, 1.), + Priority.LOW, VisualAlert.steerRequired, AudibleAlert.prompt, 1.8), }, EventName.preDriverDistracted: { @@ -444,7 +501,7 @@ EVENTS: Dict[int, Dict[str, Union[Alert, AlertCallbackType]]] = { EventName.resumeRequired: { ET.WARNING: Alert( "STOPPED", - "Press Resume to Go", + "Press Resume to Exit Standstill", AlertStatus.userPrompt, AlertSize.mid, Priority.LOW, VisualAlert.none, AudibleAlert.none, .2), }, @@ -495,24 +552,32 @@ EVENTS: Dict[int, Dict[str, Union[Alert, AlertCallbackType]]] = { # Thrown when the fan is driven at >50% but is not rotating EventName.fanMalfunction: { - ET.PERMANENT: NormalPermanentAlert("Fan Malfunction", "Contact Support"), + ET.PERMANENT: NormalPermanentAlert("Fan Malfunction", "Likely Hardware Issue"), }, - # Camera is not outputting frames at a constant framerate + # Camera is not outputting frames EventName.cameraMalfunction: { - ET.PERMANENT: NormalPermanentAlert("Camera Malfunction", "Contact Support"), + ET.PERMANENT: camera_malfunction_alert, + ET.SOFT_DISABLE: soft_disable_alert("Camera Malfunction"), + ET.NO_ENTRY: NoEntryAlert("Camera Malfunction: Reboot Your Device"), + }, + # Camera framerate too low + EventName.cameraFrameRate: { + ET.PERMANENT: NormalPermanentAlert("Camera Frame Rate Low", "Reboot your Device"), + ET.SOFT_DISABLE: soft_disable_alert("Camera Frame Rate Low"), + ET.NO_ENTRY: NoEntryAlert("Camera Frame Rate Low: Reboot Your Device"), }, # Unused EventName.gpsMalfunction: { - ET.PERMANENT: NormalPermanentAlert("GPS Malfunction", "Contact Support"), + ET.PERMANENT: NormalPermanentAlert("GPS Malfunction", "Likely Hardware Issue"), }, # When the GPS position and localizer diverge the localizer is reset to the # current GPS position. This alert is thrown when the localizer is reset # more often than expected. EventName.localizerMalfunction: { - # ET.PERMANENT: NormalPermanentAlert("Sensor Malfunction", "Contact Support"), + # ET.PERMANENT: NormalPermanentAlert("Sensor Malfunction", "Hardware Malfunction"), }, # ********** events that affect controls state transitions ********** @@ -531,6 +596,7 @@ EVENTS: Dict[int, Dict[str, Union[Alert, AlertCallbackType]]] = { EventName.buttonCancel: { ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), + ET.NO_ENTRY: NoEntryAlert("Cancel Pressed"), }, EventName.brakeHold: { @@ -549,11 +615,39 @@ EVENTS: Dict[int, Dict[str, Union[Alert, AlertCallbackType]]] = { visual_alert=VisualAlert.brakePressed), }, + EventName.preEnableStandstill: { + ET.PRE_ENABLE: Alert( + "Release Brake to Engage", + "", + AlertStatus.normal, AlertSize.small, + Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .1, creation_delay=1.), + }, + + EventName.gasPressedOverride: { + ET.OVERRIDE_LONGITUDINAL: Alert( + "", + "", + AlertStatus.normal, AlertSize.none, + Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .1), + }, + + EventName.steerOverride: { + ET.OVERRIDE_LATERAL: Alert( + "", + "", + AlertStatus.normal, AlertSize.none, + Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .1), + }, + EventName.wrongCarMode: { ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), ET.NO_ENTRY: wrong_car_mode_alert, }, + EventName.resumeBlocked: { + ET.NO_ENTRY: NoEntryAlert("Press Set to Engage"), + }, + EventName.wrongCruiseMode: { ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), ET.NO_ENTRY: NoEntryAlert("Adaptive Cruise Disabled"), @@ -565,7 +659,7 @@ EVENTS: Dict[int, Dict[str, Union[Alert, AlertCallbackType]]] = { }, EventName.outOfSpace: { - ET.PERMANENT: NormalPermanentAlert("Out of Storage"), + ET.PERMANENT: out_of_space_alert, ET.NO_ENTRY: NoEntryAlert("Out of Storage"), }, @@ -575,11 +669,12 @@ EVENTS: Dict[int, Dict[str, Union[Alert, AlertCallbackType]]] = { EventName.sensorDataInvalid: { ET.PERMANENT: Alert( - "No Data from Device Sensors", - "Reboot your Device", + "Sensor Data Invalid", + "Ensure device is mounted securely", AlertStatus.normal, AlertSize.mid, Priority.LOWER, VisualAlert.none, AudibleAlert.none, .2, creation_delay=1.), - ET.NO_ENTRY: NoEntryAlert("No Data from Device Sensors"), + ET.NO_ENTRY: NoEntryAlert("Sensor Data Invalid"), + ET.SOFT_DISABLE: soft_disable_alert("Sensor Data Invalid"), }, EventName.noGps: { @@ -596,7 +691,7 @@ EVENTS: Dict[int, Dict[str, Union[Alert, AlertCallbackType]]] = { }, EventName.overheat: { - ET.PERMANENT: NormalPermanentAlert("System Overheated"), + ET.PERMANENT: overheat_alert, ET.SOFT_DISABLE: soft_disable_alert("System Overheated"), ET.NO_ENTRY: NoEntryAlert("System Overheated"), }, @@ -612,7 +707,7 @@ EVENTS: Dict[int, Dict[str, Union[Alert, AlertCallbackType]]] = { # and attaching while making sure the device is pointed straight forward and is level. # See https://comma.ai/setup for more information EventName.calibrationInvalid: { - ET.PERMANENT: NormalPermanentAlert("Calibration Invalid", "Remount Device and Recalibrate"), + ET.PERMANENT: calibration_invalid_alert, ET.SOFT_DISABLE: soft_disable_alert("Calibration Invalid: Remount Device & Recalibrate"), ET.NO_ENTRY: NoEntryAlert("Calibration Invalid: Remount Device & Recalibrate"), }, @@ -649,12 +744,22 @@ EVENTS: Dict[int, Dict[str, Union[Alert, AlertCallbackType]]] = { # ten times the regular interval, or the average interval is more than 10% too high. EventName.commIssue: { ET.SOFT_DISABLE: soft_disable_alert("Communication Issue between Processes"), - ET.NO_ENTRY: NoEntryAlert("Communication Issue between Processes"), + ET.NO_ENTRY: comm_issue_alert, + }, + EventName.commIssueAvgFreq: { + ET.SOFT_DISABLE: soft_disable_alert("Low Communication Rate between Processes"), + ET.NO_ENTRY: NoEntryAlert("Low Communication Rate between Processes"), + }, + + EventName.controlsdLagging: { + ET.SOFT_DISABLE: soft_disable_alert("Controls Lagging"), + ET.NO_ENTRY: NoEntryAlert("Controls Process Lagging: Reboot Your Device"), }, # Thrown when manager detects a service exited unexpectedly while driving EventName.processNotRunning: { - ET.NO_ENTRY: NoEntryAlert("System Malfunction: Reboot Your Device"), + ET.NO_ENTRY: process_not_running_alert, + ET.SOFT_DISABLE: soft_disable_alert("Process Not Running"), }, EventName.radarFault: { @@ -666,8 +771,9 @@ EVENTS: Dict[int, Dict[str, Union[Alert, AlertCallbackType]]] = { # is not processing frames fast enough they have to be dropped. This alert is # thrown when over 20% of frames are dropped. EventName.modeldLagging: { - ET.SOFT_DISABLE: soft_disable_alert("Driving model lagging"), - ET.NO_ENTRY: NoEntryAlert("Driving model lagging"), + ET.SOFT_DISABLE: soft_disable_alert("Driving Model Lagging"), + ET.NO_ENTRY: NoEntryAlert("Driving Model Lagging"), + ET.PERMANENT: modeld_lagging_alert, }, # Besides predicting the path, lane lines and lead car data the model also @@ -676,8 +782,8 @@ EVENTS: Dict[int, Dict[str, Union[Alert, AlertCallbackType]]] = { # usually means the model has trouble understanding the scene. This is used # as a heuristic to warn the driver. EventName.posenetInvalid: { - ET.SOFT_DISABLE: soft_disable_alert("Model Output Uncertain"), - ET.NO_ENTRY: NoEntryAlert("Model Output Uncertain"), + ET.SOFT_DISABLE: soft_disable_alert("Posenet Speed Invalid"), + ET.NO_ENTRY: posenet_invalid_alert, }, # When the localizer detects an acceleration of more than 40 m/s^2 (~4G) we @@ -689,14 +795,14 @@ EVENTS: Dict[int, Dict[str, Union[Alert, AlertCallbackType]]] = { EventName.lowMemory: { ET.SOFT_DISABLE: soft_disable_alert("Low Memory: Reboot Your Device"), - ET.PERMANENT: NormalPermanentAlert("Low Memory", "Reboot your Device"), + ET.PERMANENT: low_memory_alert, ET.NO_ENTRY: NoEntryAlert("Low Memory: Reboot Your Device"), }, EventName.highCpuUsage: { #ET.SOFT_DISABLE: soft_disable_alert("System Malfunction: Reboot Your Device"), #ET.PERMANENT: NormalPermanentAlert("System Malfunction", "Reboot your Device"), - ET.NO_ENTRY: NoEntryAlert("System Malfunction: Reboot Your Device"), + ET.NO_ENTRY: high_cpu_usage_alert, }, EventName.accFaulted: { @@ -705,24 +811,29 @@ EVENTS: Dict[int, Dict[str, Union[Alert, AlertCallbackType]]] = { ET.NO_ENTRY: NoEntryAlert("Cruise Faulted"), }, + EventName.accFaultedTemp: { + ET.NO_ENTRY: NoEntryAlert("Cruise Temporarily Faulted"), + }, + EventName.controlsMismatch: { ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Controls Mismatch"), + ET.NO_ENTRY: NoEntryAlert("Controls Mismatch"), }, EventName.roadCameraError: { - ET.PERMANENT: NormalPermanentAlert("Camera Error", + ET.PERMANENT: NormalPermanentAlert("Camera CRC Error - Road", duration=1., creation_delay=30.), }, - EventName.driverCameraError: { - ET.PERMANENT: NormalPermanentAlert("Camera Error", + EventName.wideRoadCameraError: { + ET.PERMANENT: NormalPermanentAlert("Camera CRC Error - Road Fisheye", duration=1., creation_delay=30.), }, - EventName.wideRoadCameraError: { - ET.PERMANENT: NormalPermanentAlert("Camera Error", + EventName.driverCameraError: { + ET.PERMANENT: NormalPermanentAlert("Camera CRC Error - Driver", duration=1., creation_delay=30.), }, @@ -740,7 +851,7 @@ EVENTS: Dict[int, Dict[str, Union[Alert, AlertCallbackType]]] = { # - CAN data is received, but some message are not received at the right frequency # If you're not writing a new car port, this is usually cause by faulty wiring EventName.canError: { - ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("CAN Error: Check Connections"), + ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("CAN Error"), ET.PERMANENT: Alert( "CAN Error: Check Connections", "", @@ -749,6 +860,16 @@ EVENTS: Dict[int, Dict[str, Union[Alert, AlertCallbackType]]] = { ET.NO_ENTRY: NoEntryAlert("CAN Error: Check Connections"), }, + EventName.canBusMissing: { + ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("CAN Bus Disconnected"), + ET.PERMANENT: Alert( + "CAN Bus Disconnected: Likely Faulty Cable", + "", + AlertStatus.normal, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.none, 1., creation_delay=1.), + ET.NO_ENTRY: NoEntryAlert("CAN Bus Disconnected: Check Connections"), + }, + EventName.steerUnavailable: { ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("LKAS Fault: Restart the Car"), ET.PERMANENT: NormalPermanentAlert("LKAS Fault: Restart the car to engage"), @@ -790,18 +911,9 @@ EVENTS: Dict[int, Dict[str, Union[Alert, AlertCallbackType]]] = { # are received on the car side this usually means the relay hasn't opened correctly # and this alert is thrown. EventName.relayMalfunction: { - ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Harness Malfunction"), - ET.PERMANENT: NormalPermanentAlert("Harness Malfunction", "Check Hardware"), - ET.NO_ENTRY: NoEntryAlert("Harness Malfunction"), - }, - - EventName.noTarget: { - ET.IMMEDIATE_DISABLE: Alert( - "openpilot Canceled", - "No close lead car", - AlertStatus.normal, AlertSize.mid, - Priority.HIGH, VisualAlert.none, AudibleAlert.disengage, 3.), - ET.NO_ENTRY: NoEntryAlert("No Close Lead Car"), + ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Harness Relay Malfunction"), + ET.PERMANENT: NormalPermanentAlert("Harness Relay Malfunction", "Check Hardware"), + ET.NO_ENTRY: NoEntryAlert("Harness Relay Malfunction"), }, EventName.speedTooLow: { diff --git a/selfdrive/controls/lib/lane_planner.py b/selfdrive/controls/lib/lane_planner.py deleted file mode 100644 index 0230255ef9..0000000000 --- a/selfdrive/controls/lib/lane_planner.py +++ /dev/null @@ -1,105 +0,0 @@ -import numpy as np -from cereal import log -from common.filter_simple import FirstOrderFilter -from common.numpy_fast import interp -from common.realtime import DT_MDL -from selfdrive.hardware import EON, TICI -from selfdrive.swaglog import cloudlog - - -TRAJECTORY_SIZE = 33 -# camera offset is meters from center car to camera -# model path is in the frame of the camera. Empirically -# the model knows the difference between TICI and EON -# so a path offset is not needed -PATH_OFFSET = 0.00 -if EON: - CAMERA_OFFSET = -0.06 -elif TICI: - CAMERA_OFFSET = 0.04 -else: - CAMERA_OFFSET = 0.0 - - -class LanePlanner: - def __init__(self, wide_camera=False): - self.ll_t = np.zeros((TRAJECTORY_SIZE,)) - self.ll_x = np.zeros((TRAJECTORY_SIZE,)) - self.lll_y = np.zeros((TRAJECTORY_SIZE,)) - self.rll_y = np.zeros((TRAJECTORY_SIZE,)) - self.lane_width_estimate = FirstOrderFilter(3.7, 9.95, DT_MDL) - self.lane_width_certainty = FirstOrderFilter(1.0, 0.95, DT_MDL) - self.lane_width = 3.7 - - self.lll_prob = 0. - self.rll_prob = 0. - self.d_prob = 0. - - self.lll_std = 0. - self.rll_std = 0. - - self.l_lane_change_prob = 0. - self.r_lane_change_prob = 0. - - self.camera_offset = -CAMERA_OFFSET if wide_camera else CAMERA_OFFSET - self.path_offset = -PATH_OFFSET if wide_camera else PATH_OFFSET - - def parse_model(self, md): - lane_lines = md.laneLines - if len(lane_lines) == 4 and len(lane_lines[0].t) == TRAJECTORY_SIZE: - self.ll_t = (np.array(lane_lines[1].t) + np.array(lane_lines[2].t))/2 - # left and right ll x is the same - self.ll_x = lane_lines[1].x - self.lll_y = np.array(lane_lines[1].y) + self.camera_offset - self.rll_y = np.array(lane_lines[2].y) + self.camera_offset - self.lll_prob = md.laneLineProbs[1] - self.rll_prob = md.laneLineProbs[2] - self.lll_std = md.laneLineStds[1] - self.rll_std = md.laneLineStds[2] - - desire_state = md.meta.desireState - if len(desire_state): - self.l_lane_change_prob = desire_state[log.LateralPlan.Desire.laneChangeLeft] - self.r_lane_change_prob = desire_state[log.LateralPlan.Desire.laneChangeRight] - - def get_d_path(self, v_ego, path_t, path_xyz): - # Reduce reliance on lanelines that are too far apart or - # will be in a few seconds - path_xyz[:, 1] += self.path_offset - l_prob, r_prob = self.lll_prob, self.rll_prob - width_pts = self.rll_y - self.lll_y - prob_mods = [] - for t_check in (0.0, 1.5, 3.0): - width_at_t = interp(t_check * (v_ego + 7), self.ll_x, width_pts) - prob_mods.append(interp(width_at_t, [4.0, 5.0], [1.0, 0.0])) - mod = min(prob_mods) - l_prob *= mod - r_prob *= mod - - # Reduce reliance on uncertain lanelines - l_std_mod = interp(self.lll_std, [.15, .3], [1.0, 0.0]) - r_std_mod = interp(self.rll_std, [.15, .3], [1.0, 0.0]) - l_prob *= l_std_mod - r_prob *= r_std_mod - - # Find current lanewidth - self.lane_width_certainty.update(l_prob * r_prob) - current_lane_width = abs(self.rll_y[0] - self.lll_y[0]) - self.lane_width_estimate.update(current_lane_width) - speed_lane_width = interp(v_ego, [0., 31.], [2.8, 3.5]) - self.lane_width = self.lane_width_certainty.x * self.lane_width_estimate.x + \ - (1 - self.lane_width_certainty.x) * speed_lane_width - - clipped_lane_width = min(4.0, self.lane_width) - path_from_left_lane = self.lll_y + clipped_lane_width / 2.0 - path_from_right_lane = self.rll_y - clipped_lane_width / 2.0 - - self.d_prob = l_prob + r_prob - l_prob * r_prob - lane_path_y = (l_prob * path_from_left_lane + r_prob * path_from_right_lane) / (l_prob + r_prob + 0.0001) - safe_idxs = np.isfinite(self.ll_t) - if safe_idxs[0]: - lane_path_y_interp = np.interp(path_t, self.ll_t[safe_idxs], lane_path_y[safe_idxs]) - path_xyz[:,1] = self.d_prob * lane_path_y_interp + (1.0 - self.d_prob) * path_xyz[:,1] - else: - cloudlog.warning("Lateral mpc - NaNs in laneline times, ignoring") - return path_xyz diff --git a/selfdrive/controls/lib/latcontrol.py b/selfdrive/controls/lib/latcontrol.py index eb16aca2e8..78b59fda59 100644 --- a/selfdrive/controls/lib/latcontrol.py +++ b/selfdrive/controls/lib/latcontrol.py @@ -1,7 +1,7 @@ from abc import abstractmethod, ABC -from common.realtime import DT_CTRL from common.numpy_fast import clip +from common.realtime import DT_CTRL MIN_STEER_SPEED = 0.3 @@ -12,15 +12,18 @@ class LatControl(ABC): self.sat_limit = CP.steerLimitTimer self.sat_count = 0. + # we define the steer torque scale as [-1.0...1.0] + self.steer_max = 1.0 + @abstractmethod - def update(self, active, CS, CP, VM, params, last_actuators, desired_curvature, desired_curvature_rate): + def update(self, active, CS, VM, params, last_actuators, steer_limited, desired_curvature, desired_curvature_rate, llk): pass def reset(self): self.sat_count = 0. - def _check_saturation(self, saturated, CS): - if saturated and CS.vEgo > 10. and not CS.steeringRateLimited and not CS.steeringPressed: + def _check_saturation(self, saturated, CS, steer_limited): + if saturated and CS.vEgo > 10. and not steer_limited and not CS.steeringPressed: self.sat_count += self.sat_count_rate else: self.sat_count -= self.sat_count_rate diff --git a/selfdrive/controls/lib/latcontrol_angle.py b/selfdrive/controls/lib/latcontrol_angle.py index 414df2b662..2507771a7d 100644 --- a/selfdrive/controls/lib/latcontrol_angle.py +++ b/selfdrive/controls/lib/latcontrol_angle.py @@ -7,7 +7,7 @@ STEER_ANGLE_SATURATION_THRESHOLD = 2.5 # Degrees class LatControlAngle(LatControl): - def update(self, active, CS, CP, VM, params, last_actuators, desired_curvature, desired_curvature_rate): + def update(self, active, CS, VM, params, last_actuators, steer_limited, desired_curvature, desired_curvature_rate, llk): angle_log = log.ControlsState.LateralAngleState.new_message() if not active: @@ -19,7 +19,7 @@ class LatControlAngle(LatControl): angle_steers_des += params.angleOffsetDeg angle_control_saturated = abs(angle_steers_des - CS.steeringAngleDeg) > STEER_ANGLE_SATURATION_THRESHOLD - angle_log.saturated = self._check_saturation(angle_control_saturated, CS) + angle_log.saturated = self._check_saturation(angle_control_saturated, CS, steer_limited) angle_log.steeringAngleDeg = float(CS.steeringAngleDeg) angle_log.steeringAngleDesiredDeg = angle_steers_des return 0, float(angle_steers_des), angle_log diff --git a/selfdrive/controls/lib/latcontrol_indi.py b/selfdrive/controls/lib/latcontrol_indi.py index dc1b31bad9..2bc3cef76b 100644 --- a/selfdrive/controls/lib/latcontrol_indi.py +++ b/selfdrive/controls/lib/latcontrol_indi.py @@ -5,7 +5,6 @@ from cereal import log from common.filter_simple import FirstOrderFilter from common.numpy_fast import clip, interp from common.realtime import DT_CTRL -from selfdrive.controls.lib.drive_helpers import get_steer_max from selfdrive.controls.lib.latcontrol import LatControl, MIN_STEER_SPEED @@ -41,7 +40,6 @@ class LatControlINDI(LatControl): self._inner_loop_gain = (CP.lateralTuning.indi.innerLoopGainBP, CP.lateralTuning.indi.innerLoopGainV) self.steer_filter = FirstOrderFilter(0., self.RC, DT_CTRL) - self.reset() @property @@ -65,7 +63,7 @@ class LatControlINDI(LatControl): self.steer_filter.x = 0. self.speed = 0. - def update(self, active, CS, CP, VM, params, last_actuators, desired_curvature, desired_curvature_rate): + def update(self, active, CS, VM, params, last_actuators, steer_limited, desired_curvature, desired_curvature_rate, llk): self.speed = CS.vEgo # Update Kalman filter y = np.array([[math.radians(CS.steeringAngleDeg)], [math.radians(CS.steeringRateDeg)]]) @@ -80,6 +78,7 @@ class LatControlINDI(LatControl): steers_des += math.radians(params.angleOffsetDeg) indi_log.steeringAngleDesiredDeg = math.degrees(steers_des) + # desired rate is the desired rate of change in the setpoint, not the absolute desired curvature rate_des = VM.get_steer_from_curvature(-desired_curvature_rate, CS.vEgo, 0) indi_log.steeringRateDesiredDeg = math.degrees(rate_des) @@ -107,8 +106,7 @@ class LatControlINDI(LatControl): output_steer = self.steer_filter.x + delta_u - steers_max = get_steer_max(CP, CS.vEgo) - output_steer = clip(output_steer, -steers_max, steers_max) + output_steer = clip(output_steer, -self.steer_max, self.steer_max) indi_log.active = True indi_log.rateSetPoint = float(rate_sp) @@ -117,6 +115,6 @@ class LatControlINDI(LatControl): indi_log.delayedOutput = float(self.steer_filter.x) indi_log.delta = float(delta_u) indi_log.output = float(output_steer) - indi_log.saturated = self._check_saturation(steers_max - abs(output_steer) < 1e-3, CS) + indi_log.saturated = self._check_saturation(self.steer_max - abs(output_steer) < 1e-3, CS, steer_limited) return float(output_steer), float(steers_des), indi_log diff --git a/selfdrive/controls/lib/latcontrol_lqr.py b/selfdrive/controls/lib/latcontrol_lqr.py deleted file mode 100644 index 5c273a45be..0000000000 --- a/selfdrive/controls/lib/latcontrol_lqr.py +++ /dev/null @@ -1,86 +0,0 @@ -import math -import numpy as np - -from common.numpy_fast import clip -from common.realtime import DT_CTRL -from cereal import log -from selfdrive.controls.lib.drive_helpers import get_steer_max -from selfdrive.controls.lib.latcontrol import LatControl, MIN_STEER_SPEED - - -class LatControlLQR(LatControl): - def __init__(self, CP, CI): - super().__init__(CP, CI) - self.scale = CP.lateralTuning.lqr.scale - self.ki = CP.lateralTuning.lqr.ki - - self.A = np.array(CP.lateralTuning.lqr.a).reshape((2, 2)) - self.B = np.array(CP.lateralTuning.lqr.b).reshape((2, 1)) - self.C = np.array(CP.lateralTuning.lqr.c).reshape((1, 2)) - self.K = np.array(CP.lateralTuning.lqr.k).reshape((1, 2)) - self.L = np.array(CP.lateralTuning.lqr.l).reshape((2, 1)) - self.dc_gain = CP.lateralTuning.lqr.dcGain - - self.x_hat = np.array([[0], [0]]) - self.i_unwind_rate = 0.3 * DT_CTRL - self.i_rate = 1.0 * DT_CTRL - - self.reset() - - def reset(self): - super().reset() - self.i_lqr = 0.0 - - def update(self, active, CS, CP, VM, params, last_actuators, desired_curvature, desired_curvature_rate): - lqr_log = log.ControlsState.LateralLQRState.new_message() - - steers_max = get_steer_max(CP, CS.vEgo) - torque_scale = (0.45 + CS.vEgo / 60.0)**2 # Scale actuator model with speed - - # Subtract offset. Zero angle should correspond to zero torque - steering_angle_no_offset = CS.steeringAngleDeg - params.angleOffsetAverageDeg - - desired_angle = math.degrees(VM.get_steer_from_curvature(-desired_curvature, CS.vEgo, params.roll)) - - instant_offset = params.angleOffsetDeg - params.angleOffsetAverageDeg - desired_angle += instant_offset # Only add offset that originates from vehicle model errors - lqr_log.steeringAngleDesiredDeg = desired_angle - - # Update Kalman filter - angle_steers_k = float(self.C.dot(self.x_hat)) - e = steering_angle_no_offset - angle_steers_k - self.x_hat = self.A.dot(self.x_hat) + self.B.dot(CS.steeringTorqueEps / torque_scale) + self.L.dot(e) - - if CS.vEgo < MIN_STEER_SPEED or not active: - lqr_log.active = False - lqr_output = 0. - output_steer = 0. - self.reset() - else: - lqr_log.active = True - - # LQR - u_lqr = float(desired_angle / self.dc_gain - self.K.dot(self.x_hat)) - lqr_output = torque_scale * u_lqr / self.scale - - # Integrator - if CS.steeringPressed: - self.i_lqr -= self.i_unwind_rate * float(np.sign(self.i_lqr)) - else: - error = desired_angle - angle_steers_k - i = self.i_lqr + self.ki * self.i_rate * error - control = lqr_output + i - - if (error >= 0 and (control <= steers_max or i < 0.0)) or \ - (error <= 0 and (control >= -steers_max or i > 0.0)): - self.i_lqr = i - - output_steer = lqr_output + self.i_lqr - output_steer = clip(output_steer, -steers_max, steers_max) - - lqr_log.steeringAngleDeg = angle_steers_k - lqr_log.i = self.i_lqr - lqr_log.output = output_steer - lqr_log.lqrOutput = lqr_output - lqr_log.saturated = self._check_saturation(steers_max - abs(output_steer) < 1e-3, CS) - return output_steer, desired_angle, lqr_log diff --git a/selfdrive/controls/lib/latcontrol_pid.py b/selfdrive/controls/lib/latcontrol_pid.py index f5ff5a95e5..6bd678073e 100644 --- a/selfdrive/controls/lib/latcontrol_pid.py +++ b/selfdrive/controls/lib/latcontrol_pid.py @@ -1,54 +1,48 @@ import math -from selfdrive.controls.lib.pid import PIController -from selfdrive.controls.lib.drive_helpers import get_steer_max -from selfdrive.controls.lib.latcontrol import LatControl, MIN_STEER_SPEED from cereal import log +from selfdrive.controls.lib.latcontrol import LatControl, MIN_STEER_SPEED +from selfdrive.controls.lib.pid import PIDController class LatControlPID(LatControl): def __init__(self, CP, CI): super().__init__(CP, CI) - self.pid = PIController((CP.lateralTuning.pid.kpBP, CP.lateralTuning.pid.kpV), - (CP.lateralTuning.pid.kiBP, CP.lateralTuning.pid.kiV), - k_f=CP.lateralTuning.pid.kf, pos_limit=1.0, neg_limit=-1.0) + self.pid = PIDController((CP.lateralTuning.pid.kpBP, CP.lateralTuning.pid.kpV), + (CP.lateralTuning.pid.kiBP, CP.lateralTuning.pid.kiV), + k_f=CP.lateralTuning.pid.kf, pos_limit=self.steer_max, neg_limit=-self.steer_max) self.get_steer_feedforward = CI.get_steer_feedforward_function() def reset(self): super().reset() self.pid.reset() - def update(self, active, CS, CP, VM, params, last_actuators, desired_curvature, desired_curvature_rate): + def update(self, active, CS, VM, params, last_actuators, steer_limited, desired_curvature, desired_curvature_rate, llk): pid_log = log.ControlsState.LateralPIDState.new_message() pid_log.steeringAngleDeg = float(CS.steeringAngleDeg) pid_log.steeringRateDeg = float(CS.steeringRateDeg) angle_steers_des_no_offset = math.degrees(VM.get_steer_from_curvature(-desired_curvature, CS.vEgo, params.roll)) angle_steers_des = angle_steers_des_no_offset + params.angleOffsetDeg + error = angle_steers_des - CS.steeringAngleDeg pid_log.steeringAngleDesiredDeg = angle_steers_des - pid_log.angleError = angle_steers_des - CS.steeringAngleDeg + pid_log.angleError = error if CS.vEgo < MIN_STEER_SPEED or not active: output_steer = 0.0 pid_log.active = False self.pid.reset() else: - steers_max = get_steer_max(CP, CS.vEgo) - self.pid.pos_limit = steers_max - self.pid.neg_limit = -steers_max - # offset does not contribute to resistive torque steer_feedforward = self.get_steer_feedforward(angle_steers_des_no_offset, CS.vEgo) - deadzone = 0.0 - - output_steer = self.pid.update(angle_steers_des, CS.steeringAngleDeg, override=CS.steeringPressed, - feedforward=steer_feedforward, speed=CS.vEgo, deadzone=deadzone) + output_steer = self.pid.update(error, override=CS.steeringPressed, + feedforward=steer_feedforward, speed=CS.vEgo) pid_log.active = True pid_log.p = self.pid.p pid_log.i = self.pid.i pid_log.f = self.pid.f pid_log.output = output_steer - pid_log.saturated = self._check_saturation(steers_max - abs(output_steer) < 1e-3, CS) + pid_log.saturated = self._check_saturation(self.steer_max - abs(output_steer) < 1e-3, CS, steer_limited) return output_steer, angle_steers_des, pid_log diff --git a/selfdrive/controls/lib/latcontrol_torque.py b/selfdrive/controls/lib/latcontrol_torque.py new file mode 100644 index 0000000000..d10d39d945 --- /dev/null +++ b/selfdrive/controls/lib/latcontrol_torque.py @@ -0,0 +1,89 @@ +import math + +from cereal import log +from common.numpy_fast import interp +from selfdrive.controls.lib.latcontrol import LatControl, MIN_STEER_SPEED +from selfdrive.controls.lib.pid import PIDController +from selfdrive.controls.lib.vehicle_model import ACCELERATION_DUE_TO_GRAVITY + +# At higher speeds (25+mph) we can assume: +# Lateral acceleration achieved by a specific car correlates to +# torque applied to the steering rack. It does not correlate to +# wheel slip, or to speed. + +# This controller applies torque to achieve desired lateral +# accelerations. To compensate for the low speed effects we +# use a LOW_SPEED_FACTOR in the error. Additionally, there is +# friction in the steering wheel that needs to be overcome to +# move it at all, this is compensated for too. + +LOW_SPEED_X = [0, 10, 20, 30] +LOW_SPEED_Y = [15, 13, 10, 5] + + +class LatControlTorque(LatControl): + def __init__(self, CP, CI): + super().__init__(CP, CI) + self.torque_params = CP.lateralTuning.torque + self.pid = PIDController(self.torque_params.kp, self.torque_params.ki, + k_f=self.torque_params.kf, pos_limit=self.steer_max, neg_limit=-self.steer_max) + self.torque_from_lateral_accel = CI.torque_from_lateral_accel() + self.use_steering_angle = self.torque_params.useSteeringAngle + self.steering_angle_deadzone_deg = self.torque_params.steeringAngleDeadzoneDeg + + def update_live_torque_params(self, latAccelFactor, latAccelOffset, friction): + self.torque_params.latAccelFactor = latAccelFactor + self.torque_params.latAccelOffset = latAccelOffset + self.torque_params.friction = friction + + def update(self, active, CS, VM, params, last_actuators, steer_limited, desired_curvature, desired_curvature_rate, llk): + pid_log = log.ControlsState.LateralTorqueState.new_message() + + if CS.vEgo < MIN_STEER_SPEED or not active: + output_torque = 0.0 + pid_log.active = False + else: + if self.use_steering_angle: + actual_curvature = -VM.calc_curvature(math.radians(CS.steeringAngleDeg - params.angleOffsetDeg), CS.vEgo, params.roll) + curvature_deadzone = abs(VM.calc_curvature(math.radians(self.steering_angle_deadzone_deg), CS.vEgo, 0.0)) + else: + actual_curvature_vm = -VM.calc_curvature(math.radians(CS.steeringAngleDeg - params.angleOffsetDeg), CS.vEgo, params.roll) + actual_curvature_llk = llk.angularVelocityCalibrated.value[2] / CS.vEgo + actual_curvature = interp(CS.vEgo, [2.0, 5.0], [actual_curvature_vm, actual_curvature_llk]) + curvature_deadzone = 0.0 + desired_lateral_accel = desired_curvature * CS.vEgo ** 2 + + # desired rate is the desired rate of change in the setpoint, not the absolute desired curvature + # desired_lateral_jerk = desired_curvature_rate * CS.vEgo ** 2 + actual_lateral_accel = actual_curvature * CS.vEgo ** 2 + lateral_accel_deadzone = curvature_deadzone * CS.vEgo ** 2 + + low_speed_factor = interp(CS.vEgo, LOW_SPEED_X, LOW_SPEED_Y)**2 + setpoint = desired_lateral_accel + low_speed_factor * desired_curvature + measurement = actual_lateral_accel + low_speed_factor * actual_curvature + error = setpoint - measurement + gravity_adjusted_lateral_accel = desired_lateral_accel - params.roll * ACCELERATION_DUE_TO_GRAVITY + pid_log.error = self.torque_from_lateral_accel(error, self.torque_params, error, + lateral_accel_deadzone, friction_compensation=False) + ff = self.torque_from_lateral_accel(gravity_adjusted_lateral_accel, self.torque_params, + desired_lateral_accel - actual_lateral_accel, + lateral_accel_deadzone, friction_compensation=True) + + freeze_integrator = steer_limited or CS.steeringPressed or CS.vEgo < 5 + output_torque = self.pid.update(pid_log.error, + feedforward=ff, + speed=CS.vEgo, + freeze_integrator=freeze_integrator) + + pid_log.active = True + pid_log.p = self.pid.p + pid_log.i = self.pid.i + pid_log.d = self.pid.d + pid_log.f = self.pid.f + pid_log.output = -output_torque + pid_log.actualLateralAccel = actual_lateral_accel + pid_log.desiredLateralAccel = desired_lateral_accel + pid_log.saturated = self._check_saturation(self.steer_max - abs(output_torque) < 1e-3, CS, steer_limited) + + # TODO left is positive in this convention + return -output_torque, 0.0, pid_log diff --git a/selfdrive/controls/lib/lateral_mpc_lib/SConscript b/selfdrive/controls/lib/lateral_mpc_lib/SConscript index f402e6e15e..df1e2a2a1a 100644 --- a/selfdrive/controls/lib/lateral_mpc_lib/SConscript +++ b/selfdrive/controls/lib/lateral_mpc_lib/SConscript @@ -43,11 +43,21 @@ generated_files = [ f'{gen}/lat_cost/lat_cost_y_0_fun.h', ] + build_files +acados_dir = '#third_party/acados' +acados_templates_dir = '#pyextra/acados_template/c_templates_tera' + +source_list = ['lat_mpc.py', + f'{acados_dir}/include/acados_c/ocp_nlp_interface.h', + f'{acados_dir}/x86_64/lib/libacados.so', + f'{acados_dir}/larch64/lib/libacados.so', + f'{acados_templates_dir}/acados_solver.in.c', +] + lenv = env.Clone() lenv.Clean(generated_files, Dir(gen)) lenv.Command(generated_files, - ["lat_mpc.py"], + source_list, f"cd {Dir('.').abspath} && python3 lat_mpc.py") lenv["CFLAGS"].append("-DACADOS_WITH_QPOASES") diff --git a/selfdrive/controls/lib/lateral_mpc_lib/lat_mpc.py b/selfdrive/controls/lib/lateral_mpc_lib/lat_mpc.py index e4a73bf97d..9607532ace 100755 --- a/selfdrive/controls/lib/lateral_mpc_lib/lat_mpc.py +++ b/selfdrive/controls/lib/lateral_mpc_lib/lat_mpc.py @@ -5,31 +5,35 @@ import numpy as np from casadi import SX, vertcat, sin, cos from common.realtime import sec_since_boot -from selfdrive.controls.lib.drive_helpers import LAT_MPC_N as N from selfdrive.modeld.constants import T_IDXS if __name__ == '__main__': # generating code from pyextra.acados_template import AcadosModel, AcadosOcp, AcadosOcpSolver else: - # from pyextra.acados_template import AcadosOcpSolverFast - from selfdrive.controls.lib.lateral_mpc_lib.c_generated_code.acados_ocp_solver_pyx import AcadosOcpSolverFast # pylint: disable=no-name-in-module, import-error + from selfdrive.controls.lib.lateral_mpc_lib.c_generated_code.acados_ocp_solver_pyx import AcadosOcpSolverCython # pylint: disable=no-name-in-module, import-error LAT_MPC_DIR = os.path.dirname(os.path.abspath(__file__)) EXPORT_DIR = os.path.join(LAT_MPC_DIR, "c_generated_code") -JSON_FILE = "acados_ocp_lat.json" +JSON_FILE = os.path.join(LAT_MPC_DIR, "acados_ocp_lat.json") X_DIM = 4 P_DIM = 2 +N = 16 +COST_E_DIM = 3 +COST_DIM = COST_E_DIM + 2 +SPEED_OFFSET = 10.0 +MODEL_NAME = 'lat' +ACADOS_SOLVER_TYPE = 'SQP_RTI' def gen_lat_model(): model = AcadosModel() - model.name = 'lat' + model.name = MODEL_NAME # set up states & controls x_ego = SX.sym('x_ego') y_ego = SX.sym('y_ego') psi_ego = SX.sym('psi_ego') - curv_ego = SX.sym('curv_ego') - model.x = vertcat(x_ego, y_ego, psi_ego, curv_ego) + psi_rate_ego = SX.sym('psi_rate_ego') + model.x = vertcat(x_ego, y_ego, psi_ego, psi_rate_ego) # parameters v_ego = SX.sym('v_ego') @@ -37,28 +41,28 @@ def gen_lat_model(): model.p = vertcat(v_ego, rotation_radius) # controls - curv_rate = SX.sym('curv_rate') - model.u = vertcat(curv_rate) + psi_accel_ego = SX.sym('psi_accel_ego') + model.u = vertcat(psi_accel_ego) # xdot x_ego_dot = SX.sym('x_ego_dot') y_ego_dot = SX.sym('y_ego_dot') psi_ego_dot = SX.sym('psi_ego_dot') - curv_ego_dot = SX.sym('curv_ego_dot') + psi_rate_ego_dot = SX.sym('psi_rate_ego_dot') - model.xdot = vertcat(x_ego_dot, y_ego_dot, psi_ego_dot, curv_ego_dot) + model.xdot = vertcat(x_ego_dot, y_ego_dot, psi_ego_dot, psi_rate_ego_dot) # dynamics model - f_expl = vertcat(v_ego * cos(psi_ego) - rotation_radius * sin(psi_ego) * (v_ego * curv_ego), - v_ego * sin(psi_ego) + rotation_radius * cos(psi_ego) * (v_ego * curv_ego), - v_ego * curv_ego, - curv_rate) + f_expl = vertcat(v_ego * cos(psi_ego) - rotation_radius * sin(psi_ego) * psi_rate_ego, + v_ego * sin(psi_ego) + rotation_radius * cos(psi_ego) * psi_rate_ego, + psi_rate_ego, + psi_accel_ego) model.f_impl_expr = model.xdot - f_expl model.f_expl_expr = f_expl return model -def gen_lat_mpc_solver(): +def gen_lat_ocp(): ocp = AcadosOcp() ocp.model = gen_lat_model() @@ -71,26 +75,35 @@ def gen_lat_mpc_solver(): ocp.cost.cost_type = 'NONLINEAR_LS' ocp.cost.cost_type_e = 'NONLINEAR_LS' - Q = np.diag([0.0, 0.0]) - QR = np.diag([0.0, 0.0, 0.0]) + Q = np.diag(np.zeros(COST_E_DIM)) + QR = np.diag(np.zeros(COST_DIM)) ocp.cost.W = QR ocp.cost.W_e = Q - y_ego, psi_ego = ocp.model.x[1], ocp.model.x[2] - curv_rate = ocp.model.u[0] + y_ego, psi_ego, psi_rate_ego = ocp.model.x[1], ocp.model.x[2], ocp.model.x[3] + psi_rate_ego_dot = ocp.model.u[0] v_ego = ocp.model.p[0] ocp.parameter_values = np.zeros((P_DIM, )) - ocp.cost.yref = np.zeros((3, )) - ocp.cost.yref_e = np.zeros((2, )) - # TODO hacky weights to keep behavior the same + ocp.cost.yref = np.zeros((COST_DIM, )) + ocp.cost.yref_e = np.zeros((COST_E_DIM, )) + # Add offset to smooth out low speed control + # TODO unclear if this right solution long term + v_ego_offset = v_ego + SPEED_OFFSET + # TODO there are two costs on psi_rate_ego_dot, one + # is correlated to jerk the other to steering wheel movement + # the steering wheel movement cost is added to prevent excessive + # wheel movements ocp.model.cost_y_expr = vertcat(y_ego, - ((v_ego +5.0) * psi_ego), - ((v_ego +5.0) * 4 * curv_rate)) + v_ego_offset * psi_ego, + v_ego_offset * psi_rate_ego, + v_ego_offset * psi_rate_ego_dot, + psi_rate_ego_dot / (v_ego + 0.1)) ocp.model.cost_y_expr_e = vertcat(y_ego, - ((v_ego +5.0) * psi_ego)) + v_ego_offset * psi_ego, + v_ego_offset * psi_rate_ego) # set constraints ocp.constraints.constr_type = 'BGH' @@ -103,7 +116,7 @@ def gen_lat_mpc_solver(): ocp.solver_options.qp_solver = 'PARTIAL_CONDENSING_HPIPM' ocp.solver_options.hessian_approx = 'GAUSS_NEWTON' ocp.solver_options.integrator_type = 'ERK' - ocp.solver_options.nlp_solver_type = 'SQP_RTI' + ocp.solver_options.nlp_solver_type = ACADOS_SOLVER_TYPE ocp.solver_options.qp_solver_iter_max = 1 ocp.solver_options.qp_solver_cond_N = 1 @@ -117,16 +130,16 @@ def gen_lat_mpc_solver(): class LateralMpc(): def __init__(self, x0=np.zeros(X_DIM)): - self.solver = AcadosOcpSolverFast('lat', N, EXPORT_DIR) + self.solver = AcadosOcpSolverCython(MODEL_NAME, ACADOS_SOLVER_TYPE, N) self.reset(x0) def reset(self, x0=np.zeros(X_DIM)): self.x_sol = np.zeros((N+1, X_DIM)) self.u_sol = np.zeros((N, 1)) - self.yref = np.zeros((N+1, 3)) + self.yref = np.zeros((N+1, COST_DIM)) for i in range(N): self.solver.cost_set(i, "yref", self.yref[i]) - self.solver.cost_set(N, "yref", self.yref[N][:2]) + self.solver.cost_set(N, "yref", self.yref[N][:COST_E_DIM]) # Somehow needed for stable init for i in range(N+1): @@ -139,14 +152,17 @@ class LateralMpc(): self.solve_time = 0.0 self.cost = 0 - def set_weights(self, path_weight, heading_weight, steer_rate_weight): - W = np.asfortranarray(np.diag([path_weight, heading_weight, steer_rate_weight])) + def set_weights(self, path_weight, heading_weight, + lat_accel_weight, lat_jerk_weight, + steering_rate_weight): + W = np.asfortranarray(np.diag([path_weight, heading_weight, + lat_accel_weight, lat_jerk_weight, + steering_rate_weight])) for i in range(N): self.solver.cost_set(i, 'W', W) - #TODO hacky weights to keep behavior the same - self.solver.cost_set(N, 'W', (3/20.)*W[:2,:2]) + self.solver.cost_set(N, 'W', W[:COST_E_DIM,:COST_E_DIM]) - def run(self, x0, p, y_pts, heading_pts): + def run(self, x0, p, y_pts, heading_pts, yaw_rate_pts): x0_cp = np.copy(x0) p_cp = np.copy(p) self.solver.constraints_set(0, "lbx", x0_cp) @@ -154,12 +170,13 @@ class LateralMpc(): self.yref[:,0] = y_pts v_ego = p_cp[0] # rotation_radius = p_cp[1] - self.yref[:,1] = heading_pts*(v_ego+5.0) + self.yref[:,1] = heading_pts * (v_ego + SPEED_OFFSET) + self.yref[:,2] = yaw_rate_pts * (v_ego + SPEED_OFFSET) for i in range(N): self.solver.cost_set(i, "yref", self.yref[i]) self.solver.set(i, "p", p_cp) self.solver.set(N, "p", p_cp) - self.solver.cost_set(N, "yref", self.yref[N][:2]) + self.solver.cost_set(N, "yref", self.yref[N][:COST_E_DIM]) t = sec_since_boot() self.solution_status = self.solver.solve() @@ -173,5 +190,6 @@ class LateralMpc(): if __name__ == "__main__": - ocp = gen_lat_mpc_solver() - AcadosOcpSolver.generate(ocp, json_file=JSON_FILE, build=False) + ocp = gen_lat_ocp() + AcadosOcpSolver.generate(ocp, json_file=JSON_FILE) + # AcadosOcpSolver.build(ocp.code_export_directory, with_cython=True) diff --git a/selfdrive/controls/lib/lateral_planner.py b/selfdrive/controls/lib/lateral_planner.py index a9c6411394..932ad49535 100644 --- a/selfdrive/controls/lib/lateral_planner.py +++ b/selfdrive/controls/lib/lateral_planner.py @@ -1,28 +1,42 @@ import numpy as np from common.realtime import sec_since_boot, DT_MDL from common.numpy_fast import interp -from selfdrive.swaglog import cloudlog +from system.swaglog import cloudlog from selfdrive.controls.lib.lateral_mpc_lib.lat_mpc import LateralMpc -from selfdrive.controls.lib.drive_helpers import CONTROL_N, MPC_COST_LAT, LAT_MPC_N, CAR_ROTATION_RADIUS -from selfdrive.controls.lib.lane_planner import LanePlanner, TRAJECTORY_SIZE +from selfdrive.controls.lib.lateral_mpc_lib.lat_mpc import N as LAT_MPC_N +from selfdrive.controls.lib.drive_helpers import CONTROL_N, MIN_SPEED from selfdrive.controls.lib.desire_helper import DesireHelper import cereal.messaging as messaging from cereal import log +TRAJECTORY_SIZE = 33 +CAMERA_OFFSET = 0.04 + + +PATH_COST = 1.0 +LATERAL_MOTION_COST = 0.11 +LATERAL_ACCEL_COST = 0.0 +LATERAL_JERK_COST = 0.05 +# Extreme steering rate is unpleasant, even +# when it does not cause bad jerk. +# TODO this cost should be lowered when low +# speed lateral control is stable on all cars +STEERING_RATE_COST = 800.0 + class LateralPlanner: - def __init__(self, CP, use_lanelines=True, wide_camera=False): - self.use_lanelines = use_lanelines - self.LP = LanePlanner(wide_camera) + def __init__(self, CP): self.DH = DesireHelper() + # Vehicle model parameters used to calculate lateral movement of car + self.factor1 = CP.wheelbase - CP.centerToFront + self.factor2 = (CP.centerToFront * CP.mass) / (CP.wheelbase * CP.tireStiffnessRear) self.last_cloudlog_t = 0 - self.steer_rate_cost = CP.steerRateCost self.solution_invalid_cnt = 0 self.path_xyz = np.zeros((TRAJECTORY_SIZE, 3)) - self.path_xyz_stds = np.ones((TRAJECTORY_SIZE, 3)) self.plan_yaw = np.zeros((TRAJECTORY_SIZE,)) + self.plan_yaw_rate = np.zeros((TRAJECTORY_SIZE,)) self.t_idxs = np.arange(TRAJECTORY_SIZE) self.y_pts = np.zeros(TRAJECTORY_SIZE) @@ -34,52 +48,50 @@ class LateralPlanner: self.lat_mpc.reset(x0=self.x0) def update(self, sm): - v_ego = sm['carState'].vEgo + # clip speed , lateral planning is not possible at 0 speed + self.v_ego = max(MIN_SPEED, sm['carState'].vEgo) measured_curvature = sm['controlsState'].curvature # Parse model predictions md = sm['modelV2'] - self.LP.parse_model(md) if len(md.position.x) == TRAJECTORY_SIZE and len(md.orientation.x) == TRAJECTORY_SIZE: self.path_xyz = np.column_stack([md.position.x, md.position.y, md.position.z]) self.t_idxs = np.array(md.position.t) - self.plan_yaw = list(md.orientation.z) - if len(md.position.xStd) == TRAJECTORY_SIZE: - self.path_xyz_stds = np.column_stack([md.position.xStd, md.position.yStd, md.position.zStd]) + self.plan_yaw = np.array(md.orientation.z) + self.plan_yaw_rate = np.array(md.orientationRate.z) # Lane change logic - lane_change_prob = self.LP.l_lane_change_prob + self.LP.r_lane_change_prob - self.DH.update(sm['carState'], sm['controlsState'].active, lane_change_prob) - - # Turn off lanes during lane change - if self.DH.desire == log.LateralPlan.Desire.laneChangeRight or self.DH.desire == log.LateralPlan.Desire.laneChangeLeft: - self.LP.lll_prob *= self.DH.lane_change_ll_prob - self.LP.rll_prob *= self.DH.lane_change_ll_prob - - # Calculate final driving path and set MPC costs - if self.use_lanelines: - d_path_xyz = self.LP.get_d_path(v_ego, self.t_idxs, self.path_xyz) - self.lat_mpc.set_weights(MPC_COST_LAT.PATH, MPC_COST_LAT.HEADING, self.steer_rate_cost) - else: - d_path_xyz = self.path_xyz - path_cost = np.clip(abs(self.path_xyz[0, 1] / self.path_xyz_stds[0, 1]), 0.5, 1.5) * MPC_COST_LAT.PATH - # Heading cost is useful at low speed, otherwise end of plan can be off-heading - heading_cost = interp(v_ego, [5.0, 10.0], [MPC_COST_LAT.HEADING, 0.0]) - self.lat_mpc.set_weights(path_cost, heading_cost, self.steer_rate_cost) - - y_pts = np.interp(v_ego * self.t_idxs[:LAT_MPC_N + 1], np.linalg.norm(d_path_xyz, axis=1), d_path_xyz[:, 1]) - heading_pts = np.interp(v_ego * self.t_idxs[:LAT_MPC_N + 1], np.linalg.norm(self.path_xyz, axis=1), self.plan_yaw) + desire_state = md.meta.desireState + if len(desire_state): + self.l_lane_change_prob = desire_state[log.LateralPlan.Desire.laneChangeLeft] + self.r_lane_change_prob = desire_state[log.LateralPlan.Desire.laneChangeRight] + lane_change_prob = self.l_lane_change_prob + self.r_lane_change_prob + self.DH.update(sm['carState'], sm['carControl'].latActive, lane_change_prob) + + d_path_xyz = self.path_xyz + self.lat_mpc.set_weights(PATH_COST, LATERAL_MOTION_COST, + LATERAL_ACCEL_COST, LATERAL_JERK_COST, + STEERING_RATE_COST) + + y_pts = np.interp(self.v_ego * self.t_idxs[:LAT_MPC_N + 1], np.linalg.norm(d_path_xyz, axis=1), d_path_xyz[:, 1]) + heading_pts = np.interp(self.v_ego * self.t_idxs[:LAT_MPC_N + 1], np.linalg.norm(self.path_xyz, axis=1), self.plan_yaw) + yaw_rate_pts = np.interp(self.v_ego * self.t_idxs[:LAT_MPC_N + 1], np.linalg.norm(self.path_xyz, axis=1), self.plan_yaw_rate) self.y_pts = y_pts assert len(y_pts) == LAT_MPC_N + 1 assert len(heading_pts) == LAT_MPC_N + 1 - # self.x0[4] = v_ego - p = np.array([v_ego, CAR_ROTATION_RADIUS]) + assert len(yaw_rate_pts) == LAT_MPC_N + 1 + lateral_factor = max(0, self.factor1 - (self.factor2 * self.v_ego**2)) + p = np.array([self.v_ego, lateral_factor]) self.lat_mpc.run(self.x0, p, y_pts, - heading_pts) - # init state for next + heading_pts, + yaw_rate_pts) + # init state for next iteration + # mpc.u_sol is the desired second derivative of psi given x0 curv state. + # with x0[3] = measured_yaw_rate, this would be the actual desired yaw rate. + # instead, interpolate x_sol so that x0[3] is the desired yaw rate for lat_control. self.x0[3] = interp(DT_MDL, self.t_idxs[:LAT_MPC_N + 1], self.lat_mpc.x_sol[:, 3]) # Check for infeasible MPC solution @@ -87,7 +99,7 @@ class LateralPlanner: t = sec_since_boot() if mpc_nans or self.lat_mpc.solution_status != 0: self.reset_mpc() - self.x0[3] = measured_curvature + self.x0[3] = measured_curvature * self.v_ego if t > self.last_cloudlog_t + 5.0: self.last_cloudlog_t = t cloudlog.warning("Lateral mpc - nan: True") @@ -100,23 +112,21 @@ class LateralPlanner: def publish(self, sm, pm): plan_solution_valid = self.solution_invalid_cnt < 2 plan_send = messaging.new_message('lateralPlan') - plan_send.valid = sm.all_alive_and_valid(service_list=['carState', 'controlsState', 'modelV2']) + plan_send.valid = sm.all_checks(service_list=['carState', 'controlsState', 'modelV2']) lateralPlan = plan_send.lateralPlan - lateralPlan.laneWidth = float(self.LP.lane_width) + lateralPlan.modelMonoTime = sm.logMonoTime['modelV2'] lateralPlan.dPathPoints = self.y_pts.tolist() lateralPlan.psis = self.lat_mpc.x_sol[0:CONTROL_N, 2].tolist() - lateralPlan.curvatures = self.lat_mpc.x_sol[0:CONTROL_N, 3].tolist() - lateralPlan.curvatureRates = [float(x) for x in self.lat_mpc.u_sol[0:CONTROL_N - 1]] + [0.0] - lateralPlan.lProb = float(self.LP.lll_prob) - lateralPlan.rProb = float(self.LP.rll_prob) - lateralPlan.dProb = float(self.LP.d_prob) + + lateralPlan.curvatures = (self.lat_mpc.x_sol[0:CONTROL_N, 3]/self.v_ego).tolist() + lateralPlan.curvatureRates = [float(x/self.v_ego) for x in self.lat_mpc.u_sol[0:CONTROL_N - 1]] + [0.0] lateralPlan.mpcSolutionValid = bool(plan_solution_valid) lateralPlan.solverExecutionTime = self.lat_mpc.solve_time lateralPlan.desire = self.DH.desire - lateralPlan.useLaneLines = self.use_lanelines + lateralPlan.useLaneLines = False lateralPlan.laneChangeState = self.DH.lane_change_state lateralPlan.laneChangeDirection = self.DH.lane_change_direction diff --git a/selfdrive/controls/lib/longcontrol.py b/selfdrive/controls/lib/longcontrol.py index 3ba50fd0cf..545a4c43ff 100644 --- a/selfdrive/controls/lib/longcontrol.py +++ b/selfdrive/controls/lib/longcontrol.py @@ -1,25 +1,30 @@ from cereal import car from common.numpy_fast import clip, interp from common.realtime import DT_CTRL -from selfdrive.controls.lib.pid import PIController -from selfdrive.controls.lib.drive_helpers import CONTROL_N +from selfdrive.controls.lib.drive_helpers import CONTROL_N, apply_deadzone +from selfdrive.controls.lib.pid import PIDController from selfdrive.modeld.constants import T_IDXS LongCtrlState = car.CarControl.Actuators.LongControlState -# As per ISO 15622:2018 for all speeds -ACCEL_MIN_ISO = -3.5 # m/s^2 -ACCEL_MAX_ISO = 2.0 # m/s^2 - -def long_control_state_trans(CP, active, long_control_state, v_ego, v_target_future, - brake_pressed, cruise_standstill): - """Update longitudinal control state machine""" - stopping_condition = (v_ego < 2.0 and cruise_standstill) or \ - (v_ego < CP.vEgoStopping and - (v_target_future < CP.vEgoStopping or brake_pressed)) - - starting_condition = v_target_future > CP.vEgoStarting and not cruise_standstill +def long_control_state_trans(CP, active, long_control_state, v_ego, v_target, + v_target_1sec, brake_pressed, cruise_standstill): + # Ignore cruise standstill if car has a gas interceptor + cruise_standstill = cruise_standstill and not CP.enableGasInterceptor + accelerating = v_target_1sec > v_target + planned_stop = (v_target < CP.vEgoStopping and + v_target_1sec < CP.vEgoStopping and + not accelerating) + stay_stopped = (v_ego < CP.vEgoStopping and + (brake_pressed or cruise_standstill)) + stopping_condition = planned_stop or stay_stopped + + starting_condition = (v_target_1sec > CP.vEgoStarting and + accelerating and + not cruise_standstill and + not brake_pressed) + started_condition = v_ego > CP.vEgoStarting if not active: long_control_state = LongCtrlState.off @@ -33,18 +38,27 @@ def long_control_state_trans(CP, active, long_control_state, v_ego, v_target_fut long_control_state = LongCtrlState.stopping elif long_control_state == LongCtrlState.stopping: - if starting_condition: + if starting_condition and CP.startingState: + long_control_state = LongCtrlState.starting + elif starting_condition: + long_control_state = LongCtrlState.pid + + elif long_control_state == LongCtrlState.starting: + if stopping_condition: + long_control_state = LongCtrlState.stopping + elif started_condition: long_control_state = LongCtrlState.pid return long_control_state -class LongControl(): +class LongControl: def __init__(self, CP): + self.CP = CP self.long_control_state = LongCtrlState.off # initialized to off - self.pid = PIController((CP.longitudinalTuning.kpBP, CP.longitudinalTuning.kpV), - (CP.longitudinalTuning.kiBP, CP.longitudinalTuning.kiV), - k_f = CP.longitudinalTuning.kf, rate=1 / DT_CTRL) + self.pid = PIDController((CP.longitudinalTuning.kpBP, CP.longitudinalTuning.kpV), + (CP.longitudinalTuning.kiBP, CP.longitudinalTuning.kiV), + k_f=CP.longitudinalTuning.kf, rate=1 / DT_CTRL) self.v_pid = 0.0 self.last_output_accel = 0.0 @@ -53,67 +67,68 @@ class LongControl(): self.pid.reset() self.v_pid = v_pid - def update(self, active, CS, CP, long_plan, accel_limits, t_since_plan): + def update(self, active, CS, long_plan, accel_limits, t_since_plan): """Update longitudinal control. This updates the state machine and runs a PID loop""" # Interp control trajectory speeds = long_plan.speeds if len(speeds) == CONTROL_N: - v_target = interp(t_since_plan, T_IDXS[:CONTROL_N], speeds) - a_target = interp(t_since_plan, T_IDXS[:CONTROL_N], long_plan.accels) + v_target_now = interp(t_since_plan, T_IDXS[:CONTROL_N], speeds) + a_target_now = interp(t_since_plan, T_IDXS[:CONTROL_N], long_plan.accels) + + v_target_lower = interp(self.CP.longitudinalActuatorDelayLowerBound + t_since_plan, T_IDXS[:CONTROL_N], speeds) + a_target_lower = 2 * (v_target_lower - v_target_now) / self.CP.longitudinalActuatorDelayLowerBound - a_target_now - v_target_lower = interp(CP.longitudinalActuatorDelayLowerBound + t_since_plan, T_IDXS[:CONTROL_N], speeds) - a_target_lower = 2 * (v_target_lower - v_target) / CP.longitudinalActuatorDelayLowerBound - a_target + v_target_upper = interp(self.CP.longitudinalActuatorDelayUpperBound + t_since_plan, T_IDXS[:CONTROL_N], speeds) + a_target_upper = 2 * (v_target_upper - v_target_now) / self.CP.longitudinalActuatorDelayUpperBound - a_target_now - v_target_upper = interp(CP.longitudinalActuatorDelayUpperBound + t_since_plan, T_IDXS[:CONTROL_N], speeds) - a_target_upper = 2 * (v_target_upper - v_target) / CP.longitudinalActuatorDelayUpperBound - a_target + v_target = min(v_target_lower, v_target_upper) a_target = min(a_target_lower, a_target_upper) - v_target_future = speeds[-1] + v_target_1sec = interp(self.CP.longitudinalActuatorDelayUpperBound + t_since_plan + 1.0, T_IDXS[:CONTROL_N], speeds) else: v_target = 0.0 - v_target_future = 0.0 + v_target_now = 0.0 + v_target_1sec = 0.0 a_target = 0.0 - # TODO: This check is not complete and needs to be enforced by MPC - a_target = clip(a_target, ACCEL_MIN_ISO, ACCEL_MAX_ISO) - self.pid.neg_limit = accel_limits[0] self.pid.pos_limit = accel_limits[1] - # Update state machine output_accel = self.last_output_accel - self.long_control_state = long_control_state_trans(CP, active, self.long_control_state, CS.vEgo, - v_target_future, CS.brakePressed, + self.long_control_state = long_control_state_trans(self.CP, active, self.long_control_state, CS.vEgo, + v_target, v_target_1sec, CS.brakePressed, CS.cruiseState.standstill) - if self.long_control_state == LongCtrlState.off or CS.gasPressed: + if self.long_control_state == LongCtrlState.off: self.reset(CS.vEgo) output_accel = 0. - # tracking objects and driving + elif self.long_control_state == LongCtrlState.stopping: + if output_accel > self.CP.stopAccel: + output_accel = min(output_accel, 0.0) + output_accel -= self.CP.stoppingDecelRate * DT_CTRL + self.reset(CS.vEgo) + + elif self.long_control_state == LongCtrlState.starting: + output_accel = self.CP.startAccel + self.reset(CS.vEgo) + elif self.long_control_state == LongCtrlState.pid: - self.v_pid = v_target + self.v_pid = v_target_now # Toyota starts braking more when it thinks you want to stop # Freeze the integrator so we don't accelerate to compensate, and don't allow positive acceleration - prevent_overshoot = not CP.stoppingControl and CS.vEgo < 1.5 and v_target_future < 0.7 and v_target_future < self.v_pid - deadzone = interp(CS.vEgo, CP.longitudinalTuning.deadzoneBP, CP.longitudinalTuning.deadzoneV) + # TODO too complex, needs to be simplified and tested on toyotas + prevent_overshoot = not self.CP.stoppingControl and CS.vEgo < 1.5 and v_target_1sec < 0.7 and v_target_1sec < self.v_pid + deadzone = interp(CS.vEgo, self.CP.longitudinalTuning.deadzoneBP, self.CP.longitudinalTuning.deadzoneV) freeze_integrator = prevent_overshoot - output_accel = self.pid.update(self.v_pid, CS.vEgo, speed=CS.vEgo, deadzone=deadzone, feedforward=a_target, freeze_integrator=freeze_integrator) - - if prevent_overshoot: - output_accel = min(output_accel, 0.0) - - # Intention is to stop, switch to a different brake control until we stop - elif self.long_control_state == LongCtrlState.stopping: - # Keep applying brakes until the car is stopped - if not CS.standstill or output_accel > CP.stopAccel: - output_accel -= CP.stoppingDecelRate * DT_CTRL - output_accel = clip(output_accel, accel_limits[0], accel_limits[1]) - self.reset(CS.vEgo) + error = self.v_pid - CS.vEgo + error_deadzone = apply_deadzone(error, deadzone) + output_accel = self.pid.update(error_deadzone, speed=CS.vEgo, + feedforward=a_target, + freeze_integrator=freeze_integrator) - self.last_output_accel = output_accel - final_accel = clip(output_accel, accel_limits[0], accel_limits[1]) + self.last_output_accel = clip(output_accel, accel_limits[0], accel_limits[1]) - return final_accel + return self.last_output_accel diff --git a/selfdrive/controls/lib/longitudinal_mpc_lib/SConscript b/selfdrive/controls/lib/longitudinal_mpc_lib/SConscript index 4c43985d1f..5a9e69c297 100644 --- a/selfdrive/controls/lib/longitudinal_mpc_lib/SConscript +++ b/selfdrive/controls/lib/longitudinal_mpc_lib/SConscript @@ -28,8 +28,6 @@ casadi_cost_0 = [ casadi_constraints = [ f'{gen}/long_constraints/long_constr_h_fun.c', f'{gen}/long_constraints/long_constr_h_fun_jac_uxt_zt.c', - f'{gen}/long_constraints/long_constr_h_e_fun.c', - f'{gen}/long_constraints/long_constr_h_e_fun_jac_uxt_zt.c', ] build_files = [f'{gen}/acados_solver_long.c'] + casadi_model + casadi_cost_y + casadi_cost_e + \ @@ -47,17 +45,26 @@ generated_files = [ f'{gen}/long_model/long_model.h', f'{gen}/long_constraints/long_h_constraint.h', - f'{gen}/long_constraints/long_h_e_constraint.h', f'{gen}/long_cost/long_cost_y_fun.h', f'{gen}/long_cost/long_cost_y_e_fun.h', f'{gen}/long_cost/long_cost_y_0_fun.h', ] + build_files +acados_dir = '#third_party/acados' +acados_templates_dir = '#pyextra/acados_template/c_templates_tera' + +source_list = ['long_mpc.py', + f'{acados_dir}/include/acados_c/ocp_nlp_interface.h', + f'{acados_dir}/x86_64/lib/libacados.so', + f'{acados_dir}/larch64/lib/libacados.so', + f'{acados_templates_dir}/acados_solver.in.c', +] + lenv = env.Clone() lenv.Clean(generated_files, Dir(gen)) lenv.Command(generated_files, - ["long_mpc.py"], + source_list, f"cd {Dir('.').abspath} && python3 long_mpc.py") lenv["CFLAGS"].append("-DACADOS_WITH_QPOASES") diff --git a/selfdrive/controls/lib/longitudinal_mpc_lib/long_mpc.py b/selfdrive/controls/lib/longitudinal_mpc_lib/long_mpc.py index f9f9c31bb4..79a9ec4f0c 100644 --- a/selfdrive/controls/lib/longitudinal_mpc_lib/long_mpc.py +++ b/selfdrive/controls/lib/longitudinal_mpc_lib/long_mpc.py @@ -3,28 +3,28 @@ import os import numpy as np from common.realtime import sec_since_boot -from common.numpy_fast import clip, interp -from selfdrive.swaglog import cloudlog +from common.numpy_fast import clip +from system.swaglog import cloudlog from selfdrive.modeld.constants import index_function from selfdrive.controls.lib.radar_helpers import _LEAD_ACCEL_TAU if __name__ == '__main__': # generating code from pyextra.acados_template import AcadosModel, AcadosOcp, AcadosOcpSolver else: - # from pyextra.acados_template import AcadosOcpSolver as AcadosOcpSolverFast - from selfdrive.controls.lib.longitudinal_mpc_lib.c_generated_code.acados_ocp_solver_pyx import AcadosOcpSolverFast # pylint: disable=no-name-in-module, import-error + from selfdrive.controls.lib.longitudinal_mpc_lib.c_generated_code.acados_ocp_solver_pyx import AcadosOcpSolverCython # pylint: disable=no-name-in-module, import-error from casadi import SX, vertcat +MODEL_NAME = 'long' LONG_MPC_DIR = os.path.dirname(os.path.abspath(__file__)) EXPORT_DIR = os.path.join(LONG_MPC_DIR, "c_generated_code") -JSON_FILE = "acados_ocp_long.json" +JSON_FILE = os.path.join(LONG_MPC_DIR, "acados_ocp_long.json") -SOURCES = ['lead0', 'lead1', 'cruise'] +SOURCES = ['lead0', 'lead1', 'cruise', 'e2e'] X_DIM = 3 U_DIM = 1 -PARAM_DIM= 4 +PARAM_DIM = 6 COST_E_DIM = 5 COST_DIM = COST_E_DIM + 1 CONSTR_DIM = 4 @@ -34,21 +34,25 @@ X_EGO_COST = 0. V_EGO_COST = 0. A_EGO_COST = 0. J_EGO_COST = 5.0 -A_CHANGE_COST = .5 +A_CHANGE_COST = 200. DANGER_ZONE_COST = 100. -CRASH_DISTANCE = .5 +CRASH_DISTANCE = .25 +LEAD_DANGER_FACTOR = 0.75 LIMIT_COST = 1e6 +ACADOS_SOLVER_TYPE = 'SQP_RTI' # Fewer timestamps don't hurt performance and lead to # much better convergence of the MPC with low iterations N = 12 MAX_T = 10.0 -T_IDXS_LST = [index_function(idx, max_val=MAX_T, max_idx=N+1) for idx in range(N+1)] +T_IDXS_LST = [index_function(idx, max_val=MAX_T, max_idx=N) for idx in range(N+1)] T_IDXS = np.array(T_IDXS_LST) +FCW_IDXS = T_IDXS < 5.0 T_DIFFS = np.diff(T_IDXS, prepend=[0.]) MIN_ACCEL = -3.5 +MAX_ACCEL = 2.0 T_FOLLOW = 1.45 COMFORT_BRAKE = 2.5 STOP_DISTANCE = 6.0 @@ -56,8 +60,8 @@ STOP_DISTANCE = 6.0 def get_stopped_equivalence_factor(v_lead): return (v_lead**2) / (2 * COMFORT_BRAKE) -def get_safe_obstacle_distance(v_ego): - return (v_ego**2) / (2 * COMFORT_BRAKE) + T_FOLLOW * v_ego + STOP_DISTANCE +def get_safe_obstacle_distance(v_ego, t_follow=T_FOLLOW): + return (v_ego**2) / (2 * COMFORT_BRAKE) + t_follow * v_ego + STOP_DISTANCE def desired_follow_distance(v_ego, v_lead): return get_safe_obstacle_distance(v_ego) - get_stopped_equivalence_factor(v_lead) @@ -65,7 +69,7 @@ def desired_follow_distance(v_ego, v_lead): def gen_long_model(): model = AcadosModel() - model.name = 'long' + model.name = MODEL_NAME # set up states & controls x_ego = SX.sym('x_ego') @@ -88,7 +92,9 @@ def gen_long_model(): a_max = SX.sym('a_max') x_obstacle = SX.sym('x_obstacle') prev_a = SX.sym('prev_a') - model.p = vertcat(a_min, a_max, x_obstacle, prev_a) + lead_t_follow = SX.sym('lead_t_follow') + lead_danger_factor = SX.sym('lead_danger_factor') + model.p = vertcat(a_min, a_max, x_obstacle, prev_a, lead_t_follow, lead_danger_factor) # dynamics model f_expl = vertcat(v_ego, a_ego, j_ego) @@ -97,7 +103,7 @@ def gen_long_model(): return model -def gen_long_mpc_solver(): +def gen_long_ocp(): ocp = AcadosOcp() ocp.model = gen_long_model() @@ -122,11 +128,13 @@ def gen_long_mpc_solver(): a_min, a_max = ocp.model.p[0], ocp.model.p[1] x_obstacle = ocp.model.p[2] prev_a = ocp.model.p[3] + lead_t_follow = ocp.model.p[4] + lead_danger_factor = ocp.model.p[5] ocp.cost.yref = np.zeros((COST_DIM, )) ocp.cost.yref_e = np.zeros((COST_E_DIM, )) - desired_dist_comfort = get_safe_obstacle_distance(v_ego) + desired_dist_comfort = get_safe_obstacle_distance(v_ego, lead_t_follow) # The main cost in normal operation is how close you are to the "desired" distance # from an obstacle at every timestep. This obstacle can be a lead car @@ -136,7 +144,7 @@ def gen_long_mpc_solver(): x_ego, v_ego, a_ego, - 20*(a_ego - prev_a), + a_ego - prev_a, j_ego] ocp.model.cost_y_expr = vertcat(*costs) ocp.model.cost_y_expr_e = vertcat(*costs[:-1]) @@ -147,13 +155,12 @@ def gen_long_mpc_solver(): constraints = vertcat(v_ego, (a_ego - a_min), (a_max - a_ego), - ((x_obstacle - x_ego) - (3/4) * (desired_dist_comfort)) / (v_ego + 10.)) + ((x_obstacle - x_ego) - lead_danger_factor * (desired_dist_comfort)) / (v_ego + 10.)) ocp.model.con_h_expr = constraints - ocp.model.con_h_expr_e = vertcat(np.zeros(CONSTR_DIM)) x0 = np.zeros(X_DIM) ocp.constraints.x0 = x0 - ocp.parameter_values = np.array([-1.2, 1.2, 0.0, 0.0]) + ocp.parameter_values = np.array([-1.2, 1.2, 0.0, 0.0, T_FOLLOW, LEAD_DANGER_FACTOR]) # We put all constraint cost weights to 0 and only set them at runtime cost_weights = np.zeros(CONSTR_DIM) @@ -163,9 +170,7 @@ def gen_long_mpc_solver(): ocp.cost.zu = cost_weights ocp.constraints.lh = np.zeros(CONSTR_DIM) - ocp.constraints.lh_e = np.zeros(CONSTR_DIM) ocp.constraints.uh = 1e4*np.ones(CONSTR_DIM) - ocp.constraints.uh_e = 1e4*np.ones(CONSTR_DIM) ocp.constraints.idxsh = np.arange(CONSTR_DIM) # The HPIPM solver can give decent solutions even when it is stopped early @@ -175,12 +180,13 @@ def gen_long_mpc_solver(): ocp.solver_options.qp_solver = 'PARTIAL_CONDENSING_HPIPM' ocp.solver_options.hessian_approx = 'GAUSS_NEWTON' ocp.solver_options.integrator_type = 'ERK' - ocp.solver_options.nlp_solver_type = 'SQP_RTI' - ocp.solver_options.qp_solver_cond_N = N//4 + ocp.solver_options.nlp_solver_type = ACADOS_SOLVER_TYPE + ocp.solver_options.qp_solver_cond_N = 1 # More iterations take too much time and less lead to inaccurate convergence in # some situations. Ideally we would run just 1 iteration to ensure fixed runtime. ocp.solver_options.qp_solver_iter_max = 10 + ocp.solver_options.qp_tol = 1e-3 # set prediction horizon ocp.solver_options.tf = Tf @@ -191,13 +197,16 @@ def gen_long_mpc_solver(): class LongitudinalMpc: - def __init__(self, e2e=False): - self.e2e = e2e + def __init__(self, mode='acc'): + self.mode = mode + self.solver = AcadosOcpSolverCython(MODEL_NAME, ACADOS_SOLVER_TYPE, N) self.reset() self.source = SOURCES[2] def reset(self): - self.solver = AcadosOcpSolverFast('long', N, EXPORT_DIR) + # self.solver = AcadosOcpSolverCython(MODEL_NAME, ACADOS_SOLVER_TYPE, N) + self.solver.reset() + # self.solver.options_set('print_level', 2) self.v_solution = np.zeros(N+1) self.a_solution = np.zeros(N+1) self.prev_a = np.array(self.a_solution) @@ -215,56 +224,50 @@ class LongitudinalMpc: self.status = False self.crash_cnt = 0.0 self.solution_status = 0 + # timers self.solve_time = 0.0 + self.time_qp_solution = 0.0 + self.time_linearization = 0.0 + self.time_integrator = 0.0 self.x0 = np.zeros(X_DIM) self.set_weights() - def set_weights(self, prev_accel_constraint=True): - if self.e2e: - self.set_weights_for_xva_policy() - self.params[:,0] = -10. - self.params[:,1] = 10. - self.params[:,2] = 1e5 - else: - self.set_weights_for_lead_policy(prev_accel_constraint) - - def set_weights_for_lead_policy(self, prev_accel_constraint=True): - a_change_cost = A_CHANGE_COST if prev_accel_constraint else 0 - W = np.asfortranarray(np.diag([X_EGO_OBSTACLE_COST, X_EGO_COST, V_EGO_COST, A_EGO_COST, a_change_cost, J_EGO_COST])) + def set_cost_weights(self, cost_weights, constraint_cost_weights): + W = np.asfortranarray(np.diag(cost_weights)) for i in range(N): - W[4,4] = a_change_cost * np.interp(T_IDXS[i], [0.0, 1.0, 2.0], [1.0, 1.0, 0.0]) + # TODO don't hardcode A_CHANGE_COST idx + # reduce the cost on (a-a_prev) later in the horizon. + W[4,4] = cost_weights[4] * np.interp(T_IDXS[i], [0.0, 1.0, 2.0], [1.0, 1.0, 0.0]) self.solver.cost_set(i, 'W', W) # Setting the slice without the copy make the array not contiguous, # causing issues with the C interface. self.solver.cost_set(N, 'W', np.copy(W[:COST_E_DIM, :COST_E_DIM])) # Set L2 slack cost on lower bound constraints - Zl = np.array([LIMIT_COST, LIMIT_COST, LIMIT_COST, DANGER_ZONE_COST]) + Zl = np.array(constraint_cost_weights) for i in range(N): self.solver.cost_set(i, 'Zl', Zl) - def set_weights_for_xva_policy(self): - W = np.asfortranarray(np.diag([0., 10., 1., 10., 0.0, 1.])) - for i in range(N): - self.solver.cost_set(i, 'W', W) - # Setting the slice without the copy make the array not contiguous, - # causing issues with the C interface. - self.solver.cost_set(N, 'W', np.copy(W[:COST_E_DIM, :COST_E_DIM])) - - # Set L2 slack cost on lower bound constraints - Zl = np.array([LIMIT_COST, LIMIT_COST, LIMIT_COST, 0.0]) - for i in range(N): - self.solver.cost_set(i, 'Zl', Zl) + def set_weights(self, prev_accel_constraint=True): + if self.mode == 'acc': + a_change_cost = A_CHANGE_COST if prev_accel_constraint else 0 + cost_weights = [X_EGO_OBSTACLE_COST, X_EGO_COST, V_EGO_COST, A_EGO_COST, a_change_cost, J_EGO_COST] + constraint_cost_weights = [LIMIT_COST, LIMIT_COST, LIMIT_COST, DANGER_ZONE_COST] + elif self.mode == 'blended': + a_change_cost = 40.0 if prev_accel_constraint else 0 + cost_weights = [0., 0.1, 0.2, 5.0, a_change_cost, 1.0] + constraint_cost_weights = [LIMIT_COST, LIMIT_COST, LIMIT_COST, 50.0] + else: + raise NotImplementedError(f'Planner mode {self.mode} not recognized in planner cost set') + self.set_cost_weights(cost_weights, constraint_cost_weights) def set_cur_state(self, v, a): - if abs(self.x0[1] - v) > 2.: - self.x0[1] = v - self.x0[2] = a + v_prev = self.x0[1] + self.x0[1] = v + self.x0[2] = a + if abs(v_prev - v) > 2.: # probably only helps if v < v_prev for i in range(0, N+1): self.solver.set(i, 'x', self.x0) - else: - self.x0[1] = v - self.x0[2] = a @staticmethod def extrapolate_lead(x_lead, v_lead, a_lead, a_lead_tau): @@ -298,66 +301,109 @@ class LongitudinalMpc: return lead_xv def set_accel_limits(self, min_a, max_a): + # TODO this sets a max accel limit, but the minimum limit is only for cruise decel + # needs refactor self.cruise_min_a = min_a - self.cruise_max_a = max_a + self.max_a = max_a - def update(self, carstate, radarstate, v_cruise): + def update(self, carstate, radarstate, v_cruise, x, v, a, j): v_ego = self.x0[1] self.status = radarstate.leadOne.status or radarstate.leadTwo.status lead_xv_0 = self.process_lead(radarstate.leadOne) lead_xv_1 = self.process_lead(radarstate.leadTwo) - # set accel limits in params - self.params[:,0] = interp(float(self.status), [0.0, 1.0], [self.cruise_min_a, MIN_ACCEL]) - self.params[:,1] = self.cruise_max_a - # To estimate a safe distance from a moving lead, we calculate how much stopping # distance that lead needs as a minimum. We can add that to the current distance # and then treat that as a stopped car/obstacle at this new distance. lead_0_obstacle = lead_xv_0[:,0] + get_stopped_equivalence_factor(lead_xv_0[:,1]) lead_1_obstacle = lead_xv_1[:,0] + get_stopped_equivalence_factor(lead_xv_1[:,1]) - # Fake an obstacle for cruise, this ensures smooth acceleration to set speed - # when the leads are no factor. - v_lower = v_ego + (T_IDXS * self.cruise_min_a * 1.05) - v_upper = v_ego + (T_IDXS * self.cruise_max_a * 1.05) - v_cruise_clipped = np.clip(v_cruise * np.ones(N+1), - v_lower, - v_upper) - cruise_obstacle = np.cumsum(T_DIFFS * v_cruise_clipped) + get_safe_obstacle_distance(v_cruise_clipped) - - x_obstacles = np.column_stack([lead_0_obstacle, lead_1_obstacle, cruise_obstacle]) - self.source = SOURCES[np.argmin(x_obstacles[0])] - self.params[:,2] = np.min(x_obstacles, axis=1) - self.params[:,3] = np.copy(self.prev_a) + self.params[:,0] = MIN_ACCEL + self.params[:,1] = self.max_a + + # Update in ACC mode or ACC/e2e blend + if self.mode == 'acc': + self.params[:,5] = LEAD_DANGER_FACTOR + + # Fake an obstacle for cruise, this ensures smooth acceleration to set speed + # when the leads are no factor. + v_lower = v_ego + (T_IDXS * self.cruise_min_a * 1.05) + v_upper = v_ego + (T_IDXS * self.max_a * 1.05) + v_cruise_clipped = np.clip(v_cruise * np.ones(N+1), + v_lower, + v_upper) + cruise_obstacle = np.cumsum(T_DIFFS * v_cruise_clipped) + get_safe_obstacle_distance(v_cruise_clipped) + x_obstacles = np.column_stack([lead_0_obstacle, lead_1_obstacle, cruise_obstacle]) + self.source = SOURCES[np.argmin(x_obstacles[0])] + + # These are not used in ACC mode + x[:], v[:], a[:], j[:] = 0.0, 0.0, 0.0, 0.0 + + elif self.mode == 'blended': + self.params[:,5] = 1.0 + + x_obstacles = np.column_stack([lead_0_obstacle, + lead_1_obstacle]) + cruise_target = T_IDXS * np.clip(v_cruise, v_ego - 2.0, 1e3) + x[0] + xforward = ((v[1:] + v[:-1]) / 2) * (T_IDXS[1:] - T_IDXS[:-1]) + x = np.cumsum(np.insert(xforward, 0, x[0])) + + x_and_cruise = np.column_stack([x, cruise_target]) + x = np.min(x_and_cruise, axis=1) + + self.source = 'e2e' if x_and_cruise[1,0] < x_and_cruise[1,1] else 'cruise' - self.run() - if (np.any(lead_xv_0[:,0] - self.x_sol[:,0] < CRASH_DISTANCE) and - radarstate.leadOne.modelProb > 0.9): - self.crash_cnt += 1 else: - self.crash_cnt = 0 + raise NotImplementedError(f'Planner mode {self.mode} not recognized in planner update') - def update_with_xva(self, x, v, a): self.yref[:,1] = x self.yref[:,2] = v self.yref[:,3] = a + self.yref[:,5] = j for i in range(N): - self.solver.cost_set(i, "yref", self.yref[i]) - self.solver.cost_set(N, "yref", self.yref[N][:COST_E_DIM]) + self.solver.set(i, "yref", self.yref[i]) + self.solver.set(N, "yref", self.yref[N][:COST_E_DIM]) + + self.params[:,2] = np.min(x_obstacles, axis=1) self.params[:,3] = np.copy(self.prev_a) + self.params[:,4] = T_FOLLOW + self.run() + if (np.any(lead_xv_0[FCW_IDXS,0] - self.x_sol[FCW_IDXS,0] < CRASH_DISTANCE) and + radarstate.leadOne.modelProb > 0.9): + self.crash_cnt += 1 + else: + self.crash_cnt = 0 + + # Check if it got within lead comfort range + # TODO This should be done cleaner + if self.mode == 'blended': + if any((lead_0_obstacle - get_safe_obstacle_distance(self.x_sol[:,1], T_FOLLOW))- self.x_sol[:,0] < 0.0): + self.source = 'lead0' + if any((lead_1_obstacle - get_safe_obstacle_distance(self.x_sol[:,1], T_FOLLOW))- self.x_sol[:,0] < 0.0) and \ + (lead_1_obstacle[0] - lead_0_obstacle[0]): + self.source = 'lead1' def run(self): + # t0 = sec_since_boot() + # reset = 0 for i in range(N+1): self.solver.set(i, 'p', self.params[i]) self.solver.constraints_set(0, "lbx", self.x0) self.solver.constraints_set(0, "ubx", self.x0) - t = sec_since_boot() self.solution_status = self.solver.solve() - self.solve_time = sec_since_boot() - t + self.solve_time = float(self.solver.get_stats('time_tot')[0]) + self.time_qp_solution = float(self.solver.get_stats('time_qp')[0]) + self.time_linearization = float(self.solver.get_stats('time_lin')[0]) + self.time_integrator = float(self.solver.get_stats('time_sim')[0]) + + # qp_iter = self.solver.get_stats('statistics')[-1][-1] # SQP_RTI specific + # print(f"long_mpc timings: tot {self.solve_time:.2e}, qp {self.time_qp_solution:.2e}, lin {self.time_linearization:.2e}, integrator {self.time_integrator:.2e}, qp_iter {qp_iter}") + # res = self.solver.get_residuals() + # print(f"long_mpc residuals: {res[0]:.2e}, {res[1]:.2e}, {res[2]:.2e}, {res[3]:.2e}") + # self.solver.print_statistics() for i in range(N+1): self.x_sol[i] = self.solver.get(i, 'x') @@ -370,13 +416,17 @@ class LongitudinalMpc: self.prev_a = np.interp(T_IDXS + 0.05, T_IDXS, self.a_solution) + t = sec_since_boot() if self.solution_status != 0: if t > self.last_cloudlog_t + 5.0: self.last_cloudlog_t = t cloudlog.warning(f"Long mpc reset, solution_status: {self.solution_status}") self.reset() + # reset = 1 + # print(f"long_mpc timings: total internal {self.solve_time:.2e}, external: {(sec_since_boot() - t0):.2e} qp {self.time_qp_solution:.2e}, lin {self.time_linearization:.2e} qp_iter {qp_iter}, reset {reset}") if __name__ == "__main__": - ocp = gen_long_mpc_solver() - AcadosOcpSolver.generate(ocp, json_file=JSON_FILE, build=False) + ocp = gen_long_ocp() + AcadosOcpSolver.generate(ocp, json_file=JSON_FILE) + # AcadosOcpSolver.build(ocp.code_export_directory, with_cython=True) diff --git a/selfdrive/controls/lib/longitudinal_planner.py b/selfdrive/controls/lib/longitudinal_planner.py index 865442f735..a0f6318323 100755 --- a/selfdrive/controls/lib/longitudinal_planner.py +++ b/selfdrive/controls/lib/longitudinal_planner.py @@ -1,24 +1,24 @@ #!/usr/bin/env python3 import math import numpy as np -from common.numpy_fast import interp +from common.numpy_fast import clip, interp import cereal.messaging as messaging +from common.conversions import Conversions as CV from common.filter_simple import FirstOrderFilter from common.realtime import DT_MDL from selfdrive.modeld.constants import T_IDXS -from selfdrive.config import Conversions as CV from selfdrive.controls.lib.longcontrol import LongCtrlState -from selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc import LongitudinalMpc +from selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc import LongitudinalMpc, MIN_ACCEL, MAX_ACCEL from selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc import T_IDXS as T_IDXS_MPC from selfdrive.controls.lib.drive_helpers import V_CRUISE_MAX, CONTROL_N -from selfdrive.swaglog import cloudlog +from system.swaglog import cloudlog LON_MPC_STEP = 0.2 # first step is 0.2s AWARENESS_DECEL = -0.2 # car smoothly decel at .2m/s^2 when user is distracted A_CRUISE_MIN = -1.2 -A_CRUISE_MAX_VALS = [1.2, 1.2, 0.8, 0.6] -A_CRUISE_MAX_BP = [0., 15., 25., 40.] +A_CRUISE_MAX_VALS = [1.6, 1.2, 0.8, 0.6] +A_CRUISE_MAX_BP = [0., 10.0, 25., 40.] # Lookup table for turns _A_TOTAL_MAX_V = [1.7, 3.2] @@ -35,6 +35,8 @@ def limit_accel_in_turns(v_ego, angle_steers, a_target, CP): this should avoid accelerating when losing the target in turns """ + # FIXME: This function to calculate lateral accel is incorrect and should use the VehicleModel + # The lookup table for turns should also be updated if we do this a_total_max = interp(v_ego, _A_TOTAL_MAX_BP, _A_TOTAL_MAX_V) a_y = v_ego ** 2 * angle_steers * CV.DEG_TO_RAD / (CP.steerRatio * CP.wheelbase) a_x_allowed = math.sqrt(max(a_total_max ** 2 - a_y ** 2, 0.)) @@ -42,46 +44,72 @@ def limit_accel_in_turns(v_ego, angle_steers, a_target, CP): return [a_target[0], min(a_target[1], a_x_allowed)] -class Planner: +class LongitudinalPlanner: def __init__(self, CP, init_v=0.0, init_a=0.0): self.CP = CP self.mpc = LongitudinalMpc() - self.fcw = False self.a_desired = init_a self.v_desired_filter = FirstOrderFilter(init_v, 2.0, DT_MDL) + self.v_model_error = 0.0 self.v_desired_trajectory = np.zeros(CONTROL_N) self.a_desired_trajectory = np.zeros(CONTROL_N) self.j_desired_trajectory = np.zeros(CONTROL_N) + self.solverExecutionTime = 0.0 + + @staticmethod + def parse_model(model_msg, model_error): + if (len(model_msg.position.x) == 33 and + len(model_msg.velocity.x) == 33 and + len(model_msg.acceleration.x) == 33): + x = np.interp(T_IDXS_MPC, T_IDXS, model_msg.position.x) - model_error * T_IDXS_MPC + v = np.interp(T_IDXS_MPC, T_IDXS, model_msg.velocity.x) - model_error + a = np.interp(T_IDXS_MPC, T_IDXS, model_msg.acceleration.x) + j = np.zeros(len(T_IDXS_MPC)) + else: + x = np.zeros(len(T_IDXS_MPC)) + v = np.zeros(len(T_IDXS_MPC)) + a = np.zeros(len(T_IDXS_MPC)) + j = np.zeros(len(T_IDXS_MPC)) + return x, v, a, j def update(self, sm): - v_ego = sm['carState'].vEgo + self.mpc.mode = 'blended' if sm['controlsState'].experimentalMode else 'acc' + v_ego = sm['carState'].vEgo v_cruise_kph = sm['controlsState'].vCruise v_cruise_kph = min(v_cruise_kph, V_CRUISE_MAX) v_cruise = v_cruise_kph * CV.KPH_TO_MS - long_control_state = sm['controlsState'].longControlState + long_control_off = sm['controlsState'].longControlState == LongCtrlState.off force_slow_decel = sm['controlsState'].forceDecel # Reset current state when not engaged, or user is controlling the speed - reset_state = long_control_state == LongCtrlState.off - reset_state = reset_state or sm['carState'].gasPressed + reset_state = long_control_off if self.CP.openpilotLongitudinalControl else not sm['controlsState'].enabled # No change cost when user is controlling the speed, or when standstill prev_accel_constraint = not (reset_state or sm['carState'].standstill) + if self.mpc.mode == 'acc': + accel_limits = [A_CRUISE_MIN, get_max_accel(v_ego)] + accel_limits_turns = limit_accel_in_turns(v_ego, sm['carState'].steeringAngleDeg, accel_limits, self.CP) + else: + accel_limits = [MIN_ACCEL, MAX_ACCEL] + accel_limits_turns = [MIN_ACCEL, MAX_ACCEL] + if reset_state: self.v_desired_filter.x = v_ego - self.a_desired = 0.0 + # Clip aEgo to cruise limits to prevent large accelerations when becoming active + self.a_desired = clip(sm['carState'].aEgo, accel_limits[0], accel_limits[1]) # Prevent divergence, smooth in current v_ego self.v_desired_filter.x = max(0.0, self.v_desired_filter.update(v_ego)) + # Compute model v_ego error + if len(sm['modelV2'].temporalPose.trans): + self.v_model_error = sm['modelV2'].temporalPose.trans[0] - v_ego - accel_limits = [A_CRUISE_MIN, get_max_accel(v_ego)] - accel_limits_turns = limit_accel_in_turns(v_ego, sm['carState'].steeringAngleDeg, accel_limits, self.CP) if force_slow_decel: # if required so, force a smooth deceleration accel_limits_turns[1] = min(accel_limits_turns[1], AWARENESS_DECEL) @@ -93,14 +121,15 @@ class Planner: self.mpc.set_weights(prev_accel_constraint) self.mpc.set_accel_limits(accel_limits_turns[0], accel_limits_turns[1]) self.mpc.set_cur_state(self.v_desired_filter.x, self.a_desired) - self.mpc.update(sm['carState'], sm['radarState'], v_cruise) + x, v, a, j = self.parse_model(sm['modelV2'], self.v_model_error) + self.mpc.update(sm['carState'], sm['radarState'], v_cruise, x, v, a, j) self.v_desired_trajectory = np.interp(T_IDXS[:CONTROL_N], T_IDXS_MPC, self.mpc.v_solution) self.a_desired_trajectory = np.interp(T_IDXS[:CONTROL_N], T_IDXS_MPC, self.mpc.a_solution) self.j_desired_trajectory = np.interp(T_IDXS[:CONTROL_N], T_IDXS_MPC[:-1], self.mpc.j_solution) # TODO counter is only needed because radar is glitchy, remove once radar is gone - self.fcw = self.mpc.crash_cnt > 5 + self.fcw = self.mpc.crash_cnt > 2 and not sm['carState'].standstill if self.fcw: cloudlog.info("FCW triggered") @@ -112,7 +141,7 @@ class Planner: def publish(self, sm, pm): plan_send = messaging.new_message('longitudinalPlan') - plan_send.valid = sm.all_alive_and_valid(service_list=['carState', 'controlsState']) + plan_send.valid = sm.all_checks(service_list=['carState', 'controlsState']) longitudinalPlan = plan_send.longitudinalPlan longitudinalPlan.modelMonoTime = sm.logMonoTime['modelV2'] diff --git a/selfdrive/controls/lib/pid.py b/selfdrive/controls/lib/pid.py index c91eb692cb..965158131b 100644 --- a/selfdrive/controls/lib/pid.py +++ b/selfdrive/controls/lib/pid.py @@ -3,30 +3,26 @@ from numbers import Number from common.numpy_fast import clip, interp -def apply_deadzone(error, deadzone): - if error > deadzone: - error -= deadzone - elif error < - deadzone: - error += deadzone - else: - error = 0. - return error - -class PIController(): - def __init__(self, k_p, k_i, k_f=0., pos_limit=None, neg_limit=None, rate=100): - self._k_p = k_p # proportional gain - self._k_i = k_i # integral gain + +class PIDController(): + def __init__(self, k_p, k_i, k_f=0., k_d=0., pos_limit=1e308, neg_limit=-1e308, rate=100): + self._k_p = k_p + self._k_i = k_i + self._k_d = k_d self.k_f = k_f # feedforward gain if isinstance(self._k_p, Number): self._k_p = [[0], [self._k_p]] if isinstance(self._k_i, Number): self._k_i = [[0], [self._k_i]] + if isinstance(self._k_d, Number): + self._k_d = [[0], [self._k_d]] self.pos_limit = pos_limit self.neg_limit = neg_limit self.i_unwind_rate = 0.3 / rate self.i_rate = 1.0 / rate + self.speed = 0.0 self.reset() @@ -38,24 +34,33 @@ class PIController(): def k_i(self): return interp(self.speed, self._k_i[0], self._k_i[1]) + @property + def k_d(self): + return interp(self.speed, self._k_d[0], self._k_d[1]) + + @property + def error_integral(self): + return self.i/self.k_i + def reset(self): self.p = 0.0 self.i = 0.0 + self.d = 0.0 self.f = 0.0 self.control = 0 - def update(self, setpoint, measurement, speed=0.0, override=False, feedforward=0., deadzone=0., freeze_integrator=False): + def update(self, error, error_rate=0.0, speed=0.0, override=False, feedforward=0., freeze_integrator=False): self.speed = speed - error = float(apply_deadzone(setpoint - measurement, deadzone)) - self.p = error * self.k_p + self.p = float(error) * self.k_p self.f = feedforward * self.k_f + self.d = error_rate * self.k_d if override: self.i -= self.i_unwind_rate * float(np.sign(self.i)) else: i = self.i + error * self.k_i * self.i_rate - control = self.p + self.f + i + control = self.p + i + self.d + self.f # Update when changing i will move the control away from the limits # or when i will move towards the sign of the error @@ -64,7 +69,7 @@ class PIController(): not freeze_integrator: self.i = i - control = self.p + self.f + self.i + control = self.p + self.i + self.d + self.f self.control = clip(control, self.neg_limit, self.pos_limit) return self.control diff --git a/selfdrive/controls/lib/radar_helpers.py b/selfdrive/controls/lib/radar_helpers.py index 4f87fdf09b..4bb0179267 100644 --- a/selfdrive/controls/lib/radar_helpers.py +++ b/selfdrive/controls/lib/radar_helpers.py @@ -1,10 +1,8 @@ from common.numpy_fast import mean from common.kalman.simple_kalman import KF1D -from selfdrive.config import RADAR_TO_CAMERA -# the longer lead decels, the more likely it will keep decelerating -# TODO is this a good default? +# Default lead acceleration decay set to 50% at 1s _LEAD_ACCEL_TAU = 1.5 # radar tracks @@ -13,6 +11,8 @@ SPEED, ACCEL = 0, 1 # Kalman filter states enum # stationary qualification parameters v_ego_stationary = 4. # no stationary object flag below this speed +RADAR_TO_CENTER = 2.7 # (deprecated) RADAR is ~ 2.7m ahead from center of car +RADAR_TO_CAMERA = 1.52 # RADAR is ~ 1.5m ahead from center of mesh frame class Track(): def __init__(self, v_lead, kalman_params): @@ -151,7 +151,8 @@ class Cluster(): def potential_low_speed_lead(self, v_ego): # stop for stuff in front of you and low speed, even without model confirmation - return abs(self.yRel) < 1.5 and (v_ego < v_ego_stationary) and self.dRel < 25 + # Radar points closer than 0.75, are almost always glitches on toyota radars + return abs(self.yRel) < 1.0 and (v_ego < v_ego_stationary) and (0.75 < self.dRel < 25) def is_potential_fcw(self, model_prob): return model_prob > .9 diff --git a/selfdrive/controls/lib/tests/test_latcontrol.py b/selfdrive/controls/lib/tests/test_latcontrol.py index 8345840eca..f15ab2fa56 100755 --- a/selfdrive/controls/lib/tests/test_latcontrol.py +++ b/selfdrive/controls/lib/tests/test_latcontrol.py @@ -9,7 +9,7 @@ from selfdrive.car.honda.values import CAR as HONDA from selfdrive.car.toyota.values import CAR as TOYOTA from selfdrive.car.nissan.values import CAR as NISSAN from selfdrive.controls.lib.latcontrol_pid import LatControlPID -from selfdrive.controls.lib.latcontrol_lqr import LatControlLQR +from selfdrive.controls.lib.latcontrol_torque import LatControlTorque from selfdrive.controls.lib.latcontrol_indi import LatControlINDI from selfdrive.controls.lib.latcontrol_angle import LatControlAngle from selfdrive.controls.lib.vehicle_model import VehicleModel @@ -17,7 +17,7 @@ from selfdrive.controls.lib.vehicle_model import VehicleModel class TestLatControl(unittest.TestCase): - @parameterized.expand([(HONDA.CIVIC, LatControlPID), (TOYOTA.RAV4, LatControlLQR), (TOYOTA.PRIUS, LatControlINDI), (NISSAN.LEAF, LatControlAngle)]) + @parameterized.expand([(HONDA.CIVIC, LatControlPID), (TOYOTA.RAV4, LatControlTorque), (TOYOTA.PRIUS, LatControlINDI), (NISSAN.LEAF, LatControlAngle)]) def test_saturation(self, car_name, controller): CarInterface, CarController, CarState = interfaces[car_name] CP = CarInterface.get_params(car_name) @@ -26,7 +26,6 @@ class TestLatControl(unittest.TestCase): controller = controller(CP, CI) - CS = car.CarState.new_message() CS.vEgo = 30 @@ -35,7 +34,7 @@ class TestLatControl(unittest.TestCase): params = log.LiveParametersData.new_message() for _ in range(1000): - _, _, lac_log = controller.update(True, CS, CP, VM, params, last_actuators, 1, 0) + _, _, lac_log = controller.update(True, CS, CP, VM, params, last_actuators, True, 1, 0) self.assertTrue(lac_log.saturated) diff --git a/selfdrive/controls/lib/tests/test_vehicle_model.py b/selfdrive/controls/lib/tests/test_vehicle_model.py index f2636027e8..3e08cb0aa0 100755 --- a/selfdrive/controls/lib/tests/test_vehicle_model.py +++ b/selfdrive/controls/lib/tests/test_vehicle_model.py @@ -41,7 +41,7 @@ class TestVehicleModel(unittest.TestCase): self.assertAlmostEqual(float(yr1), yr2) def test_syn_ss_sol_simulate(self): - """Verifies that dyn_ss_sol mathes a simulation""" + """Verifies that dyn_ss_sol matches a simulation""" for roll in np.linspace(math.radians(-20), math.radians(20), num=11): for u in np.linspace(1, 30, num=10): diff --git a/selfdrive/controls/lib/vehicle_model.py b/selfdrive/controls/lib/vehicle_model.py index 3f180d3252..0750384918 100755 --- a/selfdrive/controls/lib/vehicle_model.py +++ b/selfdrive/controls/lib/vehicle_model.py @@ -29,22 +29,22 @@ class VehicleModel: CP: Car Parameters """ # for math readability, convert long names car params into short names - self.m = CP.mass - self.j = CP.rotationalInertia - self.l = CP.wheelbase - self.aF = CP.centerToFront - self.aR = CP.wheelbase - CP.centerToFront - self.chi = CP.steerRatioRear - - self.cF_orig = CP.tireStiffnessFront - self.cR_orig = CP.tireStiffnessRear + self.m: float = CP.mass + self.j: float = CP.rotationalInertia + self.l: float = CP.wheelbase + self.aF: float = CP.centerToFront + self.aR: float = CP.wheelbase - CP.centerToFront + self.chi: float = CP.steerRatioRear + + self.cF_orig: float = CP.tireStiffnessFront + self.cR_orig: float = CP.tireStiffnessRear self.update_params(1.0, CP.steerRatio) def update_params(self, stiffness_factor: float, steer_ratio: float) -> None: """Update the vehicle model with a new stiffness factor and steer ratio""" - self.cF = stiffness_factor * self.cF_orig - self.cR = stiffness_factor * self.cR_orig - self.sR = steer_ratio + self.cF: float = stiffness_factor * self.cF_orig + self.cR: float = stiffness_factor * self.cR_orig + self.sR: float = steer_ratio def steady_state_sol(self, sa: float, u: float, roll: float) -> np.ndarray: """Returns the steady state solution. @@ -221,10 +221,10 @@ def dyn_ss_sol(sa: float, u: float, roll: float, VM: VehicleModel) -> np.ndarray """ A, B = create_dyn_state_matrices(u, VM) inp = np.array([[sa], [roll]]) - return -solve(A, B) @ inp + return -solve(A, B) @ inp # type: ignore -def calc_slip_factor(VM): +def calc_slip_factor(VM: VehicleModel) -> float: """The slip factor is a measure of how the curvature changes with speed it's positive for Oversteering vehicle, negative (usual case) otherwise. """ diff --git a/selfdrive/controls/plannerd.py b/selfdrive/controls/plannerd.py index 02f1c19a77..93d0c80dac 100755 --- a/selfdrive/controls/plannerd.py +++ b/selfdrive/controls/plannerd.py @@ -2,31 +2,25 @@ from cereal import car from common.params import Params from common.realtime import Priority, config_realtime_process -from selfdrive.swaglog import cloudlog -from selfdrive.controls.lib.longitudinal_planner import Planner +from system.swaglog import cloudlog +from selfdrive.controls.lib.longitudinal_planner import LongitudinalPlanner from selfdrive.controls.lib.lateral_planner import LateralPlanner -from selfdrive.hardware import TICI import cereal.messaging as messaging def plannerd_thread(sm=None, pm=None): - config_realtime_process(5 if TICI else 2, Priority.CTRL_LOW) + config_realtime_process(5, Priority.CTRL_LOW) cloudlog.info("plannerd is waiting for CarParams") params = Params() CP = car.CarParams.from_bytes(params.get("CarParams", block=True)) cloudlog.info("plannerd got CarParams: %s", CP.carName) - use_lanelines = not params.get_bool('EndToEndToggle') - wide_camera = params.get_bool('EnableWideCamera') if TICI else False - - cloudlog.event("e2e mode", on=use_lanelines) - - longitudinal_planner = Planner(CP) - lateral_planner = LateralPlanner(CP, use_lanelines=use_lanelines, wide_camera=wide_camera) + longitudinal_planner = LongitudinalPlanner(CP) + lateral_planner = LateralPlanner(CP) if sm is None: - sm = messaging.SubMaster(['carState', 'controlsState', 'radarState', 'modelV2'], + sm = messaging.SubMaster(['carControl', 'carState', 'controlsState', 'radarState', 'modelV2'], poll=['radarState', 'modelV2'], ignore_avg_freq=['radarState']) if pm is None: diff --git a/selfdrive/controls/radard.py b/selfdrive/controls/radard.py index 65f8480c7c..3d958139d6 100755 --- a/selfdrive/controls/radard.py +++ b/selfdrive/controls/radard.py @@ -8,11 +8,9 @@ from cereal import car from common.numpy_fast import interp from common.params import Params from common.realtime import Ratekeeper, Priority, config_realtime_process -from selfdrive.config import RADAR_TO_CAMERA from selfdrive.controls.lib.cluster.fastcluster_py import cluster_points_centroid -from selfdrive.controls.lib.radar_helpers import Cluster, Track -from selfdrive.swaglog import cloudlog -from selfdrive.hardware import TICI +from selfdrive.controls.lib.radar_helpers import Cluster, Track, RADAR_TO_CAMERA +from system.swaglog import cloudlog class KalmanParams(): @@ -104,7 +102,7 @@ class RadarD(): self.ready = False - def update(self, sm, rr, enable_lead): + def update(self, sm, rr): self.current_time = 1e-9*max(sm.logMonoTime.values()) if sm.updated['carState']: @@ -164,24 +162,23 @@ class RadarD(): # *** publish radarState *** dat = messaging.new_message('radarState') - dat.valid = sm.all_alive_and_valid() and len(rr.errors) == 0 + dat.valid = sm.all_checks() and len(rr.errors) == 0 radarState = dat.radarState radarState.mdMonoTime = sm.logMonoTime['modelV2'] radarState.canMonoTimes = list(rr.canMonoTimes) radarState.radarErrors = list(rr.errors) radarState.carStateMonoTime = sm.logMonoTime['carState'] - if enable_lead: - leads_v3 = sm['modelV2'].leadsV3 - if len(leads_v3) > 1: - radarState.leadOne = get_lead(self.v_ego, self.ready, clusters, leads_v3[0], low_speed_override=True) - radarState.leadTwo = get_lead(self.v_ego, self.ready, clusters, leads_v3[1], low_speed_override=False) + leads_v3 = sm['modelV2'].leadsV3 + if len(leads_v3) > 1: + radarState.leadOne = get_lead(self.v_ego, self.ready, clusters, leads_v3[0], low_speed_override=True) + radarState.leadTwo = get_lead(self.v_ego, self.ready, clusters, leads_v3[1], low_speed_override=False) return dat # fuses camera and radar data for best lead detection def radard_thread(sm=None, pm=None, can_sock=None): - config_realtime_process(5 if TICI else 2, Priority.CTRL_LOW) + config_realtime_process(5, Priority.CTRL_LOW) # wait for stats about the car to come in from controls cloudlog.info("radard is waiting for CarParams") @@ -205,9 +202,6 @@ def radard_thread(sm=None, pm=None, can_sock=None): rk = Ratekeeper(1.0 / CP.radarTimeStep, print_delay_threshold=None) RD = RadarD(CP.radarTimeStep, RI.delay) - # TODO: always log leads once we can hide them conditionally - enable_lead = CP.openpilotLongitudinalControl or not CP.radarOffCan - while 1: can_strings = messaging.drain_sock_raw(can_sock, wait_for_one=True) rr = RI.update(can_strings) @@ -217,7 +211,7 @@ def radard_thread(sm=None, pm=None, can_sock=None): sm.update(0) - dat = RD.update(sm, rr, enable_lead) + dat = RD.update(sm, rr) dat.radarState.cumLagMs = -rk.remaining*1000. pm.send('radarState', dat) diff --git a/selfdrive/controls/tests/test_alerts.py b/selfdrive/controls/tests/test_alerts.py index 2502bed06b..9ed7eee122 100755 --- a/selfdrive/controls/tests/test_alerts.py +++ b/selfdrive/controls/tests/test_alerts.py @@ -10,6 +10,7 @@ from common.basedir import BASEDIR from common.params import Params from selfdrive.controls.lib.events import Alert, EVENTS, ET from selfdrive.controls.lib.alertmanager import set_offroad_alert +from selfdrive.test.process_replay.process_replay import FakeSubMaster, CONFIGS AlertSize = log.ControlsState.AlertSize @@ -19,8 +20,7 @@ OFFROAD_ALERTS_PATH = os.path.join(BASEDIR, "selfdrive/controls/lib/alerts_offro ALERTS = [] for event_types in EVENTS.values(): for alert in event_types.values(): - if isinstance(alert, Alert): - ALERTS.append(alert) + ALERTS.append(alert) class TestAlerts(unittest.TestCase): @@ -30,6 +30,12 @@ class TestAlerts(unittest.TestCase): with open(OFFROAD_ALERTS_PATH) as f: cls.offroad_alerts = json.loads(f.read()) + # Create fake objects for callback + cls.CS = car.CarState.new_message() + cls.CP = car.CarParams.new_message() + cfg = [c for c in CONFIGS if c.proc_name == 'controlsd'][0] + cls.sm = FakeSubMaster(cfg.pub_sub.keys()) + def test_events_defined(self): # Ensure all events in capnp schema are defined in events.py events = car.CarEvent.EventName.schema.enumerants @@ -42,23 +48,23 @@ class TestAlerts(unittest.TestCase): # ensure alert text doesn't exceed allowed width def test_alert_text_length(self): font_path = os.path.join(BASEDIR, "selfdrive/assets/fonts") - regular_font_path = os.path.join(font_path, "opensans_semibold.ttf") - bold_font_path = os.path.join(font_path, "opensans_semibold.ttf") - semibold_font_path = os.path.join(font_path, "opensans_semibold.ttf") - - max_text_width = 1920 - 300 # full screen width is useable, minus sidebar - # TODO: get exact scale factor. found this empirically, works well enough - font_scale_factor = 1.85 # factor to scale from nanovg units to PIL + regular_font_path = os.path.join(font_path, "Inter-SemiBold.ttf") + bold_font_path = os.path.join(font_path, "Inter-Bold.ttf") + semibold_font_path = os.path.join(font_path, "Inter-SemiBold.ttf") + max_text_width = 2160 - 300 # full screen width is usable, minus sidebar draw = ImageDraw.Draw(Image.new('RGB', (0, 0))) fonts = { - AlertSize.small: [ImageFont.truetype(semibold_font_path, int(40 * font_scale_factor))], - AlertSize.mid: [ImageFont.truetype(bold_font_path, int(48 * font_scale_factor)), - ImageFont.truetype(regular_font_path, int(36 * font_scale_factor))], + AlertSize.small: [ImageFont.truetype(semibold_font_path, 74)], + AlertSize.mid: [ImageFont.truetype(bold_font_path, 88), + ImageFont.truetype(regular_font_path, 66)], } for alert in ALERTS: + if not isinstance(alert, Alert): + alert = alert(self.CP, self.CS, self.sm, metric=False, soft_disable_time=100) + # for full size alerts, both text fields wrap the text, # so it's unlikely that they would go past the max width if alert.alert_size in (AlertSize.none, AlertSize.full): diff --git a/selfdrive/controls/tests/test_cruise_speed.py b/selfdrive/controls/tests/test_cruise_speed.py old mode 100644 new mode 100755 index 364be8db79..cd1d31cf07 --- a/selfdrive/controls/tests/test_cruise_speed.py +++ b/selfdrive/controls/tests/test_cruise_speed.py @@ -1,32 +1,149 @@ #!/usr/bin/env python3 -import unittest import numpy as np +from parameterized import parameterized_class +import unittest + +from selfdrive.controls.lib.drive_helpers import VCruiseHelper, V_CRUISE_MIN, V_CRUISE_MAX, V_CRUISE_ENABLE_MIN, IMPERIAL_INCREMENT +from cereal import car +from common.conversions import Conversions as CV from selfdrive.test.longitudinal_maneuvers.maneuver import Maneuver -def run_cruise_simulation(cruise, t_end=100.): +ButtonEvent = car.CarState.ButtonEvent +ButtonType = car.CarState.ButtonEvent.Type + + +def run_cruise_simulation(cruise, e2e, t_end=20.): man = Maneuver( '', duration=t_end, - initial_speed=float(0.), + initial_speed=max(cruise - 1., 0.0), lead_relevancy=True, initial_distance_lead=100, cruise_values=[cruise], prob_lead_values=[0.0], breakpoints=[0.], + e2e=e2e, ) valid, output = man.evaluate() assert valid - return output[-1,3] + return output[-1, 3] class TestCruiseSpeed(unittest.TestCase): def test_cruise_speed(self): - for speed in np.arange(5, 40, 5): - print(f'Testing {speed} m/s') - cruise_speed = float(speed) + for e2e in [False, True]: + for speed in np.arange(5, 40, 5): + print(f'Testing {speed} m/s') + cruise_speed = float(speed) + + simulation_steady_state = run_cruise_simulation(cruise_speed, e2e) + self.assertAlmostEqual(simulation_steady_state, cruise_speed, delta=.01, msg=f'Did not reach {speed} m/s') + + +# TODO: test pcmCruise +@parameterized_class(('pcm_cruise',), [(False,)]) +class TestVCruiseHelper(unittest.TestCase): + def setUp(self): + self.CP = car.CarParams(pcmCruise=self.pcm_cruise) # pylint: disable=E1101 + self.v_cruise_helper = VCruiseHelper(self.CP) + self.reset_cruise_speed_state() + + def reset_cruise_speed_state(self): + # Two resets previous cruise speed + for _ in range(2): + self.v_cruise_helper.update_v_cruise(car.CarState(cruiseState={"available": False}), enabled=False, is_metric=False) + + def enable(self, v_ego): + # Simulates user pressing set with a current speed + self.v_cruise_helper.initialize_v_cruise(car.CarState(vEgo=v_ego)) + + def test_adjust_speed(self): + """ + Asserts speed changes on falling edges of buttons. + """ + + self.enable(V_CRUISE_ENABLE_MIN * CV.KPH_TO_MS) + + for btn in (ButtonType.accelCruise, ButtonType.decelCruise): + for pressed in (True, False): + CS = car.CarState(cruiseState={"available": True}) + CS.buttonEvents = [ButtonEvent(type=btn, pressed=pressed)] + + self.v_cruise_helper.update_v_cruise(CS, enabled=True, is_metric=False) + self.assertEqual(pressed, self.v_cruise_helper.v_cruise_kph == self.v_cruise_helper.v_cruise_kph_last) + + def test_rising_edge_enable(self): + """ + Some car interfaces may enable on rising edge of a button, + ensure we don't adjust speed if enabled changes mid-press. + """ + + # NOTE: enabled is always one frame behind the result from button press in controlsd + for enabled, pressed in ((False, False), + (False, True), + (True, False)): + CS = car.CarState(cruiseState={"available": True}) + CS.buttonEvents = [ButtonEvent(type=ButtonType.decelCruise, pressed=pressed)] + self.v_cruise_helper.update_v_cruise(CS, enabled=enabled, is_metric=False) + if pressed: + self.enable(V_CRUISE_ENABLE_MIN * CV.KPH_TO_MS) + + # Expected diff on enabling. Speed should not change on falling edge of pressed + self.assertEqual(not pressed, self.v_cruise_helper.v_cruise_kph == self.v_cruise_helper.v_cruise_kph_last) + + def test_resume_in_standstill(self): + """ + Asserts we don't increment set speed if user presses resume/accel to exit cruise standstill. + """ + + self.enable(0) + + for standstill in (True, False): + for pressed in (True, False): + CS = car.CarState(cruiseState={"available": True, "standstill": standstill}) + CS.buttonEvents = [ButtonEvent(type=ButtonType.accelCruise, pressed=pressed)] + self.v_cruise_helper.update_v_cruise(CS, enabled=True, is_metric=False) + + # speed should only update if not at standstill and button falling edge + should_equal = standstill or pressed + self.assertEqual(should_equal, self.v_cruise_helper.v_cruise_kph == self.v_cruise_helper.v_cruise_kph_last) + + def test_set_gas_pressed(self): + """ + Asserts pressing set while enabled with gas pressed sets + the speed to the maximum of vEgo and current cruise speed. + """ + + for v_ego in np.linspace(0, 100, 101): + self.reset_cruise_speed_state() + self.enable(V_CRUISE_ENABLE_MIN * CV.KPH_TO_MS) + + # first decrement speed, then perform gas pressed logic + expected_v_cruise_kph = self.v_cruise_helper.v_cruise_kph - IMPERIAL_INCREMENT + expected_v_cruise_kph = max(expected_v_cruise_kph, v_ego * CV.MS_TO_KPH) # clip to min of vEgo + expected_v_cruise_kph = float(np.clip(round(expected_v_cruise_kph, 1), V_CRUISE_MIN, V_CRUISE_MAX)) + + CS = car.CarState(vEgo=float(v_ego), gasPressed=True, cruiseState={"available": True}) + CS.buttonEvents = [ButtonEvent(type=ButtonType.decelCruise, pressed=False)] + self.v_cruise_helper.update_v_cruise(CS, enabled=True, is_metric=False) + + # TODO: fix skipping first run due to enabled on rising edge exception + if v_ego == 0.0: + continue + self.assertEqual(expected_v_cruise_kph, self.v_cruise_helper.v_cruise_kph) + + def test_initialize_v_cruise(self): + """ + Asserts allowed cruise speeds on enabling with SET. + """ + + for v_ego in np.linspace(0, 100, 101): + self.reset_cruise_speed_state() + self.assertFalse(self.v_cruise_helper.v_cruise_initialized) - simulation_steady_state = run_cruise_simulation(cruise_speed) - self.assertAlmostEqual(simulation_steady_state, cruise_speed, delta=.01, msg=f'Did not reach {speed} m/s') + self.enable(float(v_ego)) + self.assertTrue(V_CRUISE_ENABLE_MIN <= self.v_cruise_helper.v_cruise_kph <= V_CRUISE_MAX) + self.assertTrue(self.v_cruise_helper.v_cruise_initialized) if __name__ == "__main__": diff --git a/selfdrive/controls/tests/test_following_distance.py b/selfdrive/controls/tests/test_following_distance.py index a0110a4dab..5185867d2d 100644 --- a/selfdrive/controls/tests/test_following_distance.py +++ b/selfdrive/controls/tests/test_following_distance.py @@ -5,7 +5,8 @@ import numpy as np from selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc import desired_follow_distance from selfdrive.test.longitudinal_maneuvers.maneuver import Maneuver -def run_following_distance_simulation(v_lead, t_end=100.0): + +def run_following_distance_simulation(v_lead, t_end=100.0, e2e=False): man = Maneuver( '', duration=t_end, @@ -14,6 +15,7 @@ def run_following_distance_simulation(v_lead, t_end=100.0): initial_distance_lead=100, speed_lead_values=[v_lead], breakpoints=[0.], + e2e=e2e, ) valid, output = man.evaluate() assert valid @@ -21,15 +23,15 @@ def run_following_distance_simulation(v_lead, t_end=100.0): class TestFollowingDistance(unittest.TestCase): - def test_following_distanc(self): - for speed in np.arange(0, 40, 5): - print(f'Testing {speed} m/s') - v_lead = float(speed) - - simulation_steady_state = run_following_distance_simulation(v_lead) - correct_steady_state = desired_follow_distance(v_lead, v_lead) - - self.assertAlmostEqual(simulation_steady_state, correct_steady_state, delta=(correct_steady_state*.1 + .5)) + def test_following_distance(self): + for e2e in [False, True]: + for speed in np.arange(0, 40, 5): + print(f'Testing {speed} m/s') + v_lead = float(speed) + simulation_steady_state = run_following_distance_simulation(v_lead, e2e=e2e) + correct_steady_state = desired_follow_distance(v_lead, v_lead) + err_ratio = 0.2 if e2e else 0.1 + self.assertAlmostEqual(simulation_steady_state, correct_steady_state, delta=(err_ratio * correct_steady_state + .5)) if __name__ == "__main__": diff --git a/selfdrive/controls/tests/test_lateral_mpc.py b/selfdrive/controls/tests/test_lateral_mpc.py index 4630e28a61..df5154b2b4 100644 --- a/selfdrive/controls/tests/test_lateral_mpc.py +++ b/selfdrive/controls/tests/test_lateral_mpc.py @@ -1,7 +1,8 @@ import unittest import numpy as np from selfdrive.controls.lib.lateral_mpc_lib.lat_mpc import LateralMpc -from selfdrive.controls.lib.drive_helpers import LAT_MPC_N, CAR_ROTATION_RADIUS +from selfdrive.controls.lib.drive_helpers import CAR_ROTATION_RADIUS +from selfdrive.controls.lib.lateral_mpc_lib.lat_mpc import N as LAT_MPC_N def run_mpc(lat_mpc=None, v_ref=30., x_init=0., y_init=0., psi_init=0., curvature_init=0., @@ -9,10 +10,11 @@ def run_mpc(lat_mpc=None, v_ref=30., x_init=0., y_init=0., psi_init=0., curvatur if lat_mpc is None: lat_mpc = LateralMpc() - lat_mpc.set_weights(1., 1., 1.) + lat_mpc.set_weights(1., .1, 0.0, .05, 800) y_pts = poly_shift * np.ones(LAT_MPC_N + 1) heading_pts = np.zeros(LAT_MPC_N + 1) + curv_rate_pts = np.zeros(LAT_MPC_N + 1) x0 = np.array([x_init, y_init, psi_init, curvature_init]) p = np.array([v_ref, CAR_ROTATION_RADIUS]) @@ -20,7 +22,7 @@ def run_mpc(lat_mpc=None, v_ref=30., x_init=0., y_init=0., psi_init=0., curvatur # converge in no more than 10 iterations for _ in range(10): lat_mpc.run(x0, p, - y_pts, heading_pts) + y_pts, heading_pts, curv_rate_pts) return lat_mpc.x_sol @@ -75,9 +77,9 @@ class TestLateralMpc(unittest.TestCase): def test_switch_convergence(self): lat_mpc = LateralMpc() - sol = run_mpc(lat_mpc=lat_mpc, poly_shift=30.0, v_ref=7.0) + sol = run_mpc(lat_mpc=lat_mpc, poly_shift=3.0, v_ref=7.0) right_psi_deg = np.degrees(sol[:,2]) - sol = run_mpc(lat_mpc=lat_mpc, poly_shift=-30.0, v_ref=7.0) + sol = run_mpc(lat_mpc=lat_mpc, poly_shift=-3.0, v_ref=7.0) left_psi_deg = np.degrees(sol[:,2]) np.testing.assert_almost_equal(right_psi_deg, -left_psi_deg, decimal=3) diff --git a/selfdrive/controls/tests/test_startup.py b/selfdrive/controls/tests/test_startup.py index 9d13453045..ba2d2f5c02 100755 --- a/selfdrive/controls/tests/test_startup.py +++ b/selfdrive/controls/tests/test_startup.py @@ -18,7 +18,7 @@ Ecu = car.CarParams.Ecu COROLLA_FW_VERSIONS = [ (Ecu.engine, 0x7e0, None, b'\x0230ZC2000\x00\x00\x00\x00\x00\x00\x00\x0050212000\x00\x00\x00\x00\x00\x00\x00\x00'), - (Ecu.esp, 0x7b0, None, b'F152602190\x00\x00\x00\x00\x00\x00'), + (Ecu.abs, 0x7b0, None, b'F152602190\x00\x00\x00\x00\x00\x00'), (Ecu.eps, 0x7a1, None, b'8965B02181\x00\x00\x00\x00\x00\x00'), (Ecu.fwdRadar, 0x750, 0xf, b'8821F4702100\x00\x00\x00\x00'), (Ecu.fwdCamera, 0x750, 0x6d, b'8646F0201101\x00\x00\x00\x00'), @@ -29,7 +29,7 @@ COROLLA_FW_VERSIONS_NO_DSU = COROLLA_FW_VERSIONS[:-1] CX5_FW_VERSIONS = [ (Ecu.engine, 0x7e0, None, b'PYNF-188K2-F\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), - (Ecu.esp, 0x760, None, b'K123-437K2-E\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (Ecu.abs, 0x760, None, b'K123-437K2-E\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), (Ecu.eps, 0x730, None, b'KJ01-3210X-G-00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), (Ecu.fwdRadar, 0x764, None, b'K123-67XK2-F\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), (Ecu.fwdCamera, 0x706, None, b'B61L-67XK2-T\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), @@ -42,27 +42,27 @@ class TestStartup(unittest.TestCase): # TODO: test EventName.startup for release branches # officially supported car - (EventName.startupMaster, TOYOTA.COROLLA, COROLLA_FW_VERSIONS), - (EventName.startupMaster, TOYOTA.COROLLA, COROLLA_FW_VERSIONS), + (EventName.startupMaster, TOYOTA.COROLLA, COROLLA_FW_VERSIONS, "toyota"), + (EventName.startupMaster, TOYOTA.COROLLA, COROLLA_FW_VERSIONS, "toyota"), # dashcamOnly car - (EventName.startupNoControl, MAZDA.CX5, CX5_FW_VERSIONS), - (EventName.startupNoControl, MAZDA.CX5, CX5_FW_VERSIONS), + (EventName.startupNoControl, MAZDA.CX5, CX5_FW_VERSIONS, "mazda"), + (EventName.startupNoControl, MAZDA.CX5, CX5_FW_VERSIONS, "mazda"), # unrecognized car with no fw - (EventName.startupNoFw, None, None), - (EventName.startupNoFw, None, None), + (EventName.startupNoFw, None, None, ""), + (EventName.startupNoFw, None, None, ""), # unrecognized car - (EventName.startupNoCar, None, COROLLA_FW_VERSIONS[:1]), - (EventName.startupNoCar, None, COROLLA_FW_VERSIONS[:1]), + (EventName.startupNoCar, None, COROLLA_FW_VERSIONS[:1], "toyota"), + (EventName.startupNoCar, None, COROLLA_FW_VERSIONS[:1], "toyota"), # fuzzy match - (EventName.startupMaster, TOYOTA.COROLLA, COROLLA_FW_VERSIONS_FUZZY), - (EventName.startupMaster, TOYOTA.COROLLA, COROLLA_FW_VERSIONS_FUZZY), + (EventName.startupMaster, TOYOTA.COROLLA, COROLLA_FW_VERSIONS_FUZZY, "toyota"), + (EventName.startupMaster, TOYOTA.COROLLA, COROLLA_FW_VERSIONS_FUZZY, "toyota"), ]) @with_processes(['controlsd']) - def test_startup_alert(self, expected_event, car_model, fw_versions): + def test_startup_alert(self, expected_event, car_model, fw_versions, brand): # TODO: this should be done without any real sockets controls_sock = messaging.sub_sock("controlsState") @@ -82,6 +82,7 @@ class TestStartup(unittest.TestCase): f.ecu = ecu f.address = addr f.fwVersion = version + f.brand = brand if subaddress is not None: f.subAddress = subaddress @@ -93,6 +94,9 @@ class TestStartup(unittest.TestCase): time.sleep(2) # wait for controlsd to be ready + pm.send('can', can_list_to_can_capnp([[0, 0, b"", 0]])) + time.sleep(0.1) + msg = messaging.new_message('pandaStates', 1) msg.pandaStates[0].pandaType = log.PandaState.PandaType.uno pm.send('pandaStates', msg) diff --git a/selfdrive/controls/tests/test_state_machine.py b/selfdrive/controls/tests/test_state_machine.py new file mode 100755 index 0000000000..8f263a98e7 --- /dev/null +++ b/selfdrive/controls/tests/test_state_machine.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +import unittest + +from cereal import car, log +from common.realtime import DT_CTRL +from selfdrive.car.car_helpers import interfaces +from selfdrive.controls.controlsd import Controls, SOFT_DISABLE_TIME +from selfdrive.controls.lib.events import Events, ET, Alert, Priority, AlertSize, AlertStatus, VisualAlert, \ + AudibleAlert, EVENTS + +State = log.ControlsState.OpenpilotState + +# The event types that maintain the current state +MAINTAIN_STATES = {State.enabled: (None,), State.disabled: (None,), State.softDisabling: (ET.SOFT_DISABLE,), + State.preEnabled: (ET.PRE_ENABLE,), State.overriding: (ET.OVERRIDE_LATERAL, ET.OVERRIDE_LONGITUDINAL)} +ALL_STATES = tuple(State.schema.enumerants.values()) +# The event types checked in DISABLED section of state machine +ENABLE_EVENT_TYPES = (ET.ENABLE, ET.PRE_ENABLE, ET.OVERRIDE_LATERAL, ET.OVERRIDE_LONGITUDINAL) + + +def make_event(event_types): + event = {} + for ev in event_types: + event[ev] = Alert("", "", AlertStatus.normal, AlertSize.small, Priority.LOW, + VisualAlert.none, AudibleAlert.none, 1.) + EVENTS[0] = event + return 0 + + +class TestStateMachine(unittest.TestCase): + + def setUp(self): + CarInterface, CarController, CarState = interfaces["mock"] + CP = CarInterface.get_params("mock") + CI = CarInterface(CP, CarController, CarState) + + self.controlsd = Controls(CI=CI) + self.controlsd.events = Events() + self.controlsd.soft_disable_timer = int(SOFT_DISABLE_TIME / DT_CTRL) + self.CS = car.CarState() + + def test_immediate_disable(self): + for state in ALL_STATES: + for et in MAINTAIN_STATES[state]: + self.controlsd.events.add(make_event([et, ET.IMMEDIATE_DISABLE])) + self.controlsd.state = state + self.controlsd.state_transition(self.CS) + self.assertEqual(State.disabled, self.controlsd.state) + self.controlsd.events.clear() + + def test_user_disable(self): + for state in ALL_STATES: + for et in MAINTAIN_STATES[state]: + self.controlsd.events.add(make_event([et, ET.USER_DISABLE])) + self.controlsd.state = state + self.controlsd.state_transition(self.CS) + self.assertEqual(State.disabled, self.controlsd.state) + self.controlsd.events.clear() + + def test_soft_disable(self): + for state in ALL_STATES: + if state == State.preEnabled: # preEnabled considers NO_ENTRY instead + continue + for et in MAINTAIN_STATES[state]: + self.controlsd.events.add(make_event([et, ET.SOFT_DISABLE])) + self.controlsd.state = state + self.controlsd.state_transition(self.CS) + self.assertEqual(self.controlsd.state, State.disabled if state == State.disabled else State.softDisabling) + self.controlsd.events.clear() + + def test_soft_disable_timer(self): + self.controlsd.state = State.enabled + self.controlsd.events.add(make_event([ET.SOFT_DISABLE])) + self.controlsd.state_transition(self.CS) + for _ in range(int(SOFT_DISABLE_TIME / DT_CTRL)): + self.assertEqual(self.controlsd.state, State.softDisabling) + self.controlsd.state_transition(self.CS) + + self.assertEqual(self.controlsd.state, State.disabled) + + def test_no_entry(self): + # Make sure noEntry keeps us disabled + for et in ENABLE_EVENT_TYPES: + self.controlsd.events.add(make_event([ET.NO_ENTRY, et])) + self.controlsd.state_transition(self.CS) + self.assertEqual(self.controlsd.state, State.disabled) + self.controlsd.events.clear() + + def test_no_entry_pre_enable(self): + # preEnabled with noEntry event + self.controlsd.state = State.preEnabled + self.controlsd.events.add(make_event([ET.NO_ENTRY, ET.PRE_ENABLE])) + self.controlsd.state_transition(self.CS) + self.assertEqual(self.controlsd.state, State.preEnabled) + + def test_maintain_states(self): + # Given current state's event type, we should maintain state + for state in ALL_STATES: + for et in MAINTAIN_STATES[state]: + self.controlsd.state = state + self.controlsd.events.add(make_event([et])) + self.controlsd.state_transition(self.CS) + self.assertEqual(self.controlsd.state, state) + self.controlsd.events.clear() + + +if __name__ == "__main__": + unittest.main() diff --git a/selfdrive/debug/README.md b/selfdrive/debug/README.md index d49db25d09..83b8a994db 100644 --- a/selfdrive/debug/README.md +++ b/selfdrive/debug/README.md @@ -19,7 +19,7 @@ optional arguments: ``` usage: dump.py [-h] [--pipe] [--raw] [--json] [--dump-json] [--no-print] [--addr ADDR] [--values VALUES] [socket [socket ...]] -Dump communcation sockets. See cereal/services.py for a complete list of available sockets. +Dump communication sockets. See cereal/services.py for a complete list of available sockets. positional arguments: socket socket names to dump. defaults to all services defined in cereal @@ -52,7 +52,7 @@ optional arguments: -h, --help show this help message and exit --debug enable ISO-TP/UDS stack debugging output -This tool is meant to run directly on a vehicle-installed comma two or comma three, with +This tool is meant to run directly on a vehicle-installed comma three, with the openpilot/tmux processes stopped. It should also work on a separate PC with a USB- attached comma panda. Vehicle ignition must be on. Recommend engine not be running when making changes. Must turn ignition off and on again for any changes to take effect. diff --git a/selfdrive/debug/adb.sh b/selfdrive/debug/adb.sh index 8a04d4aefd..919a82fefc 100755 --- a/selfdrive/debug/adb.sh +++ b/selfdrive/debug/adb.sh @@ -4,12 +4,7 @@ set -e PORT=5555 setprop service.adb.tcp.port $PORT -if [ -f /EON ]; then - stop adbd - start adbd -else - sudo systemctl start adbd -fi +sudo systemctl start adbd IP=$(echo $SSH_CONNECTION | awk '{ print $3}') echo "then, connect on your computer:" diff --git a/selfdrive/debug/can_print_changes.py b/selfdrive/debug/can_print_changes.py index 4fa775ac17..ff98c20e60 100755 --- a/selfdrive/debug/can_print_changes.py +++ b/selfdrive/debug/can_print_changes.py @@ -1,46 +1,107 @@ #!/usr/bin/env python3 +import argparse import binascii -import sys +import time from collections import defaultdict import cereal.messaging as messaging -from common.realtime import sec_since_boot +from selfdrive.debug.can_table import can_table +from tools.lib.logreader import logreader_from_route_or_segment +RED = '\033[91m' +CLEAR = '\033[0m' + +def update(msgs, bus, dat, low_to_high, high_to_low, quiet=False): + for x in msgs: + if x.which() != 'can': + continue + + for y in x.can: + if y.src == bus: + dat[y.address] = y.dat + + i = int.from_bytes(y.dat, byteorder='big') + l_h = low_to_high[y.address] + h_l = high_to_low[y.address] + + change = None + if (i | l_h) != l_h: + low_to_high[y.address] = i | l_h + change = "+" + + if (~i | h_l) != h_l: + high_to_low[y.address] = ~i | h_l + change = "-" + + if change and not quiet: + print(f"{time.monotonic():.2f}\t{hex(y.address)} ({y.address})\t{change}{binascii.hexlify(y.dat)}") -def can_printer(bus=0): - """Collects messages and prints when a new bit transition is observed. - This is very useful to find signals based on user triggered actions, such as blinkers and seatbelt. - Leave the script running until no new transitions are seen, then perform the action.""" - logcan = messaging.sub_sock('can') +def can_printer(bus=0, init_msgs=None, new_msgs=None, table=False): + logcan = messaging.sub_sock('can', timeout=10) + + dat = defaultdict(int) low_to_high = defaultdict(int) high_to_low = defaultdict(int) - while 1: - can_recv = messaging.drain_sock(logcan, wait_for_one=True) - for x in can_recv: - for y in x.can: - if y.src == bus: - i = int.from_bytes(y.dat, byteorder='big') + if init_msgs is not None: + update(init_msgs, bus, dat, low_to_high, high_to_low, quiet=True) - l_h = low_to_high[y.address] - h_l = high_to_low[y.address] + low_to_high_init = low_to_high.copy() + high_to_low_init = high_to_low.copy() - change = None - if (i | l_h) != l_h: - low_to_high[y.address] = i | l_h - change = "+" + if new_msgs is not None: + update(new_msgs, bus, dat, low_to_high, high_to_low) + else: + # Live mode + print(f"Waiting for messages on bus {bus}") + try: + while 1: + can_recv = messaging.drain_sock(logcan) + update(can_recv, bus, dat, low_to_high, high_to_low) + time.sleep(0.02) + except KeyboardInterrupt: + pass - if (~i | h_l) != h_l: - high_to_low[y.address] = ~i | h_l - change = "-" + print("\n\n") + tables = "" + for addr in sorted(dat.keys()): + init = low_to_high_init[addr] & high_to_low_init[addr] + now = low_to_high[addr] & high_to_low[addr] + d = now & ~init + if d == 0: + continue + b = d.to_bytes(len(dat[addr]), byteorder='big') - if change: - print(f"{sec_since_boot():.2f}\t{hex(y.address)} ({y.address})\t{change}{binascii.hexlify(y.dat)}") + byts = ''.join([(c if c == '0' else f'{RED}{c}{CLEAR}') for c in str(binascii.hexlify(b))[2:-1]]) + header = f"{hex(addr).ljust(6)}({str(addr).ljust(4)})" + print(header, byts) + tables += f"{header}\n" + tables += can_table(b) + "\n\n" + if table: + print(tables) if __name__ == "__main__": - if len(sys.argv) > 1: - can_printer(int(sys.argv[1])) - else: - can_printer() + desc = """Collects messages and prints when a new bit transition is observed. + This is very useful to find signals based on user triggered actions, such as blinkers and seatbelt. + Leave the script running until no new transitions are seen, then perform the action.""" + parser = argparse.ArgumentParser(description=desc, + formatter_class=argparse.ArgumentDefaultsHelpFormatter) + parser.add_argument("--bus", type=int, help="CAN bus to print out", default=0) + parser.add_argument("--table", action="store_true", help="Print a cabana-like table") + parser.add_argument("init", type=str, nargs='?', help="Route or segment to initialize with. Use empty quotes to compare against all zeros.") + parser.add_argument("comp", type=str, nargs='?', help="Route or segment to compare against init") + + args = parser.parse_args() + + init_lr, new_lr = None, None + if args.init: + if args.init == '': + init_lr = [] + else: + init_lr = logreader_from_route_or_segment(args.init) + if args.comp: + new_lr = logreader_from_route_or_segment(args.comp) + + can_printer(args.bus, init_msgs=init_lr, new_msgs=new_lr, table=args.table) diff --git a/selfdrive/debug/can_printer.py b/selfdrive/debug/can_printer.py index 0aaaf1350b..3f991d4e6c 100755 --- a/selfdrive/debug/can_printer.py +++ b/selfdrive/debug/can_printer.py @@ -26,8 +26,9 @@ def can_printer(bus, max_msg, addr, ascii_decode): for addr in sorted(msgs.keys()): a = f"\"{msgs[addr][-1].decode('ascii', 'backslashreplace')}\"" if ascii_decode else "" x = binascii.hexlify(msgs[addr][-1]).decode('ascii') + freq = len(msgs[addr]) / (sec_since_boot() - start) if max_msg is None or addr < max_msg: - dd += "%04X(%4d)(%6d) %s %s\n" % (addr, addr, len(msgs[addr]), x.ljust(20), a) + dd += "%04X(%4d)(%6d)(%3dHz) %s %s\n" % (addr, addr, len(msgs[addr]), freq, x.ljust(20), a) print(dd) lp = sec_since_boot() diff --git a/selfdrive/debug/can_table.py b/selfdrive/debug/can_table.py index 1569849053..11d070e708 100755 --- a/selfdrive/debug/can_table.py +++ b/selfdrive/debug/can_table.py @@ -1,10 +1,23 @@ #!/usr/bin/env python3 import argparse -import pandas as pd # pylint: disable=import-error +import pandas as pd import cereal.messaging as messaging +def can_table(dat): + rows = [] + for b in dat: + r = list(bin(b).lstrip('0b').zfill(8)) + r += [hex(b)] + rows.append(r) + + df = pd.DataFrame(data=rows) + df.columns = [str(n) for n in range(7, -1, -1)] + [' '] + table = df.to_markdown(tablefmt='grid') + return table + + if __name__ == "__main__": parser = argparse.ArgumentParser(description="Cabana-like table of bits for your terminal", formatter_class=argparse.ArgumentDefaultsHelpFormatter) @@ -28,12 +41,5 @@ if __name__ == "__main__": if latest is None: continue - rows = [] - for b in latest.dat: - r = list(bin(b).lstrip('0b').zfill(8)) - r += [hex(b)] - rows.append(r) - - df = pd.DataFrame(data=rows) - table = df.to_markdown(tablefmt='grid') + table = can_table(latest.dat) print(f"\n\n{hex(addr)} ({addr}) on bus {args.bus}\n{table}") diff --git a/selfdrive/debug/check_freq.py b/selfdrive/debug/check_freq.py index 424ad67b6d..6436abb4f1 100755 --- a/selfdrive/debug/check_freq.py +++ b/selfdrive/debug/check_freq.py @@ -1,9 +1,9 @@ #!/usr/bin/env python3 -# type: ignore - import argparse import numpy as np from collections import defaultdict, deque +from typing import DefaultDict, Deque, MutableSequence + from common.realtime import sec_since_boot import cereal.messaging as messaging @@ -19,8 +19,8 @@ if __name__ == "__main__": socket_names = args.socket sockets = {} - rcv_times = defaultdict(lambda: deque(maxlen=100)) - valids = defaultdict(lambda: deque(maxlen=100)) + rcv_times: DefaultDict[str, MutableSequence[float]] = defaultdict(lambda: deque(maxlen=100)) + valids: DefaultDict[str, Deque[bool]] = defaultdict(lambda: deque(maxlen=100)) t = sec_since_boot() for name in socket_names: @@ -31,6 +31,9 @@ if __name__ == "__main__": while True: for socket in poller.poll(100): msg = messaging.recv_one(socket) + if msg is None: + continue + name = msg.which() t = sec_since_boot() diff --git a/selfdrive/debug/check_lag.py b/selfdrive/debug/check_lag.py index c922642982..141156db91 100755 --- a/selfdrive/debug/check_lag.py +++ b/selfdrive/debug/check_lag.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -# type: ignore +from typing import Dict import cereal.messaging as messaging from cereal.services import service_list @@ -10,7 +10,7 @@ TO_CHECK = ['carState'] if __name__ == "__main__": sm = messaging.SubMaster(TO_CHECK) - prev_t = {} + prev_t: Dict[str, float] = {} while True: sm.update() diff --git a/selfdrive/debug/check_timings.py b/selfdrive/debug/check_timings.py index 03e39fd70d..fb8467a3c4 100755 --- a/selfdrive/debug/check_timings.py +++ b/selfdrive/debug/check_timings.py @@ -1,14 +1,15 @@ #!/usr/bin/env python3 -# type: ignore + import sys import time import numpy as np +from typing import DefaultDict, MutableSequence from collections import defaultdict, deque import cereal.messaging as messaging socks = {s: messaging.sub_sock(s, conflate=False) for s in sys.argv[1:]} -ts = defaultdict(lambda: deque(maxlen=100)) +ts: DefaultDict[str, MutableSequence[float]] = defaultdict(lambda: deque(maxlen=100)) if __name__ == "__main__": while True: @@ -18,7 +19,7 @@ if __name__ == "__main__": for m in msgs: ts[s].append(m.logMonoTime / 1e6) - if len(ts[s]): + if len(ts[s]) > 2: d = np.diff(ts[s]) print(f"{s:25} {np.mean(d):.2f} {np.std(d):.2f} {np.max(d):.2f} {np.min(d):.2f}") time.sleep(1) diff --git a/selfdrive/debug/clear_dtc.py b/selfdrive/debug/clear_dtc.py index f4d38367b1..d84828079d 100755 --- a/selfdrive/debug/clear_dtc.py +++ b/selfdrive/debug/clear_dtc.py @@ -1,9 +1,16 @@ #!/usr/bin/env python3 import sys +import argparse from subprocess import check_output, CalledProcessError from panda import Panda from panda.python.uds import UdsClient, MessageTimeoutError, SESSION_TYPE, DTC_GROUP_TYPE +parser = argparse.ArgumentParser(description="clear DTC status") +parser.add_argument("addr", type=lambda x: int(x,0), nargs="?", default=0x7DF) # default is functional (broadcast) address +parser.add_argument("--bus", type=int, default=0) +parser.add_argument('--debug', action='store_true') +args = parser.parse_args() + try: check_output(["pidof", "boardd"]) print("boardd is running, please kill openpilot before running this script! (aborted)") @@ -14,17 +21,20 @@ except CalledProcessError as e: panda = Panda() panda.set_safety_mode(Panda.SAFETY_ELM327) -address = 0x7DF # functional (broadcast) address -uds_client = UdsClient(panda, address, bus=0, debug=False) +uds_client = UdsClient(panda, args.addr, bus=args.bus, debug=args.debug) print("extended diagnostic session ...") try: uds_client.diagnostic_session_control(SESSION_TYPE.EXTENDED_DIAGNOSTIC) except MessageTimeoutError: - pass # functional address isn't properly handled so a timeout occurs + # functional address isn't properly handled so a timeout occurs + if args.addr != 0x7DF: + raise print("clear diagnostic info ...") try: uds_client.clear_diagnostic_information(DTC_GROUP_TYPE.ALL) except MessageTimeoutError: - pass # functional address isn't properly handled so a timeout occurs + # functional address isn't properly handled so a timeout occurs + if args.addr != 0x7DF: + pass print("") print("you may need to power cycle your vehicle now") diff --git a/selfdrive/debug/compare_fingerprints.py b/selfdrive/debug/compare_fingerprints.py deleted file mode 100755 index 5b7ba58b1e..0000000000 --- a/selfdrive/debug/compare_fingerprints.py +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env python3 -# flake8: noqa - -# put 2 fingeprints and print the diffs -f1 = { -168: 8, 257: 5, 258: 8, 264: 8, 268: 8, 270: 8, 274: 2, 280: 8, 284: 8, 288: 7, 290: 6, 291: 8, 292: 8, 294: 8, 300: 8, 308: 8, 320: 8, 324: 8, 331: 8, 332: 8, 344: 8, 368: 8, 376: 3, 384: 8, 388: 4, 448: 6, 456: 4, 464: 8, 469: 8, 480: 8, 500: 8, 501: 8, 512: 8, 514: 8, 520: 8, 528: 8, 532: 8, 544: 8, 557: 8, 559: 8, 560: 8, 564: 8, 571: 3, 579: 8, 584: 8, 608: 8, 624: 8, 625: 8, 632: 8, 639: 8, 653: 8, 654: 8, 655: 8, 658: 6, 660: 8, 669: 3, 671: 8, 672: 8, 678: 8, 680: 8, 701: 8, 703: 8, 704: 8, 705: 8, 706: 8, 709: 8, 710: 8, 719: 8, 720: 6, 729: 5, 736: 8, 737: 8, 746: 5, 752: 2, 754: 8, 760: 8, 764: 8, 766: 8, 770: 8, 773: 8, 779: 8, 782: 8, 784: 8, 792: 8, 799: 8, 800: 8, 804: 8, 816: 8, 817: 8, 820: 8, 825: 2, 826: 8, 832: 8, 838: 2, 848: 8, 853: 8, 856: 4, 860: 6, 863: 8, 878: 8, 882: 8, 897: 8, 906: 8, 908: 8, 924: 8, 926: 3, 929: 8, 937: 8, 938: 8, 939: 8, 940: 8, 941: 8, 942: 8, 943: 8, 947: 8, 948: 8, 958: 8, 959: 8, 962: 8, 969: 4, 973: 8, 974: 5, 979: 8, 980: 8, 981: 8, 982: 8, 983: 8, 984: 8, 992: 8, 993: 7, 995: 8, 996: 8, 1000: 8, 1001: 8, 1002: 8, 1003: 8, 1008: 8, 1009: 8, 1010: 8, 1011: 8, 1012: 8, 1013: 8, 1014: 8, 1015: 8, 1024: 8, 1025: 8, 1026: 8, 1031: 8, 1033: 8, 1050: 8, 1059: 8, 1082: 8, 1083: 8, 1098: 8, 1100: 8, 1537: 8, 1538: 8, 1562: 8 -} - -f2 = { -168: 8, 257: 5, 258: 8, 264: 8, 268: 8, 270: 8, 274: 2, 280: 8, 284: 8, 288: 7, 290: 6, 291: 8, 292: 8, 294: 8, 300: 8, 308: 8, 320: 8, 324: 8, 331: 8, 332: 8, 344: 8, 368: 8, 376: 3, 384: 8, 388: 4, 448: 6, 456: 4, 464: 8, 469: 8, 480: 8, 500: 8, 501: 8, 512: 8, 514: 8, 515: 7, 516: 7, 517: 7, 518: 7, 520: 8, 528: 8, 532: 8, 542: 8, 544: 8, 557: 8, 559: 8, 560: 8, 564: 8, 571: 3, 579: 8, 584: 8, 608: 8, 624: 8, 625: 8, 632: 8, 639: 8, 653: 8, 654: 8, 655: 8, 658: 6, 660: 8, 669: 3, 671: 8, 672: 8, 678: 8, 680: 8, 701: 8, 703: 8, 704: 8, 705: 8, 706: 8, 709: 8, 710: 8, 719: 8, 720: 6, 729: 5, 736: 8, 737: 8, 746: 5, 752: 2, 754: 8, 760: 8, 764: 8, 766: 8, 770: 8, 773: 8, 779: 8, 782: 8, 784: 8, 792: 8, 799: 8, 800: 8, 804: 8, 816: 8, 817: 8, 820: 8, 825: 2, 826: 8, 832: 8, 838: 2, 848: 8, 853: 8, 856: 4, 860: 6, 863: 8, 878: 8, 882: 8, 897: 8, 906: 8, 908: 8, 924: 8, 926: 3, 929: 8, 937: 8, 938: 8, 939: 8, 940: 8, 941: 8, 942: 8, 943: 8, 947: 8, 948: 8, 958: 8, 959: 8, 962: 8, 969: 4, 973: 8, 974: 5, 979: 8, 980: 8, 981: 8, 982: 8, 983: 8, 984: 8, 992: 8, 993: 7, 995: 8, 996: 8, 1000: 8, 1001: 8, 1002: 8, 1003: 8, 1008: 8, 1009: 8, 1010: 8, 1011: 8, 1012: 8, 1013: 8, 1014: 8, 1015: 8, 1024: 8, 1025: 8, 1026: 8, 1031: 8, 1033: 8, 1050: 8, 1059: 8, 1082: 8, 1083: 8, 1098: 8, 1100: 8 -} - -for k in f1: - if k not in f2 or f1[k] != f2[k]: - print(k, "not in f2") - -for k in f2: - if k not in f1 or f2[k] != f1[k]: - print(k, "not in f1") diff --git a/selfdrive/debug/count_events.py b/selfdrive/debug/count_events.py index 8b32ce9d21..93dd5bdc47 100755 --- a/selfdrive/debug/count_events.py +++ b/selfdrive/debug/count_events.py @@ -1,9 +1,13 @@ #!/usr/bin/env python3 import sys +import math +import datetime from collections import Counter from pprint import pprint from tqdm import tqdm +from typing import cast +from cereal.services import service_list from tools.lib.route import Route from tools.lib.logreader import LogReader @@ -13,6 +17,11 @@ if __name__ == "__main__": cnt_valid: Counter = Counter() cnt_events: Counter = Counter() + cams = [s for s in service_list if s.endswith('CameraState')] + cnt_cameras = dict.fromkeys(cams, 0) + + start_time = math.inf + end_time = -math.inf for q in tqdm(r.qlog_paths()): if q is None: continue @@ -21,12 +30,30 @@ if __name__ == "__main__": if msg.which() == 'carEvents': for e in msg.carEvents: cnt_events[e.name] += 1 + elif msg.which() in cams: + cnt_cameras[msg.which()] += 1 + if not msg.valid: cnt_valid[msg.which()] += 1 + end_time = max(end_time, msg.logMonoTime) + start_time = min(start_time, msg.logMonoTime) + + duration = (end_time - start_time) / 1e9 + print("Events") pprint(cnt_events) - print("\n\n") + print("\n") print("Not valid") pprint(cnt_valid) + + print("\n") + print("Cameras") + for k, v in cnt_cameras.items(): + s = service_list[k] + expected_frames = int(s.frequency * duration / cast(float, s.decimation)) + print(" ", k.ljust(20), f"{v}, {v/expected_frames:.1%} of expected") + + print("\n") + print("Route duration", datetime.timedelta(seconds=duration)) diff --git a/selfdrive/debug/cpu_usage_stat.py b/selfdrive/debug/cpu_usage_stat.py index 76e809d2c4..b3294c8728 100755 --- a/selfdrive/debug/cpu_usage_stat.py +++ b/selfdrive/debug/cpu_usage_stat.py @@ -5,8 +5,8 @@ System tools like top/htop can only show current cpu usage values, so I write th Features: Use psutil library to sample cpu usage(avergage for all cores) of openpilot processes, at a rate of 5 samples/sec. Do cpu usage statistics periodically, 5 seconds as a cycle. - Caculate the average cpu usage within this cycle. - Caculate minumium/maximium/accumulated_average cpu usage as long term inspections. + Calculate the average cpu usage within this cycle. + Calculate minumium/maximum/accumulated_average cpu usage as long term inspections. Monitor multiple processes simuteneously. Sample usage: root@localhost:/data/openpilot$ python selfdrive/debug/cpu_usage_stat.py boardd,ubloxd diff --git a/selfdrive/debug/cycle_alerts.py b/selfdrive/debug/cycle_alerts.py index f28d5373f4..b40c8e304c 100755 --- a/selfdrive/debug/cycle_alerts.py +++ b/selfdrive/debug/cycle_alerts.py @@ -1,19 +1,20 @@ #!/usr/bin/env python3 -# flake8: noqa -# pylint: skip-file -# type: ignore - import time +import random from cereal import car, log import cereal.messaging as messaging from common.realtime import DT_CTRL from selfdrive.car.honda.interface import CarInterface -from selfdrive.controls.lib.events import ET, EVENTS, Events +from selfdrive.controls.lib.events import ET, Events from selfdrive.controls.lib.alertmanager import AlertManager +from selfdrive.manager.process_config import managed_processes EventName = car.CarEvent.EventName +def randperc() -> float: + return 100. * random.random() + def cycle_alerts(duration=200, is_metric=False): # all alerts #alerts = list(EVENTS.keys()) @@ -33,9 +34,27 @@ def cycle_alerts(duration=200, is_metric=False): (EventName.driverDistracted, ET.WARNING), ] + # debug alerts + alerts = [ + #(EventName.highCpuUsage, ET.NO_ENTRY), + #(EventName.lowMemory, ET.PERMANENT), + #(EventName.overheat, ET.PERMANENT), + #(EventName.outOfSpace, ET.PERMANENT), + #(EventName.modeldLagging, ET.PERMANENT), + #(EventName.processNotRunning, ET.NO_ENTRY), + #(EventName.commIssue, ET.NO_ENTRY), + #(EventName.calibrationInvalid, ET.PERMANENT), + (EventName.cameraMalfunction, ET.PERMANENT), + (EventName.cameraFrameRate, ET.PERMANENT), + ] + + cameras = ['roadCameraState', 'wideRoadCameraState', 'driverCameraState'] + + CS = car.CarState.new_message() CP = CarInterface.get_params("HONDA CIVIC 2016") sm = messaging.SubMaster(['deviceState', 'pandaStates', 'roadCameraState', 'modelV2', 'liveCalibration', - 'driverMonitoringState', 'longitudinalPlan', 'lateralPlan', 'liveLocationKalman']) + 'driverMonitoringState', 'longitudinalPlan', 'lateralPlan', 'liveLocationKalman', + 'managerState'] + cameras) pm = messaging.PubMaster(['controlsState', 'pandaStates', 'deviceState']) @@ -44,30 +63,53 @@ def cycle_alerts(duration=200, is_metric=False): frame = 0 while True: - current_alert_types = [ET.PERMANENT, ET.USER_DISABLE, ET.IMMEDIATE_DISABLE, - ET.SOFT_DISABLE, ET.PRE_ENABLE, ET.NO_ENTRY, - ET.ENABLE, ET.WARNING] - for alert, et in alerts: events.clear() events.add(alert) - a = events.create_alerts([et, ], [CP, sm, is_metric, 0]) + sm['deviceState'].freeSpacePercent = randperc() + sm['deviceState'].memoryUsagePercent = int(randperc()) + sm['deviceState'].cpuTempC = [randperc() for _ in range(3)] + sm['deviceState'].gpuTempC = [randperc() for _ in range(3)] + sm['deviceState'].cpuUsagePercent = [int(randperc()) for _ in range(8)] + sm['modelV2'].frameDropPerc = randperc() + + if random.random() > 0.25: + sm['modelV2'].velocity.x = [random.random(), ] + if random.random() > 0.25: + CS.vEgo = random.random() + + procs = [p.get_process_state_msg() for p in managed_processes.values()] + random.shuffle(procs) + for i in range(random.randint(0, 10)): + procs[i].shouldBeRunning = True + sm['managerState'].processes = procs + + sm['liveCalibration'].rpyCalib = [-1 * random.random() for _ in range(random.randint(0, 3))] + + for s in sm.data.keys(): + prob = 0.3 if s in cameras else 0.08 + sm.alive[s] = random.random() > prob + sm.valid[s] = random.random() > prob + sm.freq_ok[s] = random.random() > prob + + a = events.create_alerts([et, ], [CP, CS, sm, is_metric, 0]) AM.add_many(frame, a) - AM.process_alerts(frame) - print(AM.alert) + alert = AM.process_alerts(frame, []) + print(alert) for _ in range(duration): dat = messaging.new_message() dat.init('controlsState') - dat.controlsState.enabled = True - - dat.controlsState.alertText1 = AM.alert_text_1 - dat.controlsState.alertText2 = AM.alert_text_2 - dat.controlsState.alertSize = AM.alert_size - dat.controlsState.alertStatus = AM.alert_status - dat.controlsState.alertBlinkingRate = AM.alert_rate - dat.controlsState.alertType = AM.alert_type - dat.controlsState.alertSound = AM.audible_alert + dat.controlsState.enabled = False + + if alert: + dat.controlsState.alertText1 = alert.alert_text_1 + dat.controlsState.alertText2 = alert.alert_text_2 + dat.controlsState.alertSize = alert.alert_size + dat.controlsState.alertStatus = alert.alert_status + dat.controlsState.alertBlinkingRate = alert.alert_rate + dat.controlsState.alertType = alert.alert_type + dat.controlsState.alertSound = alert.audible_alert pm.send('controlsState', dat) dat = messaging.new_message() diff --git a/selfdrive/debug/disable_ecu.py b/selfdrive/debug/disable_ecu.py deleted file mode 100644 index f0faf40017..0000000000 --- a/selfdrive/debug/disable_ecu.py +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env python3 -import traceback - -import cereal.messaging as messaging -from selfdrive.car.isotp_parallel_query import IsoTpParallelQuery -from selfdrive.swaglog import cloudlog - -EXT_DIAG_REQUEST = b'\x10\x03' -EXT_DIAG_RESPONSE = b'\x50\x03' -COM_CONT_REQUEST = b'\x28\x83\x03' -COM_CONT_RESPONSE = b'' - -def disable_ecu(ecu_addr, logcan, sendcan, bus, timeout=0.5, retry=5, debug=False): - print(f"ecu disable {hex(ecu_addr)} ...") - for i in range(retry): - try: - # enter extended diagnostic session - query = IsoTpParallelQuery(sendcan, logcan, bus, [ecu_addr], [EXT_DIAG_REQUEST], [EXT_DIAG_RESPONSE], debug=debug) - for addr, dat in query.get_data(timeout).items(): # pylint: disable=unused-variable - print("ecu communication control disable tx/rx ...") - # communication control disable tx and rx - query = IsoTpParallelQuery(sendcan, logcan, bus, [ecu_addr], [COM_CONT_REQUEST], [COM_CONT_RESPONSE], debug=debug) - query.get_data(0) - return True - print(f"ecu disable retry ({i+1}) ...") - except Exception: - cloudlog.warning(f"ecu disable exception: {traceback.format_exc()}") - - return False - - -if __name__ == "__main__": - import time - sendcan = messaging.pub_sock('sendcan') - logcan = messaging.sub_sock('can') - time.sleep(1) - - # honda bosch radar disable - disabled = disable_ecu(0x18DAB0F1, logcan, sendcan, 1, debug=False) - print(f"disabled: {disabled}") diff --git a/selfdrive/debug/dump.py b/selfdrive/debug/dump.py index f208920f12..fdb825eead 100755 --- a/selfdrive/debug/dump.py +++ b/selfdrive/debug/dump.py @@ -13,7 +13,7 @@ from cereal.services import service_list if __name__ == "__main__": - parser = argparse.ArgumentParser(description='Dump communcation sockets. See cereal/services.py for a complete list of available sockets.') + parser = argparse.ArgumentParser(description='Dump communication sockets. See cereal/services.py for a complete list of available sockets.') parser.add_argument('--pipe', action='store_true') parser.add_argument('--raw', action='store_true') parser.add_argument('--json', action='store_true') diff --git a/selfdrive/debug/dump_car_info.py b/selfdrive/debug/dump_car_info.py new file mode 100755 index 0000000000..c9a21c2848 --- /dev/null +++ b/selfdrive/debug/dump_car_info.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python3 +import argparse +import pickle + +from selfdrive.car.docs import get_all_car_info + + +def dump_car_info(path): + with open(path, 'wb') as f: + pickle.dump(get_all_car_info(), f) + print(f'Dumping car info to {path}') + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--path", required=True) + args = parser.parse_args() + dump_car_info(args.path) diff --git a/selfdrive/debug/filter_log_message.py b/selfdrive/debug/filter_log_message.py index 98e7d87246..af52953936 100755 --- a/selfdrive/debug/filter_log_message.py +++ b/selfdrive/debug/filter_log_message.py @@ -1,9 +1,10 @@ #!/usr/bin/env python3 +import os import argparse import json import cereal.messaging as messaging -from tools.lib.robust_logreader import RobustLogReader as LogReader +from tools.lib.logreader import LogReader from tools.lib.route import Route LEVELS = { @@ -46,7 +47,6 @@ def print_androidlog(t, msg): if __name__ == "__main__": - parser = argparse.ArgumentParser() parser.add_argument('--level', default='DEBUG') parser.add_argument('--addr', default='127.0.0.1') @@ -55,8 +55,11 @@ if __name__ == "__main__": logs = None if len(args.route): - r = Route(args.route[0]) - logs = r.log_paths() + if os.path.exists(args.route[0]): + logs = [args.route[0]] + else: + r = Route(args.route[0]) + logs = [q_log if r_log is None else r_log for (q_log, r_log) in zip(r.qlog_paths(), r.log_paths())] if len(args.route) == 2 and logs: n = int(args.route[1]) @@ -71,6 +74,8 @@ if __name__ == "__main__": for m in lr: if m.which() == 'logMessage': print_logmessage(m.logMonoTime, m.logMessage, min_level) + elif m.which() == 'errorLogMessage' and 'qlog' in log: + print_logmessage(m.logMonoTime, m.errorLogMessage, min_level) elif m.which() == 'androidLog': print_androidlog(m.logMonoTime, m.androidLog) else: diff --git a/selfdrive/debug/hyundai_enable_radar_points.py b/selfdrive/debug/hyundai_enable_radar_points.py index 8132a46552..ac7e7102d0 100755 --- a/selfdrive/debug/hyundai_enable_radar_points.py +++ b/selfdrive/debug/hyundai_enable_radar_points.py @@ -6,7 +6,7 @@ firmware versions. If you want to try on a new radar make sure to note the defau in case it's different from the other radars and you need to revert the changes. After changing the config the car should not show any faults when openpilot is not running. -These config changes are persistent accross car reboots. You need to run this script again +These config changes are persistent across car reboots. You need to run this script again to go back to the default values. USE AT YOUR OWN RISK! Safety features, like AEB and FCW, might be affected by these changes.""" @@ -74,7 +74,7 @@ if __name__ == "__main__": print("\nyou didn't type 'OK! (aborted)") sys.exit(0) - panda = Panda() # type: ignore + panda = Panda() panda.set_safety_mode(Panda.SAFETY_ELM327) uds_client = UdsClient(panda, 0x7D0, bus=args.bus, debug=args.debug) diff --git a/selfdrive/debug/internal/core_voltage_sweep.py b/selfdrive/debug/internal/core_voltage_sweep.py deleted file mode 100755 index c7c609560d..0000000000 --- a/selfdrive/debug/internal/core_voltage_sweep.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env python3 -import os -import sys -import time - -print("starting at") -os.system("cat /sys/kernel/debug/regulator/pm8994_s11/voltage") -print("volts") - -os.system("echo 99e8000.cpr3-ctrl > /sys/devices/soc/spm-regulator-10/regulator/regulator.56/99e8000.cpr3-ctrl-vdd/driver/unbind") -os.system("echo 1 > /sys/kernel/debug/regulator/pm8994_s11/enable") - -if len(sys.argv) > 1: - i = int(sys.argv[1]) - os.system("echo %d %d > /sys/kernel/debug/regulator/pm8994_s11/voltage" % (i,i)) - os.system("cat /sys/kernel/debug/regulator/pm8994_s11/voltage") -else: - for i in range(900000, 465000, -10000): - print("setting voltage to",i) - os.system("echo %d %d > /sys/kernel/debug/regulator/pm8994_s11/voltage" % (i,i)) - os.system("cat /sys/kernel/debug/regulator/pm8994_s11/voltage") - time.sleep(1) - diff --git a/selfdrive/debug/internal/measure_modeld_packet_drop.py b/selfdrive/debug/internal/measure_modeld_packet_drop.py index d5f65d06b1..6b7f7dbd13 100755 --- a/selfdrive/debug/internal/measure_modeld_packet_drop.py +++ b/selfdrive/debug/internal/measure_modeld_packet_drop.py @@ -1,11 +1,12 @@ #!/usr/bin/env python3 import cereal.messaging as messaging +from typing import Optional if __name__ == "__main__": modeld_sock = messaging.sub_sock("modelV2") last_frame_id = None - start_t = None + start_t: Optional[int] = None frame_cnt = 0 dropped = 0 diff --git a/selfdrive/debug/internal/measure_steering_accuracy.py b/selfdrive/debug/internal/measure_steering_accuracy.py deleted file mode 100755 index e06e43cdcf..0000000000 --- a/selfdrive/debug/internal/measure_steering_accuracy.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python3 -# type: ignore - -import os -import argparse -import signal -from collections import defaultdict - -import cereal.messaging as messaging - -def sigint_handler(signal, frame): - print("handler!") - exit(0) -signal.signal(signal.SIGINT, sigint_handler) - -if __name__ == "__main__": - - parser = argparse.ArgumentParser(description='Sniff a communication socket') - parser.add_argument('--addr', default='127.0.0.1') - args = parser.parse_args() - - if args.addr != "127.0.0.1": - os.environ["ZMQ"] = "1" - messaging.context = messaging.Context() - - carControl = messaging.sub_sock('carControl', addr=args.addr, conflate=True) - sm = messaging.SubMaster(['carState', 'carControl', 'controlsState'], addr=args.addr) - - msg_cnt = 0 - stats = defaultdict(lambda: {'err': 0, "cnt": 0, "=": 0, "+": 0, "-": 0}) - cnt = 0 - total_error = 0 - - while messaging.recv_one(carControl): - sm.update() - msg_cnt += 1 - - actual_speed = sm['carState'].vEgo - enabled = sm['controlsState'].enabled - steer_override = sm['controlsState'].steerOverride - - # must be above 10 m/s, engaged and not overriding steering - if actual_speed > 10.0 and enabled and not steer_override: - cnt += 1 - - # wait 5 seconds after engage/override - if cnt >= 500: - # calculate error before rounding - actual_angle = sm['controlsState'].angleSteers - desired_angle = sm['carControl'].actuators.steeringAngleDeg - angle_error = abs(desired_angle - actual_angle) - - # round numbers - actual_angle = round(actual_angle, 1) - desired_angle = round(desired_angle, 1) - angle_error = round(angle_error, 2) - angle_abs = int(abs(round(desired_angle, 0))) - - # collect stats - stats[angle_abs]["err"] += angle_error - stats[angle_abs]["cnt"] += 1 - if actual_angle == desired_angle: - stats[angle_abs]["="] += 1 - else: - if desired_angle == 0.: - overshoot = True - else: - overshoot = desired_angle < actual_angle if desired_angle > 0. else desired_angle > actual_angle - stats[angle_abs]["+" if overshoot else "-"] += 1 - else: - cnt = 0 - - if msg_cnt % 100 == 0: - print(chr(27) + "[2J") - if cnt != 0: - print("COLLECTING ...") - else: - print("DISABLED (speed too low, not engaged, or steer override)") - for k in sorted(stats.keys()): - v = stats[k] - print(f'angle: {k:#2} | error: {round(v["err"] / v["cnt"], 2):2.2f} | =:{int(v["="] / v["cnt"] * 100):#3}% | +:{int(v["+"] / v["cnt"] * 100):#4}% | -:{int(v["-"] / v["cnt"] * 100):#3}% | count: {v["cnt"]:#4}') diff --git a/selfdrive/debug/internal/power_monitor.py b/selfdrive/debug/internal/power_monitor.py index c995ef6ff2..34d2a12adc 100755 --- a/selfdrive/debug/internal/power_monitor.py +++ b/selfdrive/debug/internal/power_monitor.py @@ -10,6 +10,7 @@ def average(avg, sample): if __name__ == '__main__': + start_time = datetime.now() try: if len(sys.argv) > 1 and sys.argv[1] == "--charge": print("not disabling charging") @@ -22,7 +23,6 @@ if __name__ == '__main__': power_average = (0., 0) capacity_average = (0., 0) bat_temp_average = (0., 0) - start_time = datetime.now() while 1: with open("/sys/class/power_supply/bms/voltage_now") as f: voltage = int(f.read()) / 1e6 # volts @@ -59,6 +59,6 @@ if __name__ == '__main__': print(f" {(stop_time - start_time).total_seconds():.2f} Seconds {voltage_average[1]} samples") print("----------------------------------------------------------------") - # reenable charging + # re-enable charging os.system('echo "1" > /sys/class/power_supply/battery/charging_enabled') print("charging enabled\n") diff --git a/selfdrive/debug/internal/sensor_test_bootloop.py b/selfdrive/debug/internal/sensor_test_bootloop.py deleted file mode 100755 index 36eb112e44..0000000000 --- a/selfdrive/debug/internal/sensor_test_bootloop.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python3 -import sys -import os -import stat -import subprocess -import json -from common.text_window import TextWindow -import time - -# Required for sensord not to bus-error on startup -# commaai/cereal#22 -try: - os.mkdir("/dev/shm") -except FileExistsError: - pass -except PermissionError: - print("WARNING: failed to make /dev/shm") - -try: - with open('/tmp/sensor-test-results.json') as infile: - data = json.load(infile) -except Exception: - data = {'sensor-pass': 0, 'sensor-fail': 0} - -STARTUP_SCRIPT = "/data/data/com.termux/files/continue.sh" -try: - with open(STARTUP_SCRIPT, 'w') as startup_script: - startup_script.write("#!/usr/bin/bash\n\n/data/openpilot/selfdrive/debug/internal/sensor_test_bootloop.py\n") - os.chmod(STARTUP_SCRIPT, stat.S_IRWXU) -except Exception: - print("Failed to install new startup script -- aborting") - sys.exit(-1) - -sensord_env = {**os.environ, 'SENSOR_TEST': '1'} -process = subprocess.run("./sensord", cwd="/data/openpilot/selfdrive/sensord", env=sensord_env) # pylint: disable=subprocess-run-check - -if process.returncode == 40: - text = "Current run: SUCCESS\n" - data['sensor-pass'] += 1 -else: - text = "Current run: FAIL\n" - data['sensor-fail'] += 1 - - timestr = str(int(time.time())) - with open('/tmp/dmesg-' + timestr + '.log', 'w') as dmesg_out: - subprocess.call('dmesg', stdout=dmesg_out, shell=False) - with open("/tmp/logcat-" + timestr + '.log', 'w') as logcat_out: - subprocess.call(['logcat', '-d'], stdout=logcat_out, shell=False) - -text += "Sensor pass history: " + str(data['sensor-pass']) + "\n" -text += "Sensor fail history: " + str(data['sensor-fail']) + "\n" - -print(text) - -with open('/tmp/sensor-test-results.json', 'w') as outfile: - json.dump(data, outfile, indent=4) - -with TextWindow(text) as status: - for _ in range(100): - if status.get_status() == 1: - with open(STARTUP_SCRIPT, 'w') as startup_script: - startup_script.write("#!/usr/bin/bash\n\ncd /data/openpilot\nexec ./launch_openpilot.sh\n") - os.chmod(STARTUP_SCRIPT, stat.S_IRWXU) - break - time.sleep(0.1) - -subprocess.Popen("reboot") diff --git a/selfdrive/debug/live_cpu_and_temp.py b/selfdrive/debug/live_cpu_and_temp.py index e46c0b0a1f..c35afc474b 100755 --- a/selfdrive/debug/live_cpu_and_temp.py +++ b/selfdrive/debug/live_cpu_and_temp.py @@ -1,9 +1,11 @@ #!/usr/bin/env python3 import argparse +import capnp +from collections import defaultdict from cereal.messaging import SubMaster from common.numpy_fast import mean - +from typing import Optional, Dict def cputime_total(ct): return ct.user + ct.nice + ct.system + ct.idle + ct.iowait + ct.irq + ct.softirq @@ -40,8 +42,8 @@ if __name__ == "__main__": total_times = [0.]*8 busy_times = [0.]*8 - prev_proclog = None - prev_proclog_t = None + prev_proclog: Optional[capnp._DynamicStructReader] = None + prev_proclog_t: Optional[int] = None while True: sm.update() @@ -73,8 +75,8 @@ if __name__ == "__main__": print(f"CPU {100.0 * mean(cores):.2f}% - RAM: {last_mem:.2f}% - Temp {last_temp:.2f}C") - if args.cpu and prev_proclog is not None: - procs = {} + if args.cpu and prev_proclog is not None and prev_proclog_t is not None: + procs: Dict[str, float] = defaultdict(float) dt = (sm.logMonoTime['procLog'] - prev_proclog_t) / 1e9 for proc in m.procs: try: @@ -82,7 +84,7 @@ if __name__ == "__main__": prev_proc = [p for p in prev_proclog.procs if proc.pid == p.pid][0] cpu_time = proc_cputime_total(proc) - proc_cputime_total(prev_proc) cpu_usage = cpu_time / dt * 100. - procs[name] = cpu_usage + procs[name] += cpu_usage except IndexError: pass diff --git a/selfdrive/debug/print_docs_diff.py b/selfdrive/debug/print_docs_diff.py new file mode 100755 index 0000000000..b804286458 --- /dev/null +++ b/selfdrive/debug/print_docs_diff.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +import argparse +from collections import defaultdict +import difflib +import pickle + +from selfdrive.car.docs import get_all_car_info +from selfdrive.car.docs_definitions import Column + +FOOTNOTE_TAG = "{}" +STAR_ICON = '' +COLUMNS = "|" + "|".join([column.value for column in Column]) + "|" +COLUMN_HEADER = "|---|---|---|{}|".format("|".join([":---:"] * (len(Column) - 3))) +ARROW_SYMBOL = "➡️" + + +def load_base_car_info(path): + with open(path, "rb") as f: + return pickle.load(f) + + +def match_cars(base_cars, new_cars): + changes = [] + additions = [] + for new in new_cars: + # Addition if no close matches or close match already used + # Change if close match and not already used + matches = difflib.get_close_matches(new.name, [b.name for b in base_cars], cutoff=0.) + if not len(matches) or matches[0] in [c[1].name for c in changes]: + additions.append(new) + else: + changes.append((new, next(car for car in base_cars if car.name == matches[0]))) + + # Removal if base car not in changes + removals = [b for b in base_cars if b.name not in [c[1].name for c in changes]] + return changes, additions, removals + + +def build_column_diff(base_car, new_car): + row_builder = [] + for column in Column: + base_column = base_car.get_column(column, STAR_ICON, FOOTNOTE_TAG) + new_column = new_car.get_column(column, STAR_ICON, FOOTNOTE_TAG) + + if base_column != new_column: + row_builder.append(f"{base_column} {ARROW_SYMBOL} {new_column}") + else: + row_builder.append(new_column) + + return format_row(row_builder) + + +def format_row(builder): + return "|" + "|".join(builder) + "|" + + +def print_car_info_diff(path): + base_car_info = defaultdict(list) + new_car_info = defaultdict(list) + + for car in load_base_car_info(path): + base_car_info[car.car_fingerprint].append(car) + for car in get_all_car_info(): + new_car_info[car.car_fingerprint].append(car) + + # Add new platforms to base cars so we can detect additions and removals in one pass + base_car_info.update({car: [] for car in new_car_info if car not in base_car_info}) + + changes = defaultdict(list) + for base_car_model, base_cars in base_car_info.items(): + # Match car info changes, and get additions and removals + new_cars = new_car_info[base_car_model] + car_changes, car_additions, car_removals = match_cars(base_cars, new_cars) + + # Removals + for car_info in car_removals: + changes["removals"].append(format_row([car_info.get_column(column, STAR_ICON, FOOTNOTE_TAG) for column in Column])) + + # Additions + for car_info in car_additions: + changes["additions"].append(format_row([car_info.get_column(column, STAR_ICON, FOOTNOTE_TAG) for column in Column])) + + for new_car, base_car in car_changes: + # Column changes + row_diff = build_column_diff(base_car, new_car) + if ARROW_SYMBOL in row_diff: + changes["column"].append(row_diff) + + # Detail sentence changes + if base_car.detail_sentence != new_car.detail_sentence: + changes["detail"].append(f"- Sentence for {base_car.name} changed!\n" + + " ```diff\n" + + f" - {base_car.detail_sentence}\n" + + f" + {new_car.detail_sentence}\n" + + " ```") + + # Print diff + if any(len(c) for c in changes.values()): + markdown_builder = ["### ⚠️ This PR makes changes to [CARS.md](../blob/master/docs/CARS.md) ⚠️"] + + for title, category in (("## 🔀 Column Changes", "column"), ("## ❌ Removed", "removals"), ("## ➕ Added", "additions"), ("## 📖 Detail Sentence Changes", "detail")): + if len(changes[category]): + markdown_builder.append(title) + if category not in ("detail",): + markdown_builder.append(COLUMNS) + markdown_builder.append(COLUMN_HEADER) + markdown_builder.extend(changes[category]) + + print("\n".join(markdown_builder)) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--path", required=True) + args = parser.parse_args() + print_car_info_diff(args.path) diff --git a/selfdrive/debug/profiling/ftrace.sh b/selfdrive/debug/profiling/ftrace.sh new file mode 100755 index 0000000000..fe91a3c0d9 --- /dev/null +++ b/selfdrive/debug/profiling/ftrace.sh @@ -0,0 +1,23 @@ +#!/usr/bin/bash +set -e + +cd /sys/kernel/tracing + +echo 1 > tracing_on +echo boot > trace_clock +echo 1000 > buffer_size_kb + +# /sys/kernel/tracing/available_events +echo 1 > events/irq/enable +echo 1 > events/sched/enable +echo 1 > events/kgsl/enable +echo 1 > events/camera/enable +echo 1 > events/workqueue/enable + +echo > trace +sleep 5 +echo 0 > tracing_on + +cp trace /tmp/trace +chown comma: /tmp/trace +echo /tmp/trace diff --git a/selfdrive/debug/profiling/snapdragon/setup-agnos.sh b/selfdrive/debug/profiling/snapdragon/setup-agnos.sh index 5099fb09cb..f036ca2111 100755 --- a/selfdrive/debug/profiling/snapdragon/setup-agnos.sh +++ b/selfdrive/debug/profiling/snapdragon/setup-agnos.sh @@ -4,4 +4,4 @@ cd SnapdragonProfiler/service mv android real_android -ln -s iot_rb5_lu/ android +ln -s agl/ android diff --git a/selfdrive/debug/read_dtc_status.py b/selfdrive/debug/read_dtc_status.py new file mode 100755 index 0000000000..9ad5563975 --- /dev/null +++ b/selfdrive/debug/read_dtc_status.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +import sys +import argparse +from subprocess import check_output, CalledProcessError +from panda import Panda +from panda.python.uds import UdsClient, SESSION_TYPE, DTC_REPORT_TYPE, DTC_STATUS_MASK_TYPE +from panda.python.uds import get_dtc_num_as_str, get_dtc_status_names + +parser = argparse.ArgumentParser(description="read DTC status") +parser.add_argument("addr", type=lambda x: int(x,0)) +parser.add_argument("--bus", type=int, default=0) +parser.add_argument('--debug', action='store_true') +args = parser.parse_args() + +try: + check_output(["pidof", "boardd"]) + print("boardd is running, please kill openpilot before running this script! (aborted)") + sys.exit(1) +except CalledProcessError as e: + if e.returncode != 1: # 1 == no process found (boardd not running) + raise e + +panda = Panda() +panda.set_safety_mode(Panda.SAFETY_ELM327) +uds_client = UdsClient(panda, args.addr, bus=args.bus, debug=args.debug) +print("extended diagnostic session ...") +uds_client.diagnostic_session_control(SESSION_TYPE.EXTENDED_DIAGNOSTIC) +print("read diagnostic codes ...") +data = uds_client.read_dtc_information(DTC_REPORT_TYPE.DTC_BY_STATUS_MASK, DTC_STATUS_MASK_TYPE.ALL) +print("status availability:", " ".join(get_dtc_status_names(data[0]))) +print("DTC status:") +for i in range(1, len(data), 4): + dtc_num = get_dtc_num_as_str(data[i:i+3]) + dtc_status = " ".join(get_dtc_status_names(data[i+3])) + print(dtc_num, dtc_status) diff --git a/selfdrive/debug/run_process_on_route.py b/selfdrive/debug/run_process_on_route.py index a6e67d2b24..63b0733bba 100755 --- a/selfdrive/debug/run_process_on_route.py +++ b/selfdrive/debug/run_process_on_route.py @@ -25,7 +25,7 @@ if __name__ == "__main__": # Remove message generated by the process under test and merge in the new messages produces = {o.which() for o in outputs} inputs = [i for i in inputs if i.which() not in produces] - outputs = sorted(inputs + outputs, key=lambda x: x.logMonoTime) + outputs = sorted(inputs + outputs, key=lambda x: x.logMonoTime) # type: ignore fn = f"{args.route}_{args.process}.bz2" save_log(fn, outputs) diff --git a/selfdrive/debug/sensor_data_to_hist.py b/selfdrive/debug/sensor_data_to_hist.py new file mode 100755 index 0000000000..ceed4b0ec3 --- /dev/null +++ b/selfdrive/debug/sensor_data_to_hist.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +''' +printing the gap between interrupts in a histogram to check if the +frequency is what we expect, the bmx is not interrupt driven for as we +get interrupts in a 2kHz rate. +''' + +import argparse +import sys +import numpy as np +from collections import defaultdict + +from tools.lib.logreader import LogReader +from tools.lib.route import Route + +import matplotlib.pyplot as plt + +SRC_BMX = "bmx055" +SRC_LSM = "lsm6ds3" + + +def parseEvents(log_reader): + bmx_data = defaultdict(list) + lsm_data = defaultdict(list) + + for m in log_reader: + if m.which() not in ['accelerometer', 'gyroscope']: + continue + + d = getattr(m, m.which()).to_dict() + + if d["source"] == SRC_BMX and "acceleration" in d: + bmx_data["accel"].append(d["timestamp"] / 1e9) + + if d["source"] == SRC_BMX and "gyroUncalibrated" in d: + bmx_data["gyro"].append(d["timestamp"] / 1e9) + + if d["source"] == SRC_LSM and "acceleration" in d: + lsm_data["accel"].append(d["timestamp"] / 1e9) + + if d["source"] == SRC_LSM and "gyroUncalibrated" in d: + lsm_data["gyro"].append(d["timestamp"] / 1e9) + + return bmx_data, lsm_data + + +def cleanData(data): + if len(data) == 0: + return [], [] + + data.sort() + diffs = np.diff(data) + return data, diffs + + +def logAvgValues(data, sensor): + if len(data) == 0: + print(f"{sensor}: no data to average") + return + + avg = sum(data) / len(data) + hz = 1 / avg + print(f"{sensor}: data_points: {len(data)} avg [ns]: {avg} avg [Hz]: {hz}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("route", type=str, help="route name") + parser.add_argument("segment", type=int, help="segment number") + args = parser.parse_args() + + r = Route(args.route) + logs = r.log_paths() + + if len(logs) == 0: + print("NO data routes") + sys.exit(0) + + if args.segment >= len(logs): + print(f"RouteID: {args.segment} out of range, max: {len(logs) -1}") + sys.exit(0) + + lr = LogReader(logs[args.segment]) + bmx_data, lsm_data = parseEvents(lr) + + # sort bmx accel data, and then cal all the diffs, and to a histogram of those + bmx_accel, bmx_accel_diffs = cleanData(bmx_data["accel"]) + bmx_gyro, bmx_gyro_diffs = cleanData(bmx_data["gyro"]) + lsm_accel, lsm_accel_diffs = cleanData(lsm_data["accel"]) + lsm_gyro, lsm_gyro_diffs = cleanData(lsm_data["gyro"]) + + # get out the averages + logAvgValues(bmx_accel_diffs, "bmx accel") + logAvgValues(bmx_gyro_diffs, "bmx gyro ") + logAvgValues(lsm_accel_diffs, "lsm accel") + logAvgValues(lsm_gyro_diffs, "lsm gyro ") + + fig, axs = plt.subplots(1, 2, tight_layout=True) + axs[0].hist(bmx_accel_diffs, bins=50) + axs[0].set_title("bmx_accel") + axs[1].hist(bmx_gyro_diffs, bins=50) + axs[1].set_title("bmx_gyro") + + figl, axsl = plt.subplots(1, 2, tight_layout=True) + axsl[0].hist(lsm_accel_diffs, bins=50) + axsl[0].set_title("lsm_accel") + axsl[1].hist(lsm_gyro_diffs, bins=50) + axsl[1].set_title("lsm_gyro") + + print("check plot...") + plt.show() diff --git a/selfdrive/debug/set_car_params.py b/selfdrive/debug/set_car_params.py index bcdaed0778..24258db9f2 100755 --- a/selfdrive/debug/set_car_params.py +++ b/selfdrive/debug/set_car_params.py @@ -1,11 +1,22 @@ #!/usr/bin/env python3 import sys +from cereal import car from common.params import Params from tools.lib.route import Route from tools.lib.logreader import LogReader if __name__ == "__main__": - r = Route(sys.argv[1]) - cp = [m for m in LogReader(r.qlog_paths()[0]) if m.which() == 'carParams'] - Params().put("CarParams", cp[0].carParams.as_builder().to_bytes()) + CP = None + if len(sys.argv) > 1: + r = Route(sys.argv[1]) + cps = [m for m in LogReader(r.qlog_paths()[0]) if m.which() == 'carParams'] + CP = cps[0].carParams.as_builder() + else: + CP = car.CarParams.new_message() + CP.openpilotLongitudinalControl = True + CP.experimentalLongitudinalAvailable = False + + cp_bytes = CP.to_bytes() + for p in ("CarParams", "CarParamsCache", "CarParamsPersistent"): + Params().put(p, cp_bytes) diff --git a/selfdrive/debug/show_matching_cars.py b/selfdrive/debug/show_matching_cars.py index 79a23c1f82..d5199b2a9e 100755 --- a/selfdrive/debug/show_matching_cars.py +++ b/selfdrive/debug/show_matching_cars.py @@ -10,11 +10,11 @@ candidate_cars = all_legacy_fingerprint_cars() for addr, l in fingerprint.items(): - dat = messaging.new_message('can', 1) + dat = messaging.new_message('can', 1) - msg = dat.can[0] - msg.address = addr - msg.dat = " " * l + msg = dat.can[0] + msg.address = addr + msg.dat = " " * l - candidate_cars = eliminate_incompatible_cars(msg, candidate_cars) - print(candidate_cars) + candidate_cars = eliminate_incompatible_cars(msg, candidate_cars) + print(candidate_cars) diff --git a/selfdrive/debug/test_car_model.py b/selfdrive/debug/test_car_model.py new file mode 100755 index 0000000000..4de5b26762 --- /dev/null +++ b/selfdrive/debug/test_car_model.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +import argparse +import sys +from typing import List, Tuple +import unittest + +from selfdrive.car.tests.routes import CarTestRoute +from selfdrive.car.tests.test_models import TestCarModel + + +def create_test_models_suite(routes: List[Tuple[str, CarTestRoute]], ci=False) -> unittest.TestSuite: + test_suite = unittest.TestSuite() + for car_model, test_route in routes: + # create new test case and discover tests + test_case_args = {"car_model": car_model, "test_route": test_route, "ci": ci} + CarModelTestCase = type("CarModelTestCase", (TestCarModel,), test_case_args) + test_suite.addTest(unittest.TestLoader().loadTestsFromTestCase(CarModelTestCase)) + return test_suite + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Test any route against common issues with a new car port. " + + "Uses selfdrive/car/tests/test_models.py") + parser.add_argument("route", help="Specify route to run tests on") + parser.add_argument("--car", help="Specify car model for test route") + parser.add_argument("--segment", type=int, nargs="?", help="Specify segment of route to test") + parser.add_argument("--ci", action="store_true", help="Attempt to get logs using openpilotci, need to specify car") + args = parser.parse_args() + if len(sys.argv) == 1: + parser.print_help() + sys.exit() + + test_route = CarTestRoute(args.route, args.car, segment=args.segment) + test_suite = create_test_models_suite([(args.car, test_route)], ci=args.ci) + + unittest.TextTestRunner().run(test_suite) diff --git a/selfdrive/debug/test_fw_query_on_routes.py b/selfdrive/debug/test_fw_query_on_routes.py index 6b29ae820d..ba7d96dba0 100755 --- a/selfdrive/debug/test_fw_query_on_routes.py +++ b/selfdrive/debug/test_fw_query_on_routes.py @@ -8,23 +8,16 @@ import traceback from tqdm import tqdm from tools.lib.logreader import LogReader from tools.lib.route import Route +from selfdrive.car.interfaces import get_interface_attr from selfdrive.car.car_helpers import interface_names -from selfdrive.car.fw_versions import match_fw_to_car_exact, match_fw_to_car_fuzzy, build_fw_dict -from selfdrive.car.toyota.values import FW_VERSIONS as TOYOTA_FW_VERSIONS -from selfdrive.car.honda.values import FW_VERSIONS as HONDA_FW_VERSIONS -from selfdrive.car.hyundai.values import FW_VERSIONS as HYUNDAI_FW_VERSIONS -from selfdrive.car.volkswagen.values import FW_VERSIONS as VW_FW_VERSIONS -from selfdrive.car.mazda.values import FW_VERSIONS as MAZDA_FW_VERSIONS -from selfdrive.car.subaru.values import FW_VERSIONS as SUBARU_FW_VERSIONS +from selfdrive.car.fw_versions import match_fw_to_car NO_API = "NO_API" in os.environ -SUPPORTED_CARS = set(interface_names['toyota']) -SUPPORTED_CARS |= set(interface_names['honda']) -SUPPORTED_CARS |= set(interface_names['hyundai']) -SUPPORTED_CARS |= set(interface_names['volkswagen']) -SUPPORTED_CARS |= set(interface_names['mazda']) -SUPPORTED_CARS |= set(interface_names['subaru']) +VERSIONS = get_interface_attr('FW_VERSIONS', ignore_none=True) +SUPPORTED_BRANDS = VERSIONS.keys() +SUPPORTED_CARS = [brand for brand in SUPPORTED_BRANDS for brand in interface_names[brand]] +UNKNOWN_BRAND = "unknown" try: from xx.pipeline.c.CarState import migration @@ -63,7 +56,7 @@ if __name__ == "__main__": qlog_path = f"cd:/{dongle_id}/{time}/0/qlog.bz2" else: route = Route(route) - qlog_path = route.qlog_paths()[0] + qlog_path = next((p for p in route.qlog_paths() if p is not None), None) if qlog_path is None: continue @@ -72,30 +65,32 @@ if __name__ == "__main__": lr = LogReader(qlog_path) dongles.append(dongle_id) + CP = None for msg in lr: if msg.which() == "pandaStates": - if msg.pandaStates[0].pandaType not in ['uno', 'blackPanda', 'dos']: + if msg.pandaStates[0].pandaType in ('unknown', 'whitePanda', 'greyPanda', 'pedal'): + print("wrong panda type") break elif msg.which() == "carParams": - bts = msg.carParams.as_builder().to_bytes() - - car_fw = msg.carParams.carFw + CP = msg.carParams + car_fw = CP.carFw if len(car_fw) == 0: + print("no fw") break - live_fingerprint = msg.carParams.carFingerprint + live_fingerprint = CP.carFingerprint live_fingerprint = migration.get(live_fingerprint, live_fingerprint) if args.car is not None: live_fingerprint = args.car if live_fingerprint not in SUPPORTED_CARS: + print("not in supported cars") break - fw_versions_dict = build_fw_dict(car_fw) - exact_matches = match_fw_to_car_exact(fw_versions_dict) - fuzzy_matches = match_fw_to_car_fuzzy(fw_versions_dict) + _, exact_matches = match_fw_to_car(car_fw, allow_exact=True, allow_fuzzy=False) + _, fuzzy_matches = match_fw_to_car(car_fw, allow_exact=False, allow_fuzzy=True) if (len(exact_matches) == 1) and (list(exact_matches)[0] == live_fingerprint): good_exact += 1 @@ -112,22 +107,26 @@ if __name__ == "__main__": break print(f"{dongle_id}|{time}") - print("Old style:", live_fingerprint, "Vin", msg.carParams.carVin) + print("Old style:", live_fingerprint, "Vin", CP.carVin) print("New style (exact):", exact_matches) print("New style (fuzzy):", fuzzy_matches) - for version in car_fw: + padding = max([len(fw.brand or UNKNOWN_BRAND) for fw in car_fw]) + for version in sorted(car_fw, key=lambda fw: fw.brand): subaddr = None if version.subAddress == 0 else hex(version.subAddress) - print(f" (Ecu.{version.ecu}, {hex(version.address)}, {subaddr}): [{version.fwVersion}],") + print(f" Brand: {version.brand or UNKNOWN_BRAND:{padding}}, bus: {version.bus} - (Ecu.{version.ecu}, {hex(version.address)}, {subaddr}): [{version.fwVersion}],") print("Mismatches") found = False - for car_fws in [TOYOTA_FW_VERSIONS, HONDA_FW_VERSIONS, HYUNDAI_FW_VERSIONS, VW_FW_VERSIONS, MAZDA_FW_VERSIONS, SUBARU_FW_VERSIONS]: + for brand in SUPPORTED_BRANDS: + car_fws = VERSIONS[brand] if live_fingerprint in car_fws: found = True expected = car_fws[live_fingerprint] for (_, expected_addr, expected_sub_addr), v in expected.items(): for version in car_fw: + if version.brand != brand and len(version.brand): + continue sub_addr = None if version.subAddress == 0 else version.subAddress addr = version.address @@ -160,13 +159,16 @@ if __name__ == "__main__": print("Fuzzy match wrong! Fuzzy:", fuzzy_matches, "Live:", live_fingerprint) break + + if CP is None: + print("no CarParams in logs") except Exception: traceback.print_exc() except KeyboardInterrupt: break print() - # Print FW versions that need to be added seperated out by car and address + # Print FW versions that need to be added separated out by car and address for car, m in sorted(mismatches.items()): print(car) addrs = defaultdict(list) diff --git a/selfdrive/debug/uiview.py b/selfdrive/debug/uiview.py index 29465ecc8d..93d901f7c9 100755 --- a/selfdrive/debug/uiview.py +++ b/selfdrive/debug/uiview.py @@ -1,11 +1,15 @@ #!/usr/bin/env python3 import time -from cereal import messaging, log + +from cereal import car, log, messaging +from common.params import Params from selfdrive.manager.process_config import managed_processes if __name__ == "__main__": - procs = ['camerad', 'ui', 'modeld', 'calibrationd'] + CP = car.CarParams(notCar=True) + Params().put("CarParams", CP.to_bytes()) + procs = ['camerad', 'ui', 'modeld', 'calibrationd'] for p in procs: managed_processes[p].start() diff --git a/selfdrive/debug/vw_mqb_config.py b/selfdrive/debug/vw_mqb_config.py index 1dd28d371f..8c4dbc55ee 100755 --- a/selfdrive/debug/vw_mqb_config.py +++ b/selfdrive/debug/vw_mqb_config.py @@ -23,7 +23,7 @@ if __name__ == "__main__": desc_text = "Shows Volkswagen EPS software and coding info, and enables or disables Heading Control Assist " + \ "(Lane Assist). Useful for enabling HCA on cars without factory Lane Assist that want to use " + \ "openpilot integrated at the CAN gateway (J533)." - epilog_text = "This tool is meant to run directly on a vehicle-installed comma two or comma three, with the " + \ + epilog_text = "This tool is meant to run directly on a vehicle-installed comma three, with the " + \ "openpilot/tmux processes stopped. It should also work on a separate PC with a USB-attached comma " + \ "panda. Vehicle ignition must be on. Recommend engine not be running when making changes. Must " + \ "turn ignition off and on again for any changes to take effect." @@ -67,20 +67,30 @@ if __name__ == "__main__": print("Timeout fetching data from EPS") quit() - coding_variant, current_coding_array = None, None - # EV_SteerAssisMQB covers the majority of MQB racks (EPS_MQB_ZFLS) - # APA racks (MQB_PP_APA) have a different coding layout, which should - # be easy to support once we identify the specific config bit - if odx_file == "EV_SteerAssisMQB\x00": + coding_variant, current_coding_array, coding_byte, coding_bit = None, None, 0, 0 + coding_length = len(current_coding) + + # EV_SteerAssisMQB/MNB cover the majority of MQB racks (EPS_MQB_ZFLS) + if odx_file in ("EV_SteerAssisMQB\x00", "EV_SteerAssisMNB\x00"): coding_variant = "ZF" - current_coding_array = struct.unpack("!4B", current_coding) - hca_enabled = (current_coding_array[0] & (1 << 4) != 0) - hca_text = ("DISABLED", "ENABLED")[hca_enabled] - print(f" Lane Assist: {hca_text}") + coding_byte = 0 + coding_bit = 4 + + # APA racks (MQB_PP_APA) have a different coding layout + elif odx_file == "EV_SteerAssisVWBSMQBA\x00\x00\x00\x00": + coding_variant = "APA" + coding_byte = 3 + coding_bit = 0 + else: print("Configuration changes not yet supported on this EPS!") quit() + current_coding_array = struct.unpack(f"!{coding_length}B", current_coding) + hca_enabled = (current_coding_array[coding_byte] & (1 << coding_bit) != 0) + hca_text = ("DISABLED", "ENABLED")[hca_enabled] + print(f" Lane Assist: {hca_text}") + try: params = uds_client.read_data_by_identifier(DATA_IDENTIFIER_TYPE.APPLICATION_DATA_IDENTIFICATION).decode("utf-8") param_version_system_params = params[1:3] @@ -101,14 +111,14 @@ if __name__ == "__main__": if args.action in ["enable", "disable"]: print("\nAttempting configuration update") - assert(coding_variant == "ZF") # revisit when we have the APA rack coding bit + assert(coding_variant in ("ZF", "APA")) # ZF EPS config coding length can be anywhere from 1 to 4 bytes, but the # bit we care about is always in the same place in the first byte if args.action == "enable": - new_byte_0 = current_coding_array[0] | (1 << 4) + new_byte = current_coding_array[coding_byte] | (1 << coding_bit) else: - new_byte_0 = current_coding_array[0] & ~(1 << 4) - new_coding = new_byte_0.to_bytes(1, "little") + current_coding[1:] + new_byte = current_coding_array[coding_byte] & ~(1 << coding_bit) + new_coding = current_coding[0:coding_byte] + new_byte.to_bytes(1, "little") + current_coding[coding_byte+1:] try: seed = uds_client.security_access(ACCESS_TYPE_LEVEL_1.REQUEST_SEED) # type: ignore diff --git a/selfdrive/hardware b/selfdrive/hardware new file mode 120000 index 0000000000..02a42c502f --- /dev/null +++ b/selfdrive/hardware @@ -0,0 +1 @@ +../system/hardware/ \ No newline at end of file diff --git a/selfdrive/hardware/__init__.py b/selfdrive/hardware/__init__.py deleted file mode 100644 index 3babf1bb5d..0000000000 --- a/selfdrive/hardware/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -import os -from typing import cast - -from selfdrive.hardware.base import HardwareBase -from selfdrive.hardware.eon.hardware import Android -from selfdrive.hardware.tici.hardware import Tici -from selfdrive.hardware.pc.hardware import Pc - -EON = os.path.isfile('/EON') -TICI = os.path.isfile('/TICI') -PC = not (EON or TICI) - - -if EON: - HARDWARE = cast(HardwareBase, Android()) -elif TICI: - HARDWARE = cast(HardwareBase, Tici()) -else: - HARDWARE = cast(HardwareBase, Pc()) diff --git a/selfdrive/hardware/eon/androidd.py b/selfdrive/hardware/eon/androidd.py deleted file mode 100755 index 3d91468b90..0000000000 --- a/selfdrive/hardware/eon/androidd.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/env python3 -import os -import time -import psutil -from typing import Optional - -import cereal.messaging as messaging -from common.realtime import set_core_affinity, set_realtime_priority -from selfdrive.swaglog import cloudlog - - -MAX_MODEM_CRASHES = 3 -MODEM_PATH = "/sys/devices/soc/2080000.qcom,mss/subsys5" -WATCHED_PROCS = ["zygote", "zygote64", "system_server", "/system/bin/servicemanager", "/system/bin/surfaceflinger"] - - -def get_modem_crash_count() -> Optional[int]: - try: - with open(os.path.join(MODEM_PATH, "crash_count")) as f: - return int(f.read()) - except Exception: - cloudlog.exception("Error reading modem crash count") - return None - -def get_modem_state() -> str: - try: - with open(os.path.join(MODEM_PATH, "state")) as f: - return f.read().strip() - except Exception: - cloudlog.exception("Error reading modem state") - return "" - -def main(): - set_core_affinity(1) - set_realtime_priority(1) - - procs = {} - crash_count = 0 - modem_killed = False - modem_state = "ONLINE" - androidLog = messaging.sub_sock('androidLog') - - while True: - # check critical android services - if any(p is None or not p.is_running() for p in procs.values()) or not len(procs): - cur = {p: None for p in WATCHED_PROCS} - for p in psutil.process_iter(attrs=['cmdline']): - cmdline = None if not len(p.info['cmdline']) else p.info['cmdline'][0] - if cmdline in WATCHED_PROCS: - cur[cmdline] = p - - if len(procs): - for p in WATCHED_PROCS: - if cur[p] != procs[p]: - cloudlog.event("android service pid changed", proc=p, cur=cur[p], prev=procs[p], error=True) - procs.update(cur) - - # log caught NetworkPolicy exceptions - msgs = messaging.drain_sock(androidLog) - for m in msgs: - try: - if m.androidLog.tag == "NetworkPolicy" and m.androidLog.message.startswith("problem with advise persist threshold"): - cloudlog.event("network policy exception caught", androidLog=m.androidLog, error=True) - except UnicodeDecodeError: - pass - - if os.path.exists(MODEM_PATH): - # check modem state - state = get_modem_state() - if state != modem_state and not modem_killed: - cloudlog.event("modem state changed", state=state) - modem_state = state - - # check modem crashes - cnt = get_modem_crash_count() - if cnt is not None: - if cnt > crash_count: - cloudlog.event("modem crash", count=cnt) - crash_count = cnt - - # handle excessive modem crashes - if crash_count > MAX_MODEM_CRASHES and not modem_killed: - cloudlog.event("killing modem", error=True) - with open("/sys/kernel/debug/msm_subsys/modem", "w") as f: - f.write("put") - modem_killed = True - - time.sleep(1) - -if __name__ == "__main__": - main() diff --git a/selfdrive/hardware/eon/hardware.h b/selfdrive/hardware/eon/hardware.h deleted file mode 100644 index bcd1aaba74..0000000000 --- a/selfdrive/hardware/eon/hardware.h +++ /dev/null @@ -1,73 +0,0 @@ -#pragma once - -#include -#include - -#include -#include -#include - -#include "selfdrive/common/util.h" -#include "selfdrive/hardware/base.h" - -class HardwareEon : public HardwareNone { -public: - static constexpr float MAX_VOLUME = 1.0; - static constexpr float MIN_VOLUME = 0.5; - - static bool EON() { return true; } - static std::string get_os_version() { - return "NEOS " + util::read_file("/VERSION"); - }; - - static void reboot() { std::system("reboot"); }; - static void poweroff() { std::system("LD_LIBRARY_PATH= svc power shutdown"); }; - static void set_brightness(int percent) { - std::ofstream brightness_control("/sys/class/leds/lcd-backlight/brightness"); - if (brightness_control.is_open()) { - brightness_control << (int)(percent * (255/100.)) << "\n"; - brightness_control.close(); - } - }; - static void set_display_power(bool on) { - auto dtoken = android::SurfaceComposerClient::getBuiltInDisplay(android::ISurfaceComposer::eDisplayIdMain); - android::SurfaceComposerClient::setDisplayPowerMode(dtoken, on ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF); - }; - - static bool get_ssh_enabled() { - return std::system("getprop persist.neos.ssh | grep -qF '1'") == 0; - }; - static void set_ssh_enabled(bool enabled) { - std::string cmd = util::string_format("setprop persist.neos.ssh %d", enabled ? 1 : 0); - std::system(cmd.c_str()); - }; - - // android only - inline static bool launched_activity = false; - static void check_activity() { - int ret = std::system("dumpsys SurfaceFlinger --list | grep -Fq 'com.android.settings'"); - launched_activity = ret == 0; - } - - static void close_activities() { - if(launched_activity) { - std::system("pm disable com.android.settings && pm enable com.android.settings"); - } - } - - static void launch_activity(std::string activity, std::string opts = "") { - if (!launched_activity) { - std::string cmd = "am start -n " + activity + " " + opts + - " --ez extra_prefs_show_button_bar true \ - --es extra_prefs_set_next_text ''"; - std::system(cmd.c_str()); - } - launched_activity = true; - } - static void launch_wifi() { - launch_activity("com.android.settings/.wifi.WifiPickerActivity", "-a android.net.wifi.PICK_WIFI_NETWORK"); - } - static void launch_tethering() { - launch_activity("com.android.settings/.TetherSettings"); - } -}; diff --git a/selfdrive/hardware/eon/hardware.py b/selfdrive/hardware/eon/hardware.py deleted file mode 100644 index 4ab9f81fcf..0000000000 --- a/selfdrive/hardware/eon/hardware.py +++ /dev/null @@ -1,421 +0,0 @@ -import binascii -import itertools -import os -import re -import serial -import struct -import subprocess -from typing import List, Union - -from cereal import log -from selfdrive.hardware.base import HardwareBase, ThermalConfig - -try: - from common.params import Params -except Exception: - # openpilot is not built yet - Params = None - -NetworkType = log.DeviceState.NetworkType -NetworkStrength = log.DeviceState.NetworkStrength - -MODEM_PATH = "/dev/smd11" - -def service_call(call: List[str]) -> Union[bytes, None]: - try: - ret = subprocess.check_output(["service", "call", *call], encoding='utf8').strip() - if 'Parcel' not in ret: - return None - return parse_service_call_bytes(ret) - except subprocess.CalledProcessError: - return None - - -def parse_service_call_unpack(r, fmt) -> Union[bytes, None]: - try: - return struct.unpack(fmt, r)[0] - except Exception: - return None - - -def parse_service_call_string(r: bytes) -> Union[str, None]: - try: - r = r[8:] # Cut off length field - r_str = r.decode('utf_16_be') - - # All pairs of two characters seem to be swapped. Not sure why - result = "" - for a, b, in itertools.zip_longest(r_str[::2], r_str[1::2], fillvalue='\x00'): - result += b + a - - return result.replace('\x00', '') - except Exception: - return None - - -def parse_service_call_bytes(ret: str) -> Union[bytes, None]: - try: - r = b"" - for hex_part in re.findall(r'[ (]([0-9a-f]{8})', ret): - r += binascii.unhexlify(hex_part) - return r - except Exception: - return None - - -def getprop(key: str) -> Union[str, None]: - try: - return subprocess.check_output(["getprop", key], encoding='utf8').strip() - except subprocess.CalledProcessError: - return None - - -class Android(HardwareBase): - def get_os_version(self): - with open("/VERSION") as f: - return f.read().strip() - - def get_device_type(self): - try: - if int(Params().get("LastPeripheralPandaType")) == log.PandaState.PandaType.uno: - return "two" - except Exception: - pass - return "eon" - - def get_sound_card_online(self): - return (os.path.isfile('/proc/asound/card0/state') and - open('/proc/asound/card0/state').read().strip() == 'ONLINE') - - def get_imei(self, slot): - slot = str(slot) - if slot not in ("0", "1"): - raise ValueError("SIM slot must be 0 or 1") - - return parse_service_call_string(service_call(["iphonesubinfo", "3", "i32", str(slot)])) - - def get_serial(self): - ret = getprop("ro.serialno") - if len(ret) == 0: - ret = "cccccccc" - return ret - - def get_subscriber_info(self): - ret = parse_service_call_string(service_call(["iphonesubinfo", "7"])) - if ret is None or len(ret) < 8: - return "" - return ret - - def reboot(self, reason=None): - # e.g. reason="recovery" to go into recover mode - if reason is None: - reason_args = ["null"] - else: - reason_args = ["s16", reason] - - subprocess.check_output([ - "service", "call", "power", "16", # IPowerManager.reboot - "i32", "0", # no confirmation, - *reason_args, - "i32", "1" # wait - ]) - - def uninstall(self): - with open('/cache/recovery/command', 'w') as f: - f.write('--wipe_data\n') - # IPowerManager.reboot(confirm=false, reason="recovery", wait=true) - self.reboot(reason="recovery") - - def get_sim_info(self): - # Used for athena - # TODO: build using methods from this class - sim_state = getprop("gsm.sim.state").split(",") - network_type = getprop("gsm.network.type").split(',') - mcc_mnc = getprop("gsm.sim.operator.numeric") or None - - sim_id = parse_service_call_string(service_call(['iphonesubinfo', '11'])) - cell_data_state = parse_service_call_unpack(service_call(['phone', '46']), ">q") - cell_data_connected = (cell_data_state == 2) - - return { - 'sim_id': sim_id, - 'mcc_mnc': mcc_mnc, - 'network_type': network_type, - 'sim_state': sim_state, - 'data_connected': cell_data_connected - } - - def get_network_info(self): - msg = log.DeviceState.NetworkInfo.new_message() - msg.state = getprop("gsm.sim.state") or "" - msg.technology = getprop("gsm.network.type") or "" - msg.operator = getprop("gsm.sim.operator.numeric") or "" - - try: - modem = serial.Serial(MODEM_PATH, 115200, timeout=0.1) - modem.write(b"AT$QCRSRP?\r") - msg.extra = modem.read_until(b"OK\r\n").decode('utf-8') - - rsrp = msg.extra.split("$QCRSRP: ")[1].split("\r")[0].split(",") - msg.channel = int(rsrp[1]) - except Exception: - pass - - return msg - - def get_network_type(self): - wifi_check = parse_service_call_string(service_call(["connectivity", "2"])) - if wifi_check is None: - return NetworkType.none - elif 'WIFI' in wifi_check: - return NetworkType.wifi - else: - cell_check = parse_service_call_unpack(service_call(['phone', '59']), ">q") - # from TelephonyManager.java - cell_networks = { - 0: NetworkType.none, - 1: NetworkType.cell2G, - 2: NetworkType.cell2G, - 3: NetworkType.cell3G, - 4: NetworkType.cell2G, - 5: NetworkType.cell3G, - 6: NetworkType.cell3G, - 7: NetworkType.cell3G, - 8: NetworkType.cell3G, - 9: NetworkType.cell3G, - 10: NetworkType.cell3G, - 11: NetworkType.cell2G, - 12: NetworkType.cell3G, - 13: NetworkType.cell4G, - 14: NetworkType.cell4G, - 15: NetworkType.cell3G, - 16: NetworkType.cell2G, - 17: NetworkType.cell3G, - 18: NetworkType.cell4G, - 19: NetworkType.cell4G - } - return cell_networks.get(cell_check, NetworkType.none) - - def get_network_strength(self, network_type): - network_strength = NetworkStrength.unknown - - # from SignalStrength.java - def get_lte_level(rsrp, rssnr): - INT_MAX = 2147483647 - if rsrp == INT_MAX: - lvl_rsrp = NetworkStrength.unknown - elif rsrp >= -95: - lvl_rsrp = NetworkStrength.great - elif rsrp >= -105: - lvl_rsrp = NetworkStrength.good - elif rsrp >= -115: - lvl_rsrp = NetworkStrength.moderate - else: - lvl_rsrp = NetworkStrength.poor - if rssnr == INT_MAX: - lvl_rssnr = NetworkStrength.unknown - elif rssnr >= 45: - lvl_rssnr = NetworkStrength.great - elif rssnr >= 10: - lvl_rssnr = NetworkStrength.good - elif rssnr >= -30: - lvl_rssnr = NetworkStrength.moderate - else: - lvl_rssnr = NetworkStrength.poor - return max(lvl_rsrp, lvl_rssnr) - - def get_tdscdma_level(tdscmadbm): - lvl = NetworkStrength.unknown - if tdscmadbm > -25: - lvl = NetworkStrength.unknown - elif tdscmadbm >= -49: - lvl = NetworkStrength.great - elif tdscmadbm >= -73: - lvl = NetworkStrength.good - elif tdscmadbm >= -97: - lvl = NetworkStrength.moderate - elif tdscmadbm >= -110: - lvl = NetworkStrength.poor - return lvl - - def get_gsm_level(asu): - if asu <= 2 or asu == 99: - lvl = NetworkStrength.unknown - elif asu >= 12: - lvl = NetworkStrength.great - elif asu >= 8: - lvl = NetworkStrength.good - elif asu >= 5: - lvl = NetworkStrength.moderate - else: - lvl = NetworkStrength.poor - return lvl - - def get_evdo_level(evdodbm, evdosnr): - lvl_evdodbm = NetworkStrength.unknown - lvl_evdosnr = NetworkStrength.unknown - if evdodbm >= -65: - lvl_evdodbm = NetworkStrength.great - elif evdodbm >= -75: - lvl_evdodbm = NetworkStrength.good - elif evdodbm >= -90: - lvl_evdodbm = NetworkStrength.moderate - elif evdodbm >= -105: - lvl_evdodbm = NetworkStrength.poor - if evdosnr >= 7: - lvl_evdosnr = NetworkStrength.great - elif evdosnr >= 5: - lvl_evdosnr = NetworkStrength.good - elif evdosnr >= 3: - lvl_evdosnr = NetworkStrength.moderate - elif evdosnr >= 1: - lvl_evdosnr = NetworkStrength.poor - return max(lvl_evdodbm, lvl_evdosnr) - - def get_cdma_level(cdmadbm, cdmaecio): - lvl_cdmadbm = NetworkStrength.unknown - lvl_cdmaecio = NetworkStrength.unknown - if cdmadbm >= -75: - lvl_cdmadbm = NetworkStrength.great - elif cdmadbm >= -85: - lvl_cdmadbm = NetworkStrength.good - elif cdmadbm >= -95: - lvl_cdmadbm = NetworkStrength.moderate - elif cdmadbm >= -100: - lvl_cdmadbm = NetworkStrength.poor - if cdmaecio >= -90: - lvl_cdmaecio = NetworkStrength.great - elif cdmaecio >= -110: - lvl_cdmaecio = NetworkStrength.good - elif cdmaecio >= -130: - lvl_cdmaecio = NetworkStrength.moderate - elif cdmaecio >= -150: - lvl_cdmaecio = NetworkStrength.poor - return max(lvl_cdmadbm, lvl_cdmaecio) - - if network_type == NetworkType.none: - return network_strength - if network_type == NetworkType.wifi: - out = subprocess.check_output('dumpsys connectivity', shell=True).decode('utf-8') - network_strength = NetworkStrength.unknown - for line in out.split('\n'): - signal_str = "SignalStrength: " - if signal_str in line: - lvl_idx_start = line.find(signal_str) + len(signal_str) - lvl_idx_end = line.find(']', lvl_idx_start) - lvl = int(line[lvl_idx_start : lvl_idx_end]) - if lvl >= -50: - network_strength = NetworkStrength.great - elif lvl >= -60: - network_strength = NetworkStrength.good - elif lvl >= -70: - network_strength = NetworkStrength.moderate - else: - network_strength = NetworkStrength.poor - return network_strength - else: - # check cell strength - out = subprocess.check_output('dumpsys telephony.registry', shell=True).decode('utf-8') - for line in out.split('\n'): - if "mSignalStrength" in line: - arr = line.split(' ') - ns = 0 - if ("gsm" in arr[14]): - rsrp = int(arr[9]) - rssnr = int(arr[11]) - ns = get_lte_level(rsrp, rssnr) - if ns == NetworkStrength.unknown: - tdscmadbm = int(arr[13]) - ns = get_tdscdma_level(tdscmadbm) - if ns == NetworkStrength.unknown: - asu = int(arr[1]) - ns = get_gsm_level(asu) - else: - cdmadbm = int(arr[3]) - cdmaecio = int(arr[4]) - evdodbm = int(arr[5]) - evdosnr = int(arr[7]) - lvl_cdma = get_cdma_level(cdmadbm, cdmaecio) - lvl_edmo = get_evdo_level(evdodbm, evdosnr) - if lvl_edmo == NetworkStrength.unknown: - ns = lvl_cdma - elif lvl_cdma == NetworkStrength.unknown: - ns = lvl_edmo - else: - ns = min(lvl_cdma, lvl_edmo) - network_strength = max(network_strength, ns) - - return network_strength - - def get_battery_capacity(self): - return self.read_param_file("/sys/class/power_supply/battery/capacity", int, 100) - - def get_battery_status(self): - # This does not correspond with actual charging or not. - # If a USB cable is plugged in, it responds with 'Charging', even when charging is disabled - return self.read_param_file("/sys/class/power_supply/battery/status", lambda x: x.strip(), '') - - def get_battery_current(self): - return self.read_param_file("/sys/class/power_supply/battery/current_now", int) - - def get_battery_voltage(self): - return self.read_param_file("/sys/class/power_supply/battery/voltage_now", int) - - def get_battery_charging(self): - # This does correspond with actually charging - return self.read_param_file("/sys/class/power_supply/battery/charge_type", lambda x: x.strip() != "N/A", True) - - def set_battery_charging(self, on): - with open('/sys/class/power_supply/battery/charging_enabled', 'w') as f: - f.write(f"{1 if on else 0}\n") - - def get_usb_present(self): - return self.read_param_file("/sys/class/power_supply/usb/present", lambda x: bool(int(x)), False) - - def get_current_power_draw(self): - # We don't have a good direct way to measure this on android - return None - - def shutdown(self): - os.system('LD_LIBRARY_PATH="" svc power shutdown') - - def get_thermal_config(self): - return ThermalConfig(cpu=((5, 7, 10, 12), 10), gpu=((16,), 10), mem=(2, 10), bat=(29, 1000), ambient=(25, 1), pmic=((22,), 1000)) - - def set_screen_brightness(self, percentage): - with open("/sys/class/leds/lcd-backlight/brightness", "w") as f: - f.write(str(int(percentage * 2.55))) - - def get_screen_brightness(self): - try: - with open("/sys/class/leds/lcd-backlight/brightness") as f: - return int(float(f.read()) / 2.55) - except Exception: - return 0 - - def set_power_save(self, powersave_enabled): - pass - - def get_gpu_usage_percent(self): - try: - used, total = open('/sys/devices/soc/b00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/gpubusy').read().strip().split() - perc = 100.0 * int(used) / int(total) - return min(max(perc, 0), 100) - except Exception: - return 0 - - def get_modem_version(self): - return None - - def get_modem_temperatures(self): - # Not sure if we can get this on the LeEco - return [] - - def get_nvme_temperatures(self): - return [] - - def initialize_hardware(self): - pass - - def get_networks(self): - return None diff --git a/selfdrive/hardware/eon/neos.json b/selfdrive/hardware/eon/neos.json deleted file mode 100644 index 4010f7126a..0000000000 --- a/selfdrive/hardware/eon/neos.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "ota_url": "https://commadist.azureedge.net/neosupdate/ota-signed-50da8800caa5cbc224acbaa21f3a83d21802a31d89cccfc62a898903a8eb19e7.zip", - "ota_hash": "50da8800caa5cbc224acbaa21f3a83d21802a31d89cccfc62a898903a8eb19e7", - "recovery_url": "https://commadist.azureedge.net/neosupdate/recovery-fe76739438d28ea6111853a737b616afdf340ba75c01c0ee99e6a28c19ecc29f.img", - "recovery_len": 15222060, - "recovery_hash": "fe76739438d28ea6111853a737b616afdf340ba75c01c0ee99e6a28c19ecc29f" -} diff --git a/selfdrive/hardware/eon/neos.py b/selfdrive/hardware/eon/neos.py deleted file mode 100755 index 6f290fbcd1..0000000000 --- a/selfdrive/hardware/eon/neos.py +++ /dev/null @@ -1,130 +0,0 @@ -#!/usr/bin/env python3 -import argparse -import hashlib -import json -import logging -import os -import requests - -NEOSUPDATE_DIR = "/data/neoupdate" - -RECOVERY_DEV = "/dev/block/bootdevice/by-name/recovery" -RECOVERY_COMMAND = "/cache/recovery/command" - - -def get_fn(url: str): - return os.path.join(NEOSUPDATE_DIR, os.path.basename(url)) - - -def download_file(url: str, fn: str, sha256: str, display_name: str, cloudlog=logging) -> None: - # check if already downloaded - if check_hash(fn, sha256): - cloudlog.info(f"{display_name} already cached") - return - - try: - with open(fn, "ab+") as f: - headers = {"Range": f"bytes={f.tell()}-"} - r = requests.get(url, stream=True, allow_redirects=True, headers=headers) - r.raise_for_status() - - total = int(r.headers['Content-Length']) - if 'Content-Range' in r.headers: - total = int(r.headers['Content-Range'].split('/')[-1]) - - for chunk in r.iter_content(chunk_size=1024 * 1024): - f.write(chunk) - print(f"Downloading {display_name}: {f.tell() / total * 100}", flush=True) - except Exception: - cloudlog.error("download error") - if os.path.isfile(fn): - os.unlink(fn) - raise - - if not check_hash(fn, sha256): - if os.path.isfile(fn): - os.unlink(fn) - raise Exception("downloaded update failed hash check") - - -def check_hash(fn: str, sha256: str, length: int = -1) -> bool: - if not os.path.exists(fn): - return False - - h = hashlib.sha256() - with open(fn, "rb") as f: - while f.tell() != length: - r = min(max(0, length - f.tell()), 1024 * 1024) if length > 0 else 1024 * 1024 - dat = f.read(r) - if not dat: - break - h.update(dat) - return h.hexdigest().lower() == sha256.lower() - - -def flash_update(update_fn: str, out_path: str) -> None: - with open(update_fn, "rb") as update, open(out_path, "w+b") as out: - while True: - dat = update.read(8192) - if len(dat) == 0: - break - out.write(dat) - - -def download_neos_update(manifest_path: str, cloudlog=logging) -> None: - with open(manifest_path) as f: - m = json.load(f) - - os.makedirs(NEOSUPDATE_DIR, exist_ok=True) - - # handle recovery updates - if not check_hash(RECOVERY_DEV, m['recovery_hash'], m['recovery_len']): - cloudlog.info("recovery needs update") - recovery_fn = os.path.join(NEOSUPDATE_DIR, os.path.basename(m['recovery_url'])) - download_file(m['recovery_url'], recovery_fn, m['recovery_hash'], "recovery", cloudlog) - - flash_update(recovery_fn, RECOVERY_DEV) - assert check_hash(RECOVERY_DEV, m['recovery_hash'], m['recovery_len']), "recovery flash corrupted" - cloudlog.info("recovery successfully flashed") - - # download OTA update - download_file(m['ota_url'], get_fn(m['ota_url']), m['ota_hash'], "system", cloudlog) - - -def verify_update_ready(manifest_path: str) -> bool: - with open(manifest_path) as f: - m = json.load(f) - - ota_downloaded = check_hash(get_fn(m['ota_url']), m['ota_hash']) - recovery_flashed = check_hash(RECOVERY_DEV, m['recovery_hash'], m['recovery_len']) - return ota_downloaded and recovery_flashed - - -def perform_ota_update(manifest_path: str) -> None: - with open(manifest_path) as f: - m = json.load(f) - - # reboot into recovery - ota_fn = get_fn(m['ota_url']) - with open(RECOVERY_COMMAND, "w") as rf: - rf.write(f"--update_package={ota_fn}\n") - os.system("service call power 16 i32 0 s16 recovery i32 1") - - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description="NEOS update utility", - formatter_class=argparse.ArgumentDefaultsHelpFormatter) - parser.add_argument("--swap", action="store_true", help="Peform update after downloading") - parser.add_argument("--swap-if-ready", action="store_true", help="Perform update if already downloaded") - parser.add_argument("manifest", help="Manifest json") - args = parser.parse_args() - - logging.basicConfig(level=logging.INFO) - - if args.swap_if_ready: - if verify_update_ready(args.manifest): - perform_ota_update(args.manifest) - else: - download_neos_update(args.manifest, logging) - if args.swap: - perform_ota_update(args.manifest) diff --git a/selfdrive/hardware/eon/shutdownd.py b/selfdrive/hardware/eon/shutdownd.py deleted file mode 100755 index 15112e7d5e..0000000000 --- a/selfdrive/hardware/eon/shutdownd.py +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env python3 -import os -import time -import datetime - -from common.params import Params -from selfdrive.hardware.eon.hardware import getprop -from selfdrive.swaglog import cloudlog - -def main(): - prev = b"" - params = Params() - while True: - with open("/dev/__properties__", 'rb') as f: - cur = f.read() - - if cur != prev: - prev = cur - - # 0 for shutdown, 1 for reboot - prop = getprop("sys.shutdown.requested") - if prop is not None and len(prop) > 0: - os.system("pkill -9 loggerd") - params.put("LastSystemShutdown", f"'{prop}' {datetime.datetime.now()}") - os.sync() - - time.sleep(120) - cloudlog.error('shutdown false positive') - break - - time.sleep(0.1) - -if __name__ == "__main__": - main() diff --git a/selfdrive/hardware/eon/test_neos_updater.py b/selfdrive/hardware/eon/test_neos_updater.py deleted file mode 100755 index e258f943d2..0000000000 --- a/selfdrive/hardware/eon/test_neos_updater.py +++ /dev/null @@ -1,145 +0,0 @@ -#!/usr/bin/env python3 -import hashlib -import http.server -import json -import os -import unittest -import random -import requests -import shutil -import socketserver -import tempfile -import multiprocessing -from pathlib import Path - -from selfdrive.hardware.eon.neos import RECOVERY_DEV, NEOSUPDATE_DIR, get_fn, download_file, \ - verify_update_ready, download_neos_update - -EON_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__))) -MANIFEST = os.path.join(EON_DIR, "neos.json") - -PORT = 8000 - -def server_thread(port): - socketserver.TCPServer.allow_reuse_address = True - httpd = socketserver.TCPServer(("", port), http.server.SimpleHTTPRequestHandler) - httpd.serve_forever() - - -class TestNeosUpdater(unittest.TestCase): - - @classmethod - def setUpClass(cls): - # generate a fake manifest - cls.manifest = {} - for i in ('ota', 'recovery'): - with tempfile.NamedTemporaryFile(delete=False, dir=os.getcwd()) as f: - dat = os.urandom(random.randint(1000, 100000)) - f.write(dat) - cls.manifest[f"{i}_url"] = f"http://localhost:{PORT}/" + os.path.relpath(f.name) - cls.manifest[F"{i}_hash"] = hashlib.sha256(dat).hexdigest() - if i == "recovery": - cls.manifest["recovery_len"] = len(dat) - - with tempfile.NamedTemporaryFile(delete=False, mode='w') as f: - f.write(json.dumps(cls.manifest)) - cls.fake_manifest = f.name - - @classmethod - def tearDownClass(cls): - os.unlink(cls.fake_manifest) - os.unlink(os.path.basename(cls.manifest['ota_url'])) - os.unlink(os.path.basename(cls.manifest['recovery_url'])) - - def setUp(self): - # server for update files - self.server = multiprocessing.Process(target=server_thread, args=(PORT, )) - self.server.start() - - # clean up - if os.path.exists(NEOSUPDATE_DIR): - shutil.rmtree(NEOSUPDATE_DIR) - - def tearDown(self): - self.server.kill() - self.server.join(1) - - def _corrupt_recovery(self): - with open(RECOVERY_DEV, "wb") as f: - f.write(b'\x00'*100) - - def test_manifest(self): - with open(MANIFEST) as f: - m = json.load(f) - - assert m['ota_hash'] in m['ota_url'] - assert m['recovery_hash'] in m['recovery_url'] - assert m['recovery_len'] > 0 - - for url in (m['ota_url'], m['recovery_url']): - r = requests.head(m['recovery_url']) - r.raise_for_status() - self.assertEqual(r.headers['Content-Type'], "application/octet-stream") - if url == m['recovery_url']: - self.assertEqual(int(r.headers['Content-Length']), m['recovery_len']) - - def test_download_hash_check(self): - os.makedirs(NEOSUPDATE_DIR, exist_ok=True) - Path(get_fn(self.manifest['ota_url'])).touch() - with self.assertRaisesRegex(Exception, "failed hash check"): - download_file(self.manifest['ota_url'], get_fn(self.manifest['ota_url']), - self.manifest['ota_hash']+'a', "system") - - # should've unlinked after the failed hash check, should succeed now - download_file(self.manifest['ota_url'], get_fn(self.manifest['ota_url']), - self.manifest['ota_hash'], "system") - - # TODO: needs an http server that supports Content-Range - #def test_download_resume(self): - # os.makedirs(NEOSUPDATE_DIR, exist_ok=True) - # with open(os.path.basename(self.manifest['ota_url']), "rb") as src, \ - # open(get_fn(self.manifest['ota_url']), "wb") as dest: - # l = dest.write(src.read(8192)) - # assert l == 8192 - # download_file(self.manifest['ota_url'], get_fn(self.manifest['ota_url']), - # self.manifest['ota_hash'], "system") - - def test_download_no_internet(self): - self.server.kill() - os.makedirs(NEOSUPDATE_DIR, exist_ok=True) - # fail, no internet - with self.assertRaises(requests.exceptions.ConnectionError): - download_file(self.manifest['ota_url'], get_fn(self.manifest['ota_url']), - self.manifest['ota_hash'], "system") - - # already cached, ensure we don't hit the server - shutil.copyfile(os.path.basename(self.manifest['ota_url']), get_fn(self.manifest['ota_url'])) - download_file(self.manifest['ota_url'], get_fn(self.manifest['ota_url']), - self.manifest['ota_hash'], "system") - - - def test_download_update(self): - download_neos_update(self.fake_manifest) - self.assertTrue(verify_update_ready(self.fake_manifest)) - - def test_verify_update(self): - # good state - download_neos_update(self.fake_manifest) - self.assertTrue(verify_update_ready(self.fake_manifest)) - - # corrupt recovery - self._corrupt_recovery() - self.assertFalse(verify_update_ready(self.fake_manifest)) - - # back to good state - download_neos_update(self.fake_manifest) - self.assertTrue(verify_update_ready(self.fake_manifest)) - - # corrupt ota - self._corrupt_recovery() - with open(os.path.join(NEOSUPDATE_DIR, os.path.basename(self.manifest['ota_url'])), "ab") as f: - f.write(b'\x00') - self.assertFalse(verify_update_ready(self.fake_manifest)) - -if __name__ == "__main__": - unittest.main() diff --git a/selfdrive/hardware/eon/update_neos.sh b/selfdrive/hardware/eon/update_neos.sh deleted file mode 100755 index ccc6ecce44..0000000000 --- a/selfdrive/hardware/eon/update_neos.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/bash - -ROOT=$PWD/../../.. -$ROOT/installer/updater/updater "file://$ROOT/installer/updater/update.json" diff --git a/selfdrive/hardware/eon/updater b/selfdrive/hardware/eon/updater deleted file mode 100755 index eaf34e957c..0000000000 Binary files a/selfdrive/hardware/eon/updater and /dev/null differ diff --git a/selfdrive/hardware/tici/pins.py b/selfdrive/hardware/tici/pins.py deleted file mode 100644 index 7139f5e955..0000000000 --- a/selfdrive/hardware/tici/pins.py +++ /dev/null @@ -1,8 +0,0 @@ -# TODO: these are also defined in a header -# GPIO pin definitions -GPIO_HUB_RST_N = 30 -GPIO_UBLOX_RST_N = 32 -GPIO_UBLOX_SAFEBOOT_N = 33 -GPIO_UBLOX_PWR_EN = 34 -GPIO_STM_RST_N = 124 -GPIO_STM_BOOT0 = 134 diff --git a/selfdrive/hardware/tici/power_monitor.py b/selfdrive/hardware/tici/power_monitor.py deleted file mode 100755 index d7f113cf2c..0000000000 --- a/selfdrive/hardware/tici/power_monitor.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env python3 -import sys -import time - -def average(avg, sample): - # Weighted avg between existing value and new sample - return ((avg[0] * avg[1] + sample) / (avg[1] + 1), avg[1] + 1) - -if __name__ == '__main__': - - sample_time = None - if len(sys.argv) > 1: - sample_time = int(sys.argv[1]) - - start_time = time.monotonic() - try: - voltage_average = (0, 0) # average, count - current_average = (0, 0) - power_average = (0, 0) - power_total_average = (0, 0) - while sample_time is None or time.monotonic() - start_time < sample_time: - with open("/sys/bus/i2c/devices/0-0040/hwmon/hwmon1/in1_input") as f: - voltage_total = int(f.read()) / 1000. - - with open("/sys/bus/i2c/devices/0-0040/hwmon/hwmon1/curr1_input") as f: - current_total = int(f.read()) - - with open("/sys/class/power_supply/bms/voltage_now") as f: - voltage = int(f.read()) / 1e6 # volts - - with open("/sys/class/power_supply/bms/current_now") as f: - current = int(f.read()) / 1e3 # ma - - power = voltage*current - power_total = voltage_total*current_total - - # compute averages - voltage_average = average(voltage_average, voltage) - current_average = average(current_average, current) - power_average = average(power_average, power) - power_total_average = average(power_total_average, power_total) - - print(f"{power:12.2f} mW {power_total:12.2f} mW {power_total - power:12.2f} mW") - time.sleep(0.25) - finally: - stop_time = time.monotonic() - print("\n----------------------Average-----------------------------------") - voltage = voltage_average[0] - current = current_average[0] - power = power_average[0] - print(f"{voltage:.2f} volts {current:12.2f} ma {power:12.2f} mW {power_total:12.2f} mW") - print(f" {stop_time - start_time:.2f} Seconds {voltage_average[1]} samples") - print("----------------------------------------------------------------") diff --git a/selfdrive/locationd/calibrationd.py b/selfdrive/locationd/calibrationd.py index ae314e38c4..1c68eb67bd 100755 --- a/selfdrive/locationd/calibrationd.py +++ b/selfdrive/locationd/calibrationd.py @@ -8,19 +8,17 @@ and the image input into the neural network is not corrected for roll. import gc import os +import capnp import numpy as np -from typing import NoReturn +from typing import List, NoReturn, Optional from cereal import log import cereal.messaging as messaging +from common.conversions import Conversions as CV from common.params import Params, put_nonblocking from common.realtime import set_realtime_priority -from common.transformations.model import model_height -from common.transformations.camera import get_view_frame_from_road_frame from common.transformations.orientation import rot_from_euler, euler_from_rot -from selfdrive.config import Conversions as CV -from selfdrive.hardware import TICI -from selfdrive.swaglog import cloudlog +from system.swaglog import cloudlog MIN_SPEED_FILTER = 15 * CV.MPH_TO_MS MAX_VEL_ANGLE_STD = np.radians(0.25) @@ -33,6 +31,7 @@ INPUTS_NEEDED = 5 # Minimum blocks needed for valid calibration INPUTS_WANTED = 50 # We want a little bit more than we need for stability MAX_ALLOWED_SPREAD = np.radians(2) RPY_INIT = np.array([0.0,0.0,0.0]) +WIDE_FROM_DEVICE_EULER_INIT = np.array([0.0, 0.0, 0.0]) # These values are needed to accommodate biggest modelframe PITCH_LIMITS = np.array([-0.09074112085129739, 0.14907572052989657]) @@ -46,11 +45,11 @@ class Calibration: INVALID = 2 -def is_calibration_valid(rpy): - return (PITCH_LIMITS[0] < rpy[1] < PITCH_LIMITS[1]) and (YAW_LIMITS[0] < rpy[2] < YAW_LIMITS[1]) +def is_calibration_valid(rpy: np.ndarray) -> bool: + return (PITCH_LIMITS[0] < rpy[1] < PITCH_LIMITS[1]) and (YAW_LIMITS[0] < rpy[2] < YAW_LIMITS[1]) # type: ignore -def sanity_clip(rpy): +def sanity_clip(rpy: np.ndarray) -> np.ndarray: if np.isnan(rpy).any(): rpy = RPY_INIT return np.array([rpy[0], @@ -58,15 +57,17 @@ def sanity_clip(rpy): np.clip(rpy[2], YAW_LIMITS[0] - .005, YAW_LIMITS[1] + .005)]) -class Calibrator(): - def __init__(self, param_put=False): +class Calibrator: + def __init__(self, param_put: bool = False): self.param_put = param_put + self.not_car = False + # Read saved calibration params = Params() calibration_params = params.get("CalibrationParams") - self.wide_camera = TICI and params.get_bool('EnableWideCamera') rpy_init = RPY_INIT + wide_from_device_euler = WIDE_FROM_DEVICE_EULER_INIT valid_blocks = 0 if param_put and calibration_params: @@ -74,28 +75,38 @@ class Calibrator(): msg = log.Event.from_bytes(calibration_params) rpy_init = np.array(msg.liveCalibration.rpyCalib) valid_blocks = msg.liveCalibration.validBlocks + wide_from_device_euler = np.array(msg.liveCalibration.wideFromDeviceEuler) except Exception: cloudlog.exception("Error reading cached CalibrationParams") - self.reset(rpy_init, valid_blocks) + self.reset(rpy_init, valid_blocks, wide_from_device_euler) self.update_status() - def reset(self, rpy_init=RPY_INIT, valid_blocks=0, smooth_from=None): + def reset(self, rpy_init: np.ndarray = RPY_INIT, + valid_blocks: int = 0, + wide_from_device_euler_init: np.ndarray = WIDE_FROM_DEVICE_EULER_INIT, + smooth_from: Optional[np.ndarray] = None) -> None: if not np.isfinite(rpy_init).all(): self.rpy = RPY_INIT.copy() else: self.rpy = rpy_init.copy() + if not np.isfinite(wide_from_device_euler_init).all() or len(wide_from_device_euler_init) != 3: + self.wide_from_device_euler = WIDE_FROM_DEVICE_EULER_INIT.copy() + else: + self.wide_from_device_euler = wide_from_device_euler_init.copy() + if not np.isfinite(valid_blocks) or valid_blocks < 0: self.valid_blocks = 0 else: self.valid_blocks = valid_blocks self.rpys = np.tile(self.rpy, (INPUTS_WANTED, 1)) + self.wide_from_device_eulers = np.tile(self.wide_from_device_euler, (INPUTS_WANTED, 1)) self.idx = 0 self.block_idx = 0 - self.v_ego = 0 + self.v_ego = 0.0 if smooth_from is None: self.old_rpy = RPY_INIT @@ -104,15 +115,16 @@ class Calibrator(): self.old_rpy = smooth_from self.old_rpy_weight = 1.0 - def get_valid_idxs(self): + def get_valid_idxs(self) -> List[int]: # exclude current block_idx from validity window before_current = list(range(self.block_idx)) after_current = list(range(min(self.valid_blocks, self.block_idx + 1), self.valid_blocks)) return before_current + after_current - def update_status(self): + def update_status(self) -> None: valid_idxs = self.get_valid_idxs() if valid_idxs: + self.wide_from_device_euler = np.mean(self.wide_from_device_eulers[valid_idxs], axis=0) rpys = self.rpys[valid_idxs] self.rpy = np.mean(rpys, axis=0) max_rpy_calib = np.array(np.max(rpys, axis=0)) @@ -129,7 +141,7 @@ class Calibrator(): self.cal_status = Calibration.INVALID # If spread is too high, assume mounting was changed and reset to last block. - # Make the transition smooth. Abrupt transitions are not good foor feedback loop through supercombo model. + # Make the transition smooth. Abrupt transitions are not good for feedback loop through supercombo model. if max(self.calib_spread) > MAX_ALLOWED_SPREAD and self.cal_status == Calibration.CALIBRATED: self.reset(self.rpys[self.block_idx - 1], valid_blocks=INPUTS_NEEDED, smooth_from=self.rpy) @@ -137,23 +149,23 @@ class Calibrator(): if self.param_put and write_this_cycle: put_nonblocking("CalibrationParams", self.get_msg().to_bytes()) - def handle_v_ego(self, v_ego): + def handle_v_ego(self, v_ego: float) -> None: self.v_ego = v_ego - def get_smooth_rpy(self): + def get_smooth_rpy(self) -> np.ndarray: if self.old_rpy_weight > 0: return self.old_rpy_weight * self.old_rpy + (1.0 - self.old_rpy_weight) * self.rpy else: return self.rpy - def handle_cam_odom(self, trans, rot, trans_std, rot_std): + def handle_cam_odom(self, trans: List[float], + rot: List[float], + wide_from_device_euler: List[float], + trans_std: List[float]) -> Optional[np.ndarray]: self.old_rpy_weight = min(0.0, self.old_rpy_weight - 1/SMOOTH_CYCLES) straight_and_fast = ((self.v_ego > MIN_SPEED_FILTER) and (trans[0] > MIN_SPEED_FILTER) and (abs(rot[2]) < MAX_YAW_RATE_FILTER)) - if self.wide_camera: - angle_std_threshold = 4*MAX_VEL_ANGLE_STD - else: - angle_std_threshold = MAX_VEL_ANGLE_STD + angle_std_threshold = MAX_VEL_ANGLE_STD certain_if_calib = ((np.arctan2(trans_std[1], trans[0]) < angle_std_threshold) or (self.valid_blocks < INPUTS_NEEDED)) if not (straight_and_fast and certain_if_calib): @@ -165,7 +177,14 @@ class Calibrator(): new_rpy = euler_from_rot(rot_from_euler(self.get_smooth_rpy()).dot(rot_from_euler(observed_rpy))) new_rpy = sanity_clip(new_rpy) - self.rpys[self.block_idx] = (self.idx*self.rpys[self.block_idx] + (BLOCK_SIZE - self.idx) * new_rpy) / float(BLOCK_SIZE) + if len(wide_from_device_euler) == 3: + new_wide_from_device_euler = np.array(wide_from_device_euler) + else: + new_wide_from_device_euler = WIDE_FROM_DEVICE_EULER_INIT + self.rpys[self.block_idx] = (self.idx*self.rpys[self.block_idx] + + (BLOCK_SIZE - self.idx) * new_rpy) / float(BLOCK_SIZE) + self.wide_from_device_eulers[self.block_idx] = (self.idx*self.wide_from_device_eulers[self.block_idx] + + (BLOCK_SIZE - self.idx) * new_wide_from_device_euler) / float(BLOCK_SIZE) self.idx = (self.idx + 1) % BLOCK_SIZE if self.idx == 0: self.block_idx += 1 @@ -176,29 +195,38 @@ class Calibrator(): return new_rpy - def get_msg(self): + def get_msg(self) -> capnp.lib.capnp._DynamicStructBuilder: smooth_rpy = self.get_smooth_rpy() - extrinsic_matrix = get_view_frame_from_road_frame(0, smooth_rpy[1], smooth_rpy[2], model_height) msg = messaging.new_message('liveCalibration') - msg.liveCalibration.validBlocks = self.valid_blocks - msg.liveCalibration.calStatus = self.cal_status - msg.liveCalibration.calPerc = min(100 * (self.valid_blocks * BLOCK_SIZE + self.idx) // (INPUTS_NEEDED * BLOCK_SIZE), 100) - msg.liveCalibration.extrinsicMatrix = extrinsic_matrix.flatten().tolist() - msg.liveCalibration.rpyCalib = smooth_rpy.tolist() - msg.liveCalibration.rpyCalibSpread = self.calib_spread.tolist() + liveCalibration = msg.liveCalibration + + liveCalibration.validBlocks = self.valid_blocks + liveCalibration.calStatus = self.cal_status + liveCalibration.calPerc = min(100 * (self.valid_blocks * BLOCK_SIZE + self.idx) // (INPUTS_NEEDED * BLOCK_SIZE), 100) + liveCalibration.rpyCalib = smooth_rpy.tolist() + liveCalibration.rpyCalibSpread = self.calib_spread.tolist() + liveCalibration.wideFromDeviceEuler = self.wide_from_device_euler.tolist() + + if self.not_car: + liveCalibration.validBlocks = INPUTS_NEEDED + liveCalibration.calStatus = Calibration.CALIBRATED + liveCalibration.calPerc = 100. + liveCalibration.rpyCalib = [0, 0, 0] + liveCalibration.rpyCalibSpread = self.calib_spread.tolist() + return msg - def send_data(self, pm) -> None: + def send_data(self, pm: messaging.PubMaster) -> None: pm.send('liveCalibration', self.get_msg()) -def calibrationd_thread(sm=None, pm=None) -> NoReturn: +def calibrationd_thread(sm: Optional[messaging.SubMaster] = None, pm: Optional[messaging.PubMaster] = None) -> NoReturn: gc.disable() set_realtime_priority(1) if sm is None: - sm = messaging.SubMaster(['cameraOdometry', 'carState'], poll=['cameraOdometry']) + sm = messaging.SubMaster(['cameraOdometry', 'carState', 'carParams'], poll=['cameraOdometry']) if pm is None: pm = messaging.PubMaster(['liveCalibration']) @@ -209,12 +237,14 @@ def calibrationd_thread(sm=None, pm=None) -> NoReturn: timeout = 0 if sm.frame == -1 else 100 sm.update(timeout) + calibrator.not_car = sm['carParams'].notCar + if sm.updated['cameraOdometry']: calibrator.handle_v_ego(sm['carState'].vEgo) new_rpy = calibrator.handle_cam_odom(sm['cameraOdometry'].trans, sm['cameraOdometry'].rot, - sm['cameraOdometry'].transStd, - sm['cameraOdometry'].rotStd) + sm['cameraOdometry'].wideFromDeviceEuler, + sm['cameraOdometry'].transStd) if DEBUG and new_rpy is not None: print('got new rpy', new_rpy) @@ -224,7 +254,7 @@ def calibrationd_thread(sm=None, pm=None) -> NoReturn: calibrator.send_data(pm) -def main(sm=None, pm=None) -> NoReturn: +def main(sm: Optional[messaging.SubMaster] = None, pm: Optional[messaging.PubMaster] = None) -> NoReturn: calibrationd_thread(sm, pm) diff --git a/selfdrive/locationd/laikad.py b/selfdrive/locationd/laikad.py new file mode 100755 index 0000000000..6936d88acc --- /dev/null +++ b/selfdrive/locationd/laikad.py @@ -0,0 +1,395 @@ +#!/usr/bin/env python3 +import json +import math +import os +import time +from collections import defaultdict +from concurrent.futures import Future, ProcessPoolExecutor +from datetime import datetime +from enum import IntEnum +from typing import List, Optional + +import numpy as np + +from cereal import log, messaging +from common.params import Params, put_nonblocking +from laika import AstroDog +from laika.constants import SECS_IN_HR, SECS_IN_MIN +from laika.downloader import DownloadFailed +from laika.ephemeris import Ephemeris, EphemerisType, convert_ublox_ephem, parse_qcom_ephem +from laika.gps_time import GPSTime +from laika.helpers import ConstellationId +from laika.raw_gnss import GNSSMeasurement, correct_measurements, process_measurements, read_raw_ublox, read_raw_qcom +from selfdrive.locationd.laikad_helpers import calc_pos_fix_gauss_newton, get_posfix_sympy_fun +from selfdrive.locationd.models.constants import GENERATED_DIR, ObservationKind +from selfdrive.locationd.models.gnss_kf import GNSSKalman +from selfdrive.locationd.models.gnss_kf import States as GStates +from system.swaglog import cloudlog + +MAX_TIME_GAP = 10 +EPHEMERIS_CACHE = 'LaikadEphemeris' +DOWNLOADS_CACHE_FOLDER = "/tmp/comma_download_cache/" +CACHE_VERSION = 0.1 +POS_FIX_RESIDUAL_THRESHOLD = 100.0 + + +class Laikad: + def __init__(self, valid_const=("GPS", "GLONASS"), auto_fetch_orbits=True, auto_update=False, + valid_ephem_types=(EphemerisType.ULTRA_RAPID_ORBIT, EphemerisType.NAV), + save_ephemeris=False, use_qcom=False): + """ + valid_const: GNSS constellation which can be used + auto_fetch_orbits: If true fetch orbits from internet when needed + auto_update: If true download AstroDog will download all files needed. This can be ephemeris or correction data like ionosphere. + valid_ephem_types: Valid ephemeris types to be used by AstroDog + save_ephemeris: If true saves and loads nav and orbit ephemeris to cache. + """ + self.astro_dog = AstroDog(valid_const=valid_const, auto_update=auto_update, valid_ephem_types=valid_ephem_types, clear_old_ephemeris=True, cache_dir=DOWNLOADS_CACHE_FOLDER) + self.gnss_kf = GNSSKalman(GENERATED_DIR, cython=True, erratic_clock=use_qcom) + + self.auto_fetch_orbits = auto_fetch_orbits + self.orbit_fetch_executor: Optional[ProcessPoolExecutor] = None + self.orbit_fetch_future: Optional[Future] = None + + self.last_fetch_orbits_t = None + self.got_first_gnss_msg = False + self.last_cached_t = None + self.save_ephemeris = save_ephemeris + self.load_cache() + + self.posfix_functions = {constellation: get_posfix_sympy_fun(constellation) for constellation in (ConstellationId.GPS, ConstellationId.GLONASS)} + self.last_pos_fix = [] + self.last_pos_residual = [] + self.last_pos_fix_t = None + self.gps_week = None + self.use_qcom = use_qcom + + def load_cache(self): + if not self.save_ephemeris: + return + + cache = Params().get(EPHEMERIS_CACHE) + if not cache: + return + + try: + cache = json.loads(cache, object_hook=deserialize_hook) + self.astro_dog.add_orbits(cache['orbits']) + self.astro_dog.add_navs(cache['nav']) + self.last_fetch_orbits_t = cache['last_fetch_orbits_t'] + except json.decoder.JSONDecodeError: + cloudlog.exception("Error parsing cache") + timestamp = self.last_fetch_orbits_t.as_datetime() if self.last_fetch_orbits_t is not None else 'Nan' + cloudlog.debug( + f"Loaded nav ({sum([len(v) for v in cache['nav']])}) and orbits ({sum([len(v) for v in cache['orbits']])}) cache with timestamp: {timestamp}. Unique orbit and nav sats: {list(cache['orbits'].keys())} {list(cache['nav'].keys())} " + + f"With time range: {[f'{start.as_datetime()}, {end.as_datetime()}' for (start,end) in self.astro_dog.orbit_fetched_times._ranges]}") + + def cache_ephemeris(self, t: GPSTime): + if self.save_ephemeris and (self.last_cached_t is None or t - self.last_cached_t > SECS_IN_MIN): + put_nonblocking(EPHEMERIS_CACHE, json.dumps( + {'version': CACHE_VERSION, 'last_fetch_orbits_t': self.last_fetch_orbits_t, 'orbits': self.astro_dog.orbits, 'nav': self.astro_dog.nav}, + cls=CacheSerializer)) + cloudlog.debug("Cache saved") + self.last_cached_t = t + + def get_est_pos(self, t, processed_measurements): + if self.last_pos_fix_t is None or abs(self.last_pos_fix_t - t) >= 2: + min_measurements = 6 if any(p.constellation_id == ConstellationId.GLONASS for p in processed_measurements) else 5 + pos_fix, pos_fix_residual = calc_pos_fix_gauss_newton(processed_measurements, self.posfix_functions, min_measurements=min_measurements) + if len(pos_fix) > 0: + self.last_pos_fix_t = t + residual_median = np.median(np.abs(pos_fix_residual)) + if np.median(np.abs(pos_fix_residual)) < POS_FIX_RESIDUAL_THRESHOLD: + cloudlog.debug(f"Pos fix is within threshold with median: {residual_median.round()}") + self.last_pos_fix = pos_fix[:3] + self.last_pos_residual = pos_fix_residual + else: + cloudlog.debug(f"Pos fix failed with median: {residual_median.round()}. All residuals: {np.round(pos_fix_residual)}") + return self.last_pos_fix + + def is_good_report(self, gnss_msg): + if gnss_msg.which() == 'drMeasurementReport' and self.use_qcom: + constellation_id = ConstellationId.from_qcom_source(gnss_msg.drMeasurementReport.source) + # TODO support GLONASS + return constellation_id in [ConstellationId.GPS, ConstellationId.SBAS] + elif gnss_msg.which() == 'measurementReport' and not self.use_qcom: + return True + else: + return False + + def read_report(self, gnss_msg): + if self.use_qcom: + report = gnss_msg.drMeasurementReport + week = report.gpsWeek + tow = report.gpsMilliseconds / 1000.0 + new_meas = read_raw_qcom(report) + else: + report = gnss_msg.measurementReport + week = report.gpsWeek + tow = report.rcvTow + new_meas = read_raw_ublox(report) + return week, tow, new_meas + + def is_ephemeris(self, gnss_msg): + if self.use_qcom: + return gnss_msg.which() == 'drSvPoly' + else: + return gnss_msg.which() == 'ephemeris' + + def read_ephemeris(self, gnss_msg): + # TODO this only works on GLONASS + if self.use_qcom: + # TODO this is not robust to gps week rollover + if self.gps_week is None: + return + ephem = parse_qcom_ephem(gnss_msg.drSvPoly, self.gps_week) + else: + ephem = convert_ublox_ephem(gnss_msg.ephemeris) + self.astro_dog.add_navs({ephem.prn: [ephem]}) + self.cache_ephemeris(t=ephem.epoch) + + def process_gnss_msg(self, gnss_msg, gnss_mono_time: int, block=False): + if self.is_good_report(gnss_msg): + week, tow, new_meas = self.read_report(gnss_msg) + self.gps_week = week + + t = gnss_mono_time * 1e-9 + if week > 0: + self.got_first_gnss_msg = True + latest_msg_t = GPSTime(week, tow) + if self.auto_fetch_orbits: + self.fetch_orbits(latest_msg_t, block) + + # Filter measurements with unexpected pseudoranges for GPS and GLONASS satellites + new_meas = [m for m in new_meas if 1e7 < m.observables['C1C'] < 3e7] + + processed_measurements = process_measurements(new_meas, self.astro_dog) + est_pos = self.get_est_pos(t, processed_measurements) + + corrected_measurements = correct_measurements(processed_measurements, est_pos, self.astro_dog) if len(est_pos) > 0 else [] + if gnss_mono_time % 10 == 0: + cloudlog.debug(f"Measurements Incoming/Processed/Corrected: {len(new_meas), len(processed_measurements), len(corrected_measurements)}") + + self.update_localizer(est_pos, t, corrected_measurements) + kf_valid = all(self.kf_valid(t)) + ecef_pos = self.gnss_kf.x[GStates.ECEF_POS] + ecef_vel = self.gnss_kf.x[GStates.ECEF_VELOCITY] + + p = self.gnss_kf.P.diagonal() + pos_std = np.sqrt(p[GStates.ECEF_POS]) + vel_std = np.sqrt(p[GStates.ECEF_VELOCITY]) + + meas_msgs = [create_measurement_msg(m) for m in corrected_measurements] + dat = messaging.new_message("gnssMeasurements") + measurement_msg = log.LiveLocationKalman.Measurement.new_message + dat.gnssMeasurements = { + "gpsWeek": week, + "gpsTimeOfWeek": tow, + "positionECEF": measurement_msg(value=ecef_pos.tolist(), std=pos_std.tolist(), valid=kf_valid), + "velocityECEF": measurement_msg(value=ecef_vel.tolist(), std=vel_std.tolist(), valid=kf_valid), + # TODO std is incorrectly the dimension of the measurements and not 3D + "positionFixECEF": measurement_msg(value=self.last_pos_fix, std=self.last_pos_residual, valid=self.last_pos_fix_t == t), + "ubloxMonoTime": gnss_mono_time, + "correctedMeasurements": meas_msgs + } + return dat + elif self.is_ephemeris(gnss_msg): + self.read_ephemeris(gnss_msg) + + #elif gnss_msg.which() == 'ionoData': + # todo add this. Needed to better correct messages offline. First fix ublox_msg.cc to sent them. + + def update_localizer(self, est_pos, t: float, measurements: List[GNSSMeasurement]): + # Check time and outputs are valid + valid = self.kf_valid(t) + if not all(valid): + if not valid[0]: # Filter not initialized + pass + elif not valid[1]: + cloudlog.error("Time gap of over 10s detected, gnss kalman reset") + elif not valid[2]: + cloudlog.error("Gnss kalman filter state is nan") + if len(est_pos) > 0: + cloudlog.info(f"Reset kalman filter with {est_pos}") + self.init_gnss_localizer(est_pos) + else: + return + if len(measurements) > 0: + kf_add_observations(self.gnss_kf, t, measurements) + else: + # Ensure gnss filter is updated even with no new measurements + self.gnss_kf.predict(t) + + def kf_valid(self, t: float) -> List[bool]: + filter_time = self.gnss_kf.filter.get_filter_time() + return [not math.isnan(filter_time), + abs(t - filter_time) < MAX_TIME_GAP, + all(np.isfinite(self.gnss_kf.x[GStates.ECEF_POS]))] + + def init_gnss_localizer(self, est_pos): + x_initial, p_initial_diag = np.copy(GNSSKalman.x_initial), np.copy(np.diagonal(GNSSKalman.P_initial)) + x_initial[GStates.ECEF_POS] = est_pos + p_initial_diag[GStates.ECEF_POS] = 1000 ** 2 + self.gnss_kf.init_state(x_initial, covs_diag=p_initial_diag) + + def fetch_orbits(self, t: GPSTime, block): + # Download new orbits if 1 hour of orbits data left + if t + SECS_IN_HR not in self.astro_dog.orbit_fetched_times and (self.last_fetch_orbits_t is None or abs(t - self.last_fetch_orbits_t) > SECS_IN_MIN): + astro_dog_vars = self.astro_dog.valid_const, self.astro_dog.auto_update, self.astro_dog.valid_ephem_types, self.astro_dog.cache_dir + ret = None + + if block: # Used for testing purposes + ret = get_orbit_data(t, *astro_dog_vars) + elif self.orbit_fetch_future is None: + self.orbit_fetch_executor = ProcessPoolExecutor(max_workers=1) + self.orbit_fetch_future = self.orbit_fetch_executor.submit(get_orbit_data, t, *astro_dog_vars) + elif self.orbit_fetch_future.done(): + ret = self.orbit_fetch_future.result() + self.orbit_fetch_executor = self.orbit_fetch_future = None + + if ret is not None: + if ret[0] is None: + self.last_fetch_orbits_t = ret[2] + else: + self.astro_dog.orbits, self.astro_dog.orbit_fetched_times, self.last_fetch_orbits_t = ret + self.cache_ephemeris(t=t) + + +def get_orbit_data(t: GPSTime, valid_const, auto_update, valid_ephem_types, cache_dir): + astro_dog = AstroDog(valid_const=valid_const, auto_update=auto_update, valid_ephem_types=valid_ephem_types, cache_dir=cache_dir) + cloudlog.info(f"Start to download/parse orbits for time {t.as_datetime()}") + start_time = time.monotonic() + try: + astro_dog.get_orbit_data(t, only_predictions=True) + cloudlog.info(f"Done parsing orbits. Took {time.monotonic() - start_time:.1f}s") + cloudlog.debug(f"Downloaded orbits ({sum([len(v) for v in astro_dog.orbits])}): {list(astro_dog.orbits.keys())}" + + f"With time range: {[f'{start.as_datetime()}, {end.as_datetime()}' for (start,end) in astro_dog.orbit_fetched_times._ranges]}") + return astro_dog.orbits, astro_dog.orbit_fetched_times, t + except (DownloadFailed, RuntimeError, ValueError, IOError) as e: + cloudlog.warning(f"No orbit data found or parsing failure: {e}") + return None, None, t + + +def create_measurement_msg(meas: GNSSMeasurement): + c = log.GnssMeasurements.CorrectedMeasurement.new_message() + c.constellationId = meas.constellation_id.value + c.svId = meas.sv_id + c.glonassFrequency = meas.glonass_freq if meas.constellation_id == ConstellationId.GLONASS else 0 + c.pseudorange = float(meas.observables_final['C1C']) + c.pseudorangeStd = float(meas.observables_std['C1C']) + c.pseudorangeRate = float(meas.observables_final['D1C']) + c.pseudorangeRateStd = float(meas.observables_std['D1C']) + c.satPos = meas.sat_pos_final.tolist() + c.satVel = meas.sat_vel.tolist() + c.satVel = meas.sat_vel.tolist() + ephem = meas.sat_ephemeris + assert ephem is not None + week, time_of_week = -1, -1 + if ephem.eph_type == EphemerisType.NAV: + source_type = EphemerisSourceType.nav + elif ephem.eph_type == EphemerisType.QCOM_POLY: + source_type = EphemerisSourceType.qcom + else: + assert ephem.file_epoch is not None + week = ephem.file_epoch.week + time_of_week = ephem.file_epoch.tow + file_src = ephem.file_source + if file_src == 'igu': # example nasa: '2214/igu22144_00.sp3.Z' + source_type = EphemerisSourceType.nasaUltraRapid + elif file_src == 'Sta': # example nasa: '22166/ultra/Stark_1D_22061518.sp3' + source_type = EphemerisSourceType.glonassIacUltraRapid + else: + raise Exception(f"Didn't expect file source {file_src}") + + c.ephemerisSource.type = source_type.value + c.ephemerisSource.gpsWeek = week + c.ephemerisSource.gpsTimeOfWeek = int(time_of_week) + return c + + +def kf_add_observations(gnss_kf: GNSSKalman, t: float, measurements: List[GNSSMeasurement]): + ekf_data = defaultdict(list) + for m in measurements: + m_arr = m.as_array() + if m.constellation_id == ConstellationId.GPS: + ekf_data[ObservationKind.PSEUDORANGE_GPS].append(m_arr) + elif m.constellation_id == ConstellationId.GLONASS: + ekf_data[ObservationKind.PSEUDORANGE_GLONASS].append(m_arr) + ekf_data[ObservationKind.PSEUDORANGE_RATE_GPS] = ekf_data[ObservationKind.PSEUDORANGE_GPS] + ekf_data[ObservationKind.PSEUDORANGE_RATE_GLONASS] = ekf_data[ObservationKind.PSEUDORANGE_GLONASS] + for kind, data in ekf_data.items(): + if len(data) > 0: + gnss_kf.predict_and_observe(t, kind, data) + + +class CacheSerializer(json.JSONEncoder): + + def default(self, o): + if isinstance(o, Ephemeris): + return o.to_json() + if isinstance(o, GPSTime): + return o.__dict__ + if isinstance(o, np.ndarray): + return o.tolist() + return json.JSONEncoder.default(self, o) + + +def deserialize_hook(dct): + if 'ephemeris' in dct: + return Ephemeris.from_json(dct) + if 'week' in dct: + return GPSTime(dct['week'], dct['tow']) + return dct + + +class EphemerisSourceType(IntEnum): + nav = 0 + nasaUltraRapid = 1 + glonassIacUltraRapid = 2 + qcom = 3 + + +def main(sm=None, pm=None): + use_qcom = not Params().get_bool("UbloxAvailable", block=True) + if use_qcom: + raw_gnss_socket = "qcomGnss" + else: + raw_gnss_socket = "ubloxGnss" + + if sm is None: + sm = messaging.SubMaster([raw_gnss_socket, 'clocks']) + if pm is None: + pm = messaging.PubMaster(['gnssMeasurements']) + + replay = "REPLAY" in os.environ + use_internet = "LAIKAD_NO_INTERNET" not in os.environ + laikad = Laikad(save_ephemeris=not replay, auto_fetch_orbits=use_internet, use_qcom=use_qcom) + + while True: + sm.update() + + if sm.updated[raw_gnss_socket]: + gnss_msg = sm[raw_gnss_socket] + + # TODO: Understand and use remaining unknown constellations + if gnss_msg.which() == "drMeasurementReport": + if getattr(gnss_msg, gnss_msg.which()).source not in ['glonass', 'gps', 'beidou', 'sbas']: + continue + + if getattr(gnss_msg, gnss_msg.which()).gpsWeek > np.iinfo(np.int16).max: + # gpsWeek 65535 is received rarely from quectel, this cannot be + # passed to GnssMeasurements's gpsWeek (Int16) + continue + + msg = laikad.process_gnss_msg(gnss_msg, sm.logMonoTime[raw_gnss_socket], block=replay) + if msg is not None: + pm.send('gnssMeasurements', msg) + if not laikad.got_first_gnss_msg and sm.updated['clocks']: + clocks_msg = sm['clocks'] + t = GPSTime.from_datetime(datetime.utcfromtimestamp(clocks_msg.wallTimeNanos * 1E-9)) + if laikad.auto_fetch_orbits: + laikad.fetch_orbits(t, block=replay) + + +if __name__ == "__main__": + main() diff --git a/selfdrive/locationd/laikad_helpers.py b/selfdrive/locationd/laikad_helpers.py new file mode 100644 index 0000000000..f13e8e73bb --- /dev/null +++ b/selfdrive/locationd/laikad_helpers.py @@ -0,0 +1,89 @@ +import numpy as np +import sympy + +from laika.constants import EARTH_ROTATION_RATE, SPEED_OF_LIGHT +from laika.helpers import ConstellationId + + +def calc_pos_fix_gauss_newton(measurements, posfix_functions, x0=None, signal='C1C', min_measurements=6): + ''' + Calculates gps fix using gauss newton method + To solve the problem a minimal of 4 measurements are required. + If Glonass is included 5 are required to solve for the additional free variable. + returns: + 0 -> list with positions + ''' + if x0 is None: + x0 = [0, 0, 0, 0, 0] + n = len(measurements) + if n < min_measurements: + return [], [] + + Fx_pos = pr_residual(measurements, posfix_functions, signal=signal) + x = gauss_newton(Fx_pos, x0) + residual, _ = Fx_pos(x, weight=1.0) + return x.tolist(), residual.tolist() + + +def pr_residual(measurements, posfix_functions, signal='C1C'): + def Fx_pos(inp, weight=None): + vals, gradients = [], [] + + for meas in measurements: + pr = meas.observables[signal] + pr += meas.sat_clock_err * SPEED_OF_LIGHT + + w = (1 / meas.observables_std[signal]) if weight is None else weight + + val, *gradient = posfix_functions[meas.constellation_id](*inp, pr, *meas.sat_pos, w) + vals.append(val) + gradients.append(gradient) + return np.asarray(vals), np.asarray(gradients) + + return Fx_pos + + +def gauss_newton(fun, b, xtol=1e-8, max_n=25): + for _ in range(max_n): + # Compute function and jacobian on current estimate + r, J = fun(b) + + # Update estimate + delta = np.linalg.pinv(J) @ r + b -= delta + + # Check step size for stopping condition + if np.linalg.norm(delta) < xtol: + break + return b + + +def get_posfix_sympy_fun(constellation): + # Unknowns + x, y, z = sympy.Symbol('x'), sympy.Symbol('y'), sympy.Symbol('z') + bc = sympy.Symbol('bc') + bg = sympy.Symbol('bg') + var = [x, y, z, bc, bg] + + # Knowns + pr = sympy.Symbol('pr') + sat_x, sat_y, sat_z = sympy.Symbol('sat_x'), sympy.Symbol('sat_y'), sympy.Symbol('sat_z') + weight = sympy.Symbol('weight') + + theta = EARTH_ROTATION_RATE * (pr - bc) / SPEED_OF_LIGHT + val = sympy.sqrt( + (sat_x * sympy.cos(theta) + sat_y * sympy.sin(theta) - x) ** 2 + + (sat_y * sympy.cos(theta) - sat_x * sympy.sin(theta) - y) ** 2 + + (sat_z - z) ** 2 + ) + + if constellation == ConstellationId.GLONASS: + res = weight * (val - (pr - bc - bg)) + elif constellation == ConstellationId.GPS: + res = weight * (val - (pr - bc)) + else: + raise NotImplementedError(f"Constellation {constellation} not supported") + + res = [res] + [sympy.diff(res, v) for v in var] + + return sympy.lambdify([x, y, z, bc, bg, pr, sat_x, sat_y, sat_z, weight], res, modules=["numpy"]) diff --git a/selfdrive/locationd/liblocationd.cc b/selfdrive/locationd/liblocationd.cc index 250d90b382..da57fb7ff4 100755 --- a/selfdrive/locationd/liblocationd.cc +++ b/selfdrive/locationd/liblocationd.cc @@ -7,11 +7,10 @@ extern "C" { return new Localizer(); } - void localizer_get_message_bytes(Localizer *localizer, uint64_t logMonoTime, - bool inputsOK, bool sensorsOK, bool gpsOK, char *buff, size_t buff_size) - { + void localizer_get_message_bytes(Localizer *localizer, bool inputsOK, bool sensorsOK, bool gpsOK, bool msgValid, + char *buff, size_t buff_size) { MessageBuilder msg_builder; - kj::ArrayPtr arr = localizer->get_message_bytes(msg_builder, logMonoTime, inputsOK, sensorsOK, gpsOK).asChars(); + kj::ArrayPtr arr = localizer->get_message_bytes(msg_builder, inputsOK, sensorsOK, gpsOK, msgValid).asChars(); assert(buff_size >= arr.size()); memcpy(buff, arr.begin(), arr.size()); } @@ -27,4 +26,16 @@ extern "C" { memcpy(std_buff, stdev.data(), sizeof(double) * stdev.size()); } + bool is_gps_ok(Localizer *localizer){ + return localizer->is_gps_ok(); + } + + bool are_inputs_ok(Localizer *localizer){ + return localizer->are_inputs_ok(); + } + + void observation_timings_invalid_reset(Localizer *localizer){ + localizer->observation_timings_invalid_reset(); + } + } diff --git a/selfdrive/locationd/locationd.cc b/selfdrive/locationd/locationd.cc index b723878e9d..4325900c0e 100755 --- a/selfdrive/locationd/locationd.cc +++ b/selfdrive/locationd/locationd.cc @@ -19,6 +19,14 @@ const double VALID_TIME_SINCE_RESET = 1.0; // s const double VALID_POS_STD = 50.0; // m const double MAX_RESET_TRACKER = 5.0; const double SANE_GPS_UNCERTAINTY = 1500.0; // m +const double INPUT_INVALID_THRESHOLD = 5.0; // same as reset tracker +const double DECAY = 0.99995; // same as reset tracker +const double MAX_FILTER_REWIND_TIME = 0.8; // s + +// TODO: GPS sensor time offsets are empirically calculated +// They should be replaced with synced time from a real clock +const double GPS_LOCATION_SENSOR_TIME_OFFSET = 0.630; // s +const double GPS_LOCATION_EXTERNAL_SENSOR_TIME_OFFSET = 0.095; // s static VectorXd floatlist2vector(const capnp::List::Reader& floatlist) { VectorXd res(floatlist.size()); @@ -195,51 +203,69 @@ VectorXd Localizer::get_stdev() { return this->kf->get_P().diagonal().array().sqrt(); } -void Localizer::handle_sensors(double current_time, const capnp::List::Reader& log) { +bool Localizer::are_inputs_ok() { + return this->critical_services_valid(this->observation_values_invalid) && !this->observation_timings_invalid; +} + +void Localizer::observation_timings_invalid_reset(){ + this->observation_timings_invalid = false; +} + +void Localizer::handle_sensor(double current_time, const cereal::SensorEventData::Reader& log) { // TODO does not yet account for double sensor readings in the log - for (int i = 0; i < log.size(); i++) { - const cereal::SensorEventData::Reader& sensor_reading = log[i]; - // Ignore empty readings (e.g. in case the magnetometer had no data ready) - if (sensor_reading.getTimestamp() == 0) { - continue; - } + // Ignore empty readings (e.g. in case the magnetometer had no data ready) + if (log.getTimestamp() == 0) { + return; + } - double sensor_time = 1e-9 * sensor_reading.getTimestamp(); + double sensor_time = 1e-9 * log.getTimestamp(); + + // sensor time and log time should be close + if (std::abs(current_time - sensor_time) > 0.1) { + LOGE("Sensor reading ignored, sensor timestamp more than 100ms off from log time"); + this->observation_timings_invalid = true; + return; + } + else if (!this->is_timestamp_valid(sensor_time)) { + this->observation_timings_invalid = true; + return; + } - // sensor time and log time should be close - if (std::abs(current_time - sensor_time) > 0.1) { - LOGE("Sensor reading ignored, sensor timestamp more than 100ms off from log time"); - return; - } + // TODO: handle messages from two IMUs at the same time + if (log.getSource() == cereal::SensorEventData::SensorSource::BMX055) { + return; + } - // TODO: handle messages from two IMUs at the same time - if (sensor_reading.getSource() == cereal::SensorEventData::SensorSource::BMX055) { - continue; + // Gyro Uncalibrated + if (log.getSensor() == SENSOR_GYRO_UNCALIBRATED && log.getType() == SENSOR_TYPE_GYROSCOPE_UNCALIBRATED) { + auto v = log.getGyroUncalibrated().getV(); + auto meas = Vector3d(-v[2], -v[1], -v[0]); + if (meas.norm() < ROTATION_SANITY_CHECK) { + this->kf->predict_and_observe(sensor_time, OBSERVATION_PHONE_GYRO, { meas }); + this->observation_values_invalid["gyroscope"] *= DECAY; } - - // Gyro Uncalibrated - if (sensor_reading.getSensor() == SENSOR_GYRO_UNCALIBRATED && sensor_reading.getType() == SENSOR_TYPE_GYROSCOPE_UNCALIBRATED) { - auto v = sensor_reading.getGyroUncalibrated().getV(); - auto meas = Vector3d(-v[2], -v[1], -v[0]); - if (meas.norm() < ROTATION_SANITY_CHECK) { - this->kf->predict_and_observe(sensor_time, OBSERVATION_PHONE_GYRO, { meas }); - } + else{ + this->observation_values_invalid["gyroscope"] += 1.0; } + } - // Accelerometer - if (sensor_reading.getSensor() == SENSOR_ACCELEROMETER && sensor_reading.getType() == SENSOR_TYPE_ACCELEROMETER) { - auto v = sensor_reading.getAcceleration().getV(); + // Accelerometer + if (log.getSensor() == SENSOR_ACCELEROMETER && log.getType() == SENSOR_TYPE_ACCELEROMETER) { + auto v = log.getAcceleration().getV(); - // TODO: reduce false positives and re-enable this check - // check if device fell, estimate 10 for g - // 40m/s**2 is a good filter for falling detection, no false positives in 20k minutes of driving - //this->device_fell |= (floatlist2vector(v) - Vector3d(10.0, 0.0, 0.0)).norm() > 40.0; + // TODO: reduce false positives and re-enable this check + // check if device fell, estimate 10 for g + // 40m/s**2 is a good filter for falling detection, no false positives in 20k minutes of driving + // this->device_fell |= (floatlist2vector(v) - Vector3d(10.0, 0.0, 0.0)).norm() > 40.0; - auto meas = Vector3d(-v[2], -v[1], -v[0]); - if (meas.norm() < ACCEL_SANITY_CHECK) { - this->kf->predict_and_observe(sensor_time, OBSERVATION_PHONE_ACCEL, { meas }); - } + auto meas = Vector3d(-v[2], -v[1], -v[0]); + if (meas.norm() < ACCEL_SANITY_CHECK) { + this->kf->predict_and_observe(sensor_time, OBSERVATION_PHONE_ACCEL, { meas }); + this->observation_values_invalid["accelerometer"] *= DECAY; + } + else{ + this->observation_values_invalid["accelerometer"] += 1.0; } } } @@ -250,32 +276,40 @@ void Localizer::input_fake_gps_observations(double current_time) { // Steps : first predict -> observe current obs with reasonable STD this->kf->predict(current_time); - VectorXd current_x = this->kf->get_x(); + VectorXd current_x = this->kf->get_x(); VectorXd ecef_pos = current_x.segment(STATE_ECEF_POS_START); VectorXd ecef_vel = current_x.segment(STATE_ECEF_VELOCITY_START); MatrixXdr ecef_pos_R = this->kf->get_fake_gps_pos_cov(); MatrixXdr ecef_vel_R = this->kf->get_fake_gps_vel_cov(); - + this->kf->predict_and_observe(current_time, OBSERVATION_ECEF_POS, { ecef_pos }, { ecef_pos_R }); this->kf->predict_and_observe(current_time, OBSERVATION_ECEF_VEL, { ecef_vel }, { ecef_vel_R }); } -void Localizer::handle_gps(double current_time, const cereal::GpsLocationData::Reader& log) { +void Localizer::handle_gps(double current_time, const cereal::GpsLocationData::Reader& log, const double sensor_time_offset) { // ignore the message if the fix is invalid - bool gps_invalid_flag = (log.getFlags() % 2 == 0); bool gps_unreasonable = (Vector2d(log.getAccuracy(), log.getVerticalAccuracy()).norm() >= SANE_GPS_UNCERTAINTY); bool gps_accuracy_insane = ((log.getVerticalAccuracy() <= 0) || (log.getSpeedAccuracy() <= 0) || (log.getBearingAccuracyDeg() <= 0)); bool gps_lat_lng_alt_insane = ((std::abs(log.getLatitude()) > 90) || (std::abs(log.getLongitude()) > 180) || (std::abs(log.getAltitude()) > ALTITUDE_SANITY_CHECK)); bool gps_vel_insane = (floatlist2vector(log.getVNED()).norm() > TRANS_SANITY_CHECK); - if (gps_invalid_flag || gps_unreasonable || gps_accuracy_insane || gps_lat_lng_alt_insane || gps_vel_insane){ + // quectel gps verticalAccuracy is clipped to 500 + bool gps_accuracy_insane_quectel = false; + if (!ublox_available) { + gps_accuracy_insane_quectel = log.getVerticalAccuracy() == 500; + } + + if (gps_invalid_flag || gps_unreasonable || gps_accuracy_insane || gps_lat_lng_alt_insane || gps_vel_insane || gps_accuracy_insane_quectel) { + this->gps_valid = false; this->determine_gps_mode(current_time); return; } + double sensor_time = current_time - sensor_time_offset; + // Process message - this->last_gps_fix = current_time; + this->gps_valid = true; this->gps_mode = true; Geodetic geodetic = { log.getLatitude(), log.getLongitude(), log.getAltitude() }; this->converter = std::make_unique(geodetic); @@ -284,8 +318,8 @@ void Localizer::handle_gps(double current_time, const cereal::GpsLocationData::R VectorXd ecef_vel = this->converter->ned2ecef({ log.getVNED()[0], log.getVNED()[1], log.getVNED()[2] }).to_vector() - ecef_pos; MatrixXdr ecef_pos_R = Vector3d::Constant(std::pow(10.0 * log.getAccuracy(),2) + std::pow(10.0 * log.getVerticalAccuracy(),2)).asDiagonal(); MatrixXdr ecef_vel_R = Vector3d::Constant(std::pow(log.getSpeedAccuracy() * 10.0, 2)).asDiagonal(); - - this->unix_timestamp_millis = log.getTimestamp(); + + this->unix_timestamp_millis = log.getUnixTimestampMillis(); double gps_est_error = (this->kf->get_x().segment(STATE_ECEF_POS_START) - ecef_pos).norm(); VectorXd orientation_ecef = quat2euler(vector2quat(this->kf->get_x().segment(STATE_ECEF_ORIENTATION_START))); @@ -304,14 +338,14 @@ void Localizer::handle_gps(double current_time, const cereal::GpsLocationData::R if (ecef_vel.norm() > 5.0 && orientation_error.norm() > 1.0) { LOGE("Locationd vs ubloxLocation orientation difference too large, kalman reset"); this->reset_kalman(NAN, initial_pose_ecef_quat, ecef_pos, ecef_vel, ecef_pos_R, ecef_vel_R); - this->kf->predict_and_observe(current_time, OBSERVATION_ECEF_ORIENTATION_FROM_GPS, { initial_pose_ecef_quat }); + this->kf->predict_and_observe(sensor_time, OBSERVATION_ECEF_ORIENTATION_FROM_GPS, { initial_pose_ecef_quat }); } else if (gps_est_error > 100.0) { LOGE("Locationd vs ubloxLocation position difference too large, kalman reset"); this->reset_kalman(NAN, initial_pose_ecef_quat, ecef_pos, ecef_vel, ecef_pos_R, ecef_vel_R); } - this->kf->predict_and_observe(current_time, OBSERVATION_ECEF_POS, { ecef_pos }, { ecef_pos_R }); - this->kf->predict_and_observe(current_time, OBSERVATION_ECEF_VEL, { ecef_vel }, { ecef_vel_R }); + this->kf->predict_and_observe(sensor_time, OBSERVATION_ECEF_POS, { ecef_pos }, { ecef_pos_R }); + this->kf->predict_and_observe(sensor_time, OBSERVATION_ECEF_VEL, { ecef_vel }, { ecef_vel_R }); } void Localizer::handle_car_state(double current_time, const cereal::CarState::Reader& log) { @@ -325,8 +359,14 @@ void Localizer::handle_car_state(double current_time, const cereal::CarState::Re void Localizer::handle_cam_odo(double current_time, const cereal::CameraOdometry::Reader& log) { VectorXd rot_device = this->device_from_calib * floatlist2vector(log.getRot()); VectorXd trans_device = this->device_from_calib * floatlist2vector(log.getTrans()); + + if (!this->is_timestamp_valid(current_time)) { + this->observation_timings_invalid = true; + return; + } if ((rot_device.norm() > ROTATION_SANITY_CHECK) || (trans_device.norm() > TRANS_SANITY_CHECK)) { + this->observation_values_invalid["cameraOdometry"] += 1.0; return; } @@ -334,10 +374,12 @@ void Localizer::handle_cam_odo(double current_time, const cereal::CameraOdometry VectorXd trans_calib_std = floatlist2vector(log.getTransStd()); if ((rot_calib_std.minCoeff() <= MIN_STD_SANITY_CHECK) || (trans_calib_std.minCoeff() <= MIN_STD_SANITY_CHECK)) { + this->observation_values_invalid["cameraOdometry"] += 1.0; return; } if ((rot_calib_std.norm() > 10 * ROTATION_SANITY_CHECK) || (trans_calib_std.norm() > 10 * TRANS_SANITY_CHECK)) { + this->observation_values_invalid["cameraOdometry"] += 1.0; return; } @@ -353,12 +395,19 @@ void Localizer::handle_cam_odo(double current_time, const cereal::CameraOdometry { rot_device }, { rot_device_cov }); this->kf->predict_and_observe(current_time, OBSERVATION_CAMERA_ODO_TRANSLATION, { trans_device }, { trans_device_cov }); + this->observation_values_invalid["cameraOdometry"] *= DECAY; } void Localizer::handle_live_calib(double current_time, const cereal::LiveCalibrationData::Reader& log) { + if (!this->is_timestamp_valid(current_time)) { + this->observation_timings_invalid = true; + return; + } + if (log.getRpyCalib().size() > 0) { auto live_calib = floatlist2vector(log.getRpyCalib()); if ((live_calib.minCoeff() < -CALIB_RPY_SANITY_CHECK) || (live_calib.maxCoeff() > CALIB_RPY_SANITY_CHECK)) { + this->observation_values_invalid["liveCalibration"] += 1.0; return; } @@ -366,6 +415,7 @@ void Localizer::handle_live_calib(double current_time, const cereal::LiveCalibra this->device_from_calib = euler2rot(this->calib); this->calib_from_device = this->device_from_calib.transpose(); this->calibrated = log.getCalStatus() == 1; + this->observation_values_invalid["liveCalibration"] *= DECAY; } } @@ -397,8 +447,8 @@ void Localizer::time_check(double current_time) { void Localizer::update_reset_tracker() { // reset tracker is tuned to trigger when over 1reset/10s over 2min period - if (this->isGpsOK()) { - this->reset_tracker *= .99995; + if (this->is_gps_ok()) { + this->reset_tracker *= DECAY; } else { this->reset_tracker = 0.0; } @@ -420,7 +470,7 @@ void Localizer::reset_kalman(double current_time, VectorXd init_orient, VectorXd init_P.block(STATE_ECEF_ORIENTATION_ERR_START, STATE_ECEF_ORIENTATION_ERR_START).diagonal() = reset_orientation_P.diagonal(); init_P.block(STATE_ECEF_VELOCITY_ERR_START, STATE_ECEF_VELOCITY_ERR_START).diagonal() = init_vel_R.diagonal(); init_P.block(STATE_ANGULAR_VELOCITY_ERR_START, STATE_ANGULAR_VELOCITY_ERR_START, non_ecef_state_err_len, non_ecef_state_err_len).diagonal() = current_P.block(STATE_ANGULAR_VELOCITY_ERR_START, STATE_ANGULAR_VELOCITY_ERR_START, non_ecef_state_err_len, non_ecef_state_err_len).diagonal(); - + this->reset_kalman(current_time, current_x, init_P); } @@ -442,10 +492,14 @@ void Localizer::handle_msg_bytes(const char *data, const size_t size) { void Localizer::handle_msg(const cereal::Event::Reader& log) { double t = log.getLogMonoTime() * 1e-9; this->time_check(t); - if (log.isSensorEvents()) { - this->handle_sensors(t, log.getSensorEvents()); + if (log.isAccelerometer()) { + this->handle_sensor(t, log.getAccelerometer()); + } else if (log.isGyroscope()) { + this->handle_sensor(t, log.getGyroscope()); + } else if (log.isGpsLocation()) { + this->handle_gps(t, log.getGpsLocation(), GPS_LOCATION_SENSOR_TIME_OFFSET); } else if (log.isGpsLocationExternal()) { - this->handle_gps(t, log.getGpsLocationExternal()); + this->handle_gps(t, log.getGpsLocationExternal(), GPS_LOCATION_EXTERNAL_SENSOR_TIME_OFFSET); } else if (log.isCarState()) { this->handle_car_state(t, log.getCarState()); } else if (log.isCameraOdometry()) { @@ -457,28 +511,44 @@ void Localizer::handle_msg(const cereal::Event::Reader& log) { this->update_reset_tracker(); } -kj::ArrayPtr Localizer::get_message_bytes(MessageBuilder& msg_builder, uint64_t logMonoTime, - bool inputsOK, bool sensorsOK, bool gpsOK) -{ +kj::ArrayPtr Localizer::get_message_bytes(MessageBuilder& msg_builder, bool inputsOK, + bool sensorsOK, bool gpsOK, bool msgValid) { cereal::Event::Builder evt = msg_builder.initEvent(); - evt.setLogMonoTime(logMonoTime); + evt.setValid(msgValid); cereal::LiveLocationKalman::Builder liveLoc = evt.initLiveLocationKalman(); this->build_live_location(liveLoc); - liveLoc.setInputsOK(inputsOK); liveLoc.setSensorsOK(sensorsOK); liveLoc.setGpsOK(gpsOK); + liveLoc.setInputsOK(inputsOK); return msg_builder.toBytes(); } +bool Localizer::is_gps_ok() { + return this->gps_valid; +} + +bool Localizer::critical_services_valid(std::map critical_services) { + for (auto &kv : critical_services){ + if (kv.second >= INPUT_INVALID_THRESHOLD){ + return false; + } + } + return true; +} -bool Localizer::isGpsOK() { - return this->kf->get_filter_time() - this->last_gps_fix < 1.0; +bool Localizer::is_timestamp_valid(double current_time) { + double filter_time = this->kf->get_filter_time(); + if (!std::isnan(filter_time) && ((filter_time - current_time) > MAX_FILTER_REWIND_TIME)) { + LOGE("Observation timestamp is older than the max rewind threshold of the filter"); + return false; + } + return true; } void Localizer::determine_gps_mode(double current_time) { - // 1. If the pos_std is greater than what's not acceptible and localizer is in gps-mode, reset to no-gps-mode - // 2. If the pos_std is greater than what's not acceptible and localizer is in no-gps-mode, fake obs - // 3. If the pos_std is smaller than what's not acceptible, let gps-mode be whatever it is + // 1. If the pos_std is greater than what's not acceptable and localizer is in gps-mode, reset to no-gps-mode + // 2. If the pos_std is greater than what's not acceptable and localizer is in no-gps-mode, fake obs + // 3. If the pos_std is smaller than what's not acceptable, let gps-mode be whatever it is VectorXd current_pos_std = this->kf->get_P().block(STATE_ECEF_POS_ERR_START, STATE_ECEF_POS_ERR_START).diagonal().array().sqrt(); if (current_pos_std.norm() > SANE_GPS_UNCERTAINTY){ if (this->gps_mode){ @@ -492,31 +562,54 @@ void Localizer::determine_gps_mode(double current_time) { } int Localizer::locationd_thread() { - const std::initializer_list service_list = - { "gpsLocationExternal", "sensorEvents", "cameraOdometry", "liveCalibration", "carState" }; - PubMaster pm({ "liveLocationKalman" }); - SubMaster sm(service_list, nullptr, { "gpsLocationExternal" }); + ublox_available = Params().getBool("UbloxAvailable", true); + + const char* gps_location_socket; + if (ublox_available) { + gps_location_socket = "gpsLocationExternal"; + } else { + gps_location_socket = "gpsLocation"; + } + const std::initializer_list service_list = {gps_location_socket, "cameraOdometry", "liveCalibration", + "carState", "carParams", "accelerometer", "gyroscope"}; + PubMaster pm({"liveLocationKalman"}); + + // TODO: remove carParams once we're always sending at 100Hz + SubMaster sm(service_list, {}, nullptr, {gps_location_socket, "carParams"}); + + uint64_t cnt = 0; + bool filterInitialized = false; + const std::vector critical_input_services = {"cameraOdometry", "liveCalibration", "accelerometer", "gyroscope"}; + for (std::string service : critical_input_services) { + this->observation_values_invalid.insert({service, 0.0}); + } while (!do_exit) { sm.update(); - for (const char* service : service_list) { - if (sm.updated(service) && sm.valid(service)) { - const cereal::Event::Reader log = sm[service]; - this->handle_msg(log); + if (filterInitialized){ + this->observation_timings_invalid_reset(); + for (const char* service : service_list) { + if (sm.updated(service) && sm.valid(service)){ + const cereal::Event::Reader log = sm[service]; + this->handle_msg(log); + } } + } else { + filterInitialized = sm.allAliveAndValid(); } - if (sm.updated("cameraOdometry")) { - uint64_t logMonoTime = sm["cameraOdometry"].getLogMonoTime(); - bool inputsOK = sm.allAliveAndValid(); - bool sensorsOK = sm.alive("sensorEvents") && sm.valid("sensorEvents"); - bool gpsOK = this->isGpsOK(); + // 100Hz publish for notcars, 20Hz for cars + const char* trigger_msg = sm["carParams"].getCarParams().getNotCar() ? "accelerometer" : "cameraOdometry"; + if (sm.updated(trigger_msg)) { + bool inputsOK = sm.allAliveAndValid() && this->are_inputs_ok(); + bool gpsOK = this->is_gps_ok(); + bool sensorsOK = sm.allAliveAndValid({"accelerometer", "gyroscope"}); MessageBuilder msg_builder; - kj::ArrayPtr bytes = this->get_message_bytes(msg_builder, logMonoTime, inputsOK, sensorsOK, gpsOK); + kj::ArrayPtr bytes = this->get_message_bytes(msg_builder, inputsOK, sensorsOK, gpsOK, filterInitialized); pm.send("liveLocationKalman", bytes.begin(), bytes.size()); - if (sm.frame % 1200 == 0 && gpsOK) { // once a minute + if (cnt % 1200 == 0 && gpsOK) { // once a minute VectorXd posGeo = this->get_position_geodetic(); std::string lastGPSPosJSON = util::string_format( "{\"latitude\": %.15f, \"longitude\": %.15f, \"altitude\": %.15f}", posGeo(0), posGeo(1), posGeo(2)); @@ -525,6 +618,7 @@ int Localizer::locationd_thread() { Params().put("LastGPSPosition", gpsjson); }, lastGPSPosJSON).detach(); } + cnt++; } } return 0; diff --git a/selfdrive/locationd/locationd.h b/selfdrive/locationd/locationd.h index 9bc864bf6d..f0872d9f56 100755 --- a/selfdrive/locationd/locationd.h +++ b/selfdrive/locationd/locationd.h @@ -3,15 +3,16 @@ #include #include #include +#include #include #include "cereal/messaging/messaging.h" #include "common/transformations/coordinates.hpp" #include "common/transformations/orientation.hpp" -#include "selfdrive/common/params.h" -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/timing.h" -#include "selfdrive/common/util.h" +#include "common/params.h" +#include "common/swaglog.h" +#include "common/timing.h" +#include "common/util.h" #include "selfdrive/sensord/sensors/constants.h" #define VISION_DECIMATION 2 @@ -32,11 +33,15 @@ public: void finite_check(double current_time = NAN); void time_check(double current_time = NAN); void update_reset_tracker(); - bool isGpsOK(); + bool is_gps_ok(); + bool critical_services_valid(std::map critical_services); + bool is_timestamp_valid(double current_time); void determine_gps_mode(double current_time); + bool are_inputs_ok(); + void observation_timings_invalid_reset(); - kj::ArrayPtr get_message_bytes(MessageBuilder& msg_builder, uint64_t logMonoTime, - bool inputsOK, bool sensorsOK, bool gpsOK); + kj::ArrayPtr get_message_bytes(MessageBuilder& msg_builder, + bool inputsOK, bool sensorsOK, bool gpsOK, bool msgValid); void build_live_location(cereal::LiveLocationKalman::Builder& fix); Eigen::VectorXd get_position_geodetic(); @@ -45,8 +50,8 @@ public: void handle_msg_bytes(const char *data, const size_t size); void handle_msg(const cereal::Event::Reader& log); - void handle_sensors(double current_time, const capnp::List::Reader& log); - void handle_gps(double current_time, const cereal::GpsLocationData::Reader& log); + void handle_sensor(double current_time, const cereal::SensorEventData::Reader& log); + void handle_gps(double current_time, const cereal::GpsLocationData::Reader& log, const double sensor_time_offset); void handle_car_state(double current_time, const cereal::CarState::Reader& log); void handle_cam_odo(double current_time, const cereal::CameraOdometry::Reader& log); void handle_live_calib(double current_time, const cereal::LiveCalibrationData::Reader& log); @@ -68,8 +73,11 @@ private: std::unique_ptr converter; int64_t unix_timestamp_millis = 0; - double last_gps_fix = 0; double reset_tracker = 0.0; bool device_fell = false; bool gps_mode = false; + bool gps_valid = false; + bool ublox_available = true; + bool observation_timings_invalid = false; + std::map observation_values_invalid; }; diff --git a/selfdrive/locationd/models/car_kf.py b/selfdrive/locationd/models/car_kf.py index 75534efa5a..3faf4f8d4e 100755 --- a/selfdrive/locationd/models/car_kf.py +++ b/selfdrive/locationd/models/car_kf.py @@ -7,7 +7,7 @@ import numpy as np from selfdrive.controls.lib.vehicle_model import ACCELERATION_DUE_TO_GRAVITY from selfdrive.locationd.models.constants import ObservationKind -from selfdrive.swaglog import cloudlog +from system.swaglog import cloudlog from rednose.helpers.kalmanfilter import KalmanFilter @@ -15,7 +15,7 @@ if __name__ == '__main__': # Generating sympy import sympy as sp from rednose.helpers.ekf_sym import gen_code else: - from rednose.helpers.ekf_sym_pyx import EKF_sym # pylint: disable=no-name-in-module, import-error + from rednose.helpers.ekf_sym_pyx import EKF_sym_pyx # pylint: disable=no-name-in-module, import-error i = 0 @@ -171,7 +171,7 @@ class CarKalman(KalmanFilter): if P_initial is not None: self.P_initial = P_initial # init filter - self.filter = EKF_sym(generated_dir, self.name, self.Q, self.initial_x, self.P_initial, dim_state, dim_state_err, global_vars=self.global_vars, logger=cloudlog) + self.filter = EKF_sym_pyx(generated_dir, self.name, self.Q, self.initial_x, self.P_initial, dim_state, dim_state_err, global_vars=self.global_vars, logger=cloudlog) if __name__ == "__main__": diff --git a/selfdrive/locationd/models/constants.py b/selfdrive/locationd/models/constants.py index f22f503ee0..6d328ce6f5 100644 --- a/selfdrive/locationd/models/constants.py +++ b/selfdrive/locationd/models/constants.py @@ -27,9 +27,10 @@ class ObservationKind: PSEUDORANGE_RATE_GLONASS = 21 PSEUDORANGE = 22 PSEUDORANGE_RATE = 23 - ECEF_VEL = 31 + ECEF_VEL = 35 ECEF_ORIENTATION_FROM_GPS = 32 NO_ACCEL = 33 + ORB_FEATURES_WIDE = 34 ROAD_FRAME_XY_SPEED = 24 # (x, y) [m/s] ROAD_FRAME_YAW_RATE = 25 # [rad/s] @@ -63,6 +64,8 @@ class ObservationKind: 'imu frame eulers', 'GLONASS pseudorange', 'GLONASS pseudorange rate', + 'pseudorange', + 'pseudorange rate', 'Road Frame x,y speed', 'Road Frame yaw rate', @@ -72,6 +75,10 @@ class ObservationKind: 'Steer Ratio', 'Road Frame x speed', 'Road Roll', + 'ECEF orientation from GPS', + 'NO accel', + 'ORB features wide camera', + 'ECEF_VEL', ] @classmethod diff --git a/selfdrive/locationd/models/gnss_helpers.py b/selfdrive/locationd/models/gnss_helpers.py new file mode 100644 index 0000000000..b6c1771ec6 --- /dev/null +++ b/selfdrive/locationd/models/gnss_helpers.py @@ -0,0 +1,19 @@ +import numpy as np +from laika.raw_gnss import GNSSMeasurement + +def parse_prr(m): + sat_pos_vel_i = np.concatenate((m[GNSSMeasurement.SAT_POS], + m[GNSSMeasurement.SAT_VEL])) + R_i = np.atleast_2d(m[GNSSMeasurement.PRR_STD]**2) + z_i = m[GNSSMeasurement.PRR] + return z_i, R_i, sat_pos_vel_i + +def parse_pr(m): + pseudorange = m[GNSSMeasurement.PR] + pseudorange_stdev = m[GNSSMeasurement.PR_STD] + sat_pos_freq_i = np.concatenate((m[GNSSMeasurement.SAT_POS], + np.array([m[GNSSMeasurement.GLONASS_FREQ]]))) + z_i = np.atleast_1d(pseudorange) + R_i = np.atleast_2d(pseudorange_stdev**2) + return z_i, R_i, sat_pos_freq_i + diff --git a/selfdrive/locationd/models/gnss_kf.py b/selfdrive/locationd/models/gnss_kf.py index 3f4baab7b5..0d661dc321 100755 --- a/selfdrive/locationd/models/gnss_kf.py +++ b/selfdrive/locationd/models/gnss_kf.py @@ -3,11 +3,16 @@ import sys from typing import List import numpy as np -import sympy as sp -from rednose.helpers.ekf_sym import EKF_sym, gen_code from selfdrive.locationd.models.constants import ObservationKind -from selfdrive.locationd.models.loc_kf import parse_pr, parse_prr +from selfdrive.locationd.models.gnss_helpers import parse_pr, parse_prr + +if __name__ == '__main__': # Generating sympy + import sympy as sp + from rednose.helpers.ekf_sym import gen_code +else: + from rednose.helpers.ekf_sym_pyx import EKF_sym_pyx # pylint: disable=no-name-in-module,import-error + from rednose.helpers.ekf_sym import EKF_sym # pylint: disable=no-name-in-module,import-error class States(): @@ -34,12 +39,6 @@ class GNSSKalman(): 1e14, (100)**2, (0.2)**2, (10)**2, (1)**2]) - # process noise - Q = np.diag([0.03**2, 0.03**2, 0.03**2, - 3**2, 3**2, 3**2, - (.1)**2, (0)**2, (0.005)**2, - .1**2, (.01)**2]) - maha_test_kinds: List[int] = [] # ObservationKind.PSEUDORANGE_RATE, ObservationKind.PSEUDORANGE, ObservationKind.PSEUDORANGE_GLONASS] @staticmethod @@ -115,12 +114,20 @@ class GNSSKalman(): gen_code(generated_dir, name, f_sym, dt, state_sym, obs_eqs, dim_state, dim_state, maha_test_kinds=maha_test_kinds) - def __init__(self, generated_dir): + def __init__(self, generated_dir, cython=False, erratic_clock=False): + # process noise + clock_error_drift = 100.0 if erratic_clock else 0.1 + self.Q = np.diag([0.03**2, 0.03**2, 0.03**2, + 3**2, 3**2, 3**2, + (clock_error_drift)**2, (0)**2, (0.005)**2, + .1**2, (.01)**2]) + self.dim_state = self.x_initial.shape[0] # init filter - self.filter = EKF_sym(generated_dir, self.name, self.Q, self.x_initial, self.P_initial, self.dim_state, - self.dim_state, maha_test_kinds=self.maha_test_kinds) + filter_cls = EKF_sym_pyx if cython else EKF_sym + self.filter = filter_cls(generated_dir, self.name, self.Q, self.x_initial, self.P_initial, self.dim_state, + self.dim_state, maha_test_kinds=self.maha_test_kinds) self.init_state(GNSSKalman.x_initial, covs=GNSSKalman.P_initial) @property diff --git a/selfdrive/locationd/models/live_kf.cc b/selfdrive/locationd/models/live_kf.cc index 5ff0f26995..f8c03365e1 100755 --- a/selfdrive/locationd/models/live_kf.cc +++ b/selfdrive/locationd/models/live_kf.cc @@ -44,7 +44,7 @@ LiveKalman::LiveKalman() { // init filter this->filter = std::make_shared(this->name, get_mapmat(this->Q), get_mapvec(this->initial_x), get_mapmat(initial_P), this->dim_state, this->dim_state_err, 0, 0, 0, std::vector(), - std::vector{3}, std::vector(), 0.2); + std::vector{3}, std::vector(), 0.8); } void LiveKalman::init_state(VectorXd& state, VectorXd& covs_diag, double filter_time) { diff --git a/selfdrive/locationd/models/loc_kf.py b/selfdrive/locationd/models/loc_kf.py index 199cc7e205..4c947422b1 100755 --- a/selfdrive/locationd/models/loc_kf.py +++ b/selfdrive/locationd/models/loc_kf.py @@ -5,33 +5,14 @@ import sys import numpy as np import sympy as sp -from selfdrive.locationd.models.constants import ObservationKind from rednose.helpers.ekf_sym import EKF_sym, gen_code from rednose.helpers.lst_sq_computer import LstSqComputer from rednose.helpers.sympy_helpers import euler_rotate, quat_matrix_r, quat_rotate -EARTH_GM = 3.986005e14 # m^3/s^2 (gravitational constant * mass of earth) - - -def parse_prr(m): - from laika.raw_gnss import GNSSMeasurement - sat_pos_vel_i = np.concatenate((m[GNSSMeasurement.SAT_POS], - m[GNSSMeasurement.SAT_VEL])) - R_i = np.atleast_2d(m[GNSSMeasurement.PRR_STD]**2) - z_i = m[GNSSMeasurement.PRR] - return z_i, R_i, sat_pos_vel_i - - -def parse_pr(m): - from laika.raw_gnss import GNSSMeasurement - pseudorange = m[GNSSMeasurement.PR] - pseudorange_stdev = m[GNSSMeasurement.PR_STD] - sat_pos_freq_i = np.concatenate((m[GNSSMeasurement.SAT_POS], - np.array([m[GNSSMeasurement.GLONASS_FREQ]]))) - z_i = np.atleast_1d(pseudorange) - R_i = np.atleast_2d(pseudorange_stdev**2) - return z_i, R_i, sat_pos_freq_i +from selfdrive.locationd.models.constants import ObservationKind +from selfdrive.locationd.models.gnss_helpers import parse_pr, parse_prr +EARTH_GM = 3.986005e14 # m^3/s^2 (gravitational constant * mass of earth) class States(): ECEF_POS = slice(0, 3) # x, y and z in ECEF in meters @@ -44,13 +25,15 @@ class States(): ODO_SCALE_UNUSED = slice(18, 19) # odometer scale ACCELERATION = slice(19, 22) # Acceleration in device frame in m/s**2 FOCAL_SCALE_UNUSED = slice(22, 23) # focal length scale - IMU_OFFSET = slice(23, 26) # imu offset angles in radians + IMU_FROM_DEVICE_EULER = slice(23, 26) # imu offset angles in radians GLONASS_BIAS = slice(26, 27) # GLONASS bias in m expressed as bias + freq_num*freq_slope GLONASS_FREQ_SLOPE = slice(27, 28) # GLONASS bias in m expressed as bias + freq_num*freq_slope CLOCK_ACCELERATION = slice(28, 29) # clock acceleration in light-meters/s**2, ACCELEROMETER_SCALE_UNUSED = slice(29, 30) # scale of mems accelerometer ACCELEROMETER_BIAS = slice(30, 33) # bias of mems accelerometer - # We curently do not use ACCELEROMETER_SCALE to avoid instability due to too many free variables (ACCELEROMETER_SCALE, ACCELEROMETER_BIAS, IMU_OFFSET). + # TODO the offset is likely a translation of the sensor, not a rotation of the camera + WIDE_FROM_DEVICE_EULER = slice(33, 36) # wide camera offset angles in radians (tici only) + # We currently do not use ACCELEROMETER_SCALE to avoid instability due to too many free variables (ACCELEROMETER_SCALE, ACCELEROMETER_BIAS, IMU_FROM_DEVICE_EULER). # From experiments we see that ACCELEROMETER_BIAS is more correct than ACCELEROMETER_SCALE # Error-state has different slices because it is an ESKF @@ -64,12 +47,13 @@ class States(): ODO_SCALE_ERR_UNUSED = slice(17, 18) ACCELERATION_ERR = slice(18, 21) FOCAL_SCALE_ERR_UNUSED = slice(21, 22) - IMU_OFFSET_ERR = slice(22, 25) + IMU_FROM_DEVICE_EULER_ERR = slice(22, 25) GLONASS_BIAS_ERR = slice(25, 26) GLONASS_FREQ_SLOPE_ERR = slice(26, 27) CLOCK_ACCELERATION_ERR = slice(27, 28) ACCELEROMETER_SCALE_ERR_UNUSED = slice(28, 29) ACCELEROMETER_BIAS_ERR = slice(29, 32) + WIDE_FROM_DEVICE_EULER_ERR = slice(32, 35) class LocKalman(): @@ -87,6 +71,7 @@ class LocKalman(): 0, 0, 0, 1, + 0, 0, 0, 0, 0, 0], dtype=np.float64) # state covariance @@ -99,30 +84,16 @@ class LocKalman(): 0.02**2, 2**2, 2**2, 2**2, 0.01**2, - (0.01)**2, (0.01)**2, (0.01)**2, + 0.01**2, 0.01**2, 0.01**2, 10**2, 1**2, 0.2**2, 0.05**2, - 0.05**2, 0.05**2, 0.05**2]) - - # process noise - Q = np.diag([0.03**2, 0.03**2, 0.03**2, - 0.0**2, 0.0**2, 0.0**2, - 0.0**2, 0.0**2, 0.0**2, - 0.1**2, 0.1**2, 0.1**2, - (.1)**2, (0.0)**2, - (0.005 / 100)**2, (0.005 / 100)**2, (0.005 / 100)**2, - (0.02 / 100)**2, - 3**2, 3**2, 3**2, - 0.001**2, - (0.05 / 60)**2, (0.05 / 60)**2, (0.05 / 60)**2, - (.1)**2, (.01)**2, - 0.005**2, - (0.02 / 100)**2, - (0.005 / 100)**2, (0.005 / 100)**2, (0.005 / 100)**2]) + 0.05**2, 0.05**2, 0.05**2, + 0.01**2, 0.01**2, 0.01**2]) + # measurements that need to pass mahalanobis distance outlier rejector - maha_test_kinds = [ObservationKind.ORB_FEATURES] # , ObservationKind.PSEUDORANGE, ObservationKind.PSEUDORANGE_RATE] + maha_test_kinds = [ObservationKind.ORB_FEATURES, ObservationKind.ORB_FEATURES_WIDE] # , ObservationKind.PSEUDORANGE, ObservationKind.PSEUDORANGE_RATE] dim_augment = 7 dim_augment_err = 6 @@ -153,13 +124,15 @@ class LocKalman(): cd = state[States.CLOCK_DRIFT, :] roll_bias, pitch_bias, yaw_bias = state[States.GYRO_BIAS, :] acceleration = state[States.ACCELERATION, :] - imu_angles = state[States.IMU_OFFSET, :] - imu_angles[0, 0] = 0 - imu_angles[2, 0] = 0 + imu_from_device_euler = state[States.IMU_FROM_DEVICE_EULER, :] + imu_from_device_euler[0, 0] = 0 # not observable enough + imu_from_device_euler[2, 0] = 0 # not observable enough glonass_bias = state[States.GLONASS_BIAS, :] glonass_freq_slope = state[States.GLONASS_FREQ_SLOPE, :] ca = state[States.CLOCK_ACCELERATION, :] accel_bias = state[States.ACCELEROMETER_BIAS, :] + wide_from_device_euler = state[States.WIDE_FROM_DEVICE_EULER, :] + wide_from_device_euler[0, 0] = 0 # not observable enough dt = sp.Symbol('dt') @@ -284,15 +257,15 @@ class LocKalman(): los_vector[2] * (sat_vz - vz) + cd[0]]) - imu_rot = euler_rotate(*imu_angles) - h_gyro_sym = imu_rot * sp.Matrix([vroll + roll_bias, + imu_from_device = euler_rotate(*imu_from_device_euler) + h_gyro_sym = imu_from_device * sp.Matrix([vroll + roll_bias, vpitch + pitch_bias, vyaw + yaw_bias]) pos = sp.Matrix([x, y, z]) # add 1 for stability, prevent division by 0 gravity = quat_rot.T * ((EARTH_GM / ((x**2 + y**2 + z**2 + 1)**(3.0 / 2.0))) * pos) - h_acc_sym = imu_rot * (gravity + acceleration + accel_bias) + h_acc_sym = imu_from_device * (gravity + acceleration + accel_bias) h_acc_stationary_sym = acceleration h_phone_rot_sym = sp.Matrix([vroll, vpitch, vyaw]) h_relative_motion = sp.Matrix(quat_rot.T * v) @@ -308,22 +281,29 @@ class LocKalman(): [h_phone_rot_sym, ObservationKind.CAMERA_ODO_ROTATION, None], [h_acc_stationary_sym, ObservationKind.NO_ACCEL, None]] + wide_from_device = euler_rotate(*wide_from_device_euler) # MSCKF configuration if N > 0: # experimentally found this is correct value for imx298 with 910 focal length # this is a variable so it can change with focus, but we disregard that for now + # TODO: this isn't correct for tici focal_scale = 1.01 # Add observation functions for orb feature tracks track_epos_sym = sp.MatrixSymbol('track_epos_sym', 3, 1) track_x, track_y, track_z = track_epos_sym h_track_sym = sp.Matrix(np.zeros(((1 + N) * 2, 1))) + h_track_wide_cam_sym = sp.Matrix(np.zeros(((1 + N) * 2, 1))) + track_pos_sym = sp.Matrix([track_x - x, track_y - y, track_z - z]) track_pos_rot_sym = quat_rot.T * track_pos_sym + track_pos_rot_wide_cam_sym = wide_from_device * track_pos_rot_sym h_track_sym[-2:, :] = sp.Matrix([focal_scale * (track_pos_rot_sym[1] / track_pos_rot_sym[0]), - focal_scale * (track_pos_rot_sym[2] / track_pos_rot_sym[0])]) + focal_scale * (track_pos_rot_sym[2] / track_pos_rot_sym[0])]) + h_track_wide_cam_sym[-2:, :] = sp.Matrix([focal_scale * (track_pos_rot_wide_cam_sym[1] / track_pos_rot_wide_cam_sym[0]), + focal_scale * (track_pos_rot_wide_cam_sym[2] / track_pos_rot_wide_cam_sym[0])]) h_msckf_test_sym = sp.Matrix(np.zeros(((1 + N) * 3, 1))) - h_msckf_test_sym[-3:, :] = sp.Matrix([track_x - x, track_y - y, track_z - z]) + h_msckf_test_sym[-3:, :] = track_pos_sym for n in range(N): idx = dim_main + n * dim_augment @@ -333,21 +313,45 @@ class LocKalman(): quat_rot = quat_rotate(*q) track_pos_sym = sp.Matrix([track_x - x, track_y - y, track_z - z]) track_pos_rot_sym = quat_rot.T * track_pos_sym + track_pos_rot_wide_cam_sym = wide_from_device * track_pos_rot_sym h_track_sym[n * 2:n * 2 + 2, :] = sp.Matrix([focal_scale * (track_pos_rot_sym[1] / track_pos_rot_sym[0]), focal_scale * (track_pos_rot_sym[2] / track_pos_rot_sym[0])]) - h_msckf_test_sym[n * 3:n * 3 + 3, :] = sp.Matrix([track_x - x, track_y - y, track_z - z]) + h_track_wide_cam_sym[n * 2: n * 2 + 2, :] = sp.Matrix([focal_scale * (track_pos_rot_wide_cam_sym[1] / track_pos_rot_wide_cam_sym[0]), + focal_scale * (track_pos_rot_wide_cam_sym[2] / track_pos_rot_wide_cam_sym[0])]) + h_msckf_test_sym[n * 3:n * 3 + 3, :] = track_pos_sym obs_eqs.append([h_msckf_test_sym, ObservationKind.MSCKF_TEST, track_epos_sym]) obs_eqs.append([h_track_sym, ObservationKind.ORB_FEATURES, track_epos_sym]) + obs_eqs.append([h_track_wide_cam_sym, ObservationKind.ORB_FEATURES_WIDE, track_epos_sym]) obs_eqs.append([h_track_sym, ObservationKind.FEATURE_TRACK_TEST, track_epos_sym]) - msckf_params = [dim_main, dim_augment, dim_main_err, dim_augment_err, N, [ObservationKind.MSCKF_TEST, ObservationKind.ORB_FEATURES]] + msckf_params = [dim_main, dim_augment, dim_main_err, dim_augment_err, N, [ObservationKind.MSCKF_TEST, ObservationKind.ORB_FEATURES, ObservationKind.ORB_FEATURES_WIDE]] else: msckf_params = None gen_code(generated_dir, name, f_sym, dt, state_sym, obs_eqs, dim_state, dim_state_err, eskf_params, msckf_params, maha_test_kinds) - def __init__(self, generated_dir, N=4, max_tracks=3000): + def __init__(self, generated_dir, N=4, erratic_clock=False): name = f"{self.name}_{N}" + + # process noise + clock_error_drift = 100.0 if erratic_clock else 0.1 + self.Q = np.diag([0.03**2, 0.03**2, 0.03**2, + 0.0**2, 0.0**2, 0.0**2, + 0.0**2, 0.0**2, 0.0**2, + 0.1**2, 0.1**2, 0.1**2, + (clock_error_drift)**2, (0)**2, + (0.005 / 100)**2, (0.005 / 100)**2, (0.005 / 100)**2, + (0.02 / 100)**2, + 3**2, 3**2, 3**2, + 0.001**2, + (0.05 / 60)**2, (0.05 / 60)**2, (0.05 / 60)**2, + (.1)**2, (.01)**2, + 0.005**2, + (0.02 / 100)**2, + (0.005 / 100)**2, (0.005 / 100)**2, (0.005 / 100)**2, + (0.05 / 60)**2, (0.05 / 60)**2, (0.05 / 60)**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]), ObservationKind.PHONE_ACCEL: np.diag([.5**2, .5**2, .5**2]), @@ -367,7 +371,6 @@ class LocKalman(): if self.N > 0: x_initial, P_initial, Q = self.pad_augmented(self.x_initial, self.P_initial, self.Q) # lgtm[py/mismatched-multiple-assignment] pylint: disable=unbalanced-tuple-unpacking self.computer = LstSqComputer(generated_dir, N) - self.max_tracks = max_tracks self.quaternion_idxs = [3, ] + [(self.dim_main + i * self.dim_augment + 3)for i in range(self.N)] @@ -427,7 +430,7 @@ class LocKalman(): r = self.predict_and_update_pseudorange(data, t, kind) elif kind == ObservationKind.PSEUDORANGE_RATE_GPS or kind == ObservationKind.PSEUDORANGE_RATE_GLONASS: r = self.predict_and_update_pseudorange_rate(data, t, kind) - elif kind == ObservationKind.ORB_FEATURES: + elif kind == ObservationKind.ORB_FEATURES or kind == ObservationKind.ORB_FEATURES_WIDE: r = self.predict_and_update_orb_features(data, t, kind) elif kind == ObservationKind.MSCKF_TEST: r = self.predict_and_update_msckf_test(data, t, kind) @@ -474,14 +477,14 @@ class LocKalman(): z = trans[:, :3] R = np.zeros((len(trans), 3, 3)) for i, _ in enumerate(z): - R[i, :, :] = np.diag(trans[i, 3:]**2) + 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) + R[i, :, :] = np.diag(rot[i, 3:]**2) return self.filter.predict_and_update_batch(t, kind, z, R) def predict_and_update_orb_features(self, tracks, t, kind): @@ -492,8 +495,12 @@ class LocKalman(): ecef_pos[:] = np.nan poses = self.x[self.dim_main:].reshape((-1, 7)) times = tracks.reshape((len(tracks), self.N + 1, 4))[:, :, 0] - good_counter = 0 - if times.any() and np.allclose(times[0, :-1], self.filter.get_augment_times(), rtol=1e-6): + if kind==ObservationKind.ORB_FEATURES: + pt_std = 0.005 + else: + pt_std = 0.02 + if times.any(): + assert np.allclose(times[0, :-1], self.filter.get_augment_times(), atol=1e-7, rtol=0.0) for i, track in enumerate(tracks): img_positions = track.reshape((self.N + 1, 4))[:, 2:] @@ -502,23 +509,24 @@ class LocKalman(): ecef_pos[i] = self.computer.compute_pos(poses, img_positions[:-1]) z[i] = img_positions.flatten() - R[i, :, :] = np.diag([0.005**2] * (k)) - if np.isfinite(ecef_pos[i][0]): - good_counter += 1 - if good_counter > self.max_tracks: - break + R[i, :, :] = np.diag([pt_std**2] * (k)) + good_idxs = np.all(np.isfinite(ecef_pos), axis=1) + + # This code relies on wide and narrow orb features being captured at the same time, + # and wide features to be processed first. + ret = self.filter.predict_and_update_batch(t, kind, z[good_idxs], R[good_idxs], ecef_pos[good_idxs], + augment=kind==ObservationKind.ORB_FEATURES) + if ret is None: + return + # have to do some weird stuff here to keep # to have the observations input from mesh3d # consistent with the outputs of the filter # Probably should be replaced, not sure how. - ret = self.filter.predict_and_update_batch(t, kind, z[good_idxs], R[good_idxs], ecef_pos[good_idxs], augment=True) - if ret is None: - return - y_full = np.zeros((z.shape[0], z.shape[1] - 3)) if sum(good_idxs) > 0: - y_full[good_idxs] = np.array(ret[6]) + y_full[good_idxs] = np.array(ret[6]) ret = ret[:6] + (y_full, z, ecef_pos) return ret diff --git a/selfdrive/locationd/paramsd.py b/selfdrive/locationd/paramsd.py index 0efb4d04be..9bd4ed0837 100755 --- a/selfdrive/locationd/paramsd.py +++ b/selfdrive/locationd/paramsd.py @@ -1,23 +1,23 @@ #!/usr/bin/env python3 -import gc import math - import json import numpy as np import cereal.messaging as messaging from cereal import car from common.params import Params, put_nonblocking -from common.realtime import set_realtime_priority, DT_MDL +from common.realtime import config_realtime_process, DT_MDL from common.numpy_fast import clip from selfdrive.locationd.models.car_kf import CarKalman, ObservationKind, States from selfdrive.locationd.models.constants import GENERATED_DIR -from selfdrive.swaglog import cloudlog +from system.swaglog import cloudlog MAX_ANGLE_OFFSET_DELTA = 20 * DT_MDL # Max 20 deg/s ROLL_MAX_DELTA = np.radians(20.0) * DT_MDL # 20deg in 1 second is well within curvature limits ROLL_MIN, ROLL_MAX = math.radians(-10), math.radians(10) +LATERAL_ACC_SENSOR_THRESHOLD = 4.0 + class ParamsLearner: def __init__(self, CP, steer_ratio, stiffness_factor, angle_offset, P_initial=None): @@ -33,6 +33,8 @@ class ParamsLearner: self.active = False self.speed = 0.0 + self.yaw_rate = 0.0 + self.yaw_rate_std = 0.0 self.roll = 0.0 self.steering_pressed = False self.steering_angle = 0.0 @@ -41,8 +43,8 @@ class ParamsLearner: def handle_log(self, t, which, msg): if which == 'liveLocationKalman': - yaw_rate = msg.angularVelocityCalibrated.value[2] - yaw_rate_std = msg.angularVelocityCalibrated.std[2] + self.yaw_rate = msg.angularVelocityCalibrated.value[2] + self.yaw_rate_std = msg.angularVelocityCalibrated.std[2] localizer_roll = msg.orientationNED.value[0] localizer_roll_std = np.radians(1) if np.isnan(msg.orientationNED.std[0]) else msg.orientationNED.std[0] @@ -58,17 +60,17 @@ class ParamsLearner: self.roll = clip(roll, self.roll - ROLL_MAX_DELTA, self.roll + ROLL_MAX_DELTA) yaw_rate_valid = msg.angularVelocityCalibrated.valid - yaw_rate_valid = yaw_rate_valid and 0 < yaw_rate_std < 10 # rad/s - yaw_rate_valid = yaw_rate_valid and abs(yaw_rate) < 1 # rad/s + yaw_rate_valid = yaw_rate_valid and 0 < self.yaw_rate_std < 10 # rad/s + yaw_rate_valid = yaw_rate_valid and abs(self.yaw_rate) < 1 # rad/s if self.active: - if msg.inputsOK and msg.posenetOK: + if msg.posenetOK: if yaw_rate_valid: self.kf.predict_and_observe(t, ObservationKind.ROAD_FRAME_YAW_RATE, - np.array([[-yaw_rate]]), - np.array([np.atleast_2d(yaw_rate_std**2)])) + np.array([[-self.yaw_rate]]), + np.array([np.atleast_2d(self.yaw_rate_std**2)])) self.kf.predict_and_observe(t, ObservationKind.ROAD_ROLL, @@ -90,7 +92,7 @@ class ParamsLearner: self.speed = msg.vEgo in_linear_region = abs(self.steering_angle) < 45 or not self.steering_pressed - self.active = self.speed > 5 and in_linear_region + self.active = self.speed > 1 and in_linear_region if self.active: self.kf.predict_and_observe(t, ObservationKind.STEER_ANGLE, np.array([[math.radians(msg.steeringAngleDeg)]])) @@ -103,8 +105,7 @@ class ParamsLearner: def main(sm=None, pm=None): - gc.disable() - set_realtime_priority(5) + config_realtime_process([0, 1, 2, 3], 5) if sm is None: sm = messaging.SubMaster(['liveLocationKalman', 'carState'], poll=['liveLocationKalman']) @@ -160,10 +161,11 @@ def main(sm=None, pm=None): while True: sm.update() - for which in sorted(sm.updated.keys(), key=lambda x: sm.logMonoTime[x]): - if sm.updated[which]: - t = sm.logMonoTime[which] * 1e-9 - learner.handle_log(t, which, sm[which]) + if sm.all_checks(): + for which in sorted(sm.updated.keys(), key=lambda x: sm.logMonoTime[x]): + if sm.updated[which]: + t = sm.logMonoTime[which] * 1e-9 + learner.handle_log(t, which, sm[which]) if sm.updated['liveLocationKalman']: x = learner.kf.x @@ -175,13 +177,14 @@ def main(sm=None, pm=None): angle_offset_average = clip(math.degrees(x[States.ANGLE_OFFSET]), angle_offset_average - MAX_ANGLE_OFFSET_DELTA, angle_offset_average + MAX_ANGLE_OFFSET_DELTA) angle_offset = clip(math.degrees(x[States.ANGLE_OFFSET] + x[States.ANGLE_OFFSET_FAST]), angle_offset - MAX_ANGLE_OFFSET_DELTA, angle_offset + MAX_ANGLE_OFFSET_DELTA) + # Account for the opposite signs of the yaw rates + sensors_valid = bool(abs(learner.speed * (x[States.YAW_RATE] + learner.yaw_rate)) < LATERAL_ACC_SENSOR_THRESHOLD) msg = messaging.new_message('liveParameters') - msg.logMonoTime = sm.logMonoTime['carState'] liveParameters = msg.liveParameters liveParameters.posenetValid = True - liveParameters.sensorValid = True + liveParameters.sensorValid = sensors_valid liveParameters.steerRatio = float(x[States.STEER_RATIO]) liveParameters.stiffnessFactor = float(x[States.STIFFNESS]) liveParameters.roll = float(x[States.ROAD_ROLL]) @@ -198,6 +201,8 @@ def main(sm=None, pm=None): liveParameters.angleOffsetAverageStd = float(P[States.ANGLE_OFFSET]) liveParameters.angleOffsetFastStd = float(P[States.ANGLE_OFFSET_FAST]) + msg.valid = sm.all_checks() + if sm.frame % 1200 == 0: # once a minute params = { 'carFingerprint': CP.carFingerprint, diff --git a/selfdrive/locationd/test/_test_locationd_lib.py b/selfdrive/locationd/test/_test_locationd_lib.py new file mode 100755 index 0000000000..c4a053bbc6 --- /dev/null +++ b/selfdrive/locationd/test/_test_locationd_lib.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +"""This test can't be run together with other locationd tests. +cffi.dlopen breaks the list of registered filters.""" +import os +import random +import unittest + +from cffi import FFI + +import cereal.messaging as messaging +from cereal import log + +SENSOR_DECIMATION = 1 +VISION_DECIMATION = 1 + +LIBLOCATIOND_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '../liblocationd.so')) + + +class TestLocationdLib(unittest.TestCase): + def setUp(self): + header = '''typedef ...* Localizer_t; +Localizer_t localizer_init(); +void localizer_get_message_bytes(Localizer_t localizer, bool inputsOK, bool sensorsOK, bool gpsOK, bool msgValid, char *buff, size_t buff_size); +void localizer_handle_msg_bytes(Localizer_t localizer, const char *data, size_t size);''' + + self.ffi = FFI() + self.ffi.cdef(header) + self.lib = self.ffi.dlopen(LIBLOCATIOND_PATH) + + self.localizer = self.lib.localizer_init() + + self.buff_size = 2048 + self.msg_buff = self.ffi.new(f'char[{self.buff_size}]') + + def localizer_handle_msg(self, msg_builder): + bytstr = msg_builder.to_bytes() + self.lib.localizer_handle_msg_bytes(self.localizer, self.ffi.from_buffer(bytstr), len(bytstr)) + + def localizer_get_msg(self, t=0, inputsOK=True, sensorsOK=True, gpsOK=True, msgValid=True): + self.lib.localizer_get_message_bytes(self.localizer, inputsOK, sensorsOK, gpsOK, msgValid, self.ffi.addressof(self.msg_buff, 0), self.buff_size) + return log.Event.from_bytes(self.ffi.buffer(self.msg_buff), nesting_limit=self.buff_size // 8) + + def test_liblocalizer(self): + msg = messaging.new_message('liveCalibration') + msg.liveCalibration.validBlocks = random.randint(1, 10) + msg.liveCalibration.rpyCalib = [random.random() / 10 for _ in range(3)] + + self.localizer_handle_msg(msg) + liveloc = self.localizer_get_msg() + self.assertTrue(liveloc is not None) + + @unittest.skip("temporarily disabled due to false positives") + def test_device_fell(self): + msg = messaging.new_message('accelerometer') + msg.accelerometer.sensor = 1 + msg.accelerometer.timestamp = msg.logMonoTime + msg.accelerometer.type = 1 + msg.accelerometer.init('acceleration') + msg.accelerometer.acceleration.v = [10.0, 0.0, 0.0] # zero with gravity + self.localizer_handle_msg(msg) + + ret = self.localizer_get_msg() + self.assertTrue(ret.liveLocationKalman.deviceStable) + + msg = messaging.new_message('accelerometer') + msg.accelerometer.sensor = 1 + msg.accelerometer.timestamp = msg.logMonoTime + msg.accelerometer.type = 1 + msg.accelerometer.init('acceleration') + msg.accelerometer.acceleration.v = [50.1, 0.0, 0.0] # more than 40 m/s**2 + self.localizer_handle_msg(msg) + + ret = self.localizer_get_msg() + self.assertFalse(ret.liveLocationKalman.deviceStable) + + def test_posenet_spike(self): + for _ in range(SENSOR_DECIMATION): + msg = messaging.new_message('carState') + msg.carState.vEgo = 6.0 # more than 5 m/s + self.localizer_handle_msg(msg) + + ret = self.localizer_get_msg() + self.assertTrue(ret.liveLocationKalman.posenetOK) + + for _ in range(20 * VISION_DECIMATION): # size of hist_old + msg = messaging.new_message('cameraOdometry') + msg.cameraOdometry.rot = [0.0, 0.0, 0.0] + msg.cameraOdometry.rotStd = [0.1, 0.1, 0.1] + msg.cameraOdometry.trans = [0.0, 0.0, 0.0] + msg.cameraOdometry.transStd = [2.0, 0.1, 0.1] + self.localizer_handle_msg(msg) + + for _ in range(20 * VISION_DECIMATION): # size of hist_new + msg = messaging.new_message('cameraOdometry') + msg.cameraOdometry.rot = [0.0, 0.0, 0.0] + msg.cameraOdometry.rotStd = [1.0, 1.0, 1.0] + msg.cameraOdometry.trans = [0.0, 0.0, 0.0] + msg.cameraOdometry.transStd = [10.1, 0.1, 0.1] # more than 4 times larger + self.localizer_handle_msg(msg) + + ret = self.localizer_get_msg() + self.assertFalse(ret.liveLocationKalman.posenetOK) + +if __name__ == "__main__": + unittest.main() + diff --git a/selfdrive/locationd/test/test_laikad.py b/selfdrive/locationd/test/test_laikad.py new file mode 100755 index 0000000000..198ecfe935 --- /dev/null +++ b/selfdrive/locationd/test/test_laikad.py @@ -0,0 +1,265 @@ +#!/usr/bin/env python3 +import time +import unittest +from collections import defaultdict +from datetime import datetime +from unittest import mock +from unittest.mock import Mock, patch + +from common.params import Params +from laika.constants import SECS_IN_DAY +from laika.downloader import DownloadFailed +from laika.ephemeris import EphemerisType, GPSEphemeris +from laika.gps_time import GPSTime +from laika.helpers import ConstellationId, TimeRangeHolder +from laika.raw_gnss import GNSSMeasurement, read_raw_ublox +from selfdrive.locationd.laikad import EPHEMERIS_CACHE, EphemerisSourceType, Laikad, create_measurement_msg +from selfdrive.test.openpilotci import get_url +from tools.lib.logreader import LogReader + + +def get_log(segs=range(0)): + logs = [] + for i in segs: + logs.extend(LogReader(get_url("4cf7a6ad03080c90|2021-09-29--13-46-36", i))) + return [m for m in logs if m.which() == 'ubloxGnss'] + + +def verify_messages(lr, laikad, return_one_success=False): + good_msgs = [] + for m in lr: + msg = laikad.process_gnss_msg(m.ubloxGnss, m.logMonoTime, block=True) + if msg is not None and len(msg.gnssMeasurements.correctedMeasurements) > 0: + good_msgs.append(msg) + if return_one_success: + return msg + return good_msgs + + +def get_first_gps_time(logs): + for m in logs: + if m.ubloxGnss.which == 'measurementReport': + new_meas = read_raw_ublox(m.ubloxGnss.measurementReport) + if len(new_meas) > 0: + return new_meas[0].recv_time + + +def get_measurement_mock(gpstime, sat_ephemeris): + meas = GNSSMeasurement(ConstellationId.GPS, 1, gpstime.week, gpstime.tow, {'C1C': 0., 'D1C': 0.}, {'C1C': 0., 'D1C': 0.}) + # Fake measurement being processed + meas.observables_final = meas.observables + meas.sat_ephemeris = sat_ephemeris + return meas + + +GPS_TIME_PREDICTION_ORBITS_RUSSIAN_SRC = GPSTime.from_datetime(datetime(2022, month=1, day=29, hour=12)) + + +class TestLaikad(unittest.TestCase): + + @classmethod + def setUpClass(cls): + logs = get_log(range(1)) + cls.logs = logs + first_gps_time = get_first_gps_time(logs) + cls.first_gps_time = first_gps_time + + def setUp(self): + Params().remove(EPHEMERIS_CACHE) + + def test_fetch_orbits_non_blocking(self): + gpstime = GPSTime.from_datetime(datetime(2021, month=3, day=1)) + laikad = Laikad() + laikad.fetch_orbits(gpstime, block=False) + laikad.orbit_fetch_future.result(30) + # Get results and save orbits to laikad: + laikad.fetch_orbits(gpstime, block=False) + + ephem = laikad.astro_dog.orbits['G01'][0] + self.assertIsNotNone(ephem) + + laikad.fetch_orbits(gpstime+2*SECS_IN_DAY, block=False) + laikad.orbit_fetch_future.result(30) + # Get results and save orbits to laikad: + laikad.fetch_orbits(gpstime + 2 * SECS_IN_DAY, block=False) + + ephem2 = laikad.astro_dog.orbits['G01'][0] + self.assertIsNotNone(ephem) + self.assertNotEqual(ephem, ephem2) + + def test_fetch_orbits_with_wrong_clocks(self): + laikad = Laikad() + + def check_has_orbits(): + self.assertGreater(len(laikad.astro_dog.orbits), 0) + ephem = laikad.astro_dog.orbits['G01'][0] + self.assertIsNotNone(ephem) + real_current_time = GPSTime.from_datetime(datetime(2021, month=3, day=1)) + wrong_future_clock_time = real_current_time + SECS_IN_DAY + + laikad.fetch_orbits(wrong_future_clock_time, block=True) + check_has_orbits() + self.assertEqual(laikad.last_fetch_orbits_t, wrong_future_clock_time) + + # Test fetching orbits with earlier time + assert real_current_time < laikad.last_fetch_orbits_t + + laikad.astro_dog.orbits = {} + laikad.fetch_orbits(real_current_time, block=True) + check_has_orbits() + self.assertEqual(laikad.last_fetch_orbits_t, real_current_time) + + def test_ephemeris_source_in_msg(self): + data_mock = defaultdict(str) + data_mock['sv_id'] = 1 + + gpstime = GPS_TIME_PREDICTION_ORBITS_RUSSIAN_SRC + laikad = Laikad() + laikad.fetch_orbits(gpstime, block=True) + meas = get_measurement_mock(gpstime, laikad.astro_dog.orbits['R01'][0]) + msg = create_measurement_msg(meas) + self.assertEqual(msg.ephemerisSource.type.raw, EphemerisSourceType.glonassIacUltraRapid) + # Verify gps satellite returns same source + meas = get_measurement_mock(gpstime, laikad.astro_dog.orbits['R01'][0]) + msg = create_measurement_msg(meas) + self.assertEqual(msg.ephemerisSource.type.raw, EphemerisSourceType.glonassIacUltraRapid) + + # Test nasa source by using older date + gpstime = GPSTime.from_datetime(datetime(2021, month=3, day=1)) + laikad = Laikad() + laikad.fetch_orbits(gpstime, block=True) + meas = get_measurement_mock(gpstime, laikad.astro_dog.orbits['G01'][0]) + msg = create_measurement_msg(meas) + self.assertEqual(msg.ephemerisSource.type.raw, EphemerisSourceType.nasaUltraRapid) + + # Test nav source type + ephem = GPSEphemeris(data_mock, gpstime) + meas = get_measurement_mock(gpstime, ephem) + msg = create_measurement_msg(meas) + self.assertEqual(msg.ephemerisSource.type.raw, EphemerisSourceType.nav) + + def test_laika_online(self): + laikad = Laikad(auto_update=True, valid_ephem_types=EphemerisType.ULTRA_RAPID_ORBIT) + correct_msgs = verify_messages(self.logs, laikad) + + correct_msgs_expected = 555 + self.assertEqual(correct_msgs_expected, len(correct_msgs)) + self.assertEqual(correct_msgs_expected, len([m for m in correct_msgs if m.gnssMeasurements.positionECEF.valid])) + + def test_kf_becomes_valid(self): + laikad = Laikad(auto_update=False) + m = self.logs[0] + self.assertFalse(all(laikad.kf_valid(m.logMonoTime * 1e-9))) + kf_valid = False + for m in self.logs: + laikad.process_gnss_msg(m.ubloxGnss, m.logMonoTime, block=True) + kf_valid = all(laikad.kf_valid(m.logMonoTime * 1e-9)) + if kf_valid: + break + self.assertTrue(kf_valid) + + def test_laika_online_nav_only(self): + laikad = Laikad(auto_update=True, valid_ephem_types=EphemerisType.NAV) + # Disable fetch_orbits to test NAV only + laikad.fetch_orbits = Mock() + correct_msgs = verify_messages(self.logs, laikad) + correct_msgs_expected = 559 + self.assertEqual(correct_msgs_expected, len(correct_msgs)) + self.assertEqual(correct_msgs_expected, len([m for m in correct_msgs if m.gnssMeasurements.positionECEF.valid])) + + @mock.patch('laika.downloader.download_and_cache_file') + def test_laika_offline(self, downloader_mock): + downloader_mock.side_effect = DownloadFailed("Mock download failed") + laikad = Laikad(auto_update=False) + laikad.fetch_orbits(GPS_TIME_PREDICTION_ORBITS_RUSSIAN_SRC, block=True) + + @mock.patch('laika.downloader.download_and_cache_file') + def test_download_failed_russian_source(self, downloader_mock): + downloader_mock.side_effect = DownloadFailed + laikad = Laikad(auto_update=False) + correct_msgs = verify_messages(self.logs, laikad) + self.assertEqual(16, len(correct_msgs)) + self.assertEqual(16, len([m for m in correct_msgs if m.gnssMeasurements.positionECEF.valid])) + + def test_laika_get_orbits(self): + laikad = Laikad(auto_update=False) + # Pretend process has loaded the orbits on startup by using the time of the first gps message. + laikad.fetch_orbits(self.first_gps_time, block=True) + self.dict_has_values(laikad.astro_dog.orbits) + + @unittest.skip("Use to debug live data") + def test_laika_get_orbits_now(self): + laikad = Laikad(auto_update=False) + laikad.fetch_orbits(GPSTime.from_datetime(datetime.utcnow()), block=True) + prn = "G01" + self.assertGreater(len(laikad.astro_dog.orbits[prn]), 0) + prn = "R01" + self.assertGreater(len(laikad.astro_dog.orbits[prn]), 0) + print(min(laikad.astro_dog.orbits[prn], key=lambda e: e.epoch).epoch.as_datetime()) + + def test_get_orbits_in_process(self): + laikad = Laikad(auto_update=False) + has_orbits = False + for m in self.logs: + laikad.process_gnss_msg(m.ubloxGnss, m.logMonoTime, block=False) + if laikad.orbit_fetch_future is not None: + laikad.orbit_fetch_future.result() + vals = laikad.astro_dog.orbits.values() + has_orbits = len(vals) > 0 and max([len(v) for v in vals]) > 0 + if has_orbits: + break + self.assertTrue(has_orbits) + self.assertGreater(len(laikad.astro_dog.orbit_fetched_times._ranges), 0) + self.assertEqual(None, laikad.orbit_fetch_future) + + def test_cache(self): + laikad = Laikad(auto_update=True, save_ephemeris=True) + + def wait_for_cache(): + max_time = 2 + while Params().get(EPHEMERIS_CACHE) is None: + time.sleep(0.1) + max_time -= 0.1 + if max_time < 0: + self.fail("Cache has not been written after 2 seconds") + + # Test cache with no ephemeris + laikad.cache_ephemeris(t=GPSTime(0, 0)) + wait_for_cache() + Params().remove(EPHEMERIS_CACHE) + + laikad.astro_dog.get_navs(self.first_gps_time) + laikad.fetch_orbits(self.first_gps_time, block=True) + + # Wait for cache to save + wait_for_cache() + + # Check both nav and orbits separate + laikad = Laikad(auto_update=False, valid_ephem_types=EphemerisType.NAV, save_ephemeris=True) + # Verify orbits and nav are loaded from cache + self.dict_has_values(laikad.astro_dog.orbits) + self.dict_has_values(laikad.astro_dog.nav) + # Verify cache is working for only nav by running a segment + msg = verify_messages(self.logs, laikad, return_one_success=True) + self.assertIsNotNone(msg) + + with patch('selfdrive.locationd.laikad.get_orbit_data', return_value=None) as mock_method: + # Verify no orbit downloads even if orbit fetch times is reset since the cache has recently been saved and we don't want to download high frequently + laikad.astro_dog.orbit_fetched_times = TimeRangeHolder() + laikad.fetch_orbits(self.first_gps_time, block=False) + mock_method.assert_not_called() + + # Verify cache is working for only orbits by running a segment + laikad = Laikad(auto_update=False, valid_ephem_types=EphemerisType.ULTRA_RAPID_ORBIT, save_ephemeris=True) + msg = verify_messages(self.logs, laikad, return_one_success=True) + self.assertIsNotNone(msg) + # Verify orbit data is not downloaded + mock_method.assert_not_called() + + def dict_has_values(self, dct): + self.assertGreater(len(dct), 0) + self.assertGreater(min([len(v) for v in dct.values()]), 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/selfdrive/locationd/test/test_locationd.py b/selfdrive/locationd/test/test_locationd.py index 76f82efc10..7569530211 100755 --- a/selfdrive/locationd/test/test_locationd.py +++ b/selfdrive/locationd/test/test_locationd.py @@ -1,116 +1,28 @@ #!/usr/bin/env python3 -import os import json import random import unittest import time -from cffi import FFI +import capnp -from cereal import log import cereal.messaging as messaging +from cereal.services import service_list from common.params import Params from selfdrive.manager.process_config import managed_processes -SENSOR_DECIMATION = 1 -VISION_DECIMATION = 1 - -LIBLOCATIOND_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '../liblocationd.so')) - - -class TestLocationdLib(unittest.TestCase): - def setUp(self): - header = '''typedef ...* Localizer_t; -Localizer_t localizer_init(); -void localizer_get_message_bytes(Localizer_t localizer, uint64_t logMonoTime, bool inputsOK, bool sensorsOK, bool gpsOK, char *buff, size_t buff_size); -void localizer_handle_msg_bytes(Localizer_t localizer, const char *data, size_t size);''' - - self.ffi = FFI() - self.ffi.cdef(header) - self.lib = self.ffi.dlopen(LIBLOCATIOND_PATH) - - self.localizer = self.lib.localizer_init() - - self.buff_size = 2048 - self.msg_buff = self.ffi.new(f'char[{self.buff_size}]') - - def localizer_handle_msg(self, msg_builder): - bytstr = msg_builder.to_bytes() - self.lib.localizer_handle_msg_bytes(self.localizer, self.ffi.from_buffer(bytstr), len(bytstr)) - - def localizer_get_msg(self, t=0, inputsOK=True, sensorsOK=True, gpsOK=True): - self.lib.localizer_get_message_bytes(self.localizer, t, inputsOK, sensorsOK, gpsOK, self.ffi.addressof(self.msg_buff, 0), self.buff_size) - return log.Event.from_bytes(self.ffi.buffer(self.msg_buff), nesting_limit=self.buff_size // 8) - - def test_liblocalizer(self): - msg = messaging.new_message('liveCalibration') - msg.liveCalibration.validBlocks = random.randint(1, 10) - msg.liveCalibration.rpyCalib = [random.random() / 10 for _ in range(3)] - - self.localizer_handle_msg(msg) - liveloc = self.localizer_get_msg() - self.assertTrue(liveloc is not None) - - @unittest.skip("temporarily disabled due to false positives") - def test_device_fell(self): - msg = messaging.new_message('sensorEvents', 1) - msg.sensorEvents[0].sensor = 1 - msg.sensorEvents[0].timestamp = msg.logMonoTime - msg.sensorEvents[0].type = 1 - msg.sensorEvents[0].init('acceleration') - msg.sensorEvents[0].acceleration.v = [10.0, 0.0, 0.0] # zero with gravity - self.localizer_handle_msg(msg) - - ret = self.localizer_get_msg() - self.assertTrue(ret.liveLocationKalman.deviceStable) - - msg = messaging.new_message('sensorEvents', 1) - msg.sensorEvents[0].sensor = 1 - msg.sensorEvents[0].timestamp = msg.logMonoTime - msg.sensorEvents[0].type = 1 - msg.sensorEvents[0].init('acceleration') - msg.sensorEvents[0].acceleration.v = [50.1, 0.0, 0.0] # more than 40 m/s**2 - self.localizer_handle_msg(msg) - - ret = self.localizer_get_msg() - self.assertFalse(ret.liveLocationKalman.deviceStable) - - def test_posenet_spike(self): - for _ in range(SENSOR_DECIMATION): - msg = messaging.new_message('carState') - msg.carState.vEgo = 6.0 # more than 5 m/s - self.localizer_handle_msg(msg) - - ret = self.localizer_get_msg() - self.assertTrue(ret.liveLocationKalman.posenetOK) - - for _ in range(20 * VISION_DECIMATION): # size of hist_old - msg = messaging.new_message('cameraOdometry') - msg.cameraOdometry.rot = [0.0, 0.0, 0.0] - msg.cameraOdometry.rotStd = [0.1, 0.1, 0.1] - msg.cameraOdometry.trans = [0.0, 0.0, 0.0] - msg.cameraOdometry.transStd = [2.0, 0.1, 0.1] - self.localizer_handle_msg(msg) - - for _ in range(20 * VISION_DECIMATION): # size of hist_new - msg = messaging.new_message('cameraOdometry') - msg.cameraOdometry.rot = [0.0, 0.0, 0.0] - msg.cameraOdometry.rotStd = [1.0, 1.0, 1.0] - msg.cameraOdometry.trans = [0.0, 0.0, 0.0] - msg.cameraOdometry.transStd = [10.1, 0.1, 0.1] # more than 4 times larger - self.localizer_handle_msg(msg) - - ret = self.localizer_get_msg() - self.assertFalse(ret.liveLocationKalman.posenetOK) class TestLocationdProc(unittest.TestCase): MAX_WAITS = 1000 + LLD_MSGS = ['gpsLocationExternal', 'cameraOdometry', 'carState', 'liveCalibration', + 'accelerometer', 'gyroscope', 'magnetometer'] def setUp(self): random.seed(123489234) - self.pm = messaging.PubMaster({'gpsLocationExternal', 'cameraOdometry'}) + self.pm = messaging.PubMaster(self.LLD_MSGS) + Params().put_bool("UbloxAvailable", True) managed_processes['locationd'].prepare() managed_processes['locationd'].start() @@ -127,43 +39,54 @@ class TestLocationdProc(unittest.TestCase): waits_left -= 1 time.sleep(0.0001) - def test_params_gps(self): - # first reset params - Params().put('LastGPSPosition', json.dumps({"latitude": 0.0, "longitude": 0.0, "altitude": 0.0})) + def get_fake_msg(self, name, t): + try: + msg = messaging.new_message(name) + except capnp.lib.capnp.KjException: + msg = messaging.new_message(name, 0) - lat = 30 + (random.random() * 10.0) - lon = -70 + (random.random() * 10.0) - alt = 5 + (random.random() * 10.0) - - for _ in range(1000): # because of kalman filter, send often - msg = messaging.new_message('gpsLocationExternal') - msg.logMonoTime = 0 + if name == "gpsLocationExternal": msg.gpsLocationExternal.flags = 1 msg.gpsLocationExternal.verticalAccuracy = 1.0 msg.gpsLocationExternal.speedAccuracy = 1.0 msg.gpsLocationExternal.bearingAccuracyDeg = 1.0 msg.gpsLocationExternal.vNED = [0.0, 0.0, 0.0] - msg.gpsLocationExternal.latitude = lat - msg.gpsLocationExternal.longitude = lon - msg.gpsLocationExternal.altitude = alt - self.send_msg(msg) - - for _ in range(250): # params is only written so often - msg = messaging.new_message('cameraOdometry') - msg.logMonoTime = 0 + msg.gpsLocationExternal.latitude = self.lat + msg.gpsLocationExternal.longitude = self.lon + msg.gpsLocationExternal.unixTimestampMillis = t * 1e6 + msg.gpsLocationExternal.altitude = self.alt + elif name == 'cameraOdometry': msg.cameraOdometry.rot = [0.0, 0.0, 0.0] msg.cameraOdometry.rotStd = [0.0, 0.0, 0.0] msg.cameraOdometry.trans = [0.0, 0.0, 0.0] msg.cameraOdometry.transStd = [0.0, 0.0, 0.0] - self.send_msg(msg) + msg.logMonoTime = t + return msg + def test_params_gps(self): + # first reset params + Params().remove('LastGPSPosition') + + self.lat = 30 + (random.random() * 10.0) + self.lon = -70 + (random.random() * 10.0) + self.alt = 5 + (random.random() * 10.0) + self.fake_duration = 90 # secs + # get fake messages at the correct frequency, listed in services.py + fake_msgs = [] + for sec in range(self.fake_duration): + for name in self.LLD_MSGS: + for j in range(int(service_list[name].frequency)): + fake_msgs.append(self.get_fake_msg(name, int((sec + j / service_list[name].frequency) * 1e9))) + + for fake_msg in sorted(fake_msgs, key=lambda x: x.logMonoTime): + self.send_msg(fake_msg) time.sleep(1) # wait for async params write lastGPS = json.loads(Params().get('LastGPSPosition')) - self.assertAlmostEqual(lastGPS['latitude'], lat, places=3) - self.assertAlmostEqual(lastGPS['longitude'], lon, places=3) - self.assertAlmostEqual(lastGPS['altitude'], alt, places=3) + self.assertAlmostEqual(lastGPS['latitude'], self.lat, places=3) + self.assertAlmostEqual(lastGPS['longitude'], self.lon, places=3) + self.assertAlmostEqual(lastGPS['altitude'], self.alt, places=3) if __name__ == "__main__": diff --git a/selfdrive/locationd/test/test_ublox_processing.py b/selfdrive/locationd/test/test_ublox_processing.py new file mode 100755 index 0000000000..427003b24c --- /dev/null +++ b/selfdrive/locationd/test/test_ublox_processing.py @@ -0,0 +1,80 @@ +import unittest + +import numpy as np + +from laika import AstroDog +from laika.helpers import ConstellationId +from laika.raw_gnss import calc_pos_fix, correct_measurements, process_measurements, read_raw_ublox +from selfdrive.test.openpilotci import get_url +from tools.lib.logreader import LogReader + + +def get_gnss_measurements(log_reader): + gnss_measurements = [] + for msg in log_reader: + if msg.which() == "ubloxGnss": + ublox_msg = msg.ubloxGnss + if ublox_msg.which == 'measurementReport': + report = ublox_msg.measurementReport + if len(report.measurements) > 0: + gnss_measurements.append(read_raw_ublox(report)) + return gnss_measurements + + +class TestUbloxProcessing(unittest.TestCase): + NUM_TEST_PROCESS_MEAS = 10 + + @classmethod + def setUpClass(cls): + lr = LogReader(get_url("4cf7a6ad03080c90|2021-09-29--13-46-36", 0)) + cls.gnss_measurements = get_gnss_measurements(lr) + + def test_read_ublox_raw(self): + count_gps = 0 + count_glonass = 0 + for measurements in self.gnss_measurements: + for m in measurements: + if m.constellation_id == ConstellationId.GPS: + count_gps += 1 + elif m.constellation_id == ConstellationId.GLONASS: + count_glonass += 1 + + self.assertEqual(count_gps, 5036) + self.assertEqual(count_glonass, 3651) + + def test_get_fix(self): + dog = AstroDog() + position_fix_found = 0 + count_processed_measurements = 0 + count_corrected_measurements = 0 + position_fix_found_after_correcting = 0 + + pos_ests = [] + for measurements in self.gnss_measurements[:self.NUM_TEST_PROCESS_MEAS]: + processed_meas = process_measurements(measurements, dog) + count_processed_measurements += len(processed_meas) + pos_fix = calc_pos_fix(processed_meas) + if len(pos_fix) > 0 and all(pos_fix[0] != 0): + position_fix_found += 1 + + corrected_meas = correct_measurements(processed_meas, pos_fix[0][:3], dog) + count_corrected_measurements += len(corrected_meas) + + pos_fix = calc_pos_fix(corrected_meas) + if len(pos_fix) > 0 and all(pos_fix[0] != 0): + pos_ests.append(pos_fix[0]) + position_fix_found_after_correcting += 1 + + mean_fix = np.mean(np.array(pos_ests)[:, :3], axis=0) + np.testing.assert_allclose(mean_fix, [-2452306.662377, -4778343.136806, 3428550.090557], rtol=0, atol=1) + + # Note that can happen that there are less corrected measurements compared to processed when they are invalid. + # However, not for the current segment + self.assertEqual(position_fix_found, self.NUM_TEST_PROCESS_MEAS) + self.assertEqual(position_fix_found_after_correcting, self.NUM_TEST_PROCESS_MEAS) + self.assertEqual(count_processed_measurements, 69) + self.assertEqual(count_corrected_measurements, 69) + + +if __name__ == "__main__": + unittest.main() diff --git a/selfdrive/locationd/test/ubloxd.py b/selfdrive/locationd/test/ubloxd.py index af9b86127e..82aa502ceb 100755 --- a/selfdrive/locationd/test/ubloxd.py +++ b/selfdrive/locationd/test/ubloxd.py @@ -41,13 +41,13 @@ def configure_ublox(dev): ITMF_config2 = 25374 payload = struct.pack('= min_pts for v, min_pts in zip(self.buckets.values(), self.buckets_min_points.values())) and (self.__len__() >= self.min_points_total) + + def add_point(self, x, y): + for bound_min, bound_max in self.x_bounds: + if (x >= bound_min) and (x < bound_max): + self.buckets[(bound_min, bound_max)].append([x, 1.0, y]) + break + + def get_points(self, num_points=None): + points = np.vstack([x.arr for x in self.buckets.values()]) + if num_points is None: + return points + return points[np.random.choice(np.arange(len(points)), min(len(points), num_points), replace=False)] + + def load_points(self, points): + for x, y in points: + self.add_point(x, y) + + +class TorqueEstimator: + def __init__(self, CP, decimated=False): + self.hist_len = int(HISTORY / DT_MDL) + self.lag = CP.steerActuatorDelay + .2 # from controlsd + if decimated: + self.min_bucket_points = MIN_BUCKET_POINTS / 10 + self.min_points_total = MIN_POINTS_TOTAL_QLOG + self.fit_points = FIT_POINTS_TOTAL_QLOG + else: + self.min_bucket_points = MIN_BUCKET_POINTS + self.min_points_total = MIN_POINTS_TOTAL + self.fit_points = FIT_POINTS_TOTAL + + self.offline_friction = 0.0 + self.offline_latAccelFactor = 0.0 + self.resets = 0.0 + self.use_params = CP.carName in ALLOWED_CARS + + if CP.lateralTuning.which() == 'torque': + self.offline_friction = CP.lateralTuning.torque.friction + self.offline_latAccelFactor = CP.lateralTuning.torque.latAccelFactor + + self.reset() + + initial_params = { + 'latAccelFactor': self.offline_latAccelFactor, + 'latAccelOffset': 0.0, + 'frictionCoefficient': self.offline_friction, + 'points': [] + } + self.decay = MIN_FILTER_DECAY + self.min_lataccel_factor = (1.0 - FACTOR_SANITY) * self.offline_latAccelFactor + self.max_lataccel_factor = (1.0 + FACTOR_SANITY) * self.offline_latAccelFactor + self.min_friction = (1.0 - FRICTION_SANITY) * self.offline_friction + self.max_friction = (1.0 + FRICTION_SANITY) * self.offline_friction + + # try to restore cached params + params = Params() + params_cache = params.get("LiveTorqueCarParams") + torque_cache = params.get("LiveTorqueParameters") + if params_cache is not None and torque_cache is not None: + try: + cache_ltp = log.Event.from_bytes(torque_cache).liveTorqueParameters + cache_CP = car.CarParams.from_bytes(params_cache) + if self.get_restore_key(cache_CP, cache_ltp.version) == self.get_restore_key(CP, VERSION): + if cache_ltp.liveValid: + initial_params = { + 'latAccelFactor': cache_ltp.latAccelFactorFiltered, + 'latAccelOffset': cache_ltp.latAccelOffsetFiltered, + 'frictionCoefficient': cache_ltp.frictionCoefficientFiltered + } + initial_params['points'] = cache_ltp.points + self.decay = cache_ltp.decay + self.filtered_points.load_points(initial_params['points']) + cloudlog.info("restored torque params from cache") + except Exception: + cloudlog.exception("failed to restore cached torque params") + params.remove("LiveTorqueCarParams") + params.remove("LiveTorqueParameters") + + self.filtered_params = {} + for param in initial_params: + self.filtered_params[param] = FirstOrderFilter(initial_params[param], self.decay, DT_MDL) + + def get_restore_key(self, CP, version): + a, b = None, None + if CP.lateralTuning.which() == 'torque': + a = CP.lateralTuning.torque.friction + b = CP.lateralTuning.torque.latAccelFactor + return (CP.carFingerprint, CP.lateralTuning.which(), a, b, version) + + def reset(self): + self.resets += 1.0 + self.invalid_values_tracker = 0.0 + self.decay = MIN_FILTER_DECAY + self.raw_points = defaultdict(lambda: deque(maxlen=self.hist_len)) + self.filtered_points = PointBuckets(x_bounds=STEER_BUCKET_BOUNDS, min_points=self.min_bucket_points, min_points_total=self.min_points_total) + + def estimate_params(self): + points = self.filtered_points.get_points(self.fit_points) + # total least square solution as both x and y are noisy observations + # this is empirically the slope of the hysteresis parallelogram as opposed to the line through the diagonals + try: + _, _, v = np.linalg.svd(points, full_matrices=False) + slope, offset = -v.T[0:2, 2] / v.T[2, 2] + _, spread = np.matmul(points[:, [0, 2]], slope2rot(slope)).T + friction_coeff = np.std(spread) * FRICTION_FACTOR + except np.linalg.LinAlgError as e: + cloudlog.exception(f"Error computing live torque params: {e}") + slope = offset = friction_coeff = np.nan + return slope, offset, friction_coeff + + def update_params(self, params): + self.decay = min(self.decay + DT_MDL, MAX_FILTER_DECAY) + for param, value in params.items(): + self.filtered_params[param].update(value) + self.filtered_params[param].update_alpha(self.decay) + + def is_sane(self, latAccelFactor, latAccelOffset, friction): + if any([val is None or np.isnan(val) for val in [latAccelFactor, latAccelOffset, friction]]): + return False + return (self.max_friction >= friction >= self.min_friction) and\ + (self.max_lataccel_factor >= latAccelFactor >= self.min_lataccel_factor) + + def handle_log(self, t, which, msg): + if which == "carControl": + self.raw_points["carControl_t"].append(t + self.lag) + self.raw_points["steer_torque"].append(-msg.actuatorsOutput.steer) + self.raw_points["active"].append(msg.latActive) + elif which == "carState": + self.raw_points["carState_t"].append(t + self.lag) + self.raw_points["vego"].append(msg.vEgo) + self.raw_points["steer_override"].append(msg.steeringPressed) + elif which == "liveLocationKalman": + if len(self.raw_points['steer_torque']) == self.hist_len: + yaw_rate = msg.angularVelocityCalibrated.value[2] + roll = msg.orientationNED.value[0] + active = np.interp(np.arange(t - MIN_ENGAGE_BUFFER, t, DT_MDL), self.raw_points['carControl_t'], self.raw_points['active']).astype(bool) + steer_override = np.interp(np.arange(t - MIN_ENGAGE_BUFFER, t, DT_MDL), self.raw_points['carState_t'], self.raw_points['steer_override']).astype(bool) + vego = np.interp(t, self.raw_points['carState_t'], self.raw_points['vego']) + steer = np.interp(t, self.raw_points['carControl_t'], self.raw_points['steer_torque']) + lateral_acc = (vego * yaw_rate) - (np.sin(roll) * ACCELERATION_DUE_TO_GRAVITY) + if all(active) and (not any(steer_override)) and (vego > MIN_VEL) and (abs(steer) > STEER_MIN_THRESHOLD) and (abs(lateral_acc) <= LAT_ACC_THRESHOLD): + self.filtered_points.add_point(float(steer), float(lateral_acc)) + + def get_msg(self, valid=True, with_points=False): + msg = messaging.new_message('liveTorqueParameters') + msg.valid = valid + liveTorqueParameters = msg.liveTorqueParameters + liveTorqueParameters.version = VERSION + liveTorqueParameters.useParams = self.use_params + + if self.filtered_points.is_valid(): + latAccelFactor, latAccelOffset, friction_coeff = self.estimate_params() + liveTorqueParameters.latAccelFactorRaw = float(latAccelFactor) + liveTorqueParameters.latAccelOffsetRaw = float(latAccelOffset) + liveTorqueParameters.frictionCoefficientRaw = float(friction_coeff) + + if self.is_sane(latAccelFactor, latAccelOffset, friction_coeff): + liveTorqueParameters.liveValid = True + self.update_params({'latAccelFactor': latAccelFactor, 'latAccelOffset': latAccelOffset, 'frictionCoefficient': friction_coeff}) + self.invalid_values_tracker = max(0.0, self.invalid_values_tracker - 0.5) + else: + cloudlog.exception("Live torque parameters are outside acceptable bounds.") + liveTorqueParameters.liveValid = False + self.invalid_values_tracker += 1.0 + # Reset when ~10 invalid over 5 secs + if self.invalid_values_tracker > MAX_INVALID_THRESHOLD: + # Do not reset the filter as it may cause a drastic jump, just reset points + self.reset() + else: + liveTorqueParameters.liveValid = False + + if with_points: + liveTorqueParameters.points = self.filtered_points.get_points()[:, [0, 2]].tolist() + + liveTorqueParameters.latAccelFactorFiltered = float(self.filtered_params['latAccelFactor'].x) + liveTorqueParameters.latAccelOffsetFiltered = float(self.filtered_params['latAccelOffset'].x) + liveTorqueParameters.frictionCoefficientFiltered = float(self.filtered_params['frictionCoefficient'].x) + liveTorqueParameters.totalBucketPoints = len(self.filtered_points) + liveTorqueParameters.decay = self.decay + liveTorqueParameters.maxResets = self.resets + return msg + + +def main(sm=None, pm=None): + config_realtime_process([0, 1, 2, 3], 5) + + if sm is None: + sm = messaging.SubMaster(['carControl', 'carState', 'liveLocationKalman'], poll=['liveLocationKalman']) + + if pm is None: + pm = messaging.PubMaster(['liveTorqueParameters']) + + params = Params() + CP = car.CarParams.from_bytes(params.get("CarParams", block=True)) + estimator = TorqueEstimator(CP) + + def cache_params(sig, frame): + signal.signal(sig, signal.SIG_DFL) + cloudlog.warning("caching torque params") + + params = Params() + params.put("LiveTorqueCarParams", CP.as_builder().to_bytes()) + + msg = estimator.get_msg(with_points=True) + params.put("LiveTorqueParameters", msg.to_bytes()) + + sys.exit(0) + if "REPLAY" not in os.environ: + signal.signal(signal.SIGINT, cache_params) + + while True: + sm.update() + if sm.all_checks(): + for which in sm.updated.keys(): + if sm.updated[which]: + t = sm.logMonoTime[which] * 1e-9 + estimator.handle_log(t, which, sm[which]) + + # 4Hz driven by liveLocationKalman + if sm.frame % 5 == 0: + pm.send('liveTorqueParameters', estimator.get_msg(valid=sm.all_checks())) + + +if __name__ == "__main__": + main() diff --git a/selfdrive/locationd/ublox_msg.cc b/selfdrive/locationd/ublox_msg.cc index 9e32c7b070..b45dffae33 100644 --- a/selfdrive/locationd/ublox_msg.cc +++ b/selfdrive/locationd/ublox_msg.cc @@ -10,7 +10,7 @@ #include #include -#include "selfdrive/common/swaglog.h" +#include "common/swaglog.h" const double gpsPi = 3.1415926535898; #define UBLOX_MSG_SIZE(hdr) (*(uint16_t *)&hdr[4]) @@ -103,23 +103,17 @@ std::pair> UbloxMsgParser::gen_msg() { switch (ubx_message.msg_type()) { case 0x0107: return {"gpsLocationExternal", gen_nav_pvt(static_cast(body))}; - break; case 0x0213: return {"ubloxGnss", gen_rxm_sfrbx(static_cast(body))}; - break; case 0x0215: return {"ubloxGnss", gen_rxm_rawx(static_cast(body))}; - break; case 0x0a09: return {"ubloxGnss", gen_mon_hw(static_cast(body))}; - break; case 0x0a0b: return {"ubloxGnss", gen_mon_hw2(static_cast(body))}; - break; default: LOGE("Unknown message type %x", ubx_message.msg_type()); return {"ubloxGnss", kj::Array()}; - break; } } @@ -144,7 +138,7 @@ kj::Array UbloxMsgParser::gen_nav_pvt(ubx_t::nav_pvt_t *msg) { timeinfo.tm_sec = msg->sec(); std::time_t utc_tt = timegm(&timeinfo); - gpsLoc.setTimestamp(utc_tt * 1e+03 + msg->nano() * 1e-06); + gpsLoc.setUnixTimestampMillis(utc_tt * 1e+03 + msg->nano() * 1e-06); float f[] = { msg->vel_n() * 1e-03f, msg->vel_e() * 1e-03f, msg->vel_d() * 1e-03f }; gpsLoc.setVNED(f); gpsLoc.setVerticalAccuracy(msg->v_acc() * 1e-03); diff --git a/selfdrive/locationd/ublox_msg.h b/selfdrive/locationd/ublox_msg.h index da1c180c0b..542e72816b 100644 --- a/selfdrive/locationd/ublox_msg.h +++ b/selfdrive/locationd/ublox_msg.h @@ -8,7 +8,7 @@ #include #include "cereal/messaging/messaging.h" -#include "selfdrive/common/util.h" +#include "common/util.h" #include "selfdrive/locationd/generated/gps.h" #include "selfdrive/locationd/generated/ubx.h" diff --git a/selfdrive/locationd/ubloxd.cc b/selfdrive/locationd/ubloxd.cc index ae07284c8e..d9b3e7647d 100644 --- a/selfdrive/locationd/ubloxd.cc +++ b/selfdrive/locationd/ubloxd.cc @@ -3,8 +3,8 @@ #include #include "cereal/messaging/messaging.h" -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/util.h" +#include "common/swaglog.h" +#include "common/util.h" #include "selfdrive/locationd/ublox_msg.h" ExitHandler do_exit; diff --git a/selfdrive/logcatd/SConscript b/selfdrive/logcatd/SConscript deleted file mode 100644 index 8811f32fe6..0000000000 --- a/selfdrive/logcatd/SConscript +++ /dev/null @@ -1,6 +0,0 @@ -Import('env', 'cereal', 'messaging', 'common', 'arch') - -if arch == "aarch64": - env.Program('logcatd', 'logcatd_android.cc', LIBS=[cereal, messaging, common, 'cutils', 'zmq', 'capnp', 'kj']) -else: - env.Program('logcatd', 'logcatd_systemd.cc', LIBS=[cereal, messaging, common, 'zmq', 'capnp', 'kj', 'systemd', 'json11']) diff --git a/selfdrive/logcatd/logcatd_android.cc b/selfdrive/logcatd/logcatd_android.cc deleted file mode 100644 index 8c2524d94a..0000000000 --- a/selfdrive/logcatd/logcatd_android.cc +++ /dev/null @@ -1,51 +0,0 @@ -#include -#include -#include -#include - -#include - -#include "cereal/messaging/messaging.h" - -#undef LOG_ID_KERNEL -#define LOG_ID_KERNEL 5 - -int main() { - std::signal(SIGINT, exit); - std::signal(SIGTERM, exit); - setpriority(PRIO_PROCESS, 0, -15); - - // setup android logging - logger_list *logger_list = android_logger_list_alloc(ANDROID_LOG_RDONLY, 0, 0); - assert(logger_list); - for (auto log_id : {LOG_ID_MAIN, LOG_ID_RADIO, LOG_ID_SYSTEM, LOG_ID_CRASH, (log_id_t)LOG_ID_KERNEL}) { - logger *logger = android_logger_open(logger_list, log_id); - assert(logger); - } - - PubMaster pm({"androidLog"}); - - while (true) { - log_msg log_msg; - int err = android_logger_list_read(logger_list, &log_msg); - if (err <= 0) break; - - AndroidLogEntry entry; - err = android_log_processLogBuffer(&log_msg.entry_v1, &entry); - if (err < 0) continue; - - MessageBuilder msg; - auto androidEntry = msg.initEvent().initAndroidLog(); - androidEntry.setId(log_msg.id()); - androidEntry.setTs(entry.tv_sec * NS_PER_SEC + entry.tv_nsec); - androidEntry.setPriority(entry.priority); - androidEntry.setPid(entry.pid); - androidEntry.setTid(entry.tid); - androidEntry.setTag(entry.tag); - androidEntry.setMessage(entry.message); - pm.send("androidLog", msg); - } - - android_logger_list_free(logger_list); - return 0; -} diff --git a/selfdrive/logcatd/tests/test_logcatd_android.py b/selfdrive/logcatd/tests/test_logcatd_android.py deleted file mode 100755 index 4e0c903dfa..0000000000 --- a/selfdrive/logcatd/tests/test_logcatd_android.py +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env python3 -import os -import random -import string -import time -import unittest -import uuid - -import cereal.messaging as messaging -from selfdrive.test.helpers import with_processes - -class TestLogcatdAndroid(unittest.TestCase): - - @with_processes(['logcatd']) - def test_log(self): - sock = messaging.sub_sock("androidLog", conflate=False) - - # make sure sockets are ready - time.sleep(1) - messaging.drain_sock(sock) - - sent_msgs = {} - for _ in range(random.randint(2, 10)): - # write some log messages - for __ in range(random.randint(5, 50)): - tag = uuid.uuid4().hex - msg = ''.join(random.choice(string.ascii_letters) for _ in range(random.randrange(2, 50))) - sent_msgs[tag] = {'recv_cnt': 0, 'msg': msg} - os.system(f"log -t '{tag}' '{msg}'") - - time.sleep(1) - msgs = messaging.drain_sock(sock) - for m in msgs: - self.assertTrue(m.valid) - self.assertLess(time.monotonic() - (m.logMonoTime / 1e9), 30) - tag = m.androidLog.tag - if tag in sent_msgs: - sent_msgs[tag]['recv_cnt'] += 1 - self.assertEqual(m.androidLog.message.strip(), sent_msgs[tag]['msg']) - - for v in sent_msgs.values(): - self.assertEqual(v['recv_cnt'], 1) - -if __name__ == "__main__": - unittest.main() diff --git a/selfdrive/loggerd/.gitignore b/selfdrive/loggerd/.gitignore index 4a8755b956..53dc24e6f2 100644 --- a/selfdrive/loggerd/.gitignore +++ b/selfdrive/loggerd/.gitignore @@ -1,2 +1,4 @@ loggerd +encoderd +bootlog tests/test_logger diff --git a/selfdrive/loggerd/SConscript b/selfdrive/loggerd/SConscript index 76fbcae6c4..92706c53ec 100644 --- a/selfdrive/loggerd/SConscript +++ b/selfdrive/loggerd/SConscript @@ -1,22 +1,13 @@ -Import('env', 'arch', 'cereal', 'messaging', 'common', 'visionipc', 'gpucommon') - +Import('env', 'arch', 'cereal', 'messaging', 'common', 'visionipc') libs = [common, cereal, messaging, visionipc, 'zmq', 'capnp', 'kj', 'z', 'avformat', 'avcodec', 'swscale', 'avutil', - 'yuv', 'bz2', 'OpenCL'] + 'yuv', 'OpenCL', 'pthread'] -src = ['logger.cc', 'loggerd.cc'] -if arch in ["aarch64", "larch64"]: - src += ['omx_encoder.cc'] - libs += ['OmxCore', 'gsl', 'CB'] + gpucommon - if arch == "aarch64": - libs += ['OmxVenc', 'cutils'] - else: - libs += ['pthread'] -else: - src += ['raw_logger.cc'] - libs += ['pthread'] +src = ['logger.cc', 'video_writer.cc', 'encoder/encoder.cc', 'encoder/v4l_encoder.cc'] +if arch != "larch64": + src += ['encoder/ffmpeg_encoder.cc'] if arch == "Darwin": # fix OpenCL @@ -26,8 +17,9 @@ if arch == "Darwin": logger_lib = env.Library('logger', src) libs.insert(0, logger_lib) -env.Program('loggerd', ['main.cc'], LIBS=libs) +env.Program('loggerd', ['loggerd.cc'], LIBS=libs) +env.Program('encoderd', ['encoderd.cc'], LIBS=libs) env.Program('bootlog.cc', LIBS=libs) if GetOption('test'): - env.Program('tests/test_logger', ['tests/test_runner.cc', 'tests/test_loggerd.cc', 'tests/test_logger.cc', env.Object('logger_util', '#/selfdrive/ui/replay/util.cc')], LIBS=libs + ['curl', 'crypto']) + env.Program('tests/test_logger', ['tests/test_runner.cc', 'tests/test_logger.cc'], LIBS=libs + ['curl', 'crypto']) diff --git a/selfdrive/loggerd/bootlog.cc b/selfdrive/loggerd/bootlog.cc index a723124847..e882e4cf8d 100644 --- a/selfdrive/loggerd/bootlog.cc +++ b/selfdrive/loggerd/bootlog.cc @@ -2,19 +2,11 @@ #include #include "cereal/messaging/messaging.h" -#include "selfdrive/common/swaglog.h" +#include "common/swaglog.h" #include "selfdrive/loggerd/logger.h" static kj::Array build_boot_log() { - std::vector bootlog_commands; - if (Hardware::TICI()) { - bootlog_commands.push_back("journalctl"); - bootlog_commands.push_back("sudo nvme smart-log --output-format=json /dev/nvme0"); - } else if (Hardware::EON()) { - bootlog_commands.push_back("logcat -d"); - } - MessageBuilder msg; auto boot = msg.initEvent().initBoot(); @@ -33,17 +25,22 @@ static kj::Array build_boot_log() { } // Gather output of commands - i = 0; + std::vector bootlog_commands = { + "[ -x \"$(command -v journalctl)\" ] && journalctl", + }; + + if (Hardware::TICI()) { + bootlog_commands.push_back("[ -e /dev/nvme0 ] && sudo nvme smart-log --output-format=json /dev/nvme0"); + } + auto commands = boot.initCommands().initEntries(bootlog_commands.size()); - for (auto &command : bootlog_commands) { - auto lentry = commands[i]; + for (int j = 0; j < bootlog_commands.size(); j++) { + auto lentry = commands[j]; - lentry.setKey(command); + lentry.setKey(bootlog_commands[j]); - const std::string result = util::check_output(command); + const std::string result = util::check_output(bootlog_commands[j]); lentry.setValue(capnp::Data::Reader((const kj::byte*)result.data(), result.size())); - - i++; } boot.setLaunchLog(util::read_file("/tmp/launch_log")); @@ -51,20 +48,18 @@ static kj::Array build_boot_log() { } int main(int argc, char** argv) { - const std::string path = LOG_ROOT + "/boot/" + logger_get_route_name() + ".bz2"; + const std::string path = LOG_ROOT + "/boot/" + logger_get_route_name(); LOGW("bootlog to %s", path.c_str()); // Open bootlog bool r = util::create_directories(LOG_ROOT + "/boot/", 0775); assert(r); - BZFile bz_file(path.c_str()); - + RawFile file(path.c_str()); // Write initdata - bz_file.write(logger_build_init_data().asBytes()); - + file.write(logger_build_init_data().asBytes()); // Write bootlog - bz_file.write(build_boot_log().asBytes()); + file.write(build_boot_log().asBytes()); return 0; } diff --git a/selfdrive/loggerd/config.py b/selfdrive/loggerd/config.py index 6cd20a68ab..168c9fba91 100644 --- a/selfdrive/loggerd/config.py +++ b/selfdrive/loggerd/config.py @@ -1,6 +1,6 @@ import os from pathlib import Path -from selfdrive.hardware import PC +from system.hardware import PC if os.environ.get('LOG_ROOT', False): ROOT = os.environ['LOG_ROOT'] diff --git a/selfdrive/loggerd/deleter.py b/selfdrive/loggerd/deleter.py index e7006a08cf..5606288024 100644 --- a/selfdrive/loggerd/deleter.py +++ b/selfdrive/loggerd/deleter.py @@ -2,7 +2,7 @@ import os import shutil import threading -from selfdrive.swaglog import cloudlog +from system.swaglog import cloudlog from selfdrive.loggerd.config import ROOT, get_available_bytes, get_available_percent from selfdrive.loggerd.uploader import listdir_by_creation @@ -28,7 +28,10 @@ def deleter_thread(exit_event): try: cloudlog.info(f"deleting {delete_path}") - shutil.rmtree(delete_path) + if os.path.isfile(delete_path): + os.remove(delete_path) + else: + shutil.rmtree(delete_path) break except OSError: cloudlog.exception(f"issue deleting {delete_path}") diff --git a/selfdrive/loggerd/encoder.h b/selfdrive/loggerd/encoder.h deleted file mode 100644 index 572a635a7d..0000000000 --- a/selfdrive/loggerd/encoder.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include - -class VideoEncoder { -public: - virtual ~VideoEncoder() {} - virtual int encode_frame(const uint8_t *y_ptr, const uint8_t *u_ptr, const uint8_t *v_ptr, - int in_width, int in_height, uint64_t ts) = 0; - virtual void encoder_open(const char* path) = 0; - virtual void encoder_close() = 0; -}; diff --git a/selfdrive/loggerd/encoder/encoder.cc b/selfdrive/loggerd/encoder/encoder.cc new file mode 100644 index 0000000000..943f37803d --- /dev/null +++ b/selfdrive/loggerd/encoder/encoder.cc @@ -0,0 +1,82 @@ +#include +#include "selfdrive/loggerd/encoder/encoder.h" + +VideoEncoder::~VideoEncoder() {} + +void VideoEncoder::publisher_init() { + // publish + service_name = this->type == DriverCam ? "driverEncodeData" : + (this->type == WideRoadCam ? "wideRoadEncodeData" : + (this->in_width == this->out_width ? "roadEncodeData" : "qRoadEncodeData")); + pm.reset(new PubMaster({service_name})); +} + +void VideoEncoder::publisher_publish(VideoEncoder *e, int segment_num, uint32_t idx, VisionIpcBufExtra &extra, + unsigned int flags, kj::ArrayPtr header, kj::ArrayPtr dat) { + // broadcast packet + MessageBuilder msg; + auto event = msg.initEvent(true); + auto edat = (e->type == DriverCam) ? event.initDriverEncodeData() : + ((e->type == WideRoadCam) ? event.initWideRoadEncodeData() : + (e->in_width == e->out_width ? event.initRoadEncodeData() : event.initQRoadEncodeData())); + auto edata = edat.initIdx(); + struct timespec ts; + timespec_get(&ts, TIME_UTC); + edat.setUnixTimestampNanos((uint64_t)ts.tv_sec*1000000000 + ts.tv_nsec); + edata.setFrameId(extra.frame_id); + edata.setTimestampSof(extra.timestamp_sof); + edata.setTimestampEof(extra.timestamp_eof); + edata.setType(e->codec); + edata.setEncodeId(e->cnt++); + edata.setSegmentNum(segment_num); + edata.setSegmentId(idx); + edata.setFlags(flags); + edata.setLen(dat.size()); + edat.setData(dat); + if (flags & V4L2_BUF_FLAG_KEYFRAME) edat.setHeader(header); + + auto words = new kj::Array(capnp::messageToFlatArray(msg)); + auto bytes = words->asBytes(); + e->pm->send(e->service_name, bytes.begin(), bytes.size()); + if (e->write) { + e->to_write.push(words); + } else { + delete words; + } +} + +// TODO: writing should be moved to loggerd +void VideoEncoder::write_handler(VideoEncoder *e, const char *path) { + VideoWriter writer(path, e->filename, e->codec != cereal::EncodeIndex::Type::FULL_H_E_V_C, e->out_width, e->out_height, e->fps, e->codec); + + bool first = true; + kj::Array* out_buf; + while ((out_buf = e->to_write.pop())) { + capnp::FlatArrayMessageReader cmsg(*out_buf); + cereal::Event::Reader event = cmsg.getRoot(); + + auto edata = (e->type == DriverCam) ? event.getDriverEncodeData() : + ((e->type == WideRoadCam) ? event.getWideRoadEncodeData() : + (e->in_width == e->out_width ? event.getRoadEncodeData() : event.getQRoadEncodeData())); + auto idx = edata.getIdx(); + auto flags = idx.getFlags(); + + if (first) { + assert(flags & V4L2_BUF_FLAG_KEYFRAME); + auto header = edata.getHeader(); + writer.write((uint8_t *)header.begin(), header.size(), idx.getTimestampEof()/1000, true, false); + first = false; + } + + // dangerous cast from const, but should be fine + auto data = edata.getData(); + if (data.size() > 0) { + writer.write((uint8_t *)data.begin(), data.size(), idx.getTimestampEof()/1000, false, flags & V4L2_BUF_FLAG_KEYFRAME); + } + + // free the data + delete out_buf; + } + + // VideoWriter is freed on out of scope +} diff --git a/selfdrive/loggerd/encoder/encoder.h b/selfdrive/loggerd/encoder/encoder.h new file mode 100644 index 0000000000..21ef65cf12 --- /dev/null +++ b/selfdrive/loggerd/encoder/encoder.h @@ -0,0 +1,62 @@ +#pragma once + +#include +#include +#include + +#include "cereal/messaging/messaging.h" +#include "cereal/visionipc/visionipc.h" +#include "common/queue.h" +#include "selfdrive/loggerd/video_writer.h" +#include "system/camerad/cameras/camera_common.h" + +#define V4L2_BUF_FLAG_KEYFRAME 8 + +class VideoEncoder { +public: + VideoEncoder(const char* filename, CameraType type, int in_width, int in_height, int fps, + int bitrate, cereal::EncodeIndex::Type codec, int out_width, int out_height, bool write) + : filename(filename), type(type), in_width(in_width), in_height(in_height), fps(fps), + bitrate(bitrate), codec(codec), out_width(out_width), out_height(out_height), write(write) { } + virtual ~VideoEncoder(); + virtual int encode_frame(VisionBuf* buf, VisionIpcBufExtra *extra) = 0; + virtual void encoder_open(const char* path) = 0; + virtual void encoder_close() = 0; + + void publisher_init(); + static void publisher_publish(VideoEncoder *e, int segment_num, uint32_t idx, VisionIpcBufExtra &extra, unsigned int flags, kj::ArrayPtr header, kj::ArrayPtr dat); + + void writer_open(const char* path) { + if (this->write) write_handler_thread = std::thread(VideoEncoder::write_handler, this, path); + } + + void writer_close() { + if (this->write) { + to_write.push(NULL); + write_handler_thread.join(); + } + assert(to_write.empty()); + } + +protected: + bool write; + const char* filename; + int in_width, in_height; + int out_width, out_height, fps; + int bitrate; + cereal::EncodeIndex::Type codec; + CameraType type; + +private: + // total frames encoded + int cnt = 0; + + // publishing + std::unique_ptr pm; + const char *service_name; + + // writing support + static void write_handler(VideoEncoder *e, const char *path); + std::thread write_handler_thread; + SafeQueue* > to_write; +}; diff --git a/selfdrive/loggerd/encoder/ffmpeg_encoder.cc b/selfdrive/loggerd/encoder/ffmpeg_encoder.cc new file mode 100644 index 0000000000..5f8d140e8b --- /dev/null +++ b/selfdrive/loggerd/encoder/ffmpeg_encoder.cc @@ -0,0 +1,153 @@ +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +#include "selfdrive/loggerd/encoder/ffmpeg_encoder.h" + +#include +#include + +#include +#include +#include + +#define __STDC_CONSTANT_MACROS + +#include "libyuv.h" + +extern "C" { +#include +#include +#include +} + +#include "common/swaglog.h" +#include "common/util.h" + +const int env_debug_encoder = (getenv("DEBUG_ENCODER") != NULL) ? atoi(getenv("DEBUG_ENCODER")) : 0; + +void FfmpegEncoder::encoder_init() { + frame = av_frame_alloc(); + assert(frame); + frame->format = AV_PIX_FMT_YUV420P; + frame->width = out_width; + frame->height = out_height; + frame->linesize[0] = out_width; + frame->linesize[1] = out_width/2; + frame->linesize[2] = out_width/2; + + convert_buf.resize(in_width * in_height * 3 / 2); + + if (in_width != out_width || in_height != out_height) { + downscale_buf.resize(out_width * out_height * 3 / 2); + } + + publisher_init(); +} + +FfmpegEncoder::~FfmpegEncoder() { + encoder_close(); + av_frame_free(&frame); +} + +void FfmpegEncoder::encoder_open(const char* path) { + const AVCodec *codec = avcodec_find_encoder(AV_CODEC_ID_FFVHUFF); + + this->codec_ctx = avcodec_alloc_context3(codec); + assert(this->codec_ctx); + this->codec_ctx->width = frame->width; + this->codec_ctx->height = frame->height; + this->codec_ctx->pix_fmt = AV_PIX_FMT_YUV420P; + this->codec_ctx->time_base = (AVRational){ 1, fps }; + int err = avcodec_open2(this->codec_ctx, codec, NULL); + assert(err >= 0); + + writer_open(path); + is_open = true; + segment_num++; + counter = 0; +} + +void FfmpegEncoder::encoder_close() { + if (!is_open) return; + + writer_close(); + avcodec_free_context(&codec_ctx); + is_open = false; +} + +int FfmpegEncoder::encode_frame(VisionBuf* buf, VisionIpcBufExtra *extra) { + assert(buf->width == this->in_width); + assert(buf->height == this->in_height); + + uint8_t *cy = convert_buf.data(); + uint8_t *cu = cy + in_width * in_height; + uint8_t *cv = cu + (in_width / 2) * (in_height / 2); + libyuv::NV12ToI420(buf->y, buf->stride, + buf->uv, buf->stride, + cy, in_width, + cu, in_width/2, + cv, in_width/2, + in_width, in_height); + + if (downscale_buf.size() > 0) { + uint8_t *out_y = downscale_buf.data(); + uint8_t *out_u = out_y + frame->width * frame->height; + uint8_t *out_v = out_u + (frame->width / 2) * (frame->height / 2); + libyuv::I420Scale(cy, in_width, + cu, in_width/2, + cv, in_width/2, + in_width, in_height, + out_y, frame->width, + out_u, frame->width/2, + out_v, frame->width/2, + frame->width, frame->height, + libyuv::kFilterNone); + frame->data[0] = out_y; + frame->data[1] = out_u; + frame->data[2] = out_v; + } else { + frame->data[0] = cy; + frame->data[1] = cu; + frame->data[2] = cv; + } + frame->pts = counter*50*1000; // 50ms per frame + + int ret = counter; + + int err = avcodec_send_frame(this->codec_ctx, frame); + if (err < 0) { + LOGE("avcodec_send_frame error %d", err); + ret = -1; + } + + AVPacket pkt; + av_init_packet(&pkt); + pkt.data = NULL; + pkt.size = 0; + while (ret >= 0) { + err = avcodec_receive_packet(this->codec_ctx, &pkt); + if (err == AVERROR_EOF) { + break; + } else if (err == AVERROR(EAGAIN)) { + // Encoder might need a few frames on startup to get started. Keep going + ret = 0; + break; + } else if (err < 0) { + LOGE("avcodec_receive_packet error %d", err); + ret = -1; + break; + } + + if (env_debug_encoder) { + printf("%20s got %8d bytes flags %8x idx %4d id %8d\n", this->filename, pkt.size, pkt.flags, counter, extra->frame_id); + } + + publisher_publish(this, segment_num, counter, *extra, + (pkt.flags & AV_PKT_FLAG_KEY) ? V4L2_BUF_FLAG_KEYFRAME : 0, + kj::arrayPtr(pkt.data, (size_t)0), // TODO: get the header + kj::arrayPtr(pkt.data, pkt.size)); + + counter++; + } + av_packet_unref(&pkt); + return ret; +} diff --git a/selfdrive/loggerd/encoder/ffmpeg_encoder.h b/selfdrive/loggerd/encoder/ffmpeg_encoder.h new file mode 100644 index 0000000000..497a28b651 --- /dev/null +++ b/selfdrive/loggerd/encoder/ffmpeg_encoder.h @@ -0,0 +1,37 @@ +#pragma once + +#include +#include +#include +#include + +extern "C" { +#include +#include +#include +} + +#include "selfdrive/loggerd/encoder/encoder.h" +#include "selfdrive/loggerd/loggerd.h" + +class FfmpegEncoder : public VideoEncoder { + public: + FfmpegEncoder(const char* filename, CameraType type, int in_width, int in_height, int fps, + int bitrate, cereal::EncodeIndex::Type codec, int out_width, int out_height, bool write) : + VideoEncoder(filename, type, in_width, in_height, fps, bitrate, cereal::EncodeIndex::Type::BIG_BOX_LOSSLESS, out_width, out_height, write) { encoder_init(); } + ~FfmpegEncoder(); + void encoder_init(); + int encode_frame(VisionBuf* buf, VisionIpcBufExtra *extra); + void encoder_open(const char* path); + void encoder_close(); + +private: + int segment_num = -1; + int counter = 0; + bool is_open = false; + + AVCodecContext *codec_ctx; + AVFrame *frame = NULL; + std::vector convert_buf; + std::vector downscale_buf; +}; diff --git a/selfdrive/loggerd/encoder/v4l_encoder.cc b/selfdrive/loggerd/encoder/v4l_encoder.cc new file mode 100644 index 0000000000..88aeb21256 --- /dev/null +++ b/selfdrive/loggerd/encoder/v4l_encoder.cc @@ -0,0 +1,311 @@ +#include +#include +#include + +#include "selfdrive/loggerd/encoder/v4l_encoder.h" +#include "common/util.h" +#include "common/timing.h" + +#include "libyuv.h" +#include "msm_media_info.h" + +// has to be in this order +#include "v4l2-controls.h" +#include +#define V4L2_QCOM_BUF_FLAG_CODECCONFIG 0x00020000 +#define V4L2_QCOM_BUF_FLAG_EOS 0x02000000 + +// echo 0x7fffffff > /sys/kernel/debug/msm_vidc/debug_level +const int env_debug_encoder = (getenv("DEBUG_ENCODER") != NULL) ? atoi(getenv("DEBUG_ENCODER")) : 0; + +#define checked_ioctl(x,y,z) { int _ret = HANDLE_EINTR(ioctl(x,y,z)); if (_ret!=0) { LOGE("checked_ioctl failed %d %lx %p", x, y, z); } assert(_ret==0); } + +static void dequeue_buffer(int fd, v4l2_buf_type buf_type, unsigned int *index=NULL, unsigned int *bytesused=NULL, unsigned int *flags=NULL, struct timeval *timestamp=NULL) { + v4l2_plane plane = {0}; + v4l2_buffer v4l_buf = { + .type = buf_type, + .memory = V4L2_MEMORY_USERPTR, + .m = { .planes = &plane, }, + .length = 1, + }; + checked_ioctl(fd, VIDIOC_DQBUF, &v4l_buf); + + if (index) *index = v4l_buf.index; + if (bytesused) *bytesused = v4l_buf.m.planes[0].bytesused; + if (flags) *flags = v4l_buf.flags; + if (timestamp) *timestamp = v4l_buf.timestamp; + assert(v4l_buf.m.planes[0].data_offset == 0); +} + +static void queue_buffer(int fd, v4l2_buf_type buf_type, unsigned int index, VisionBuf *buf, struct timeval timestamp={}) { + v4l2_plane plane = { + .length = (unsigned int)buf->len, + .m = { .userptr = (unsigned long)buf->addr, }, + .bytesused = (uint32_t)buf->len, + .reserved = {(unsigned int)buf->fd} + }; + + v4l2_buffer v4l_buf = { + .type = buf_type, + .index = index, + .memory = V4L2_MEMORY_USERPTR, + .m = { .planes = &plane, }, + .length = 1, + .flags = V4L2_BUF_FLAG_TIMESTAMP_COPY, + .timestamp = timestamp + }; + + checked_ioctl(fd, VIDIOC_QBUF, &v4l_buf); +} + +static void request_buffers(int fd, v4l2_buf_type buf_type, unsigned int count) { + struct v4l2_requestbuffers reqbuf = { + .type = buf_type, + .memory = V4L2_MEMORY_USERPTR, + .count = count + }; + checked_ioctl(fd, VIDIOC_REQBUFS, &reqbuf); +} + +void V4LEncoder::dequeue_handler(V4LEncoder *e) { + std::string dequeue_thread_name = "dq-"+std::string(e->filename); + util::set_thread_name(dequeue_thread_name.c_str()); + + e->segment_num++; + uint32_t idx = -1; + bool exit = false; + + // POLLIN is capture, POLLOUT is frame + struct pollfd pfd; + pfd.events = POLLIN | POLLOUT; + pfd.fd = e->fd; + + // save the header + kj::Array header; + + while (!exit) { + int rc = poll(&pfd, 1, 1000); + if (!rc) { LOGE("encoder dequeue poll timeout"); continue; } + + if (env_debug_encoder >= 2) { + printf("%20s poll %x at %.2f ms\n", e->filename, pfd.revents, millis_since_boot()); + } + + int frame_id = -1; + if (pfd.revents & POLLIN) { + unsigned int bytesused, flags, index; + struct timeval timestamp; + dequeue_buffer(e->fd, V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, &index, &bytesused, &flags, ×tamp); + e->buf_out[index].sync(VISIONBUF_SYNC_FROM_DEVICE); + uint8_t *buf = (uint8_t*)e->buf_out[index].addr; + int64_t ts = timestamp.tv_sec * 1000000 + timestamp.tv_usec; + + // eof packet, we exit + if (flags & V4L2_QCOM_BUF_FLAG_EOS) { + exit = true; + } else if (flags & V4L2_QCOM_BUF_FLAG_CODECCONFIG) { + // save header + header = kj::heapArray(buf, bytesused); + } else { + VisionIpcBufExtra extra = e->extras.pop(); + assert(extra.timestamp_eof/1000 == ts); // stay in sync + frame_id = extra.frame_id; + ++idx; + e->publisher_publish(e, e->segment_num, idx, extra, flags, header, kj::arrayPtr(buf, bytesused)); + } + + if (env_debug_encoder) { + printf("%20s got(%d) %6d bytes flags %8x idx %3d/%4d id %8d ts %ld lat %.2f ms (%lu frames free)\n", + e->filename, index, bytesused, flags, e->segment_num, idx, frame_id, ts, millis_since_boot()-(ts/1000.), e->free_buf_in.size()); + } + + // requeue the buffer + queue_buffer(e->fd, V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, index, &e->buf_out[index]); + } + + if (pfd.revents & POLLOUT) { + unsigned int index; + dequeue_buffer(e->fd, V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, &index); + e->free_buf_in.push(index); + } + } +} + +void V4LEncoder::encoder_init() { + fd = open("/dev/v4l/by-path/platform-aa00000.qcom_vidc-video-index1", O_RDWR|O_NONBLOCK); + assert(fd >= 0); + + struct v4l2_capability cap; + checked_ioctl(fd, VIDIOC_QUERYCAP, &cap); + LOGD("opened encoder device %s %s = %d", cap.driver, cap.card, fd); + assert(strcmp((const char *)cap.driver, "msm_vidc_driver") == 0); + assert(strcmp((const char *)cap.card, "msm_vidc_venc") == 0); + + struct v4l2_format fmt_out = { + .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, + .fmt = { + .pix_mp = { + // downscales are free with v4l + .width = (unsigned int)out_width, + .height = (unsigned int)out_height, + .pixelformat = (codec == cereal::EncodeIndex::Type::FULL_H_E_V_C) ? V4L2_PIX_FMT_HEVC : V4L2_PIX_FMT_H264, + .field = V4L2_FIELD_ANY, + .colorspace = V4L2_COLORSPACE_DEFAULT, + } + } + }; + checked_ioctl(fd, VIDIOC_S_FMT, &fmt_out); + + v4l2_streamparm streamparm = { + .type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, + .parm = { + .output = { + // TODO: more stuff here? we don't know + .timeperframe = { + .numerator = 1, + .denominator = 20 + } + } + } + }; + checked_ioctl(fd, VIDIOC_S_PARM, &streamparm); + + struct v4l2_format fmt_in = { + .type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, + .fmt = { + .pix_mp = { + .width = (unsigned int)in_width, + .height = (unsigned int)in_height, + .pixelformat = V4L2_PIX_FMT_NV12, + .field = V4L2_FIELD_ANY, + .colorspace = V4L2_COLORSPACE_470_SYSTEM_BG, + } + } + }; + checked_ioctl(fd, VIDIOC_S_FMT, &fmt_in); + + LOGD("in buffer size %d, out buffer size %d", + fmt_in.fmt.pix_mp.plane_fmt[0].sizeimage, + fmt_out.fmt.pix_mp.plane_fmt[0].sizeimage); + + // shared ctrls + { + struct v4l2_control ctrls[] = { + { .id = V4L2_CID_MPEG_VIDEO_HEADER_MODE, .value = V4L2_MPEG_VIDEO_HEADER_MODE_SEPARATE}, + { .id = V4L2_CID_MPEG_VIDEO_BITRATE, .value = bitrate}, + { .id = V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL, .value = V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_VBR_CFR}, + { .id = V4L2_CID_MPEG_VIDC_VIDEO_PRIORITY, .value = V4L2_MPEG_VIDC_VIDEO_PRIORITY_REALTIME_DISABLE}, + { .id = V4L2_CID_MPEG_VIDC_VIDEO_IDR_PERIOD, .value = 1}, + }; + for (auto ctrl : ctrls) { + checked_ioctl(fd, VIDIOC_S_CTRL, &ctrl); + } + } + + if (codec == cereal::EncodeIndex::Type::FULL_H_E_V_C) { + struct v4l2_control ctrls[] = { + { .id = V4L2_CID_MPEG_VIDC_VIDEO_HEVC_PROFILE, .value = V4L2_MPEG_VIDC_VIDEO_HEVC_PROFILE_MAIN}, + { .id = V4L2_CID_MPEG_VIDC_VIDEO_HEVC_TIER_LEVEL, .value = V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_5}, + { .id = V4L2_CID_MPEG_VIDC_VIDEO_NUM_P_FRAMES, .value = 29}, + { .id = V4L2_CID_MPEG_VIDC_VIDEO_NUM_B_FRAMES, .value = 0}, + }; + for (auto ctrl : ctrls) { + checked_ioctl(fd, VIDIOC_S_CTRL, &ctrl); + } + } else { + struct v4l2_control ctrls[] = { + { .id = V4L2_CID_MPEG_VIDEO_H264_PROFILE, .value = V4L2_MPEG_VIDEO_H264_PROFILE_HIGH}, + { .id = V4L2_CID_MPEG_VIDEO_H264_LEVEL, .value = V4L2_MPEG_VIDEO_H264_LEVEL_UNKNOWN}, + { .id = V4L2_CID_MPEG_VIDC_VIDEO_NUM_P_FRAMES, .value = 14}, + { .id = V4L2_CID_MPEG_VIDC_VIDEO_NUM_B_FRAMES, .value = 0}, + { .id = V4L2_CID_MPEG_VIDEO_H264_ENTROPY_MODE, .value = V4L2_MPEG_VIDEO_H264_ENTROPY_MODE_CABAC}, + { .id = V4L2_CID_MPEG_VIDC_VIDEO_H264_CABAC_MODEL, .value = V4L2_CID_MPEG_VIDC_VIDEO_H264_CABAC_MODEL_0}, + { .id = V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_MODE, .value = 0}, + { .id = V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_ALPHA, .value = 0}, + { .id = V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_BETA, .value = 0}, + { .id = V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE, .value = 0}, + }; + for (auto ctrl : ctrls) { + checked_ioctl(fd, VIDIOC_S_CTRL, &ctrl); + } + } + + // allocate buffers + request_buffers(fd, V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, BUF_OUT_COUNT); + request_buffers(fd, V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, BUF_IN_COUNT); + + // start encoder + v4l2_buf_type buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; + checked_ioctl(fd, VIDIOC_STREAMON, &buf_type); + buf_type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; + checked_ioctl(fd, VIDIOC_STREAMON, &buf_type); + + // queue up output buffers + for (unsigned int i = 0; i < BUF_OUT_COUNT; i++) { + buf_out[i].allocate(fmt_out.fmt.pix_mp.plane_fmt[0].sizeimage); + queue_buffer(fd, V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, i, &buf_out[i]); + } + // queue up input buffers + for (unsigned int i = 0; i < BUF_IN_COUNT; i++) { + free_buf_in.push(i); + } + + publisher_init(); +} + +void V4LEncoder::encoder_open(const char* path) { + dequeue_handler_thread = std::thread(V4LEncoder::dequeue_handler, this); + writer_open(path); + this->is_open = true; + this->counter = 0; +} + +int V4LEncoder::encode_frame(VisionBuf* buf, VisionIpcBufExtra *extra) { + struct timeval timestamp { + .tv_sec = (long)(extra->timestamp_eof/1000000000), + .tv_usec = (long)((extra->timestamp_eof/1000) % 1000000), + }; + + // reserve buffer + int buffer_in = free_buf_in.pop(); + + // push buffer + extras.push(*extra); + //buf->sync(VISIONBUF_SYNC_TO_DEVICE); + queue_buffer(fd, V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, buffer_in, buf, timestamp); + + return this->counter++; +} + +void V4LEncoder::encoder_close() { + if (this->is_open) { + // pop all the frames before closing, then put the buffers back + for (int i = 0; i < BUF_IN_COUNT; i++) free_buf_in.pop(); + for (int i = 0; i < BUF_IN_COUNT; i++) free_buf_in.push(i); + // no frames, stop the encoder + struct v4l2_encoder_cmd encoder_cmd = { .cmd = V4L2_ENC_CMD_STOP }; + checked_ioctl(fd, VIDIOC_ENCODER_CMD, &encoder_cmd); + // join waits for V4L2_QCOM_BUF_FLAG_EOS + dequeue_handler_thread.join(); + assert(extras.empty()); + writer_close(); + } + this->is_open = false; +} + +V4LEncoder::~V4LEncoder() { + encoder_close(); + v4l2_buf_type buf_type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; + checked_ioctl(fd, VIDIOC_STREAMOFF, &buf_type); + request_buffers(fd, V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, 0); + buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; + checked_ioctl(fd, VIDIOC_STREAMOFF, &buf_type); + request_buffers(fd, V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, 0); + close(fd); + + for (int i = 0; i < BUF_OUT_COUNT; i++) { + if (buf_out[i].free() != 0) { + LOGE("Failed to free buffer"); + } + } +} diff --git a/selfdrive/loggerd/encoder/v4l_encoder.h b/selfdrive/loggerd/encoder/v4l_encoder.h new file mode 100644 index 0000000000..c2a53dd6ef --- /dev/null +++ b/selfdrive/loggerd/encoder/v4l_encoder.h @@ -0,0 +1,33 @@ +#pragma once + +#include "common/queue.h" +#include "selfdrive/loggerd/encoder/encoder.h" + +#define BUF_IN_COUNT 7 +#define BUF_OUT_COUNT 6 + +class V4LEncoder : public VideoEncoder { +public: + V4LEncoder(const char* filename, CameraType type, int in_width, int in_height, int fps, + int bitrate, cereal::EncodeIndex::Type codec, int out_width, int out_height, bool write) : + VideoEncoder(filename, type, in_width, in_height, fps, bitrate, codec, out_width, out_height, write) { encoder_init(); } + ~V4LEncoder(); + void encoder_init(); + int encode_frame(VisionBuf* buf, VisionIpcBufExtra *extra); + void encoder_open(const char* path); + void encoder_close(); +private: + int fd; + + bool is_open = false; + int segment_num = -1; + int counter = 0; + + SafeQueue extras; + + static void dequeue_handler(V4LEncoder *e); + std::thread dequeue_handler_thread; + + VisionBuf buf_out[BUF_OUT_COUNT]; + SafeQueue free_buf_in; +}; diff --git a/selfdrive/loggerd/encoderd.cc b/selfdrive/loggerd/encoderd.cc new file mode 100644 index 0000000000..db5f4b61ab --- /dev/null +++ b/selfdrive/loggerd/encoderd.cc @@ -0,0 +1,149 @@ +#include "selfdrive/loggerd/loggerd.h" + +ExitHandler do_exit; + +struct EncoderdState { + int max_waiting = 0; + + // Sync logic for startup + std::atomic encoders_ready = 0; + std::atomic start_frame_id = 0; + bool camera_ready[WideRoadCam + 1] = {}; + bool camera_synced[WideRoadCam + 1] = {}; +}; + +// Handle initial encoder syncing by waiting for all encoders to reach the same frame id +bool sync_encoders(EncoderdState *s, CameraType cam_type, uint32_t frame_id) { + if (s->camera_synced[cam_type]) return true; + + if (s->max_waiting > 1 && s->encoders_ready != s->max_waiting) { + // add a small margin to the start frame id in case one of the encoders already dropped the next frame + update_max_atomic(s->start_frame_id, frame_id + 2); + if (std::exchange(s->camera_ready[cam_type], true) == false) { + ++s->encoders_ready; + LOGD("camera %d encoder ready", cam_type); + } + return false; + } else { + if (s->max_waiting == 1) update_max_atomic(s->start_frame_id, frame_id); + bool synced = frame_id >= s->start_frame_id; + s->camera_synced[cam_type] = synced; + if (!synced) LOGD("camera %d waiting for frame %d, cur %d", cam_type, (int)s->start_frame_id, frame_id); + return synced; + } +} + + +void encoder_thread(EncoderdState *s, const LogCameraInfo &cam_info) { + util::set_thread_name(cam_info.filename); + + std::vector encoders; + VisionIpcClient vipc_client = VisionIpcClient("camerad", cam_info.stream_type, false); + + int cur_seg = 0; + while (!do_exit) { + if (!vipc_client.connect(false)) { + util::sleep_for(5); + continue; + } + + // init encoders + if (encoders.empty()) { + VisionBuf buf_info = vipc_client.buffers[0]; + LOGW("encoder %s init %dx%d", cam_info.filename, buf_info.width, buf_info.height); + + if (buf_info.width > 0 && buf_info.height > 0) { + // main encoder + encoders.push_back(new Encoder(cam_info.filename, cam_info.type, buf_info.width, buf_info.height, + cam_info.fps, cam_info.bitrate, + cam_info.is_h265 ? cereal::EncodeIndex::Type::FULL_H_E_V_C : cereal::EncodeIndex::Type::QCAMERA_H264, + buf_info.width, buf_info.height, false)); + // qcamera encoder + if (cam_info.has_qcamera) { + encoders.push_back(new Encoder(qcam_info.filename, cam_info.type, buf_info.width, buf_info.height, + qcam_info.fps, qcam_info.bitrate, + qcam_info.is_h265 ? cereal::EncodeIndex::Type::FULL_H_E_V_C : cereal::EncodeIndex::Type::QCAMERA_H264, + qcam_info.frame_width, qcam_info.frame_height, false)); + } + } else { + LOGE("not initting empty encoder"); + s->max_waiting--; + break; + } + } + + for (int i = 0; i < encoders.size(); ++i) { + encoders[i]->encoder_open(NULL); + } + + bool lagging = false; + while (!do_exit) { + VisionIpcBufExtra extra; + VisionBuf* buf = vipc_client.recv(&extra); + if (buf == nullptr) continue; + + // detect loop around and drop the frames + if (buf->get_frame_id() != extra.frame_id) { + if (!lagging) { + LOGE("encoder %s lag buffer id: %d extra id: %d", cam_info.filename, buf->get_frame_id(), extra.frame_id); + lagging = true; + } + continue; + } + lagging = false; + + if (!sync_encoders(s, cam_info.type, extra.frame_id)) { + continue; + } + if (do_exit) break; + + // do rotation if required + const int frames_per_seg = SEGMENT_LENGTH * MAIN_FPS; + if (cur_seg >= 0 && extra.frame_id >= ((cur_seg + 1) * frames_per_seg) + s->start_frame_id) { + for (auto &e : encoders) { + e->encoder_close(); + e->encoder_open(NULL); + } + ++cur_seg; + } + + // encode a frame + for (int i = 0; i < encoders.size(); ++i) { + int out_id = encoders[i]->encode_frame(buf, &extra); + + if (out_id == -1) { + LOGE("Failed to encode frame. frame_id: %d", extra.frame_id); + } + } + } + } + + LOG("encoder destroy"); + for(auto &e : encoders) { + e->encoder_close(); + delete e; + } +} + +void encoderd_thread() { + EncoderdState s; + + std::vector encoder_threads; + for (const auto &cam : cameras_logged) { + encoder_threads.push_back(std::thread(encoder_thread, &s, cam)); + s.max_waiting++; + } + for (auto &t : encoder_threads) t.join(); +} + +int main() { + if (!Hardware::PC()) { + int ret; + ret = util::set_realtime_priority(52); + assert(ret == 0); + ret = util::set_core_affinity({3}); + assert(ret == 0); + } + encoderd_thread(); + return 0; +} diff --git a/selfdrive/loggerd/logger.cc b/selfdrive/loggerd/logger.cc index 6ba520d162..aaf267e523 100644 --- a/selfdrive/loggerd/logger.cc +++ b/selfdrive/loggerd/logger.cc @@ -14,38 +14,21 @@ #include #include #include -#ifdef QCOM -#include -#endif -#include "selfdrive/common/params.h" -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/version.h" - -// ***** logging helpers ***** - -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))); -} +#include "common/params.h" +#include "common/swaglog.h" +#include "common/version.h" // ***** log metadata ***** kj::Array logger_build_init_data() { MessageBuilder msg; auto init = msg.initEvent().initInitData(); - if (Hardware::EON()) { - init.setDeviceType(cereal::InitData::DeviceType::NEO); - } else if (Hardware::TICI()) { - init.setDeviceType(cereal::InitData::DeviceType::TICI); - } else { - init.setDeviceType(cereal::InitData::DeviceType::PC); - } - init.setVersion(COMMA_VERSION); + init.setDirty(!getenv("CLEAN")); + init.setDeviceType(Hardware::get_device_type()); + // log kernel args std::ifstream cmdline_stream("/proc/cmdline"); std::vector kernel_args; std::string buf; @@ -61,22 +44,6 @@ kj::Array logger_build_init_data() { init.setKernelVersion(util::read_file("/proc/version")); init.setOsVersion(util::read_file("/VERSION")); -#ifdef QCOM - { - std::vector > properties; - property_list(append_property, (void*)&properties); - - auto lentries = init.initAndroidProperties().initEntries(properties.size()); - for (int i=0; i params_map = params.readAll(); @@ -88,16 +55,31 @@ kj::Array logger_build_init_data() { init.setDongleId(params_map["DongleId"]); auto lparams = init.initParams().initEntries(params_map.size()); - int i = 0; + int j = 0; for (auto& [key, value] : params_map) { - auto lentry = lparams[i]; + auto lentry = lparams[j]; lentry.setKey(key); if ( !(params.getKeyType(key) & DONT_LOG) ) { lentry.setValue(capnp::Data::Reader((const kj::byte*)value.data(), value.size())); } - i++; + j++; + } + // log commands + std::vector log_commands = { + "df -h", // usage for all filesystems + }; + + auto commands = init.initCommands().initEntries(log_commands.size()); + for (int i = 0; i < log_commands.size(); i++) { + auto lentry = commands[i]; + + lentry.setKey(log_commands[i]); + + const std::string result = util::check_output(log_commands[i]); + lentry.setValue(capnp::Data::Reader((const kj::byte*)result.data(), result.size())); } + return capnp::messageToFlatArray(msg); } @@ -128,13 +110,12 @@ static void lh_log_sentinel(LoggerHandle *h, SentinelType type) { // ***** logging functions ***** -void logger_init(LoggerState *s, const char* log_name, bool has_qlog) { +void logger_init(LoggerState *s, bool has_qlog) { pthread_mutex_init(&s->lock, NULL); s->part = -1; s->has_qlog = has_qlog; s->route_name = logger_get_route_name(); - snprintf(s->log_name, sizeof(s->log_name), "%s", log_name); s->init_data = logger_build_init_data(); } @@ -151,8 +132,8 @@ static LoggerHandle* logger_open(LoggerState *s, const char* root_path) { snprintf(h->segment_path, sizeof(h->segment_path), "%s/%s--%d", root_path, s->route_name.c_str(), 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->log_path, sizeof(h->log_path), "%s/rlog", h->segment_path); + snprintf(h->qlog_path, sizeof(h->qlog_path), "%s/qlog", h->segment_path); snprintf(h->lock_path, sizeof(h->lock_path), "%s.lock", h->log_path); h->end_sentinel_type = SentinelType::END_OF_SEGMENT; h->exit_signal = 0; @@ -163,9 +144,9 @@ static LoggerHandle* logger_open(LoggerState *s, const char* root_path) { if (lock_file == NULL) return NULL; fclose(lock_file); - h->log = std::make_unique(h->log_path); + h->log = std::make_unique(h->log_path); if (s->has_qlog) { - h->q_log = std::make_unique(h->qlog_path); + h->q_log = std::make_unique(h->qlog_path); } pthread_mutex_init(&h->lock, NULL); @@ -201,7 +182,7 @@ int logger_next(LoggerState *s, const char* root_path, pthread_mutex_unlock(&s->lock); - // write beggining of log metadata + // write beginning of log metadata log_init_data(s); lh_log_sentinel(s->cur_handle, is_start_of_route ? SentinelType::START_OF_ROUTE : SentinelType::START_OF_SEGMENT); return 0; diff --git a/selfdrive/loggerd/logger.h b/selfdrive/loggerd/logger.h index bdda9d6917..e7594cee88 100644 --- a/selfdrive/loggerd/logger.h +++ b/selfdrive/loggerd/logger.h @@ -7,55 +7,37 @@ #include #include -#include #include #include #include "cereal/messaging/messaging.h" -#include "selfdrive/common/util.h" -#include "selfdrive/common/swaglog.h" -#include "selfdrive/hardware/hw.h" +#include "common/util.h" +#include "common/swaglog.h" +#include "system/hardware/hw.h" const std::string LOG_ROOT = Path::log_root(); #define LOGGER_MAX_HANDLES 16 -class BZFile { +class RawFile { public: - BZFile(const char* path) { + RawFile(const char* path) { file = util::safe_fopen(path, "wb"); assert(file != nullptr); - int bzerror; - bz_file = BZ2_bzWriteOpen(&bzerror, file, 9, 0, 30); - assert(bzerror == BZ_OK); } - ~BZFile() { - int bzerror; - BZ2_bzWriteClose(&bzerror, bz_file, 0, nullptr, nullptr); - if (bzerror != BZ_OK) { - LOGE("BZ2_bzWriteClose error, bzerror=%d", bzerror); - } + ~RawFile() { util::safe_fflush(file); int err = fclose(file); assert(err == 0); } inline void write(void* data, size_t size) { - int bzerror; - do { - BZ2_bzWrite(&bzerror, bz_file, data, size); - } while (bzerror == BZ_IO_ERROR && errno == EINTR); - - if (bzerror != BZ_OK && !error_logged) { - LOGE("BZ2_bzWrite error, bzerror=%d", bzerror); - error_logged = true; - } + int written = util::safe_fwrite(data, 1, size, file); + assert(written == size); } inline void write(kj::ArrayPtr array) { write(array.begin(), array.size()); } private: - bool error_logged = false; FILE* file = nullptr; - BZFILE* bz_file = nullptr; }; typedef cereal::Sentinel::SentinelType SentinelType; @@ -69,7 +51,7 @@ typedef struct LoggerHandle { char log_path[4096]; char qlog_path[4096]; char lock_path[4096]; - std::unique_ptr log, q_log; + std::unique_ptr log, q_log; } LoggerHandle; typedef struct LoggerState { @@ -86,7 +68,7 @@ typedef struct LoggerState { kj::Array logger_build_init_data(); std::string logger_get_route_name(); -void logger_init(LoggerState *s, const char* log_name, bool has_qlog); +void logger_init(LoggerState *s, 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); diff --git a/selfdrive/loggerd/loggerd.cc b/selfdrive/loggerd/loggerd.cc index d402c5787f..9beb3c3bf1 100644 --- a/selfdrive/loggerd/loggerd.cc +++ b/selfdrive/loggerd/loggerd.cc @@ -1,180 +1,168 @@ #include "selfdrive/loggerd/loggerd.h" +#include "selfdrive/loggerd/video_writer.h" ExitHandler do_exit; -// Handle initial encoder syncing by waiting for all encoders to reach the same frame id -bool sync_encoders(LoggerdState *s, CameraType cam_type, uint32_t frame_id) { - if (s->camera_synced[cam_type]) return true; +struct LoggerdState { + LoggerState logger = {}; + char segment_path[4096]; + std::atomic rotate_segment; + std::atomic last_camera_seen_tms; + std::atomic ready_to_rotate; // count of encoders ready to rotate + int max_waiting = 0; + double last_rotate_tms = 0.; // last rotate time in ms +}; - if (s->max_waiting > 1 && s->encoders_ready != s->max_waiting) { - // add a small margin to the start frame id in case one of the encoders already dropped the next frame - update_max_atomic(s->start_frame_id, frame_id + 2); - if (std::exchange(s->camera_ready[cam_type], true) == false) { - ++s->encoders_ready; - LOGD("camera %d encoder ready", cam_type); - } - return false; - } else { - if (s->max_waiting == 1) update_max_atomic(s->start_frame_id, frame_id); - bool synced = frame_id >= s->start_frame_id; - s->camera_synced[cam_type] = synced; - if (!synced) LOGD("camera %d waiting for frame %d, cur %d", cam_type, (int)s->start_frame_id, frame_id); - return synced; - } +void logger_rotate(LoggerdState *s) { + int segment = -1; + int err = logger_next(&s->logger, LOG_ROOT.c_str(), s->segment_path, sizeof(s->segment_path), &segment); + assert(err == 0); + s->rotate_segment = segment; + s->ready_to_rotate = 0; + s->last_rotate_tms = millis_since_boot(); + LOGW((s->logger.part == 0) ? "logging to %s" : "rotated to %s", s->segment_path); } -bool trigger_rotate_if_needed(LoggerdState *s, int cur_seg, uint32_t frame_id) { - const int frames_per_seg = SEGMENT_LENGTH * MAIN_FPS; - if (cur_seg >= 0 && frame_id >= ((cur_seg + 1) * frames_per_seg) + s->start_frame_id) { - // trigger rotate and wait until the main logger has rotated to the new segment - ++s->ready_to_rotate; - std::unique_lock lk(s->rotate_lock); - s->rotate_cv.wait(lk, [&] { - return s->rotate_segment > cur_seg || do_exit; - }); - return !do_exit; +void rotate_if_needed(LoggerdState *s) { + if (s->ready_to_rotate == s->max_waiting) { + logger_rotate(s); } - return false; -} -void encoder_thread(LoggerdState *s, const LogCameraInfo &cam_info) { - util::set_thread_name(cam_info.filename); + double tms = millis_since_boot(); + if ((tms - s->last_rotate_tms) > SEGMENT_LENGTH * 1000 && + (tms - s->last_camera_seen_tms) > NO_CAMERA_PATIENCE && + !LOGGERD_TEST) { + LOGW("no camera packet seen. auto rotating"); + logger_rotate(s); + } +} - int cur_seg = -1; - int encode_idx = 0; - LoggerHandle *lh = NULL; - std::vector encoders; - VisionIpcClient vipc_client = VisionIpcClient("camerad", cam_info.stream_type, false); +struct RemoteEncoder { + std::unique_ptr writer; + int encoderd_segment_offset; + int current_segment = -1; + std::vector q; + int dropped_frames = 0; + bool recording = false; + bool marked_ready_to_rotate = false; + bool seen_first_packet = false; +}; + +int handle_encoder_msg(LoggerdState *s, Message *msg, std::string &name, struct RemoteEncoder &re) { + const LogCameraInfo &cam_info = (name == "driverEncodeData") ? cameras_logged[1] : + ((name == "wideRoadEncodeData") ? cameras_logged[2] : + ((name == "qRoadEncodeData") ? qcam_info : cameras_logged[0])); + int bytes_count = 0; + + // extract the message + capnp::FlatArrayMessageReader cmsg(kj::ArrayPtr((capnp::word *)msg->getData(), msg->getSize() / sizeof(capnp::word))); + auto event = cmsg.getRoot(); + auto edata = (name == "driverEncodeData") ? event.getDriverEncodeData() : + ((name == "wideRoadEncodeData") ? event.getWideRoadEncodeData() : + ((name == "qRoadEncodeData") ? event.getQRoadEncodeData() : event.getRoadEncodeData())); + auto idx = edata.getIdx(); + auto flags = idx.getFlags(); + + // encoderd can have started long before loggerd + if (!re.seen_first_packet) { + re.seen_first_packet = true; + re.encoderd_segment_offset = idx.getSegmentNum(); + LOGD("%s: has encoderd offset %d", name.c_str(), re.encoderd_segment_offset); + } + int offset_segment_num = idx.getSegmentNum() - re.encoderd_segment_offset; - while (!do_exit) { - if (!vipc_client.connect(false)) { - util::sleep_for(5); - continue; - } + if (offset_segment_num == s->rotate_segment) { + // loggerd is now on the segment that matches this packet - // init encoders - if (encoders.empty()) { - VisionBuf buf_info = vipc_client.buffers[0]; - LOGD("encoder init %dx%d", buf_info.width, buf_info.height); - - // main encoder - encoders.push_back(new Encoder(cam_info.filename, buf_info.width, buf_info.height, - cam_info.fps, cam_info.bitrate, cam_info.is_h265, - cam_info.downscale, cam_info.record)); - // qcamera encoder - if (cam_info.has_qcamera) { - encoders.push_back(new Encoder(qcam_info.filename, qcam_info.frame_width, qcam_info.frame_height, - qcam_info.fps, qcam_info.bitrate, qcam_info.is_h265, qcam_info.downscale)); + // if this is a new segment, we close any possible old segments, move to the new, and process any queued packets + if (re.current_segment != s->rotate_segment) { + if (re.recording) { + re.writer.reset(); + re.recording = false; } - } - - while (!do_exit) { - VisionIpcBufExtra extra; - VisionBuf* buf = vipc_client.recv(&extra); - if (buf == nullptr) continue; - - if (cam_info.trigger_rotate) { - s->last_camera_seen_tms = millis_since_boot(); - if (!sync_encoders(s, cam_info.type, extra.frame_id)) { - continue; + re.current_segment = s->rotate_segment; + re.marked_ready_to_rotate = false; + // we are in this segment now, process any queued messages before this one + if (!re.q.empty()) { + for (auto &qmsg: re.q) { + bytes_count += handle_encoder_msg(s, qmsg, name, re); } - - // check if we're ready to rotate - trigger_rotate_if_needed(s, cur_seg, extra.frame_id); - if (do_exit) break; + re.q.clear(); } + } - // rotate the encoder if the logger is on a newer segment - if (s->rotate_segment > cur_seg) { - cur_seg = s->rotate_segment; - - LOGW("camera %d rotate encoder to %s", cam_info.type, s->segment_path); - for (auto &e : encoders) { - e->encoder_close(); - e->encoder_open(s->segment_path); + // if we aren't recording yet, try to start, since we are in the correct segment + if (!re.recording) { + if (flags & V4L2_BUF_FLAG_KEYFRAME) { + // only create on iframe + if (re.dropped_frames) { + // this should only happen for the first segment, maybe + LOGW("%s: dropped %d non iframe packets before init", name.c_str(), re.dropped_frames); + re.dropped_frames = 0; } - if (lh) { - lh_close(lh); + // if we aren't actually recording, don't create the writer + if (cam_info.record) { + re.writer.reset(new VideoWriter(s->segment_path, + cam_info.filename, idx.getType() != cereal::EncodeIndex::Type::FULL_H_E_V_C, + cam_info.frame_width, cam_info.frame_height, cam_info.fps, idx.getType())); + // write the header + auto header = edata.getHeader(); + re.writer->write((uint8_t *)header.begin(), header.size(), idx.getTimestampEof()/1000, true, false); } - lh = logger_get_handle(&s->logger); + re.recording = true; + } else { + // this is a sad case when we aren't recording, but don't have an iframe + // nothing we can do but drop the frame + delete msg; + ++re.dropped_frames; + return bytes_count; } + } - // encode a frame - for (int i = 0; i < encoders.size(); ++i) { - int out_id = encoders[i]->encode_frame(buf->y, buf->u, buf->v, - buf->width, buf->height, extra.timestamp_eof); - - if (out_id == -1) { - LOGE("Failed to encode frame. frame_id: %d encode_id: %d", extra.frame_id, encode_idx); - } - - // publish encode index - if (i == 0 && out_id != -1) { - MessageBuilder msg; - // this is really ugly - bool valid = (buf->get_frame_id() == extra.frame_id); - auto eidx = cam_info.type == DriverCam ? msg.initEvent(valid).initDriverEncodeIdx() : - (cam_info.type == WideRoadCam ? msg.initEvent(valid).initWideRoadEncodeIdx() : msg.initEvent(valid).initRoadEncodeIdx()); - eidx.setFrameId(extra.frame_id); - eidx.setTimestampSof(extra.timestamp_sof); - eidx.setTimestampEof(extra.timestamp_eof); - if (Hardware::TICI()) { - eidx.setType(cereal::EncodeIndex::Type::FULL_H_E_V_C); - } else { - eidx.setType(cam_info.type == DriverCam ? cereal::EncodeIndex::Type::FRONT : cereal::EncodeIndex::Type::FULL_H_E_V_C); - } - eidx.setEncodeId(encode_idx); - eidx.setSegmentNum(cur_seg); - eidx.setSegmentId(out_id); - if (lh) { - auto bytes = msg.toBytes(); - lh_log(lh, bytes.begin(), bytes.size(), true); - } - } - } + // we have to be recording if we are here + assert(re.recording); - encode_idx++; + // if we are actually writing the video file, do so + if (re.writer) { + auto data = edata.getData(); + re.writer->write((uint8_t *)data.begin(), data.size(), idx.getTimestampEof()/1000, false, flags & V4L2_BUF_FLAG_KEYFRAME); } - if (lh) { - lh_close(lh); - lh = NULL; + // put it in log stream as the idx packet + MessageBuilder bmsg; + auto evt = bmsg.initEvent(event.getValid()); + evt.setLogMonoTime(event.getLogMonoTime()); + if (name == "driverEncodeData") { evt.setDriverEncodeIdx(idx); } + if (name == "wideRoadEncodeData") { evt.setWideRoadEncodeIdx(idx); } + if (name == "qRoadEncodeData") { evt.setQRoadEncodeIdx(idx); } + if (name == "roadEncodeData") { evt.setRoadEncodeIdx(idx); } + auto new_msg = bmsg.toBytes(); + logger_log(&s->logger, (uint8_t *)new_msg.begin(), new_msg.size(), true); // always in qlog? + bytes_count += new_msg.size(); + + // free the message, we used it + delete msg; + } else if (offset_segment_num > s->rotate_segment) { + // encoderd packet has a newer segment, this means encoderd has rolled over + if (!re.marked_ready_to_rotate) { + re.marked_ready_to_rotate = true; + ++s->ready_to_rotate; + LOGD("rotate %d -> %d ready %d/%d for %s", + s->rotate_segment.load(), offset_segment_num, + s->ready_to_rotate.load(), s->max_waiting, name.c_str()); } + // queue up all the new segment messages, they go in after the rotate + re.q.push_back(msg); + } else { + LOGE("%s: encoderd packet has a older segment!!! idx.getSegmentNum():%d s->rotate_segment:%d re.encoderd_segment_offset:%d", + name.c_str(), idx.getSegmentNum(), s->rotate_segment.load(), re.encoderd_segment_offset); + // free the message, it's useless. this should never happen + // actually, this can happen if you restart encoderd + re.encoderd_segment_offset = -s->rotate_segment.load(); + delete msg; } - LOG("encoder destroy"); - for(auto &e : encoders) { - e->encoder_close(); - delete e; - } -} - -void logger_rotate(LoggerdState *s) { - { - std::unique_lock lk(s->rotate_lock); - int segment = -1; - int err = logger_next(&s->logger, LOG_ROOT.c_str(), s->segment_path, sizeof(s->segment_path), &segment); - assert(err == 0); - s->rotate_segment = segment; - s->ready_to_rotate = 0; - s->last_rotate_tms = millis_since_boot(); - } - s->rotate_cv.notify_all(); - LOGW((s->logger.part == 0) ? "logging to %s" : "rotated to %s", s->segment_path); -} - -void rotate_if_needed(LoggerdState *s) { - if (s->ready_to_rotate == s->max_waiting) { - logger_rotate(s); - } - - double tms = millis_since_boot(); - if ((tms - s->last_rotate_tms) > SEGMENT_LENGTH * 1000 && - (tms - s->last_camera_seen_tms) > NO_CAMERA_PATIENCE && - !LOGGERD_TEST) { - LOGW("no camera packet seen. auto rotating"); - logger_rotate(s); - } + return bytes_count; } void loggerd_thread() { @@ -182,15 +170,19 @@ void loggerd_thread() { typedef struct QlogState { std::string name; int counter, freq; + bool encoder; } QlogState; std::unordered_map qlog_states; + std::unordered_map remote_encoders; std::unique_ptr ctx(Context::create()); std::unique_ptr poller(Poller::create()); // subscribe to all socks for (const auto& it : services) { - if (!it.should_log) continue; + const bool encoder = strcmp(it.name+strlen(it.name)-strlen("EncodeData"), "EncodeData") == 0; + if (!it.should_log && !encoder) continue; + LOGD("logging %s (on port %d)", it.name, it.port); SubSocket * sock = SubSocket::create(ctx.get(), it.name); assert(sock != NULL); @@ -199,23 +191,21 @@ void loggerd_thread() { .name = it.name, .counter = 0, .freq = it.decimation, + .encoder = encoder, }; } LoggerdState s; // init logger - logger_init(&s.logger, "rlog", true); + logger_init(&s.logger, true); logger_rotate(&s); Params().put("CurrentRoute", s.logger.route_name); // init encoders s.last_camera_seen_tms = millis_since_boot(); - std::vector encoder_threads; for (const auto &cam : cameras_logged) { - if (cam.enable) { - encoder_threads.push_back(std::thread(encoder_thread, &s, cam)); - if (cam.trigger_rotate) s.max_waiting++; - } + s.max_waiting++; + if (cam.has_qcamera) { s.max_waiting++; } } uint64_t msg_count = 0, bytes_count = 0; @@ -231,9 +221,15 @@ void loggerd_thread() { Message *msg = nullptr; while (!do_exit && (msg = sock->receive(true))) { const bool in_qlog = qs.freq != -1 && (qs.counter++ % qs.freq == 0); - logger_log(&s.logger, (uint8_t *)msg->getData(), msg->getSize(), in_qlog); - bytes_count += msg->getSize(); - delete msg; + + if (qs.encoder) { + s.last_camera_seen_tms = millis_since_boot(); + bytes_count += handle_encoder_msg(&s, msg, qs.name, remote_encoders[sock]); + } else { + logger_log(&s.logger, (uint8_t *)msg->getData(), msg->getSize(), in_qlog); + bytes_count += msg->getSize(); + delete msg; + } rotate_if_needed(&s); @@ -251,10 +247,6 @@ void loggerd_thread() { } } - LOGW("closing encoders"); - s.rotate_cv.notify_all(); - for (auto &t : encoder_threads) t.join(); - LOGW("closing logger"); logger_close(&s.logger, &do_exit); @@ -267,3 +259,18 @@ void loggerd_thread() { // messaging cleanup for (auto &[sock, qs] : qlog_states) delete sock; } + +int main(int argc, char** argv) { + if (!Hardware::PC()) { + int ret; + ret = util::set_core_affinity({0, 1, 2, 3}); + assert(ret == 0); + // TODO: why does this impact camerad timings? + //ret = util::set_realtime_priority(1); + //assert(ret == 0); + } + + loggerd_thread(); + + return 0; +} diff --git a/selfdrive/loggerd/loggerd.h b/selfdrive/loggerd/loggerd.h index caacbc591f..1fa6349828 100644 --- a/selfdrive/loggerd/loggerd.h +++ b/selfdrive/loggerd/loggerd.h @@ -10,31 +10,32 @@ #include #include #include +#include #include "cereal/messaging/messaging.h" #include "cereal/services.h" #include "cereal/visionipc/visionipc.h" #include "cereal/visionipc/visionipc_client.h" -#include "selfdrive/camerad/cameras/camera_common.h" -#include "selfdrive/common/params.h" -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/timing.h" -#include "selfdrive/common/util.h" -#include "selfdrive/hardware/hw.h" +#include "system/camerad/cameras/camera_common.h" +#include "common/params.h" +#include "common/swaglog.h" +#include "common/timing.h" +#include "common/util.h" +#include "system/hardware/hw.h" -#include "selfdrive/loggerd/encoder.h" +#include "selfdrive/loggerd/encoder/encoder.h" #include "selfdrive/loggerd/logger.h" -#if defined(QCOM) || defined(QCOM2) -#include "selfdrive/loggerd/omx_encoder.h" -#define Encoder OmxEncoder +#ifdef QCOM2 +#include "selfdrive/loggerd/encoder/v4l_encoder.h" +#define Encoder V4LEncoder #else -#include "selfdrive/loggerd/raw_logger.h" -#define Encoder RawLogger +#include "selfdrive/loggerd/encoder/ffmpeg_encoder.h" +#define Encoder FfmpegEncoder #endif constexpr int MAIN_FPS = 20; -const int MAIN_BITRATE = Hardware::TICI() ? 10000000 : 5000000; -const int DCAM_BITRATE = Hardware::TICI() ? MAIN_BITRATE : 2500000; +const int MAIN_BITRATE = 10000000; +const int DCAM_BITRATE = MAIN_BITRATE; #define NO_CAMERA_PATIENCE 500 // fall back to time-based rotation if all cameras are dead @@ -49,10 +50,7 @@ struct LogCameraInfo { int fps; int bitrate; bool is_h265; - bool downscale; bool has_qcamera; - bool trigger_rotate; - bool enable; bool record; }; @@ -64,24 +62,22 @@ const LogCameraInfo cameras_logged[] = { .fps = MAIN_FPS, .bitrate = MAIN_BITRATE, .is_h265 = true, - .downscale = false, .has_qcamera = true, - .trigger_rotate = true, - .enable = true, .record = true, + .frame_width = 1928, + .frame_height = 1208, }, { .type = DriverCam, .stream_type = VISION_STREAM_DRIVER, .filename = "dcamera.hevc", - .fps = MAIN_FPS, // on EONs, more compressed this way + .fps = MAIN_FPS, .bitrate = DCAM_BITRATE, .is_h265 = true, - .downscale = false, .has_qcamera = false, - .trigger_rotate = Hardware::TICI(), - .enable = true, .record = Params().getBool("RecordFront"), + .frame_width = 1928, + .frame_height = 1208, }, { .type = WideRoadCam, @@ -90,11 +86,10 @@ const LogCameraInfo cameras_logged[] = { .fps = MAIN_FPS, .bitrate = MAIN_BITRATE, .is_h265 = true, - .downscale = false, .has_qcamera = false, - .trigger_rotate = true, - .enable = Hardware::TICI(), - .record = Hardware::TICI(), + .record = true, + .frame_width = 1928, + .frame_height = 1208, }, }; const LogCameraInfo qcam_info = { @@ -102,30 +97,7 @@ const LogCameraInfo qcam_info = { .fps = MAIN_FPS, .bitrate = 256000, .is_h265 = false, - .downscale = true, - .frame_width = Hardware::TICI() ? 526 : 480, - .frame_height = Hardware::TICI() ? 330 : 360 // keep pixel count the same? -}; - -struct LoggerdState { - LoggerState logger = {}; - char segment_path[4096]; - std::mutex rotate_lock; - std::condition_variable rotate_cv; - std::atomic rotate_segment; - std::atomic last_camera_seen_tms; - std::atomic ready_to_rotate; // count of encoders ready to rotate - int max_waiting = 0; - double last_rotate_tms = 0.; // last rotate time in ms - - // Sync logic for startup - std::atomic encoders_ready = 0; - std::atomic start_frame_id = 0; - bool camera_ready[WideRoadCam + 1] = {}; - bool camera_synced[WideRoadCam + 1] = {}; + .record = true, + .frame_width = 526, + .frame_height = 330, }; - -bool sync_encoders(LoggerdState *s, CameraType cam_type, uint32_t frame_id); -bool trigger_rotate_if_needed(LoggerdState *s, int cur_seg, uint32_t frame_id); -void rotate_if_needed(LoggerdState *s); -void loggerd_thread(); diff --git a/selfdrive/loggerd/main.cc b/selfdrive/loggerd/main.cc deleted file mode 100644 index 7069aa7068..0000000000 --- a/selfdrive/loggerd/main.cc +++ /dev/null @@ -1,20 +0,0 @@ -#include "selfdrive/loggerd/loggerd.h" - -#include - -int main(int argc, char** argv) { - if (Hardware::EON()) { - setpriority(PRIO_PROCESS, 0, -20); - } else if (Hardware::TICI()) { - int ret; - ret = util::set_core_affinity({0, 1, 2, 3}); - assert(ret == 0); - // TODO: why does this impact camerad timings? - //ret = util::set_realtime_priority(1); - //assert(ret == 0); - } - - loggerd_thread(); - - return 0; -} diff --git a/selfdrive/loggerd/omx_encoder.cc b/selfdrive/loggerd/omx_encoder.cc deleted file mode 100644 index f37c900150..0000000000 --- a/selfdrive/loggerd/omx_encoder.cc +++ /dev/null @@ -1,645 +0,0 @@ -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - -#include "selfdrive/loggerd/omx_encoder.h" - -#include -#include -#include - -#include -#include -#include - -#include -#include -#include -#include -#include "libyuv.h" - -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/util.h" -#include "selfdrive/loggerd/include/msm_media_info.h" - -// Check the OMX error code and assert if an error occurred. -#define OMX_CHECK(_expr) \ - do { \ - assert(OMX_ErrorNone == (_expr)); \ - } while (0) - -extern ExitHandler do_exit; - -// ***** OMX callback functions ***** - -void OmxEncoder::wait_for_state(OMX_STATETYPE state_) { - std::unique_lock lk(this->state_lock); - while (this->state != state_) { - this->state_cv.wait(lk); - } -} - -static OMX_CALLBACKTYPE omx_callbacks = { - .EventHandler = OmxEncoder::event_handler, - .EmptyBufferDone = OmxEncoder::empty_buffer_done, - .FillBufferDone = OmxEncoder::fill_buffer_done, -}; - -OMX_ERRORTYPE OmxEncoder::event_handler(OMX_HANDLETYPE component, OMX_PTR app_data, OMX_EVENTTYPE event, - OMX_U32 data1, OMX_U32 data2, OMX_PTR event_data) { - OmxEncoder *e = (OmxEncoder*)app_data; - if (event == OMX_EventCmdComplete) { - assert(data1 == OMX_CommandStateSet); - LOG("set state event 0x%x", data2); - { - std::unique_lock lk(e->state_lock); - e->state = (OMX_STATETYPE)data2; - } - e->state_cv.notify_all(); - } else if (event == OMX_EventError) { - LOGE("OMX error 0x%08x", data1); - } else { - LOGE("OMX unhandled event %d", event); - assert(false); - } - - return OMX_ErrorNone; -} - -OMX_ERRORTYPE OmxEncoder::empty_buffer_done(OMX_HANDLETYPE component, OMX_PTR app_data, - OMX_BUFFERHEADERTYPE *buffer) { - OmxEncoder *e = (OmxEncoder*)app_data; - e->free_in.push(buffer); - return OMX_ErrorNone; -} - -OMX_ERRORTYPE OmxEncoder::fill_buffer_done(OMX_HANDLETYPE component, OMX_PTR app_data, - OMX_BUFFERHEADERTYPE *buffer) { - OmxEncoder *e = (OmxEncoder*)app_data; - e->done_out.push(buffer); - return OMX_ErrorNone; -} - -#define PORT_INDEX_IN 0 -#define PORT_INDEX_OUT 1 - -static const char* omx_color_fomat_name(uint32_t format) __attribute__((unused)); -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"; - } -} - - -// ***** encoder functions ***** -OmxEncoder::OmxEncoder(const char* filename, int width, int height, int fps, int bitrate, bool h265, bool downscale, bool write) { - this->filename = filename; - this->write = write; - this->width = width; - this->height = height; - this->fps = fps; - this->remuxing = !h265; - - this->downscale = downscale; - if (this->downscale) { - this->y_ptr2 = (uint8_t *)malloc(this->width*this->height); - this->u_ptr2 = (uint8_t *)malloc(this->width*this->height/4); - this->v_ptr2 = (uint8_t *)malloc(this->width*this->height/4); - } - - auto component = (OMX_STRING)(h265 ? "OMX.qcom.video.encoder.hevc" : "OMX.qcom.video.encoder.avc"); - int err = OMX_GetHandle(&this->handle, component, this, &omx_callbacks); - if (err != OMX_ErrorNone) { - LOGE("error getting codec: %x", err); - } - assert(err == OMX_ErrorNone); - // printf("handle: %p\n", this->handle); - - // setup input port - - OMX_PARAM_PORTDEFINITIONTYPE in_port = {0}; - in_port.nSize = sizeof(in_port); - in_port.nPortIndex = (OMX_U32) PORT_INDEX_IN; - OMX_CHECK(OMX_GetParameter(this->handle, OMX_IndexParamPortDefinition, (OMX_PTR) &in_port)); - - in_port.format.video.nFrameWidth = this->width; - in_port.format.video.nFrameHeight = this->height; - in_port.format.video.nStride = VENUS_Y_STRIDE(COLOR_FMT_NV12, this->width); - in_port.format.video.nSliceHeight = this->height; - // in_port.nBufferSize = (this->width * this->height * 3) / 2; - in_port.nBufferSize = VENUS_BUFFER_SIZE(COLOR_FMT_NV12, this->width, this->height); - in_port.format.video.xFramerate = (this->fps * 65536); - in_port.format.video.eCompressionFormat = OMX_VIDEO_CodingUnused; - // in_port.format.video.eColorFormat = OMX_COLOR_FormatYUV420SemiPlanar; - in_port.format.video.eColorFormat = (OMX_COLOR_FORMATTYPE)QOMX_COLOR_FORMATYUV420PackedSemiPlanar32m; - - OMX_CHECK(OMX_SetParameter(this->handle, OMX_IndexParamPortDefinition, (OMX_PTR) &in_port)); - OMX_CHECK(OMX_GetParameter(this->handle, OMX_IndexParamPortDefinition, (OMX_PTR) &in_port)); - this->in_buf_headers.resize(in_port.nBufferCountActual); - - // setup output port - - OMX_PARAM_PORTDEFINITIONTYPE out_port = {0}; - out_port.nSize = sizeof(out_port); - out_port.nPortIndex = (OMX_U32) PORT_INDEX_OUT; - OMX_CHECK(OMX_GetParameter(this->handle, OMX_IndexParamPortDefinition, (OMX_PTR)&out_port)); - out_port.format.video.nFrameWidth = this->width; - out_port.format.video.nFrameHeight = this->height; - out_port.format.video.xFramerate = 0; - out_port.format.video.nBitrate = bitrate; - if (h265) { - out_port.format.video.eCompressionFormat = OMX_VIDEO_CodingHEVC; - } else { - out_port.format.video.eCompressionFormat = OMX_VIDEO_CodingAVC; - } - out_port.format.video.eColorFormat = OMX_COLOR_FormatUnused; - - OMX_CHECK(OMX_SetParameter(this->handle, OMX_IndexParamPortDefinition, (OMX_PTR) &out_port)); - - OMX_CHECK(OMX_GetParameter(this->handle, OMX_IndexParamPortDefinition, (OMX_PTR) &out_port)); - this->out_buf_headers.resize(out_port.nBufferCountActual); - - OMX_VIDEO_PARAM_BITRATETYPE bitrate_type = {0}; - bitrate_type.nSize = sizeof(bitrate_type); - bitrate_type.nPortIndex = (OMX_U32) PORT_INDEX_OUT; - OMX_CHECK(OMX_GetParameter(this->handle, OMX_IndexParamVideoBitrate, (OMX_PTR) &bitrate_type)); - bitrate_type.eControlRate = OMX_Video_ControlRateVariable; - bitrate_type.nTargetBitrate = bitrate; - - OMX_CHECK(OMX_SetParameter(this->handle, OMX_IndexParamVideoBitrate, (OMX_PTR) &bitrate_type)); - - if (h265) { - // setup HEVC - #ifndef QCOM2 - OMX_VIDEO_PARAM_HEVCTYPE hevc_type = {0}; - OMX_INDEXTYPE index_type = (OMX_INDEXTYPE) OMX_IndexParamVideoHevc; - #else - OMX_VIDEO_PARAM_PROFILELEVELTYPE hevc_type = {0}; - OMX_INDEXTYPE index_type = OMX_IndexParamVideoProfileLevelCurrent; - #endif - hevc_type.nSize = sizeof(hevc_type); - hevc_type.nPortIndex = (OMX_U32) PORT_INDEX_OUT; - OMX_CHECK(OMX_GetParameter(this->handle, index_type, (OMX_PTR) &hevc_type)); - - hevc_type.eProfile = OMX_VIDEO_HEVCProfileMain; - hevc_type.eLevel = OMX_VIDEO_HEVCHighTierLevel5; - - OMX_CHECK(OMX_SetParameter(this->handle, index_type, (OMX_PTR) &hevc_type)); - } else { - // setup h264 - OMX_VIDEO_PARAM_AVCTYPE avc = { 0 }; - avc.nSize = sizeof(avc); - avc.nPortIndex = (OMX_U32) PORT_INDEX_OUT; - OMX_CHECK(OMX_GetParameter(this->handle, OMX_IndexParamVideoAvc, &avc)); - - avc.nBFrames = 0; - avc.nPFrames = 15; - - avc.eProfile = OMX_VIDEO_AVCProfileHigh; - avc.eLevel = OMX_VIDEO_AVCLevel31; - - avc.nAllowedPictureTypes |= OMX_VIDEO_PictureTypeB; - avc.eLoopFilterMode = OMX_VIDEO_AVCLoopFilterEnable; - - avc.nRefFrames = 1; - avc.bUseHadamard = OMX_TRUE; - avc.bEntropyCodingCABAC = OMX_TRUE; - avc.bWeightedPPrediction = OMX_TRUE; - avc.bconstIpred = OMX_TRUE; - - OMX_CHECK(OMX_SetParameter(this->handle, OMX_IndexParamVideoAvc, &avc)); - } - - - // 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(this->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(this->handle, OMX_IndexParamVideoProfileLevelQuerySupported, ¶ms) != OMX_ErrorNone) - // break; - // printf("profile %d level 0x%x\n", params.eProfile, params.eLevel); - // } - - OMX_CHECK(OMX_SendCommand(this->handle, OMX_CommandStateSet, OMX_StateIdle, NULL)); - - for (auto &buf : this->in_buf_headers) { - OMX_CHECK(OMX_AllocateBuffer(this->handle, &buf, PORT_INDEX_IN, this, - in_port.nBufferSize)); - } - - for (auto &buf : this->out_buf_headers) { - OMX_CHECK(OMX_AllocateBuffer(this->handle, &buf, PORT_INDEX_OUT, this, - out_port.nBufferSize)); - } - - wait_for_state(OMX_StateIdle); - - OMX_CHECK(OMX_SendCommand(this->handle, OMX_CommandStateSet, OMX_StateExecuting, NULL)); - - wait_for_state(OMX_StateExecuting); - - // give omx all the output buffers - for (auto &buf : this->out_buf_headers) { - // printf("fill %p\n", this->out_buf_headers[i]); - OMX_CHECK(OMX_FillThisBuffer(this->handle, buf)); - } - - // fill the input free queue - for (auto &buf : this->in_buf_headers) { - this->free_in.push(buf); - } - - LOGE("omx initialized - in: %d - out %d", this->in_buf_headers.size(), this->out_buf_headers.size()); -} - -void OmxEncoder::callback_handler(OmxEncoder *e) { - // OMX documentation specifies to not empty the buffer from the callback function - // so we use this intermediate handler to copy the buffer for further writing - // and give it back to OMX. We could also send the data over msgq from here. - bool exit = false; - - while (!exit) { - OMX_BUFFERHEADERTYPE *buffer = e->done_out.pop(); - OmxBuffer *new_buffer = (OmxBuffer*)malloc(sizeof(OmxBuffer) + buffer->nFilledLen); - assert(new_buffer); - - new_buffer->header = *buffer; - memcpy(new_buffer->data, buffer->pBuffer + buffer->nOffset, buffer->nFilledLen); - - e->to_write.push(new_buffer); - -#ifdef QCOM2 - if (buffer->nFlags & OMX_BUFFERFLAG_CODECCONFIG) { - buffer->nTimeStamp = 0; - } - - if (buffer->nFlags & OMX_BUFFERFLAG_EOS) { - buffer->nTimeStamp = 0; - } -#endif - - if (buffer->nFlags & OMX_BUFFERFLAG_EOS) { - exit = true; - } - - // give omx back the buffer - // TOOD: fails when shutting down - OMX_CHECK(OMX_FillThisBuffer(e->handle, buffer)); - } -} - - -void OmxEncoder::write_handler(OmxEncoder *e){ - bool exit = false; - while (!exit) { - OmxBuffer *out_buf = e->to_write.pop(); - OmxEncoder::handle_out_buf(e, out_buf); - - if (out_buf->header.nFlags & OMX_BUFFERFLAG_EOS) { - exit = true; - } - - free(out_buf); - } -} - - -void OmxEncoder::handle_out_buf(OmxEncoder *e, OmxBuffer *out_buf) { - int err; - - if (out_buf->header.nFlags & OMX_BUFFERFLAG_CODECCONFIG) { - if (e->codec_config_len < out_buf->header.nFilledLen) { - e->codec_config = (uint8_t *)realloc(e->codec_config, out_buf->header.nFilledLen); - } - e->codec_config_len = out_buf->header.nFilledLen; - memcpy(e->codec_config, out_buf->data, out_buf->header.nFilledLen); - - // TODO: is still needed? -#ifdef QCOM2 - out_buf->header.nTimeStamp = 0; -#endif - } - - if (e->of) { - //printf("write %d flags 0x%x\n", out_buf->nFilledLen, out_buf->nFlags); - size_t written = util::safe_fwrite(out_buf->data, 1, out_buf->header.nFilledLen, e->of); - if (written != out_buf->header.nFilledLen) { - LOGE("failed to write file.errno=%d", errno); - } - } - - if (e->remuxing) { - if (!e->wrote_codec_config && e->codec_config_len > 0) { - // extradata will be freed by av_free() in avcodec_free_context() - e->codec_ctx->extradata = (uint8_t*)av_mallocz(e->codec_config_len + AV_INPUT_BUFFER_PADDING_SIZE); - e->codec_ctx->extradata_size = e->codec_config_len; - memcpy(e->codec_ctx->extradata, e->codec_config, e->codec_config_len); - - err = avcodec_parameters_from_context(e->out_stream->codecpar, e->codec_ctx); - assert(err >= 0); - err = avformat_write_header(e->ofmt_ctx, NULL); - assert(err >= 0); - - e->wrote_codec_config = true; - } - - if (out_buf->header.nTimeStamp > 0) { - // input timestamps are in microseconds - AVRational in_timebase = {1, 1000000}; - - AVPacket pkt; - av_init_packet(&pkt); - pkt.data = out_buf->data; - pkt.size = out_buf->header.nFilledLen; - - enum AVRounding rnd = static_cast(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX); - pkt.pts = pkt.dts = av_rescale_q_rnd(out_buf->header.nTimeStamp, in_timebase, e->ofmt_ctx->streams[0]->time_base, rnd); - pkt.duration = av_rescale_q(50*1000, in_timebase, e->ofmt_ctx->streams[0]->time_base); - - if (out_buf->header.nFlags & OMX_BUFFERFLAG_SYNCFRAME) { - pkt.flags |= AV_PKT_FLAG_KEY; - } - - err = av_write_frame(e->ofmt_ctx, &pkt); - if (err < 0) { LOGW("ts encoder write issue"); } - - av_free_packet(&pkt); - } - } -} - -int OmxEncoder::encode_frame(const uint8_t *y_ptr, const uint8_t *u_ptr, const uint8_t *v_ptr, - int in_width, int in_height, uint64_t ts) { - int err; - if (!this->is_open) { - 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(&this->lock); - OMX_BUFFERHEADERTYPE* in_buf = nullptr; - while (!this->free_in.try_pop(in_buf, 20)) { - if (do_exit) { - return -1; - } - } - - //pthread_mutex_lock(&this->lock); - - int ret = this->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, this->width); - int in_uv_stride = VENUS_UV_STRIDE(COLOR_FMT_NV12, this->width); - // uint8_t *in_uv_ptr = in_buf_ptr + (this->width * this->height); - uint8_t *in_uv_ptr = in_buf_ptr + (in_y_stride * VENUS_Y_SCANLINES(COLOR_FMT_NV12, this->height)); - - if (this->downscale) { - I420Scale(y_ptr, in_width, - u_ptr, in_width/2, - v_ptr, in_width/2, - in_width, in_height, - this->y_ptr2, this->width, - this->u_ptr2, this->width/2, - this->v_ptr2, this->width/2, - this->width, this->height, - libyuv::kFilterNone); - y_ptr = this->y_ptr2; - u_ptr = this->u_ptr2; - v_ptr = this->v_ptr2; - } - err = libyuv::I420ToNV12(y_ptr, this->width, - u_ptr, this->width/2, - v_ptr, this->width/2, - in_y_ptr, in_y_stride, - in_uv_ptr, in_uv_stride, - this->width, this->height); - assert(err == 0); - - // in_buf->nFilledLen = (this->width*this->height) + (this->width*this->height/2); - in_buf->nFilledLen = VENUS_BUFFER_SIZE(COLOR_FMT_NV12, this->width, this->height); - in_buf->nFlags = OMX_BUFFERFLAG_ENDOFFRAME; - in_buf->nOffset = 0; - in_buf->nTimeStamp = ts/1000LL; // OMX_TICKS, in microseconds - this->last_t = in_buf->nTimeStamp; - - OMX_CHECK(OMX_EmptyThisBuffer(this->handle, in_buf)); - - this->dirty = true; - - this->counter++; - - return ret; -} - -void OmxEncoder::encoder_open(const char* path) { - int err; - - snprintf(this->vid_path, sizeof(this->vid_path), "%s/%s", path, this->filename); - LOGD("encoder_open %s remuxing:%d", this->vid_path, this->remuxing); - - if (this->remuxing) { - avformat_alloc_output_context2(&this->ofmt_ctx, NULL, NULL, this->vid_path); - assert(this->ofmt_ctx); - - this->out_stream = avformat_new_stream(this->ofmt_ctx, NULL); - assert(this->out_stream); - - // set codec correctly - av_register_all(); - - AVCodec *codec = NULL; - codec = avcodec_find_encoder(AV_CODEC_ID_H264); - assert(codec); - - this->codec_ctx = avcodec_alloc_context3(codec); - assert(this->codec_ctx); - this->codec_ctx->width = this->width; - this->codec_ctx->height = this->height; - this->codec_ctx->pix_fmt = AV_PIX_FMT_YUV420P; - this->codec_ctx->time_base = (AVRational){ 1, this->fps }; - - err = avio_open(&this->ofmt_ctx->pb, this->vid_path, AVIO_FLAG_WRITE); - assert(err >= 0); - - this->wrote_codec_config = false; - } else { - if (this->write) { - this->of = util::safe_fopen(this->vid_path, "wb"); - assert(this->of); -#ifndef QCOM2 - if (this->codec_config_len > 0) { - util::safe_fwrite(this->codec_config, 1, this->codec_config_len, this->of); - } -#endif - } - } - - // create camera lock file - snprintf(this->lock_path, sizeof(this->lock_path), "%s/%s.lock", path, this->filename); - int lock_fd = HANDLE_EINTR(open(this->lock_path, O_RDWR | O_CREAT, 0664)); - assert(lock_fd >= 0); - close(lock_fd); - - // start writer threads - callback_handler_thread = std::thread(OmxEncoder::callback_handler, this); - write_handler_thread = std::thread(OmxEncoder::write_handler, this); - - this->is_open = true; - this->counter = 0; -} - -void OmxEncoder::encoder_close() { - if (this->is_open) { - if (this->dirty) { - // drain output only if there could be frames in the encoder - - OMX_BUFFERHEADERTYPE* in_buf = this->free_in.pop(); - in_buf->nFilledLen = 0; - in_buf->nOffset = 0; - in_buf->nFlags = OMX_BUFFERFLAG_EOS; - in_buf->nTimeStamp = this->last_t + 1000000LL/this->fps; - - OMX_CHECK(OMX_EmptyThisBuffer(this->handle, in_buf)); - - this->dirty = false; - } - - callback_handler_thread.join(); - write_handler_thread.join(); - - if (this->remuxing) { - av_write_trailer(this->ofmt_ctx); - avcodec_free_context(&this->codec_ctx); - avio_closep(&this->ofmt_ctx->pb); - avformat_free_context(this->ofmt_ctx); - } else { - if (this->of) { - util::safe_fflush(this->of); - fclose(this->of); - this->of = nullptr; - } - } - unlink(this->lock_path); - } - this->is_open = false; -} - -OmxEncoder::~OmxEncoder() { - assert(!this->is_open); - - OMX_CHECK(OMX_SendCommand(this->handle, OMX_CommandStateSet, OMX_StateIdle, NULL)); - - wait_for_state(OMX_StateIdle); - - OMX_CHECK(OMX_SendCommand(this->handle, OMX_CommandStateSet, OMX_StateLoaded, NULL)); - - for (auto &buf : this->in_buf_headers) { - OMX_CHECK(OMX_FreeBuffer(this->handle, PORT_INDEX_IN, buf)); - } - - for (auto &buf : this->out_buf_headers) { - OMX_CHECK(OMX_FreeBuffer(this->handle, PORT_INDEX_OUT, buf)); - } - - wait_for_state(OMX_StateLoaded); - - OMX_CHECK(OMX_FreeHandle(this->handle)); - - OMX_BUFFERHEADERTYPE *buf; - while (this->free_in.try_pop(buf)); - while (this->done_out.try_pop(buf)); - - OmxBuffer *write_buf; - while (this->to_write.try_pop(write_buf)) { - free(write_buf); - }; - - if (this->codec_config) { - free(this->codec_config); - } - - if (this->downscale) { - free(this->y_ptr2); - free(this->u_ptr2); - free(this->v_ptr2); - } -} diff --git a/selfdrive/loggerd/omx_encoder.h b/selfdrive/loggerd/omx_encoder.h deleted file mode 100644 index e3087e31bf..0000000000 --- a/selfdrive/loggerd/omx_encoder.h +++ /dev/null @@ -1,85 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include -extern "C" { -#include -} - -#include "selfdrive/common/queue.h" -#include "selfdrive/loggerd/encoder.h" - -struct OmxBuffer { - OMX_BUFFERHEADERTYPE header; - OMX_U8 data[]; -}; - - -// OmxEncoder, lossey codec using hardware hevc -class OmxEncoder : public VideoEncoder { -public: - OmxEncoder(const char* filename, int width, int height, int fps, int bitrate, bool h265, bool downscale, bool write = true); - ~OmxEncoder(); - int encode_frame(const uint8_t *y_ptr, const uint8_t *u_ptr, const uint8_t *v_ptr, - int in_width, int in_height, uint64_t ts); - void encoder_open(const char* path); - void encoder_close(); - - // OMX callbacks - 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); - static OMX_ERRORTYPE empty_buffer_done(OMX_HANDLETYPE component, OMX_PTR app_data, - OMX_BUFFERHEADERTYPE *buffer); - static OMX_ERRORTYPE fill_buffer_done(OMX_HANDLETYPE component, OMX_PTR app_data, - OMX_BUFFERHEADERTYPE *buffer); - -private: - void wait_for_state(OMX_STATETYPE state); - static void callback_handler(OmxEncoder *e); - static void write_handler(OmxEncoder *e); - static void handle_out_buf(OmxEncoder *e, OmxBuffer *out_buf); - - int width, height, fps; - char vid_path[1024]; - char lock_path[1024]; - bool is_open = false; - bool dirty = false; - bool write = false; - int counter = 0; - std::thread callback_handler_thread; - std::thread write_handler_thread; - - const char* filename; - FILE *of = nullptr; - - size_t codec_config_len; - uint8_t *codec_config = NULL; - bool wrote_codec_config; - - std::mutex state_lock; - std::condition_variable state_cv; - OMX_STATETYPE state = OMX_StateLoaded; - - OMX_HANDLETYPE handle; - - std::vector in_buf_headers; - std::vector out_buf_headers; - - uint64_t last_t; - - SafeQueue free_in; - SafeQueue done_out; - SafeQueue to_write; - - AVFormatContext *ofmt_ctx; - AVCodecContext *codec_ctx; - AVStream *out_stream; - bool remuxing; - - bool downscale; - uint8_t *y_ptr2, *u_ptr2, *v_ptr2; -}; diff --git a/selfdrive/loggerd/raw_logger.cc b/selfdrive/loggerd/raw_logger.cc deleted file mode 100644 index 8d27e4a7a1..0000000000 --- a/selfdrive/loggerd/raw_logger.cc +++ /dev/null @@ -1,189 +0,0 @@ -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - -#include "selfdrive/loggerd/raw_logger.h" - -#include -#include - -#include -#include -#include - -#define __STDC_CONSTANT_MACROS - -#include "libyuv.h" - -extern "C" { -#include -#include -#include -} - -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/util.h" - -RawLogger::RawLogger(const char* filename, int width, int height, int fps, - int bitrate, bool h265, bool downscale, bool write) - : filename(filename), fps(fps) { - - // TODO: respect write arg - - 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 }; - - int 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; - - if (downscale) { - downscale_buf.resize(width * height * 3 / 2); - } -} - -RawLogger::~RawLogger() { - av_frame_free(&frame); - avcodec_close(codec_ctx); - av_free(codec_ctx); -} - -void RawLogger::encoder_open(const char* path) { - vid_path = util::string_format("%s/%s", path, filename); - - // create camera lock file - lock_path = util::string_format("%s/%s.lock", path, filename); - - LOG("open %s\n", lock_path.c_str()); - - int lock_fd = HANDLE_EINTR(open(lock_path.c_str(), O_RDWR | O_CREAT, 0664)); - assert(lock_fd >= 0); - close(lock_fd); - - format_ctx = NULL; - avformat_alloc_output_context2(&format_ctx, NULL, "matroska", 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; - - int 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::encoder_close() { - if (!is_open) return; - - int err = av_write_trailer(format_ctx); - assert(err == 0); - - 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::encode_frame(const uint8_t *y_ptr, const uint8_t *u_ptr, const uint8_t *v_ptr, - int in_width, int in_height, uint64_t ts) { - AVPacket pkt; - av_init_packet(&pkt); - pkt.data = NULL; - pkt.size = 0; - - if (downscale_buf.size() > 0) { - uint8_t *out_y = downscale_buf.data(); - uint8_t *out_u = out_y + codec_ctx->width * codec_ctx->height; - uint8_t *out_v = out_u + (codec_ctx->width / 2) * (codec_ctx->height / 2); - libyuv::I420Scale(y_ptr, in_width, - u_ptr, in_width/2, - v_ptr, in_width/2, - in_width, in_height, - out_y, codec_ctx->width, - out_u, codec_ctx->width/2, - out_v, codec_ctx->width/2, - codec_ctx->width, codec_ctx->height, - libyuv::kFilterNone); - frame->data[0] = out_y; - frame->data[1] = out_u; - frame->data[2] = out_v; - } else { - frame->data[0] = (uint8_t*)y_ptr; - frame->data[1] = (uint8_t*)u_ptr; - frame->data[2] = (uint8_t*)v_ptr; - } - frame->pts = counter; - - int ret = counter; - - int err = avcodec_send_frame(codec_ctx, frame); - if (ret < 0) { - LOGE("avcode_send_frame error %d", err); - ret = -1; - } - - while (ret >= 0){ - err = avcodec_receive_packet(codec_ctx, &pkt); - if (err == AVERROR_EOF) { - break; - } else if (err == AVERROR(EAGAIN)) { - // Encoder might need a few frames on startup to get started. Keep going - ret = 0; - break; - } else if (err < 0) { - LOGE("avcodec_receive_packet error %d", err); - ret = -1; - break; - } - - 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("av_interleaved_write_frame %d", err); - ret = -1; - } else { - counter++; - } - } - - av_packet_unref(&pkt); - return ret; -} diff --git a/selfdrive/loggerd/raw_logger.h b/selfdrive/loggerd/raw_logger.h deleted file mode 100644 index 3c7fed38cc..0000000000 --- a/selfdrive/loggerd/raw_logger.h +++ /dev/null @@ -1,43 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -extern "C" { -#include -#include -#include -} - -#include "selfdrive/loggerd/encoder.h" - -class RawLogger : public VideoEncoder { - public: - RawLogger(const char* filename, int width, int height, int fps, - int bitrate, bool h265, bool downscale, bool write = true); - ~RawLogger(); - int encode_frame(const uint8_t *y_ptr, const uint8_t *u_ptr, const uint8_t *v_ptr, - int in_width, int in_height, uint64_t ts); - void encoder_open(const char* path); - void encoder_close(); - -private: - const char* filename; - //bool write; - int fps; - int counter = 0; - bool is_open = false; - - std::string vid_path, lock_path; - - const AVCodec *codec = NULL; - AVCodecContext *codec_ctx = NULL; - - AVStream *stream = NULL; - AVFormatContext *format_ctx = NULL; - - AVFrame *frame = NULL; - std::vector downscale_buf; -}; diff --git a/selfdrive/loggerd/tests/fill_eon.py b/selfdrive/loggerd/tests/fill_eon.py index f273ea89ec..b40982fa9f 100755 --- a/selfdrive/loggerd/tests/fill_eon.py +++ b/selfdrive/loggerd/tests/fill_eon.py @@ -23,4 +23,4 @@ if __name__ == "__main__": # Fill up to 99 percent available_percent = get_available_percent() if available_percent < 1.0: - break + break diff --git a/selfdrive/loggerd/tests/loggerd_tests_common.py b/selfdrive/loggerd/tests/loggerd_tests_common.py index 59952fd2c3..80cfb162f1 100644 --- a/selfdrive/loggerd/tests/loggerd_tests_common.py +++ b/selfdrive/loggerd/tests/loggerd_tests_common.py @@ -8,22 +8,22 @@ import unittest import selfdrive.loggerd.uploader as uploader def create_random_file(file_path, size_mb, lock=False): - try: - os.mkdir(os.path.dirname(file_path)) - except OSError: - pass + try: + os.mkdir(os.path.dirname(file_path)) + except OSError: + pass - lock_path = file_path + ".lock" - if lock: - os.close(os.open(lock_path, os.O_CREAT | os.O_EXCL)) + lock_path = file_path + ".lock" + if lock: + os.close(os.open(lock_path, os.O_CREAT | os.O_EXCL)) - chunks = 128 - chunk_bytes = int(size_mb * 1024 * 1024 / chunks) - data = os.urandom(chunk_bytes) + chunks = 128 + chunk_bytes = int(size_mb * 1024 * 1024 / chunks) + data = os.urandom(chunk_bytes) - with open(file_path, 'wb') as f: - for _ in range(chunks): - f.write(data) + with open(file_path, 'wb') as f: + for _ in range(chunks): + f.write(data) class MockResponse(): def __init__(self, text, status_code): diff --git a/selfdrive/loggerd/tests/test_deleter.py b/selfdrive/loggerd/tests/test_deleter.py old mode 100644 new mode 100755 index e0a063bd43..80fb5c997f --- a/selfdrive/loggerd/tests/test_deleter.py +++ b/selfdrive/loggerd/tests/test_deleter.py @@ -1,12 +1,12 @@ +#!/usr/bin/env python3 import os import time import threading import unittest from collections import namedtuple -import selfdrive.loggerd.deleter as deleter from common.timeout import Timeout, TimeoutException - +import selfdrive.loggerd.deleter as deleter from selfdrive.loggerd.tests.loggerd_tests_common import UploaderTestCase Stats = namedtuple("Stats", ['f_bavail', 'f_blocks', 'f_frsize']) diff --git a/selfdrive/loggerd/tests/test_encoder.py b/selfdrive/loggerd/tests/test_encoder.py index 97c142652f..1b9bcef2d7 100755 --- a/selfdrive/loggerd/tests/test_encoder.py +++ b/selfdrive/loggerd/tests/test_encoder.py @@ -13,27 +13,19 @@ from tqdm import trange from common.params import Params from common.timeout import Timeout -from selfdrive.hardware import EON, TICI +from system.hardware import TICI from selfdrive.loggerd.config import ROOT from selfdrive.manager.process_config import managed_processes from tools.lib.logreader import LogReader SEGMENT_LENGTH = 2 -if EON: - FULL_SIZE = 1253786 # file size for a 2s segment in bytes - CAMERAS = [ - ("fcamera.hevc", 20, FULL_SIZE, "roadEncodeIdx"), - ("dcamera.hevc", 10, 770920, "driverEncodeIdx"), - ("qcamera.ts", 20, 77066, None), - ] -else: - FULL_SIZE = 2507572 - CAMERAS = [ - ("fcamera.hevc", 20, FULL_SIZE, "roadEncodeIdx"), - ("dcamera.hevc", 20, FULL_SIZE, "driverEncodeIdx"), - ("ecamera.hevc", 20, FULL_SIZE, "wideRoadEncodeIdx"), - ("qcamera.ts", 20, 77066, None), - ] +FULL_SIZE = 2507572 +CAMERAS = [ + ("fcamera.hevc", 20, FULL_SIZE, "roadEncodeIdx"), + ("dcamera.hevc", 20, FULL_SIZE, "driverEncodeIdx"), + ("ecamera.hevc", 20, FULL_SIZE, "wideRoadEncodeIdx"), + ("qcamera.ts", 20, 130000, None), +] # we check frame count, so we don't have to be too strict on size FILE_SIZE_TOLERANCE = 0.5 @@ -44,7 +36,7 @@ class TestEncoder(unittest.TestCase): # TODO: all of loggerd should work on PC @classmethod def setUpClass(cls): - if not (EON or TICI): + if not TICI: raise unittest.SkipTest def setUp(self): @@ -70,6 +62,7 @@ class TestEncoder(unittest.TestCase): managed_processes['sensord'].start() managed_processes['loggerd'].start() + managed_processes['encoderd'].start() time.sleep(1.0) managed_processes['camerad'].start() @@ -93,8 +86,6 @@ class TestEncoder(unittest.TestCase): if not record_front and "dcamera" in camera: continue - eon_dcam = EON and (camera == 'dcamera.hevc') - file_path = f"{route_prefix_path}--{i}/{camera}" # check file exists @@ -107,21 +98,21 @@ class TestEncoder(unittest.TestCase): cmd = "LD_LIBRARY_PATH=/usr/local/lib " + cmd expected_frames = fps * SEGMENT_LENGTH - frame_tolerance = 1 if eon_dcam else 0 probe = subprocess.check_output(cmd, shell=True, encoding='utf8') frame_count = int(probe.split('\n')[0].strip()) counts.append(frame_count) - self.assertTrue(abs(expected_frames - frame_count) <= frame_tolerance, - f"segment #{i}: {camera} failed frame count check: expected {expected_frames}, got {frame_count}") + self.assertEqual(frame_count, expected_frames, + f"segment #{i}: {camera} failed frame count check: expected {expected_frames}, got {frame_count}") # sanity check file size file_size = os.path.getsize(file_path) - self.assertTrue(math.isclose(file_size, size, rel_tol=FILE_SIZE_TOLERANCE)) + self.assertTrue(math.isclose(file_size, size, rel_tol=FILE_SIZE_TOLERANCE), + f"{file_path} size {file_size} isn't close to target size {size}") # Check encodeIdx if encode_idx_name is not None: - rlog_path = f"{route_prefix_path}--{i}/rlog.bz2" + rlog_path = f"{route_prefix_path}--{i}/rlog" msgs = [m for m in LogReader(rlog_path) if m.which() == encode_idx_name] encode_msgs = [getattr(m, encode_idx_name) for m in msgs] @@ -140,9 +131,8 @@ class TestEncoder(unittest.TestCase): self.assertTrue(all(valid)) - if not eon_dcam: - self.assertEqual(expected_frames * i, encode_idxs[0]) - first_frames.append(frame_idxs[0]) + self.assertEqual(expected_frames * i, encode_idxs[0]) + first_frames.append(frame_idxs[0]) self.assertEqual(len(set(encode_idxs)), len(encode_idxs)) self.assertEqual(1, len(set(first_frames))) @@ -153,19 +143,18 @@ class TestEncoder(unittest.TestCase): shutil.rmtree(f"{route_prefix_path}--{i}") try: - for i in trange(num_segments + 1): + for i in trange(num_segments): # poll for next segment with Timeout(int(SEGMENT_LENGTH*10), error_msg=f"timed out waiting for segment {i}"): - while Path(f"{route_prefix_path}--{i}") not in Path(ROOT).iterdir(): + while Path(f"{route_prefix_path}--{i+1}") not in Path(ROOT).iterdir(): time.sleep(0.1) + check_seg(i) finally: managed_processes['loggerd'].stop() + managed_processes['encoderd'].stop() managed_processes['camerad'].stop() managed_processes['sensord'].stop() - for i in trange(num_segments): - check_seg(i) - if __name__ == "__main__": unittest.main() diff --git a/selfdrive/loggerd/tests/test_logger.cc b/selfdrive/loggerd/tests/test_logger.cc index 21b1d711d8..ba7835d632 100644 --- a/selfdrive/loggerd/tests/test_logger.cc +++ b/selfdrive/loggerd/tests/test_logger.cc @@ -4,12 +4,13 @@ #include #include #include +#include #include "catch2/catch.hpp" #include "cereal/messaging/messaging.h" -#include "selfdrive/common/util.h" +#include "common/util.h" #include "selfdrive/loggerd/logger.h" -#include "selfdrive/ui/replay/util.h" +#include "tools/replay/util.h" typedef cereal::Sentinel::SentinelType SentinelType; @@ -18,10 +19,10 @@ void verify_segment(const std::string &route_path, int segment, int max_segment, SentinelType begin_sentinel = segment == 0 ? SentinelType::START_OF_ROUTE : SentinelType::START_OF_SEGMENT; SentinelType end_sentinel = segment == max_segment - 1 ? SentinelType::END_OF_ROUTE : SentinelType::END_OF_SEGMENT; - REQUIRE(!util::file_exists(segment_path + "/rlog.bz2.lock")); - for (const char *fn : {"/rlog.bz2", "/qlog.bz2"}) { + REQUIRE(!util::file_exists(segment_path + "/rlog.lock")); + for (const char *fn : {"/rlog", "/qlog"}) { const std::string log_file = segment_path + fn; - std::string log = decompressBZ2(util::read_file(log_file)); + std::string log = util::read_file(log_file); REQUIRE(!log.empty()); int event_cnt = 0, i = 0; kj::ArrayPtr words((capnp::word *)log.data(), log.size() / sizeof(capnp::word)); @@ -47,7 +48,7 @@ void verify_segment(const std::string &route_path, int segment, int max_segment, } ++i; } catch (const kj::Exception &ex) { - INFO("failed parse " << i << " excpetion :" << ex.getDescription()); + INFO("failed parse " << i << " exception :" << ex.getDescription()); REQUIRE(0); break; } @@ -70,7 +71,7 @@ TEST_CASE("logger") { ExitHandler do_exit; LoggerState logger = {}; - logger_init(&logger, "rlog", true); + logger_init(&logger, true); char segment_path[PATH_MAX] = {}; int segment = -1; @@ -78,7 +79,7 @@ TEST_CASE("logger") { const int segment_cnt = 100; for (int i = 0; i < segment_cnt; ++i) { REQUIRE(logger_next(&logger, log_root.c_str(), segment_path, sizeof(segment_path), &segment) == 0); - REQUIRE(util::file_exists(std::string(segment_path) + "/rlog.bz2.lock")); + REQUIRE(util::file_exists(std::string(segment_path) + "/rlog.lock")); REQUIRE(segment == i); write_msg(logger.cur_handle); } diff --git a/selfdrive/loggerd/tests/test_loggerd.cc b/selfdrive/loggerd/tests/test_loggerd.cc deleted file mode 100644 index d84185cbba..0000000000 --- a/selfdrive/loggerd/tests/test_loggerd.cc +++ /dev/null @@ -1,93 +0,0 @@ -#include - -#include "catch2/catch.hpp" -#include "selfdrive/loggerd/loggerd.h" - -int random_int(int min, int max) { - std::random_device dev; - std::mt19937 rng(dev()); - std::uniform_int_distribution dist(min, max); - return dist(rng); -} - -int get_synced_frame_id(LoggerdState *s, CameraType cam_type, int start_frame_id) { - int frame_id = start_frame_id; - while (!sync_encoders(s, cam_type, frame_id)) { - ++frame_id; - usleep(0); - } - return frame_id; -}; - -TEST_CASE("sync_encoders") { - const int max_waiting = GENERATE(1, 2, 3); - - for (int test_cnt = 0; test_cnt < 10; ++test_cnt) { - LoggerdState s{.max_waiting = max_waiting}; - std::vector start_frames; - std::vector> futures; - - for (int i = 0; i < max_waiting; ++i) { - int start_frame_id = random_int(0, 20); - start_frames.push_back(start_frame_id); - futures.emplace_back(std::async(std::launch::async, get_synced_frame_id, &s, (CameraType)i, start_frame_id)); - } - - // get results - int synced_frame_id = 0; - for (int i = 0; i < max_waiting; ++i) { - if (i == 0) { - synced_frame_id = futures[i].get(); - // require synced_frame_id equal start_frame_id if max_waiting == 1 - if (max_waiting == 1) { - REQUIRE(synced_frame_id == start_frames[0]); - } - } else { - REQUIRE(futures[i].get() == synced_frame_id); - } - } - } -} - -const int MAX_SEGMENT_CNT = 100; - -std::pair encoder_thread(LoggerdState *s) { - int cur_seg = 0; - uint32_t frame_id = s->start_frame_id; - - while (cur_seg < MAX_SEGMENT_CNT) { - ++frame_id; - if (trigger_rotate_if_needed(s, cur_seg, frame_id)) { - cur_seg = s->rotate_segment; - } - util::sleep_for(0); - } - - return {cur_seg, frame_id}; -} - -TEST_CASE("trigger_rotate") { - const int encoders = GENERATE(1, 2, 3); - const int start_frame_id = random_int(0, 20); - - LoggerdState s{ - .max_waiting = encoders, - .start_frame_id = start_frame_id, - }; - - std::vector>> futures; - for (int i = 0; i < encoders; ++i) { - futures.emplace_back(std::async(std::launch::async, encoder_thread, &s)); - } - - while (s.rotate_segment < MAX_SEGMENT_CNT) { - rotate_if_needed(&s); - util::sleep_for(10); - } - - for (auto &f : futures) { - auto [encoder_seg, frame_id] = f.get(); - REQUIRE(encoder_seg == MAX_SEGMENT_CNT); - REQUIRE(frame_id == start_frame_id + encoder_seg * (SEGMENT_LENGTH * MAIN_FPS)); - } -} diff --git a/selfdrive/loggerd/tests/test_loggerd.py b/selfdrive/loggerd/tests/test_loggerd.py index 13e0b720d8..9c3565d130 100755 --- a/selfdrive/loggerd/tests/test_loggerd.py +++ b/selfdrive/loggerd/tests/test_loggerd.py @@ -15,14 +15,12 @@ from cereal.services import service_list from common.basedir import BASEDIR from common.params import Params from common.timeout import Timeout -from selfdrive.hardware import TICI from selfdrive.loggerd.config import ROOT from selfdrive.manager.process_config import managed_processes -from selfdrive.version import get_version +from system.version import get_version from tools.lib.logreader import LogReader -from cereal.visionipc.visionipc_pyx import VisionIpcServer, VisionStreamType # pylint: disable=no-name-in-module, import-error -from common.transformations.camera import eon_f_frame_size, tici_f_frame_size, \ - eon_d_frame_size, tici_d_frame_size, tici_e_frame_size +from cereal.visionipc import VisionIpcServer, VisionStreamType +from common.transformations.camera import tici_f_frame_size, tici_d_frame_size, tici_e_frame_size SentinelType = log.Sentinel.SentinelType @@ -85,8 +83,10 @@ class TestLoggerd(unittest.TestCase): ("GitRemote", "gitRemote", "remote"), ] params = Params() + params.clear_all() for k, _, v in fake_params: params.put(k, v) + params.put("LaikadEphemeris", "abc") lr = list(LogReader(str(self._gen_bootlog()))) initData = lr[0].initData @@ -101,24 +101,30 @@ class TestLoggerd(unittest.TestCase): with open("/proc/version") as f: self.assertEqual(initData.kernelVersion, f.read()) - for _, k, v in fake_params: - self.assertEqual(getattr(initData, k), v) + # check params + logged_params = {entry.key: entry.value for entry in initData.params.entries} + expected_params = set(k for k, _, __ in fake_params) | {'LaikadEphemeris'} + assert set(logged_params.keys()) == expected_params, set(logged_params.keys()) ^ expected_params + assert logged_params['LaikadEphemeris'] == b'', f"DONT_LOG param value was logged: {repr(logged_params['LaikadEphemeris'])}" + for param_key, initData_key, v in fake_params: + self.assertEqual(getattr(initData, initData_key), v) + self.assertEqual(logged_params[param_key].decode(), v) + + params.put("LaikadEphemeris", "") def test_rotation(self): os.environ["LOGGERD_TEST"] = "1" Params().put("RecordFront", "1") - expected_files = {"rlog.bz2", "qlog.bz2", "qcamera.ts", "fcamera.hevc", "dcamera.hevc"} - streams = [(VisionStreamType.VISION_STREAM_ROAD, tici_f_frame_size if TICI else eon_f_frame_size, "roadCameraState"), - (VisionStreamType.VISION_STREAM_DRIVER, tici_d_frame_size if TICI else eon_d_frame_size, "driverCameraState")] - if TICI: - expected_files.add("ecamera.hevc") - streams.append((VisionStreamType.VISION_STREAM_WIDE_ROAD, tici_e_frame_size, "wideRoadCameraState")) + expected_files = {"rlog", "qlog", "qcamera.ts", "fcamera.hevc", "dcamera.hevc", "ecamera.hevc"} + streams = [(VisionStreamType.VISION_STREAM_ROAD, (*tici_f_frame_size, 2048*2346, 2048, 2048*1216), "roadCameraState"), + (VisionStreamType.VISION_STREAM_DRIVER, (*tici_d_frame_size, 2048*2346, 2048, 2048*1216), "driverCameraState"), + (VisionStreamType.VISION_STREAM_WIDE_ROAD, (*tici_e_frame_size, 2048*2346, 2048, 2048*1216), "wideRoadCameraState")] pm = messaging.PubMaster(["roadCameraState", "driverCameraState", "wideRoadCameraState"]) vipc_server = VisionIpcServer("camerad") - for stream_type, frame_size, _ in streams: - vipc_server.create_buffers(stream_type, 40, False, *(frame_size)) + for stream_type, frame_spec, _ in streams: + vipc_server.create_buffers_with_sizes(stream_type, 40, False, *(frame_spec)) vipc_server.start_listener() for _ in range(5): @@ -126,11 +132,12 @@ class TestLoggerd(unittest.TestCase): length = random.randint(1, 3) os.environ["LOGGERD_SEGMENT_LENGTH"] = str(length) managed_processes["loggerd"].start() + managed_processes["encoderd"].start() fps = 20.0 for n in range(1, int(num_segs*length*fps)+1): - for stream_type, frame_size, state in streams: - dat = np.empty(int(frame_size[0]*frame_size[1]*3/2), dtype=np.uint8) + for stream_type, frame_spec, state in streams: + dat = np.empty(frame_spec[2], dtype=np.uint8) vipc_server.send(stream_type, dat[:].flatten().tobytes(), n, n/fps, n/fps) camera_state = messaging.new_message(state) @@ -140,6 +147,7 @@ class TestLoggerd(unittest.TestCase): time.sleep(1.0/fps) managed_processes["loggerd"].stop() + managed_processes["encoderd"].stop() route_path = str(self._get_latest_log_dir()).rsplit("--", 1)[0] for n in range(num_segs): @@ -188,7 +196,7 @@ class TestLoggerd(unittest.TestCase): pm = messaging.PubMaster(services) # sleep enough for the first poll to time out - # TOOD: fix loggerd bug dropping the msgs from the first poll + # TODO: fix loggerd bug dropping the msgs from the first poll managed_processes["loggerd"].start() for s in services: while not pm.all_readers_updated(s): @@ -208,7 +216,7 @@ class TestLoggerd(unittest.TestCase): time.sleep(1) managed_processes["loggerd"].stop() - qlog_path = os.path.join(self._get_latest_log_dir(), "qlog.bz2") + qlog_path = os.path.join(self._get_latest_log_dir(), "qlog") lr = list(LogReader(qlog_path)) # check initData and sentinel @@ -254,7 +262,7 @@ class TestLoggerd(unittest.TestCase): time.sleep(2) managed_processes["loggerd"].stop() - lr = list(LogReader(os.path.join(self._get_latest_log_dir(), "rlog.bz2"))) + lr = list(LogReader(os.path.join(self._get_latest_log_dir(), "rlog"))) # check initData and sentinel self._check_init_data(lr) diff --git a/selfdrive/loggerd/tests/test_uploader.py b/selfdrive/loggerd/tests/test_uploader.py index 01b529468b..6090bbe2aa 100755 --- a/selfdrive/loggerd/tests/test_uploader.py +++ b/selfdrive/loggerd/tests/test_uploader.py @@ -6,11 +6,9 @@ import unittest import logging import json -from selfdrive.swaglog import cloudlog +from system.swaglog import cloudlog import selfdrive.loggerd.uploader as uploader -from common.xattr import getxattr - from selfdrive.loggerd.tests.loggerd_tests_common import UploaderTestCase @@ -54,11 +52,11 @@ class TestUploader(UploaderTestCase): def gen_files(self, lock=False, boot=True): f_paths = list() - for t in ["qlog.bz2", "rlog.bz2", "dcamera.hevc", "fcamera.hevc"]: + for t in ["qlog", "rlog", "dcamera.hevc", "fcamera.hevc"]: f_paths.append(self.make_file_with_data(self.seg_dir, t, 1, lock=lock)) if boot: - f_paths.append(self.make_file_with_data("boot", f"{self.seg_dir}.bz2", 1, lock=lock)) + f_paths.append(self.make_file_with_data("boot", f"{self.seg_dir}", 1, lock=lock)) return f_paths def gen_order(self, seg1, seg2, boot=True): @@ -84,7 +82,7 @@ class TestUploader(UploaderTestCase): self.assertFalse(len(log_handler.upload_order) < len(exp_order), "Some files failed to upload") self.assertFalse(len(log_handler.upload_order) > len(exp_order), "Some files were uploaded twice") for f_path in exp_order: - self.assertTrue(getxattr(os.path.join(self.root, f_path), uploader.UPLOAD_ATTR_NAME), "All files not uploaded") + self.assertTrue(os.getxattr(os.path.join(self.root, f_path.replace('.bz2', '')), uploader.UPLOAD_ATTR_NAME), "All files not uploaded") self.assertTrue(log_handler.upload_order == exp_order, "Files uploaded in wrong order") @@ -103,7 +101,7 @@ class TestUploader(UploaderTestCase): self.assertFalse(len(log_handler.upload_ignored) < len(exp_order), "Some files failed to ignore") self.assertFalse(len(log_handler.upload_ignored) > len(exp_order), "Some files were ignored twice") for f_path in exp_order: - self.assertTrue(getxattr(os.path.join(self.root, f_path), uploader.UPLOAD_ATTR_NAME), "All files not ignored") + self.assertTrue(os.getxattr(os.path.join(self.root, f_path.replace('.bz2', '')), uploader.UPLOAD_ATTR_NAME), "All files not ignored") self.assertTrue(log_handler.upload_ignored == exp_order, "Files ignored in wrong order") @@ -128,7 +126,7 @@ class TestUploader(UploaderTestCase): self.assertFalse(len(log_handler.upload_order) < len(exp_order), "Some files failed to upload") self.assertFalse(len(log_handler.upload_order) > len(exp_order), "Some files were uploaded twice") for f_path in exp_order: - self.assertTrue(getxattr(os.path.join(self.root, f_path), uploader.UPLOAD_ATTR_NAME), "All files not uploaded") + self.assertTrue(os.getxattr(os.path.join(self.root, f_path.replace('.bz2', '')), uploader.UPLOAD_ATTR_NAME), "All files not uploaded") self.assertTrue(log_handler.upload_order == exp_order, "Files uploaded in wrong order") @@ -143,8 +141,8 @@ class TestUploader(UploaderTestCase): self.join_thread() for f_path in f_paths: - self.assertFalse(getxattr(f_path, uploader.UPLOAD_ATTR_NAME), "File upload when locked") - + uploaded = uploader.UPLOAD_ATTR_NAME in os.listxattr(f_path.replace('.bz2', '')) + self.assertFalse(uploaded, "File upload when locked") def test_clear_locks_on_startup(self): f_paths = self.gen_files(lock=True, boot=False) @@ -157,4 +155,4 @@ class TestUploader(UploaderTestCase): if __name__ == "__main__": - unittest.main(failfast=True) + unittest.main() diff --git a/selfdrive/loggerd/tools/mark_all_uploaded.py b/selfdrive/loggerd/tools/mark_all_uploaded.py index ff6e3c1f17..e60e6cfa2c 100644 --- a/selfdrive/loggerd/tools/mark_all_uploaded.py +++ b/selfdrive/loggerd/tools/mark_all_uploaded.py @@ -1,9 +1,8 @@ import os -from common.xattr import setxattr from selfdrive.loggerd.uploader import UPLOAD_ATTR_NAME, UPLOAD_ATTR_VALUE from selfdrive.loggerd.config import ROOT for folder in os.walk(ROOT): for file1 in folder[2]: full_path = os.path.join(folder[0], file1) - setxattr(full_path, UPLOAD_ATTR_NAME, UPLOAD_ATTR_VALUE) + os.setxattr(full_path, UPLOAD_ATTR_NAME, UPLOAD_ATTR_VALUE) diff --git a/selfdrive/loggerd/tools/mark_unuploaded.py b/selfdrive/loggerd/tools/mark_unuploaded.py index 0d3f765af4..343805d5fc 100755 --- a/selfdrive/loggerd/tools/mark_unuploaded.py +++ b/selfdrive/loggerd/tools/mark_unuploaded.py @@ -1,8 +1,8 @@ #!/usr/bin/env python3 +import os import sys -from common.xattr import removexattr from selfdrive.loggerd.uploader import UPLOAD_ATTR_NAME for fn in sys.argv[1:]: print(f"unmarking {fn}") - removexattr(fn, UPLOAD_ATTR_NAME) + os.removexattr(fn, UPLOAD_ATTR_NAME) diff --git a/selfdrive/loggerd/uploader.py b/selfdrive/loggerd/uploader.py index afdc5a6ed1..f97bafecb9 100644 --- a/selfdrive/loggerd/uploader.py +++ b/selfdrive/loggerd/uploader.py @@ -1,4 +1,6 @@ #!/usr/bin/env python3 +import bz2 +import io import json import os import random @@ -12,15 +14,18 @@ from cereal import log import cereal.messaging as messaging from common.api import Api from common.params import Params -from selfdrive.hardware import TICI +from common.realtime import set_core_affinity +from system.hardware import TICI from selfdrive.loggerd.xattr_cache import getxattr, setxattr from selfdrive.loggerd.config import ROOT -from selfdrive.swaglog import cloudlog +from system.swaglog import cloudlog NetworkType = log.DeviceState.NetworkType UPLOAD_ATTR_NAME = 'user.upload' UPLOAD_ATTR_VALUE = b'1' +UPLOAD_QLOG_QCAM_MAX_SIZE = 100 * 1e6 # MB + allow_sleep = bool(os.getenv("UPLOADER_SLEEP", "1")) force_wifi = os.getenv("FORCEWIFI") is not None fake_upload = os.getenv("FAKEUPLOAD") is not None @@ -64,12 +69,12 @@ class Uploader(): self.immediate_count = 0 # stats for last successfully uploaded file - self.last_time = 0 - self.last_speed = 0 + self.last_time = 0.0 + self.last_speed = 0.0 self.last_filename = "" self.immediate_folders = ["crash/", "boot/"] - self.immediate_priority = {"qlog.bz2": 0, "qcamera.ts": 1} + self.immediate_priority = {"qlog": 0, "qlog.bz2": 0, "qcamera.ts": 1} def get_upload_sort(self, name): if name in self.immediate_priority: @@ -119,11 +124,11 @@ class Uploader(): for name, key, fn in upload_files: if any(f in fn for f in self.immediate_folders): - return (key, fn) + return (name, key, fn) for name, key, fn in upload_files: if name in self.immediate_priority: - return (key, fn) + return (name, key, fn) return None @@ -149,7 +154,13 @@ class Uploader(): self.last_resp = FakeResponse() else: with open(fn, "rb") as f: - self.last_resp = requests.put(url, data=f, headers=headers, timeout=10) + if key.endswith('.bz2') and not fn.endswith('.bz2'): + data = bz2.compress(f.read()) + data = io.BytesIO(data) + else: + data = f + + self.last_resp = requests.put(url, data=data, headers=headers, timeout=10) except Exception as e: self.last_exc = (e, traceback.format_exc()) raise @@ -165,40 +176,40 @@ class Uploader(): return self.last_resp - def upload(self, key, fn, network_type): + def upload(self, name, key, fn, network_type, metered): try: sz = os.path.getsize(fn) except OSError: cloudlog.exception("upload: getsize failed") return False - cloudlog.event("upload_start", key=key, fn=fn, sz=sz, network_type=network_type) + cloudlog.event("upload_start", key=key, fn=fn, sz=sz, network_type=network_type, metered=metered) if sz == 0: - try: - # tag files of 0 size as uploaded - setxattr(fn, UPLOAD_ATTR_NAME, UPLOAD_ATTR_VALUE) - except OSError: - cloudlog.event("uploader_setxattr_failed", exc=self.last_exc, key=key, fn=fn, sz=sz) + # tag files of 0 size as uploaded + success = True + elif name in self.immediate_priority and sz > UPLOAD_QLOG_QCAM_MAX_SIZE: + cloudlog.event("uploader_too_large", key=key, fn=fn, sz=sz) success = True else: start_time = time.monotonic() stat = self.normal_upload(key, fn) - if stat is not None and stat.status_code in (200, 201, 403, 412): - try: - # tag file as uploaded - setxattr(fn, UPLOAD_ATTR_NAME, UPLOAD_ATTR_VALUE) - except OSError: - cloudlog.event("uploader_setxattr_failed", exc=self.last_exc, key=key, fn=fn, sz=sz) - + if stat is not None and stat.status_code in (200, 201, 401, 403, 412): self.last_filename = fn self.last_time = time.monotonic() - start_time self.last_speed = (sz / 1e6) / self.last_time success = True - cloudlog.event("upload_success" if stat.status_code != 412 else "upload_ignored", key=key, fn=fn, sz=sz, network_type=network_type) + cloudlog.event("upload_success" if stat.status_code != 412 else "upload_ignored", key=key, fn=fn, sz=sz, network_type=network_type, metered=metered) else: success = False - cloudlog.event("upload_failed", stat=stat, exc=self.last_exc, key=key, fn=fn, sz=sz, network_type=network_type) + cloudlog.event("upload_failed", stat=stat, exc=self.last_exc, key=key, fn=fn, sz=sz, network_type=network_type, metered=metered) + + if success: + # tag file as uploaded + try: + setxattr(fn, UPLOAD_ATTR_NAME, UPLOAD_ATTR_VALUE) + except OSError: + cloudlog.event("uploader_setxattr_failed", exc=self.last_exc, key=key, fn=fn, sz=sz) return success @@ -212,7 +223,13 @@ class Uploader(): us.lastFilename = self.last_filename return msg + def uploader_fn(exit_event): + try: + set_core_affinity([0, 1, 2, 3]) + except Exception: + cloudlog.exception("failed to set core affinity") + clear_locks(ROOT) params = Params() @@ -245,9 +262,13 @@ def uploader_fn(exit_event): time.sleep(60 if offroad else 5) continue - key, fn = d + name, key, fn = d - success = uploader.upload(key, fn, sm['deviceState'].networkType.raw) + # qlogs and bootlogs need to be compressed before uploading + if key.endswith(('qlog', 'rlog')) or (key.startswith('boot/') and not key.endswith('.bz2')): + key += ".bz2" + + success = uploader.upload(name, key, fn, sm['deviceState'].networkType.raw, sm['deviceState'].networkMetered) if success: backoff = 0.1 elif allow_sleep: @@ -257,6 +278,7 @@ def uploader_fn(exit_event): pm.send("uploaderState", uploader.get_msg()) + def main(): uploader_fn(threading.Event()) diff --git a/selfdrive/loggerd/video_writer.cc b/selfdrive/loggerd/video_writer.cc new file mode 100644 index 0000000000..4f79ccafc8 --- /dev/null +++ b/selfdrive/loggerd/video_writer.cc @@ -0,0 +1,114 @@ +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#include +#include + +#include "selfdrive/loggerd/video_writer.h" +#include "common/swaglog.h" +#include "common/util.h" + +VideoWriter::VideoWriter(const char *path, const char *filename, bool remuxing, int width, int height, int fps, cereal::EncodeIndex::Type codec) + : remuxing(remuxing) { + raw = codec == cereal::EncodeIndex::Type::BIG_BOX_LOSSLESS; + vid_path = util::string_format("%s/%s", path, filename); + lock_path = util::string_format("%s/%s.lock", path, filename); + + int lock_fd = HANDLE_EINTR(open(lock_path.c_str(), O_RDWR | O_CREAT, 0664)); + assert(lock_fd >= 0); + close(lock_fd); + + LOGD("encoder_open %s remuxing:%d", this->vid_path.c_str(), this->remuxing); + if (this->remuxing) { + avformat_alloc_output_context2(&this->ofmt_ctx, NULL, raw ? "matroska" : NULL, this->vid_path.c_str()); + assert(this->ofmt_ctx); + + // set codec correctly. needed? + assert(codec != cereal::EncodeIndex::Type::FULL_H_E_V_C); + const AVCodec *avcodec = avcodec_find_encoder(raw ? AV_CODEC_ID_FFVHUFF : AV_CODEC_ID_H264); + assert(avcodec); + + this->codec_ctx = avcodec_alloc_context3(avcodec); + assert(this->codec_ctx); + this->codec_ctx->width = width; + this->codec_ctx->height = height; + this->codec_ctx->pix_fmt = AV_PIX_FMT_YUV420P; + this->codec_ctx->time_base = (AVRational){ 1, fps }; + + if (codec == cereal::EncodeIndex::Type::BIG_BOX_LOSSLESS) { + // without this, there's just noise + int err = avcodec_open2(this->codec_ctx, avcodec, NULL); + assert(err >= 0); + } + + this->out_stream = avformat_new_stream(this->ofmt_ctx, raw ? avcodec : NULL); + assert(this->out_stream); + + int err = avio_open(&this->ofmt_ctx->pb, this->vid_path.c_str(), AVIO_FLAG_WRITE); + assert(err >= 0); + + } else { + this->of = util::safe_fopen(this->vid_path.c_str(), "wb"); + assert(this->of); + } +} + +void VideoWriter::write(uint8_t *data, int len, long long timestamp, bool codecconfig, bool keyframe) { + if (of && data) { + size_t written = util::safe_fwrite(data, 1, len, of); + if (written != len) { + LOGE("failed to write file.errno=%d", errno); + } + } + + if (remuxing) { + if (codecconfig) { + if (len > 0) { + codec_ctx->extradata = (uint8_t*)av_mallocz(len + AV_INPUT_BUFFER_PADDING_SIZE); + codec_ctx->extradata_size = len; + memcpy(codec_ctx->extradata, data, len); + } + int err = avcodec_parameters_from_context(out_stream->codecpar, codec_ctx); + assert(err >= 0); + err = avformat_write_header(ofmt_ctx, NULL); + assert(err >= 0); + } else { + // input timestamps are in microseconds + AVRational in_timebase = {1, 1000000}; + + AVPacket pkt; + av_init_packet(&pkt); + pkt.data = data; + pkt.size = len; + + enum AVRounding rnd = static_cast(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX); + pkt.pts = pkt.dts = av_rescale_q_rnd(timestamp, in_timebase, ofmt_ctx->streams[0]->time_base, rnd); + pkt.duration = av_rescale_q(50*1000, in_timebase, ofmt_ctx->streams[0]->time_base); + + if (keyframe) { + pkt.flags |= AV_PKT_FLAG_KEY; + } + + // TODO: can use av_write_frame for non raw? + int err = av_interleaved_write_frame(ofmt_ctx, &pkt); + if (err < 0) { LOGW("ts encoder write issue len: %d ts: %lu", len, timestamp); } + + av_packet_unref(&pkt); + } + } +} + +VideoWriter::~VideoWriter() { + if (this->remuxing) { + if (this->raw) { avcodec_close(this->codec_ctx); } + int err = av_write_trailer(this->ofmt_ctx); + if (err != 0) LOGE("av_write_trailer failed %d", err); + avcodec_free_context(&this->codec_ctx); + err = avio_closep(&this->ofmt_ctx->pb); + if (err != 0) LOGE("avio_closep failed %d", err); + avformat_free_context(this->ofmt_ctx); + } else { + util::safe_fflush(this->of); + fclose(this->of); + this->of = nullptr; + } + unlink(this->lock_path.c_str()); +} diff --git a/selfdrive/loggerd/video_writer.h b/selfdrive/loggerd/video_writer.h new file mode 100644 index 0000000000..01a243904c --- /dev/null +++ b/selfdrive/loggerd/video_writer.h @@ -0,0 +1,26 @@ +#pragma once + +#include + +extern "C" { +#include +#include +} + +#include "cereal/messaging/messaging.h" + +class VideoWriter { +public: + VideoWriter(const char *path, const char *filename, bool remuxing, int width, int height, int fps, cereal::EncodeIndex::Type codec); + void write(uint8_t *data, int len, long long timestamp, bool codecconfig, bool keyframe); + ~VideoWriter(); +private: + std::string vid_path, lock_path; + + FILE *of = nullptr; + + AVCodecContext *codec_ctx; + AVFormatContext *ofmt_ctx; + AVStream *out_stream; + bool remuxing, raw; +}; \ No newline at end of file diff --git a/selfdrive/loggerd/xattr_cache.py b/selfdrive/loggerd/xattr_cache.py index e721692500..95e39f2032 100644 --- a/selfdrive/loggerd/xattr_cache.py +++ b/selfdrive/loggerd/xattr_cache.py @@ -1,15 +1,23 @@ -from typing import Dict, Tuple +import os +import errno +from typing import Dict, Tuple, Optional -from common.xattr import getxattr as getattr1 -from common.xattr import setxattr as setattr1 +_cached_attributes: Dict[Tuple, Optional[bytes]] = {} -cached_attributes: Dict[Tuple, bytes] = {} -def getxattr(path: str, attr_name: bytes) -> bytes: - if (path, attr_name) not in cached_attributes: - response = getattr1(path, attr_name) - cached_attributes[(path, attr_name)] = response - return cached_attributes[(path, attr_name)] +def getxattr(path: str, attr_name: str) -> Optional[bytes]: + key = (path, attr_name) + if key not in _cached_attributes: + try: + response = os.getxattr(path, attr_name) + except OSError as e: + # ENODATA means attribute hasn't been set + if e.errno == errno.ENODATA: + response = None + else: + raise + _cached_attributes[key] = response + return _cached_attributes[key] def setxattr(path: str, attr_name: str, attr_value: bytes) -> None: - cached_attributes.pop((path, attr_name), None) - return setattr1(path, attr_name, attr_value) + _cached_attributes.pop((path, attr_name), None) + return os.setxattr(path, attr_name, attr_value) diff --git a/selfdrive/manager/build.py b/selfdrive/manager/build.py index 4b97855f34..c8a7d41539 100755 --- a/selfdrive/manager/build.py +++ b/selfdrive/manager/build.py @@ -1,8 +1,6 @@ #!/usr/bin/env python3 import os import subprocess -import sys -import time import textwrap from pathlib import Path @@ -10,14 +8,14 @@ from pathlib import Path from common.basedir import BASEDIR from common.spinner import Spinner from common.text_window import TextWindow -from selfdrive.hardware import TICI -from selfdrive.swaglog import cloudlog, add_file_handler -from selfdrive.version import is_dirty +from system.hardware import AGNOS +from system.swaglog import cloudlog, add_file_handler +from system.version import is_dirty MAX_CACHE_SIZE = 4e9 if "CI" in os.environ else 2e9 -CACHE_DIR = Path("/data/scons_cache" if TICI else "/tmp/scons_cache") +CACHE_DIR = Path("/data/scons_cache" if AGNOS else "/tmp/scons_cache") -TOTAL_SCONS_NODES = 2405 +TOTAL_SCONS_NODES = 2395 MAX_BUILD_PROGRESS = 100 PREBUILT = os.path.exists(os.path.join(BASEDIR, 'prebuilt')) @@ -28,62 +26,49 @@ def build(spinner: Spinner, dirty: bool = False) -> None: nproc = os.cpu_count() j_flag = "" if nproc is None else f"-j{nproc - 1}" - for retry in [True, False]: - scons = subprocess.Popen(["scons", j_flag, "--cache-populate"], cwd=BASEDIR, env=env, stderr=subprocess.PIPE) - assert scons.stderr is not None - - compile_output = [] - - # Read progress from stderr and update spinner - while scons.poll() is None: - try: - line = scons.stderr.readline() - if line is None: - continue - line = line.rstrip() - - prefix = b'progress: ' - if line.startswith(prefix): - i = int(line[len(prefix):]) - spinner.update_progress(MAX_BUILD_PROGRESS * min(1., i / TOTAL_SCONS_NODES), 100.) - elif len(line): - compile_output.append(line) - print(line.decode('utf8', 'replace')) - except Exception: - pass - - if scons.returncode != 0: - # Read remaining output - r = scons.stderr.read().split(b'\n') - compile_output += r - - if retry and (not dirty): - if not os.getenv("CI"): - print("scons build failed, cleaning in") - for i in range(3, -1, -1): - print("....%d" % i) - time.sleep(1) - subprocess.check_call(["scons", "-c"], cwd=BASEDIR, env=env) - else: - print("scons build failed after retry") - sys.exit(1) - else: - # Build failed log errors - errors = [line.decode('utf8', 'replace') for line in compile_output - if any(err in line for err in [b'error: ', b'not found, needed by target'])] - error_s = "\n".join(errors) - add_file_handler(cloudlog) - cloudlog.error("scons build failed\n" + error_s) - - # Show TextWindow - spinner.close() - if not os.getenv("CI"): - error_s = "\n \n".join("\n".join(textwrap.wrap(e, 65)) for e in errors) - with TextWindow("openpilot failed to build\n \n" + error_s) as t: - t.wait_for_exit() - exit(1) - else: - break + scons: subprocess.Popen = subprocess.Popen(["scons", j_flag, "--cache-populate"], cwd=BASEDIR, env=env, stderr=subprocess.PIPE) + assert scons.stderr is not None + + compile_output = [] + + # Read progress from stderr and update spinner + while scons.poll() is None: + try: + line = scons.stderr.readline() + if line is None: + continue + line = line.rstrip() + + prefix = b'progress: ' + if line.startswith(prefix): + i = int(line[len(prefix):]) + spinner.update_progress(MAX_BUILD_PROGRESS * min(1., i / TOTAL_SCONS_NODES), 100.) + elif len(line): + compile_output.append(line) + print(line.decode('utf8', 'replace')) + except Exception: + pass + + if scons.returncode != 0: + # Read remaining output + r = scons.stderr.read().split(b'\n') + compile_output += r + + # Build failed log errors + errors = [line.decode('utf8', 'replace') for line in compile_output + if any(err in line for err in [b'error: ', b'not found, needed by target'])] + error_s = "\n".join(errors) + add_file_handler(cloudlog) + cloudlog.error("scons build failed\n" + error_s) + + # Show TextWindow + spinner.close() + if not os.getenv("CI"): + error_s = "\n \n".join("\n".join(textwrap.wrap(e, 65)) for e in errors) + with TextWindow("openpilot failed to build\n \n" + error_s) as t: + t.wait_for_exit() + exit(1) + # enforce max cache size cache_files = [f for f in CACHE_DIR.rglob('*') if f.is_file()] diff --git a/selfdrive/manager/helpers.py b/selfdrive/manager/helpers.py index b07362dd4d..983c7cc0b1 100644 --- a/selfdrive/manager/helpers.py +++ b/selfdrive/manager/helpers.py @@ -33,6 +33,6 @@ def unblock_stdout() -> None: pass # os.wait() returns a tuple with the pid and a 16 bit value - # whose low byte is the signal number and whose high byte is the exit satus + # whose low byte is the signal number and whose high byte is the exit status exit_status = os.wait()[1] >> 8 os._exit(exit_status) diff --git a/selfdrive/manager/manager.py b/selfdrive/manager/manager.py index 21b8cb9657..928507f65b 100755 --- a/selfdrive/manager/manager.py +++ b/selfdrive/manager/manager.py @@ -13,14 +13,14 @@ from common.basedir import BASEDIR from common.params import Params, ParamKeyType from common.text_window import TextWindow from selfdrive.boardd.set_time import set_time -from selfdrive.hardware import HARDWARE, PC +from system.hardware import HARDWARE, PC from selfdrive.manager.helpers import unblock_stdout from selfdrive.manager.process import ensure_running from selfdrive.manager.process_config import managed_processes from selfdrive.athena.registration import register, UNREGISTERED_DONGLE_ID -from selfdrive.swaglog import cloudlog, add_file_handler -from selfdrive.version import is_dirty, get_commit, get_version, get_origin, get_short_branch, \ - terms_version, training_version +from system.swaglog import cloudlog, add_file_handler +from system.version import is_dirty, get_commit, get_version, get_origin, get_short_branch, \ + terms_version, training_version, is_tested_branch sys.path.append(os.path.join(BASEDIR, "pyextra")) @@ -38,7 +38,10 @@ def manager_init() -> None: default_params: List[Tuple[str, Union[str, bytes]]] = [ ("CompletedTrainingVersion", "0"), + ("DisengageOnAccelerator", "1"), + ("GsmMetered", "1"), ("HasAcceptedTerms", "0"), + ("LanguageSetting", "main_en"), ("OpenpilotEnabledToggle", "1"), ] if not PC: @@ -47,9 +50,6 @@ def manager_init() -> None: if params.get_bool("RecordFrontLock"): params.put_bool("RecordFront", True) - if not params.get_bool("DisableRadar_Allow"): - params.delete("DisableRadar") - # set unset params for k, v in default_params: if params.get(k) is None: @@ -77,6 +77,7 @@ def manager_init() -> None: params.put("GitCommit", get_commit(default="")) params.put("GitBranch", get_short_branch(default="")) params.put("GitRemote", get_origin(default="")) + params.put_bool("IsTestedBranch", is_tested_branch()) # set dongle id reg_res = register(show_spinner=True) @@ -127,26 +128,16 @@ def manager_thread() -> None: ignore.append("pandad") ignore += [x for x in os.getenv("BLOCK", "").split(",") if len(x) > 0] - ensure_running(managed_processes.values(), started=False, not_run=ignore) - - started_prev = False - sm = messaging.SubMaster(['deviceState']) + sm = messaging.SubMaster(['deviceState', 'carParams'], poll=['deviceState']) pm = messaging.PubMaster(['managerState']) + ensure_running(managed_processes.values(), False, params=params, CP=sm['carParams'], not_run=ignore) + while True: sm.update() - not_run = ignore[:] started = sm['deviceState'].started - driverview = params.get_bool("IsDriverViewEnabled") - ensure_running(managed_processes.values(), started, driverview, not_run) - - # trigger an update after going offroad - if started_prev and not started and 'updated' in managed_processes: - os.sync() - managed_processes['updated'].signal(signal.SIGHUP) - - started_prev = started + ensure_running(managed_processes.values(), started, params=params, CP=sm['carParams'], not_run=ignore) running = ' '.join("%s%s\u001b[0m" % ("\u001b[32m" if p.proc.is_alive() else "\u001b[31m", p.name) for p in managed_processes.values() if p.proc) diff --git a/selfdrive/manager/process.py b/selfdrive/manager/process.py index ebdd2a90bf..dabfbe4ee0 100644 --- a/selfdrive/manager/process.py +++ b/selfdrive/manager/process.py @@ -4,7 +4,7 @@ import signal import struct import time import subprocess -from typing import Optional, List, ValuesView +from typing import Optional, Callable, List, ValuesView from abc import ABC, abstractmethod from multiprocessing import Process @@ -12,11 +12,12 @@ from setproctitle import setproctitle # pylint: disable=no-name-in-module import cereal.messaging as messaging import selfdrive.sentry as sentry +from cereal import car from common.basedir import BASEDIR from common.params import Params from common.realtime import sec_since_boot -from selfdrive.swaglog import cloudlog -from selfdrive.hardware import HARDWARE +from system.swaglog import cloudlog +from system.hardware import HARDWARE from cereal import log WATCHDOG_FN = "/dev/shm/wd_" @@ -69,14 +70,15 @@ class ManagerProcess(ABC): unkillable = False daemon = False sigkill = False - persistent = False - driverview = False + onroad = True + offroad = False + callback: Optional[Callable[[bool, Params, car.CarParams], bool]] = None proc: Optional[Process] = None enabled = True name = "" last_watchdog_time = 0 - watchdog_max_dt = None + watchdog_max_dt: Optional[int] = None watchdog_seen = False shutting_down = False @@ -182,13 +184,14 @@ class ManagerProcess(ABC): class NativeProcess(ManagerProcess): - def __init__(self, name, cwd, cmdline, enabled=True, persistent=False, driverview=False, unkillable=False, sigkill=False, watchdog_max_dt=None): + def __init__(self, name, cwd, cmdline, enabled=True, onroad=True, offroad=False, callback=None, unkillable=False, sigkill=False, watchdog_max_dt=None): self.name = name self.cwd = cwd self.cmdline = cmdline self.enabled = enabled - self.persistent = persistent - self.driverview = driverview + self.onroad = onroad + self.offroad = offroad + self.callback = callback self.unkillable = unkillable self.sigkill = sigkill self.watchdog_max_dt = watchdog_max_dt @@ -199,7 +202,7 @@ class NativeProcess(ManagerProcess): def start(self) -> None: # In case we only tried a non blocking stop we need to stop it before restarting if self.shutting_down: - self.stop() + self.stop() if self.proc is not None: return @@ -213,12 +216,13 @@ class NativeProcess(ManagerProcess): class PythonProcess(ManagerProcess): - def __init__(self, name, module, enabled=True, persistent=False, driverview=False, unkillable=False, sigkill=False, watchdog_max_dt=None): + def __init__(self, name, module, enabled=True, onroad=True, offroad=False, callback=None, unkillable=False, sigkill=False, watchdog_max_dt=None): self.name = name self.module = module self.enabled = enabled - self.persistent = persistent - self.driverview = driverview + self.onroad = onroad + self.offroad = offroad + self.callback = callback self.unkillable = unkillable self.sigkill = sigkill self.watchdog_max_dt = watchdog_max_dt @@ -231,7 +235,7 @@ class PythonProcess(ManagerProcess): def start(self) -> None: # In case we only tried a non blocking stop we need to stop it before restarting if self.shutting_down: - self.stop() + self.stop() if self.proc is not None: return @@ -251,7 +255,8 @@ class DaemonProcess(ManagerProcess): self.module = module self.param_name = param_name self.enabled = enabled - self.persistent = True + self.onroad = True + self.offroad = True def prepare(self) -> None: pass @@ -284,23 +289,29 @@ class DaemonProcess(ManagerProcess): pass -def ensure_running(procs: ValuesView[ManagerProcess], started: bool, driverview: bool=False, not_run: Optional[List[str]]=None) -> None: +def ensure_running(procs: ValuesView[ManagerProcess], started: bool, params=None, CP: car.CarParams=None, + not_run: Optional[List[str]]=None) -> None: if not_run is None: not_run = [] for p in procs: - if p.name in not_run: - p.stop(block=False) - elif not p.enabled: - p.stop(block=False) - elif p.persistent: - p.start() - elif p.driverview and driverview: - p.start() - elif started: + # Conditions that make a process run + run = any(( + p.offroad and not started, + p.onroad and started, + )) + if p.callback is not None and None not in (params, CP): + run = run or p.callback(started, params, CP) + + # Conditions that block a process from starting + run = run and not any(( + not p.enabled, + p.name in not_run, + )) + + if run: p.start() else: p.stop(block=False) p.check_watchdog(started) - diff --git a/selfdrive/manager/process_config.py b/selfdrive/manager/process_config.py index c017e48fab..c03e995497 100644 --- a/selfdrive/manager/process_config.py +++ b/selfdrive/manager/process_config.py @@ -1,47 +1,67 @@ import os -from selfdrive.hardware import EON, TICI, PC +from cereal import car +from common.params import Params +from system.hardware import PC, TICI from selfdrive.manager.process import PythonProcess, NativeProcess, DaemonProcess WEBCAM = os.getenv("USE_WEBCAM") is not None +def driverview(started: bool, params: Params, CP: car.CarParams) -> bool: + return params.get_bool("IsDriverViewEnabled") # type: ignore + +def notcar(started: bool, params: Params, CP: car.CarParams) -> bool: + return CP.notCar # type: ignore + +def logging(started, params, CP: car.CarParams) -> bool: + run = (not CP.notCar) or not params.get_bool("DisableLogging") + return started and run + procs = [ - DaemonProcess("manage_athenad", "selfdrive.athena.manage_athenad", "AthenadPid"), # due to qualcomm kernel bugs SIGKILLing camerad sometimes causes page table corruption - NativeProcess("camerad", "selfdrive/camerad", ["./camerad"], unkillable=True, driverview=True), - NativeProcess("clocksd", "selfdrive/clocksd", ["./clocksd"]), - NativeProcess("dmonitoringmodeld", "selfdrive/modeld", ["./dmonitoringmodeld"], enabled=(not PC or WEBCAM), driverview=True), - NativeProcess("logcatd", "selfdrive/logcatd", ["./logcatd"]), - NativeProcess("loggerd", "selfdrive/loggerd", ["./loggerd"]), + NativeProcess("camerad", "system/camerad", ["./camerad"], unkillable=True, callback=driverview), + NativeProcess("clocksd", "system/clocksd", ["./clocksd"]), + NativeProcess("logcatd", "system/logcatd", ["./logcatd"]), + NativeProcess("proclogd", "system/proclogd", ["./proclogd"]), + PythonProcess("logmessaged", "system.logmessaged", offroad=True), + PythonProcess("micd", "system.micd"), + PythonProcess("timezoned", "system.timezoned", enabled=not PC, offroad=True), + + DaemonProcess("manage_athenad", "selfdrive.athena.manage_athenad", "AthenadPid"), + NativeProcess("dmonitoringmodeld", "selfdrive/modeld", ["./dmonitoringmodeld"], enabled=(not PC or WEBCAM), callback=driverview), + NativeProcess("encoderd", "selfdrive/loggerd", ["./encoderd"]), + NativeProcess("loggerd", "selfdrive/loggerd", ["./loggerd"], onroad=False, callback=logging), NativeProcess("modeld", "selfdrive/modeld", ["./modeld"]), - NativeProcess("navd", "selfdrive/ui/navd", ["./navd"], enabled=(PC or TICI), persistent=True), - NativeProcess("proclogd", "selfdrive/proclogd", ["./proclogd"]), - NativeProcess("sensord", "selfdrive/sensord", ["./sensord"], enabled=not PC, persistent=EON, sigkill=EON), + NativeProcess("mapsd", "selfdrive/navd", ["./map_renderer"], enabled=False), + NativeProcess("navmodeld", "selfdrive/modeld", ["./navmodeld"], enabled=False), + NativeProcess("sensord", "selfdrive/sensord", ["./sensord"], enabled=not PC), NativeProcess("ubloxd", "selfdrive/locationd", ["./ubloxd"], enabled=(not PC or WEBCAM)), - NativeProcess("ui", "selfdrive/ui", ["./ui"], persistent=True, watchdog_max_dt=(5 if TICI else None)), - NativeProcess("soundd", "selfdrive/ui/soundd", ["./soundd"], persistent=True), + NativeProcess("ui", "selfdrive/ui", ["./ui"], offroad=True, watchdog_max_dt=(5 if not PC else None)), + NativeProcess("soundd", "selfdrive/ui/soundd", ["./soundd"], offroad=True), NativeProcess("locationd", "selfdrive/locationd", ["./locationd"]), NativeProcess("boardd", "selfdrive/boardd", ["./boardd"], enabled=False), PythonProcess("calibrationd", "selfdrive.locationd.calibrationd"), + PythonProcess("torqued", "selfdrive.locationd.torqued"), PythonProcess("controlsd", "selfdrive.controls.controlsd"), - PythonProcess("deleter", "selfdrive.loggerd.deleter", persistent=True), - PythonProcess("dmonitoringd", "selfdrive.monitoring.dmonitoringd", enabled=(not PC or WEBCAM), driverview=True), - PythonProcess("logmessaged", "selfdrive.logmessaged", persistent=True), - PythonProcess("pandad", "selfdrive.pandad", persistent=True), + PythonProcess("deleter", "selfdrive.loggerd.deleter", offroad=True), + PythonProcess("dmonitoringd", "selfdrive.monitoring.dmonitoringd", enabled=(not PC or WEBCAM), callback=driverview), + PythonProcess("laikad", "selfdrive.locationd.laikad"), + PythonProcess("rawgpsd", "selfdrive.sensord.rawgps.rawgpsd", enabled=TICI), + PythonProcess("navd", "selfdrive.navd.navd"), + PythonProcess("pandad", "selfdrive.boardd.pandad", offroad=True), PythonProcess("paramsd", "selfdrive.locationd.paramsd"), + PythonProcess("pigeond", "selfdrive.sensord.pigeond", enabled=TICI), PythonProcess("plannerd", "selfdrive.controls.plannerd"), PythonProcess("radard", "selfdrive.controls.radard"), - PythonProcess("thermald", "selfdrive.thermald.thermald", persistent=True), - PythonProcess("timezoned", "selfdrive.timezoned", enabled=TICI, persistent=True), - PythonProcess("tombstoned", "selfdrive.tombstoned", enabled=not PC, persistent=True), - PythonProcess("updated", "selfdrive.updated", enabled=not PC, persistent=True), - PythonProcess("uploader", "selfdrive.loggerd.uploader", persistent=True), - PythonProcess("statsd", "selfdrive.statsd", persistent=True), - - # EON only - PythonProcess("rtshield", "selfdrive.rtshield", enabled=EON), - PythonProcess("shutdownd", "selfdrive.hardware.eon.shutdownd", enabled=EON), - PythonProcess("androidd", "selfdrive.hardware.eon.androidd", enabled=EON, persistent=True), + PythonProcess("thermald", "selfdrive.thermald.thermald", offroad=True), + PythonProcess("tombstoned", "selfdrive.tombstoned", enabled=not PC, offroad=True), + PythonProcess("updated", "selfdrive.updated", enabled=not PC, onroad=False, offroad=True), + PythonProcess("uploader", "selfdrive.loggerd.uploader", offroad=True), + PythonProcess("statsd", "selfdrive.statsd", offroad=True), + + # debug procs + NativeProcess("bridge", "cereal/messaging", ["./bridge"], onroad=False, callback=notcar), + PythonProcess("webjoystick", "tools.joystick.web", onroad=False, callback=notcar), ] managed_processes = {p.name: p for p in procs} diff --git a/selfdrive/manager/test/test_manager.py b/selfdrive/manager/test/test_manager.py index d16a145031..6d4df0423a 100755 --- a/selfdrive/manager/test/test_manager.py +++ b/selfdrive/manager/test/test_manager.py @@ -4,16 +4,16 @@ import signal import time import unittest +from common.params import Params import selfdrive.manager.manager as manager -from selfdrive.hardware import EON, TICI, HARDWARE from selfdrive.manager.process import DaemonProcess from selfdrive.manager.process_config import managed_processes +from system.hardware import HARDWARE os.environ['FAKEUPLOAD'] = "1" -# TODO: make eon fast -MAX_STARTUP_TIME = 30 if EON else 15 -ALL_PROCESSES = [p.name for p in managed_processes.values() if (type(p) is not DaemonProcess) and p.enabled and (p.name not in ['updated', 'pandad'])] +MAX_STARTUP_TIME = 3 +ALL_PROCESSES = [p.name for p in managed_processes.values() if (type(p) is not DaemonProcess) and p.enabled and (p.name not in ['pandad', ])] class TestManager(unittest.TestCase): @@ -21,6 +21,10 @@ class TestManager(unittest.TestCase): os.environ['PASSIVE'] = '0' HARDWARE.set_power_save(False) + # ensure clean CarParams + params = Params() + params.clear_all() + def tearDown(self): manager.manager_cleanup() @@ -36,9 +40,12 @@ class TestManager(unittest.TestCase): t = time.monotonic() - start assert t < MAX_STARTUP_TIME, f"startup took {t}s, expected <{MAX_STARTUP_TIME}s" - # ensure all processes exit cleanly def test_clean_exit(self): + """ + Ensure all processes exit cleanly when stopped. + """ HARDWARE.set_power_save(False) + manager.manager_init() manager.manager_prepare() for p in ALL_PROCESSES: managed_processes[p].start() @@ -46,22 +53,18 @@ class TestManager(unittest.TestCase): time.sleep(10) for p in reversed(ALL_PROCESSES): - state = managed_processes[p].get_process_state_msg() - self.assertTrue(state.running, f"{p} not running") - - exit_code = managed_processes[p].stop(retry=False) - if (TICI and p in ['ui', 'navd']) or (EON and p == 'logcatd'): - # TODO: make Qt UI exit gracefully - continue - - # Make sure the process is actually dead - managed_processes[p].stop() - - # TODO: interrupted blocking read exits with 1 in cereal. use a more unique return code - exit_codes = [0, 1] - if managed_processes[p].sigkill: - exit_codes = [-signal.SIGKILL] - assert exit_code in exit_codes, f"{p} died with {exit_code}" + with self.subTest(proc=p): + state = managed_processes[p].get_process_state_msg() + self.assertTrue(state.running, f"{p} not running") + exit_code = managed_processes[p].stop(retry=False) + + self.assertTrue(exit_code is not None, f"{p} failed to exit") + + # TODO: interrupted blocking read exits with 1 in cereal. use a more unique return code + exit_codes = [0, 1] + if managed_processes[p].sigkill: + exit_codes = [-signal.SIGKILL] + self.assertIn(exit_code, exit_codes, f"{p} died with {exit_code}") if __name__ == "__main__": diff --git a/selfdrive/modeld/SConscript b/selfdrive/modeld/SConscript index 9066a653fa..82338e456b 100644 --- a/selfdrive/modeld/SConscript +++ b/selfdrive/modeld/SConscript @@ -1,10 +1,10 @@ import os -Import('env', 'arch', 'cereal', 'messaging', 'common', 'gpucommon', 'visionipc') +Import('env', 'arch', 'cereal', 'messaging', 'common', 'gpucommon', 'visionipc', 'transformations') lenv = env.Clone() libs = [cereal, messaging, common, visionipc, gpucommon, - 'OpenCL', 'SNPE', 'symphony-cpu', 'capnp', 'zmq', 'kj', 'yuv'] + 'OpenCL', 'SNPE', 'capnp', 'zmq', 'kj', 'yuv'] def get_dlsym_offset(): """Returns the offset between dlopen and dlsym in libdl.so""" @@ -23,20 +23,16 @@ common_src = [ ] thneed_src = [ - "thneed/thneed.cc", + "thneed/thneed_common.cc", + "thneed/thneed_qcom2.cc", "thneed/serialize.cc", - "thneed/optimizer.cc", "runners/thneedmodel.cc", ] use_thneed = not GetOption('no_thneed') -use_extra = True # arch == "larch64" -lenv['CXXFLAGS'].append('-DUSE_EXTRA=true' if use_extra else '-DUSE_EXTRA=false') - -if arch == "aarch64" or arch == "larch64": - libs += ['gsl', 'CB'] - libs += ['gnustl_shared'] if arch == "aarch64" else ['pthread', 'dl'] +if arch == "larch64": + libs += ['gsl', 'CB', 'pthread', 'dl'] if use_thneed: common_src += thneed_src @@ -61,30 +57,63 @@ else: # no SNPE on Mac del libs[libs.index('SNPE')] - del libs[libs.index('symphony-cpu')] del common_src[common_src.index('runners/snpemodel.cc')] common_model = lenv.Object(common_src) -# build thneed model -if use_thneed and arch in ("aarch64", "larch64"): - fn = "../../models/big_supercombo" if use_extra else "../../models/supercombo" - compiler = lenv.Program('thneed/compile', ["thneed/compile.cc"]+common_model, LIBS=libs) - cmd = f"cd {Dir('.').abspath} && {compiler[0].abspath} {fn}.dlc {fn}.thneed --binary" - - lib_paths = ':'.join(Dir(p).abspath for p in lenv["LIBPATH"]) - kernel_path = os.path.join(Dir('.').abspath, "thneed", "kernels") - cenv = Environment(ENV={'LD_LIBRARY_PATH': f"{lib_paths}:{lenv['ENV']['LD_LIBRARY_PATH']}", 'KERNEL_PATH': kernel_path}) - - kernels = [os.path.join(kernel_path, x) for x in os.listdir(kernel_path) if x.endswith(".cl")] - cenv.Command(fn + ".thneed", [fn + ".dlc", kernels, compiler], cmd) - lenv.Program('_dmonitoringmodeld', [ "dmonitoringmodeld.cc", "models/dmonitoring.cc", ]+common_model, LIBS=libs) -lenv.Program('_modeld', [ +# build thneed model +if use_thneed and arch == "larch64" or GetOption('pc_thneed'): + fn = File("models/supercombo").abspath + + if GetOption('pc_thneed'): + cmd = f"cd {Dir('#').abspath}/tinygrad_repo && GPU=1 NATIVE_EXPLOG=1 OPTWG=1 UNSAFE_FLOAT4=1 DEBUGCL=1 python3 openpilot/compile.py {fn}.onnx {fn}.thneed" + else: + cmd = f"cd {Dir('#').abspath}/tinygrad_repo && FLOAT16=1 MATMUL=1 PYOPENCL_NO_CACHE=1 NATIVE_EXPLOG=1 OPTWG=1 UNSAFE_FLOAT4=1 DEBUGCL=1 python3 openpilot/compile.py {fn}.onnx {fn}.thneed" + + # is there a better way then listing all of tinygrad? + lenv.Command(fn + ".thneed", [fn + ".onnx", + "#tinygrad_repo/openpilot/compile.py", + "#tinygrad_repo/accel/opencl/conv.cl", + "#tinygrad_repo/accel/opencl/matmul.cl", + "#tinygrad_repo/accel/opencl/ops_opencl.py", + "#tinygrad_repo/accel/opencl/preprocessing.py", + "#tinygrad_repo/extra/onnx.py", + "#tinygrad_repo/extra/thneed.py", + "#tinygrad_repo/extra/utils.py", + "#tinygrad_repo/tinygrad/llops/ops_gpu.py", + "#tinygrad_repo/tinygrad/llops/ops_opencl.py", + "#tinygrad_repo/tinygrad/helpers.py", + "#tinygrad_repo/tinygrad/mlops.py", + "#tinygrad_repo/tinygrad/ops.py", + "#tinygrad_repo/tinygrad/shapetracker.py", + "#tinygrad_repo/tinygrad/tensor.py", + "#tinygrad_repo/tinygrad/nn/__init__.py" + ], cmd) + +llenv = lenv.Clone() +if GetOption('pc_thneed'): + pc_thneed_src = [ + "thneed/thneed_common.cc", + "thneed/thneed_pc.cc", + "thneed/serialize.cc", + "runners/thneedmodel.cc", + ] + llenv['CFLAGS'].append("-DUSE_THNEED") + llenv['CXXFLAGS'].append("-DUSE_THNEED") + common_model += llenv.Object(pc_thneed_src) + libs += ['dl'] + +llenv.Program('_modeld', [ "modeld.cc", "models/driving.cc", - ]+common_model, LIBS=libs) + ]+common_model, LIBS=libs + transformations) + +lenv.Program('_navmodeld', [ + "navmodeld.cc", + "models/nav.cc", + ]+common_model, LIBS=libs + transformations) \ No newline at end of file diff --git a/selfdrive/modeld/dmonitoringmodeld b/selfdrive/modeld/dmonitoringmodeld index 9acd7bcc33..f292fe4c0b 100755 --- a/selfdrive/modeld/dmonitoringmodeld +++ b/selfdrive/modeld/dmonitoringmodeld @@ -3,15 +3,10 @@ DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" cd $DIR -if [ -d /system ]; then - if [ -f /TICI ]; then # QCOM2 - export LD_LIBRARY_PATH="/usr/lib/aarch64-linux-gnu:/data/pythonpath/third_party/snpe/larch64:$LD_LIBRARY_PATH" - else # QCOM - export LD_LIBRARY_PATH="/data/pythonpath/third_party/snpe/aarch64/:$LD_LIBRARY_PATH" - fi +if [ -f /TICI ]; then + export LD_LIBRARY_PATH="/usr/lib/aarch64-linux-gnu:/data/pythonpath/third_party/snpe/larch64:$LD_LIBRARY_PATH" export ADSP_LIBRARY_PATH="/data/pythonpath/third_party/snpe/dsp/" else - # PC export LD_LIBRARY_PATH="$DIR/../../third_party/snpe/x86_64-linux-clang:$DIR/../../openpilot/third_party/snpe/x86_64:$LD_LIBRARY_PATH" fi exec ./_dmonitoringmodeld diff --git a/selfdrive/modeld/dmonitoringmodeld.cc b/selfdrive/modeld/dmonitoringmodeld.cc index c85c05c9d1..cde13a9bee 100644 --- a/selfdrive/modeld/dmonitoringmodeld.cc +++ b/selfdrive/modeld/dmonitoringmodeld.cc @@ -5,14 +5,16 @@ #include #include "cereal/visionipc/visionipc_client.h" -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/util.h" +#include "common/swaglog.h" +#include "common/util.h" #include "selfdrive/modeld/models/dmonitoring.h" ExitHandler do_exit; void run_model(DMonitoringModelState &model, VisionIpcClient &vipc_client) { - PubMaster pm({"driverState"}); + PubMaster pm({"driverStateV2"}); + SubMaster sm({"liveCalibration"}); + float calib[CALIB_LEN] = {0}; double last = 0; while (!do_exit) { @@ -20,12 +22,20 @@ void run_model(DMonitoringModelState &model, VisionIpcClient &vipc_client) { VisionBuf *buf = vipc_client.recv(&extra); if (buf == nullptr) continue; + sm.update(0); + if (sm.updated("liveCalibration")) { + auto calib_msg = sm["liveCalibration"].getLiveCalibration().getRpyCalib(); + for (int i = 0; i < CALIB_LEN; i++) { + calib[i] = calib_msg[i]; + } + } + double t1 = millis_since_boot(); - DMonitoringResult res = dmonitoring_eval_frame(&model, buf->addr, buf->width, buf->height); + DMonitoringModelResult model_res = dmonitoring_eval_frame(&model, buf->addr, buf->width, buf->height, buf->stride, buf->uv_offset, calib); double t2 = millis_since_boot(); // send dm packet - dmonitoring_publish(pm, extra.frame_id, res, (t2 - t1) / 1000.0, model.output); + dmonitoring_publish(pm, extra.frame_id, model_res, (t2 - t1) / 1000.0, model.output); //printf("dmonitoring process: %.2fms, from last %.2fms\n", t2 - t1, t1 - last); last = t1; diff --git a/selfdrive/modeld/modeld b/selfdrive/modeld/modeld index fcf2812cb7..c067cf3d62 100755 --- a/selfdrive/modeld/modeld +++ b/selfdrive/modeld/modeld @@ -3,14 +3,9 @@ DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" cd $DIR -if [ -d /system ]; then - if [ -f /TICI ]; then # QCOM2 - export LD_LIBRARY_PATH="/usr/lib/aarch64-linux-gnu:/data/pythonpath/third_party/snpe/larch64:$LD_LIBRARY_PATH" - else # QCOM - export LD_LIBRARY_PATH="/data/pythonpath/third_party/snpe/aarch64/:$LD_LIBRARY_PATH" - fi +if [ -f /TICI ]; then + export LD_LIBRARY_PATH="/usr/lib/aarch64-linux-gnu:/data/pythonpath/third_party/snpe/larch64:$LD_LIBRARY_PATH" else - # PC export LD_LIBRARY_PATH="$DIR/../../third_party/snpe/x86_64-linux-clang:$DIR/../../openpilot/third_party/snpe/x86_64:$LD_LIBRARY_PATH" fi exec ./_modeld diff --git a/selfdrive/modeld/modeld.cc b/selfdrive/modeld/modeld.cc index 697e31a7b7..cfc71a0e27 100644 --- a/selfdrive/modeld/modeld.cc +++ b/selfdrive/modeld/modeld.cc @@ -6,55 +6,61 @@ #include #include "cereal/messaging/messaging.h" +#include "common/transformations/orientation.hpp" + #include "cereal/visionipc/visionipc_client.h" -#include "selfdrive/common/clutil.h" -#include "selfdrive/common/params.h" -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/util.h" -#include "selfdrive/hardware/hw.h" +#include "common/clutil.h" +#include "common/params.h" +#include "common/swaglog.h" +#include "common/util.h" +#include "system/hardware/hw.h" #include "selfdrive/modeld/models/driving.h" + ExitHandler do_exit; -mat3 update_calibration(Eigen::Matrix &extrinsics, bool wide_camera, bool bigmodel_frame) { +mat3 update_calibration(Eigen::Vector3d device_from_calib_euler, bool wide_camera, bool bigmodel_frame) { /* import numpy as np - from common.transformations.model import medmodel_frame_from_road_frame - medmodel_frame_from_ground = medmodel_frame_from_road_frame[:, (0, 1, 3)] - ground_from_medmodel_frame = np.linalg.inv(medmodel_frame_from_ground) + from common.transformations.model import medmodel_frame_from_calib_frame + medmodel_frame_from_calib_frame = medmodel_frame_from_calib_frame[:, :3] + calib_from_smedmodel_frame = np.linalg.inv(medmodel_frame_from_calib_frame) */ - static const auto ground_from_medmodel_frame = (Eigen::Matrix() << + static const auto calib_from_medmodel = (Eigen::Matrix() << 0.00000000e+00, 0.00000000e+00, 1.00000000e+00, - -1.09890110e-03, 0.00000000e+00, 2.81318681e-01, - -1.84808520e-20, 9.00738606e-04, -4.28751576e-02).finished(); + 1.09890110e-03, 0.00000000e+00, -2.81318681e-01, + -2.25466395e-20, 1.09890110e-03,-5.23076923e-02).finished(); - static const auto ground_from_sbigmodel_frame = (Eigen::Matrix() << + static const auto calib_from_sbigmodel = (Eigen::Matrix() << 0.00000000e+00, 7.31372216e-19, 1.00000000e+00, - -2.19780220e-03, 4.11497335e-19, 5.62637363e-01, - -5.46146580e-20, 1.80147721e-03, -2.73464241e-01).finished(); + 2.19780220e-03, 4.11497335e-19, -5.62637363e-01, + -6.66298828e-20, 2.19780220e-03, -3.33626374e-01).finished(); - const auto cam_intrinsics = Eigen::Matrix(wide_camera ? ecam_intrinsic_matrix.v : fcam_intrinsic_matrix.v); - static const mat3 yuv_transform = get_model_yuv_transform(); + static const auto view_from_device = (Eigen::Matrix() << + 0.0, 1.0, 0.0, + 0.0, 0.0, 1.0, + 1.0, 0.0, 0.0).finished(); - auto ground_from_model_frame = bigmodel_frame ? ground_from_sbigmodel_frame : ground_from_medmodel_frame; - auto camera_frame_from_road_frame = cam_intrinsics * extrinsics; - Eigen::Matrix camera_frame_from_ground; - camera_frame_from_ground.col(0) = camera_frame_from_road_frame.col(0); - camera_frame_from_ground.col(1) = camera_frame_from_road_frame.col(1); - camera_frame_from_ground.col(2) = camera_frame_from_road_frame.col(3); - auto warp_matrix = camera_frame_from_ground * ground_from_model_frame; + const auto cam_intrinsics = Eigen::Matrix(wide_camera ? ecam_intrinsic_matrix.v : fcam_intrinsic_matrix.v); + Eigen::Matrix device_from_calib = euler2rot(device_from_calib_euler).cast (); + auto calib_from_model = bigmodel_frame ? calib_from_sbigmodel : calib_from_medmodel; + auto camera_from_calib = cam_intrinsics * view_from_device * device_from_calib; + auto warp_matrix = camera_from_calib * calib_from_model; + mat3 transform = {}; for (int i=0; i<3*3; i++) { transform.v[i] = warp_matrix(i / 3, i % 3); } + static const mat3 yuv_transform = get_model_yuv_transform(); return matmul3(yuv_transform, transform); } -void run_model(ModelState &model, VisionIpcClient &vipc_client_main, VisionIpcClient &vipc_client_extra, bool main_wide_camera, bool use_extra, bool use_extra_client) { + +void run_model(ModelState &model, VisionIpcClient &vipc_client_main, VisionIpcClient &vipc_client_extra, bool main_wide_camera, bool use_extra_client) { // messaging PubMaster pm({"modelV2", "cameraOdometry"}); - SubMaster sm({"lateralPlan", "roadCameraState", "liveCalibration"}); + SubMaster sm({"lateralPlan", "roadCameraState", "liveCalibration", "driverMonitoringState"}); // setup filter to track dropped frames FirstOrderFilter frame_dropped_filter(0., 10., 1. / MODEL_FREQ); @@ -74,18 +80,9 @@ void run_model(ModelState &model, VisionIpcClient &vipc_client_main, VisionIpcCl VisionIpcBufExtra meta_extra = {0}; while (!do_exit) { - // TODO: change sync logic to use timestamp start of frame in case camerad skips a frame - // log frame id in model packet - // Keep receiving frames until we are at least 1 frame ahead of previous extra frame - while (meta_main.frame_id <= meta_extra.frame_id) { + while (meta_main.timestamp_sof < meta_extra.timestamp_sof + 25000000ULL) { buf_main = vipc_client_main.recv(&meta_main); - if (meta_main.frame_id <= meta_extra.frame_id) { - LOGE("main camera behind! main: %d (%.5f), extra: %d (%.5f)", - meta_main.frame_id, double(meta_main.timestamp_sof) / 1e9, - meta_extra.frame_id, double(meta_extra.timestamp_sof) / 1e9); - } - if (buf_main == nullptr) break; } @@ -98,20 +95,14 @@ void run_model(ModelState &model, VisionIpcClient &vipc_client_main, VisionIpcCl // Keep receiving extra frames until frame id matches main camera do { buf_extra = vipc_client_extra.recv(&meta_extra); - - if (meta_main.frame_id > meta_extra.frame_id) { - LOGE("extra camera behind! main: %d (%.5f), extra: %d (%.5f)", - meta_main.frame_id, double(meta_main.timestamp_sof) / 1e9, - meta_extra.frame_id, double(meta_extra.timestamp_sof) / 1e9); - } - } while (buf_extra != nullptr && meta_main.frame_id > meta_extra.frame_id); + } while (buf_extra != nullptr && meta_main.timestamp_sof > meta_extra.timestamp_sof + 25000000ULL); if (buf_extra == nullptr) { LOGE("vipc_client_extra no frame"); continue; } - if (meta_main.frame_id != meta_extra.frame_id || std::abs((int64_t)meta_main.timestamp_sof - (int64_t)meta_extra.timestamp_sof) > 10000000ULL) { + if (std::abs((int64_t)meta_main.timestamp_sof - (int64_t)meta_extra.timestamp_sof) > 10000000ULL) { LOGE("frames out of sync! main: %d (%.5f), extra: %d (%.5f)", meta_main.frame_id, double(meta_main.timestamp_sof) / 1e9, meta_extra.frame_id, double(meta_extra.timestamp_sof) / 1e9); @@ -125,18 +116,16 @@ void run_model(ModelState &model, VisionIpcClient &vipc_client_main, VisionIpcCl // TODO: path planner timeout? sm.update(0); int desire = ((int)sm["lateralPlan"].getLateralPlan().getDesire()); + bool is_rhd = ((bool)sm["driverMonitoringState"].getDriverMonitoringState().getIsRHD()); frame_id = sm["roadCameraState"].getRoadCameraState().getFrameId(); if (sm.updated("liveCalibration")) { - auto extrinsic_matrix = sm["liveCalibration"].getLiveCalibration().getExtrinsicMatrix(); - Eigen::Matrix extrinsic_matrix_eigen; - for (int i = 0; i < 4*3; i++) { - extrinsic_matrix_eigen(i / 4, i % 4) = extrinsic_matrix[i]; - } - - model_transform_main = update_calibration(extrinsic_matrix_eigen, main_wide_camera, false); - if (use_extra) { - model_transform_extra = update_calibration(extrinsic_matrix_eigen, Hardware::TICI(), true); + auto rpy_calib = sm["liveCalibration"].getLiveCalibration().getRpyCalib(); + Eigen::Vector3d device_from_calib_euler; + for (int i=0; i<3; i++) { + device_from_calib_euler(i) = rpy_calib[i]; } + model_transform_main = update_calibration(device_from_calib_euler, main_wide_camera, false); + model_transform_extra = update_calibration(device_from_calib_euler, true, true); live_calib_seen = true; } @@ -145,11 +134,6 @@ void run_model(ModelState &model, VisionIpcClient &vipc_client_main, VisionIpcCl vec_desire[desire] = 1.0; } - double mt1 = millis_since_boot(); - ModelOutput *model_output = model_eval_frame(&model, buf_main, buf_extra, model_transform_main, model_transform_extra, vec_desire); - double mt2 = millis_since_boot(); - float model_execution_time = (mt2 - mt1) / 1000.0; - // tracked dropped frames uint32_t vipc_dropped_frames = meta_main.frame_id - last_vipc_frame_id - 1; float frames_dropped = frame_dropped_filter.update((float)std::min(vipc_dropped_frames, 10U)); @@ -160,10 +144,22 @@ void run_model(ModelState &model, VisionIpcClient &vipc_client_main, VisionIpcCl run_count++; float frame_drop_ratio = frames_dropped / (1 + frames_dropped); + bool prepare_only = vipc_dropped_frames > 0; - model_publish(pm, meta_main.frame_id, frame_id, frame_drop_ratio, *model_output, meta_main.timestamp_eof, model_execution_time, - kj::ArrayPtr(model.output.data(), model.output.size()), live_calib_seen); - posenet_publish(pm, meta_main.frame_id, vipc_dropped_frames, *model_output, meta_main.timestamp_eof, live_calib_seen); + if (prepare_only) { + LOGE("skipping model eval. Dropped %d frames", vipc_dropped_frames); + } + + double mt1 = millis_since_boot(); + ModelOutput *model_output = model_eval_frame(&model, buf_main, buf_extra, model_transform_main, model_transform_extra, vec_desire, is_rhd, prepare_only); + double mt2 = millis_since_boot(); + float model_execution_time = (mt2 - mt1) / 1000.0; + + if (model_output != nullptr) { + model_publish(pm, meta_main.frame_id, meta_extra.frame_id, frame_id, frame_drop_ratio, *model_output, meta_main.timestamp_eof, model_execution_time, + kj::ArrayPtr(model.output.data(), model.output.size()), live_calib_seen); + posenet_publish(pm, meta_main.frame_id, vipc_dropped_frames, *model_output, meta_main.timestamp_eof, live_calib_seen); + } //printf("model process: %.2fms, from last %.2fms, vipc_frame_id %u, frame_id, %u, frame_drop %.3f\n", mt2 - mt1, mt1 - last, extra.frame_id, frame_id, frame_drop_ratio); last = mt1; @@ -176,13 +172,12 @@ int main(int argc, char **argv) { int ret; ret = util::set_realtime_priority(54); assert(ret == 0); - util::set_core_affinity({Hardware::EON() ? 2 : 7}); + util::set_core_affinity({7}); assert(ret == 0); } - bool main_wide_camera = Hardware::TICI() ? Params().getBool("EnableWideCamera") : false; - bool use_extra = USE_EXTRA; - bool use_extra_client = Hardware::TICI() && use_extra && !main_wide_camera; + bool main_wide_camera = Params().getBool("WideCameraOnly"); + bool use_extra_client = !main_wide_camera; // set for single camera mode // cl init cl_device_id device_id = cl_get_device_id(CL_DEVICE_TYPE_DEFAULT); @@ -190,7 +185,7 @@ int main(int argc, char **argv) { // init the models ModelState model; - model_init(&model, device_id, context, use_extra); + model_init(&model, device_id, context); LOGW("models loaded, modeld starting"); VisionIpcClient vipc_client_main = VisionIpcClient("camerad", main_wide_camera ? VISION_STREAM_WIDE_ROAD : VISION_STREAM_ROAD, true, device_id, context); @@ -215,7 +210,7 @@ int main(int argc, char **argv) { LOGW("connected extra cam with buffer size: %d (%d x %d)", wb->len, wb->width, wb->height); } - run_model(model, vipc_client_main, vipc_client_extra, main_wide_camera, use_extra, use_extra_client); + run_model(model, vipc_client_main, vipc_client_extra, main_wide_camera, use_extra_client); } model_free(&model); diff --git a/selfdrive/modeld/models/README.md b/selfdrive/modeld/models/README.md new file mode 100644 index 0000000000..6b704cbfa8 --- /dev/null +++ b/selfdrive/modeld/models/README.md @@ -0,0 +1,59 @@ +## Neural networks in openpilot +To view the architecture of the ONNX networks, you can use [netron](https://netron.app/) + +## Supercombo +### Supercombo input format (Full size: 393738 x float32) +* **image stream** + * Two consecutive images (256 * 512 * 3 in RGB) recorded at 20 Hz : 393216 = 2 * 6 * 128 * 256 + * Each 256 * 512 image is represented in YUV420 with 6 channels : 6 * 128 * 256 + * Channels 0,1,2,3 represent the full-res Y channel and are represented in numpy as Y[::2, ::2], Y[::2, 1::2], Y[1::2, ::2], and Y[1::2, 1::2] + * Channel 4 represents the half-res U channel + * Channel 5 represents the half-res V channel +* **wide image stream** + * Two consecutive images (256 * 512 * 3 in RGB) recorded at 20 Hz : 393216 = 2 * 6 * 128 * 256 + * Each 256 * 512 image is represented in YUV420 with 6 channels : 6 * 128 * 256 + * Channels 0,1,2,3 represent the full-res Y channel and are represented in numpy as Y[::2, ::2], Y[::2, 1::2], Y[1::2, ::2], and Y[1::2, 1::2] + * Channel 4 represents the half-res U channel + * Channel 5 represents the half-res V channel +* **desire** + * one-hot encoded vector to command model to execute certain actions, bit only needs to be sent for 1 frame : 8 +* **traffic convention** + * one-hot encoded vector to tell model whether traffic is right-hand or left-hand traffic : 2 +* **recurrent state** + * The recurrent state vector that is fed back into the GRU for temporal context : 512 + + +### Supercombo output format (Full size: XXX x float32) +Read [here](https://github.com/commaai/openpilot/blob/90af436a121164a51da9fa48d093c29f738adf6a/selfdrive/modeld/models/driving.h#L236) for more. + + +## Driver Monitoring Model +* .onnx model can be run with onnx runtimes +* .dlc file is a pre-quantized model and only runs on qualcomm DSPs + +### input format +* single image (640 * 320 * 3 in RGB): + * full input size is 6 * 640/2 * 320/2 = 307200 + * represented in YUV420 with 6 channels: + * Channels 0,1,2,3 represent the full-res Y channel and are represented in numpy as Y[::2, ::2], Y[::2, 1::2], Y[1::2, ::2], and Y[1::2, 1::2] + * Channel 4 represents the half-res U channel + * Channel 5 represents the half-res V channel + * normalized, ranging from -1.0 to 1.0 + +### output format +* 39 x float32 outputs ([parsing example](https://github.com/commaai/openpilot/blob/master/selfdrive/modeld/models/dmonitoring.cc#L165)) + * face pose: 12 = 6 + 6 + * face orientation [pitch, yaw, roll] in camera frame: 3 + * face position [dx, dy] relative to image center: 2 + * normalized face size: 1 + * standard deviations for above outputs: 6 + * face visible probability: 1 + * eyes: 20 = (8 + 1) + (8 + 1) + 1 + 1 + * eye position and size, and their standard deviations: 8 + * eye visible probability: 1 + * eye closed probability: 1 + * wearing sunglasses probability: 1 + * poor camera vision probability: 1 + * face partially out-of-frame probability: 1 + * (deprecated) distracted probabilities: 2 + * face covered probability: 1 diff --git a/selfdrive/modeld/models/commonmodel.cc b/selfdrive/modeld/models/commonmodel.cc index 1a1f6eaea6..b7c9051c6e 100644 --- a/selfdrive/modeld/models/commonmodel.cc +++ b/selfdrive/modeld/models/commonmodel.cc @@ -5,9 +5,9 @@ #include #include -#include "selfdrive/common/clutil.h" -#include "selfdrive/common/mat.h" -#include "selfdrive/common/timing.h" +#include "common/clutil.h" +#include "common/mat.h" +#include "common/timing.h" ModelFrame::ModelFrame(cl_device_id device_id, cl_context context) { input_frames = std::make_unique(buf_size); @@ -22,9 +22,9 @@ ModelFrame::ModelFrame(cl_device_id device_id, cl_context context) { loadyuv_init(&loadyuv, context, device_id, MODEL_WIDTH, MODEL_HEIGHT); } -float* ModelFrame::prepare(cl_mem yuv_cl, int frame_width, int frame_height, const mat3 &projection, cl_mem *output) { +float* ModelFrame::prepare(cl_mem yuv_cl, int frame_width, int frame_height, int frame_stride, int frame_uv_offset, const mat3 &projection, cl_mem *output) { transform_queue(&this->transform, q, - yuv_cl, frame_width, frame_height, + yuv_cl, frame_width, frame_height, frame_stride, frame_uv_offset, y_cl, u_cl, v_cl, MODEL_WIDTH, MODEL_HEIGHT, projection); if (output == NULL) { @@ -70,7 +70,3 @@ void softmax(const float* input, float* output, size_t len) { float sigmoid(float input) { return 1 / (1 + expf(-input)); } - -float softplus(float input) { - return log1p(expf(input)); -} diff --git a/selfdrive/modeld/models/commonmodel.h b/selfdrive/modeld/models/commonmodel.h index 19af75eef4..1a079da055 100644 --- a/selfdrive/modeld/models/commonmodel.h +++ b/selfdrive/modeld/models/commonmodel.h @@ -12,21 +12,26 @@ #include #endif -#include "selfdrive/common/mat.h" +#include "common/mat.h" +#include "cereal/messaging/messaging.h" #include "selfdrive/modeld/transforms/loadyuv.h" #include "selfdrive/modeld/transforms/transform.h" const bool send_raw_pred = getenv("SEND_RAW_PRED") != NULL; void softmax(const float* input, float* output, size_t len); -float softplus(float input); float sigmoid(float input); +template +constexpr const kj::ArrayPtr to_kj_array_ptr(const std::array &arr) { + return kj::ArrayPtr(arr.data(), arr.size()); +} + class ModelFrame { public: ModelFrame(cl_device_id device_id, cl_context context); ~ModelFrame(); - float* prepare(cl_mem yuv_cl, int width, int height, const mat3& transform, cl_mem *output); + float* prepare(cl_mem yuv_cl, int width, int height, int frame_stride, int frame_uv_offset, const mat3& transform, cl_mem *output); const int MODEL_WIDTH = 512; const int MODEL_HEIGHT = 256; diff --git a/selfdrive/modeld/models/dmonitoring.cc b/selfdrive/modeld/models/dmonitoring.cc index 005d0bcc53..e7e6d46612 100644 --- a/selfdrive/modeld/models/dmonitoring.cc +++ b/selfdrive/modeld/models/dmonitoring.cc @@ -2,16 +2,16 @@ #include "libyuv.h" -#include "selfdrive/common/mat.h" -#include "selfdrive/common/modeldata.h" -#include "selfdrive/common/params.h" -#include "selfdrive/common/timing.h" -#include "selfdrive/hardware/hw.h" +#include "common/mat.h" +#include "common/modeldata.h" +#include "common/params.h" +#include "common/timing.h" +#include "system/hardware/hw.h" #include "selfdrive/modeld/models/dmonitoring.h" -constexpr int MODEL_WIDTH = 320; -constexpr int MODEL_HEIGHT = 640; +constexpr int MODEL_WIDTH = 1440; +constexpr int MODEL_HEIGHT = 960; template static inline T *get_buffer(std::vector &buf, const size_t size) { @@ -19,209 +19,114 @@ static inline T *get_buffer(std::vector &buf, const size_t size) { return buf.data(); } -static inline void init_yuv_buf(std::vector &buf, const int width, int height) { - uint8_t *y = get_buffer(buf, width * height * 3 / 2); - uint8_t *u = y + width * height; - uint8_t *v = u + (width / 2) * (height / 2); - - // needed on comma two to make the padded border black - // equivalent to RGB(0,0,0) in YUV space - memset(y, 16, width * height); - memset(u, 128, (width / 2) * (height / 2)); - memset(v, 128, (width / 2) * (height / 2)); -} - void dmonitoring_init(DMonitoringModelState* s) { - s->is_rhd = Params().getBool("IsRHD"); - for (int x = 0; x < std::size(s->tensor); ++x) { - s->tensor[x] = (x - 128.f) * 0.0078125f; - } - init_yuv_buf(s->resized_buf, MODEL_WIDTH, MODEL_HEIGHT); #ifdef USE_ONNX_MODEL - s->m = new ONNXModel("../../models/dmonitoring_model.onnx", &s->output[0], OUTPUT_SIZE, USE_DSP_RUNTIME); + s->m = new ONNXModel("models/dmonitoring_model.onnx", &s->output[0], OUTPUT_SIZE, USE_DSP_RUNTIME, false, true); #else - s->m = new SNPEModel("../../models/dmonitoring_model_q.dlc", &s->output[0], OUTPUT_SIZE, USE_DSP_RUNTIME); + s->m = new SNPEModel("models/dmonitoring_model_q.dlc", &s->output[0], OUTPUT_SIZE, USE_DSP_RUNTIME, false, true); #endif -} -static inline auto get_yuv_buf(std::vector &buf, const int width, int height) { - uint8_t *y = get_buffer(buf, width * height * 3 / 2); - uint8_t *u = y + width * height; - uint8_t *v = u + (width /2) * (height / 2); - return std::make_tuple(y, u, v); + s->m->addCalib(s->calib, CALIB_LEN); } -struct Rect {int x, y, w, h;}; -void crop_yuv(uint8_t *raw, int width, int height, uint8_t *y, uint8_t *u, uint8_t *v, const Rect &rect) { - uint8_t *raw_y = raw; - uint8_t *raw_u = raw_y + (width * height); - uint8_t *raw_v = raw_u + ((width / 2) * (height / 2)); - for (int r = 0; r < rect.h / 2; r++) { - memcpy(y + 2 * r * rect.w, raw_y + (2 * r + rect.y) * width + rect.x, rect.w); - memcpy(y + (2 * r + 1) * rect.w, raw_y + (2 * r + rect.y + 1) * width + rect.x, rect.w); - memcpy(u + r * (rect.w / 2), raw_u + (r + (rect.y / 2)) * width / 2 + (rect.x / 2), rect.w / 2); - memcpy(v + r * (rect.w / 2), raw_v + (r + (rect.y / 2)) * width / 2 + (rect.x / 2), rect.w / 2); +void parse_driver_data(DriverStateResult &ds_res, const DMonitoringModelState* s, int out_idx_offset) { + for (int i = 0; i < 3; ++i) { + ds_res.face_orientation[i] = s->output[out_idx_offset+i] * REG_SCALE; + ds_res.face_orientation_std[i] = exp(s->output[out_idx_offset+6+i]); } -} - -DMonitoringResult dmonitoring_eval_frame(DMonitoringModelState* s, void* stream_buf, int width, int height) { - Rect crop_rect; - if (width == TICI_CAM_WIDTH) { - const int cropped_height = tici_dm_crop::width / 1.33; - crop_rect = {width / 2 - tici_dm_crop::width / 2 + tici_dm_crop::x_offset, - height / 2 - cropped_height / 2 + tici_dm_crop::y_offset, - cropped_height / 2, - cropped_height}; - if (!s->is_rhd) { - crop_rect.x += tici_dm_crop::width - crop_rect.w; - } - } else { - const int adapt_width = 372; - crop_rect = {0, 0, adapt_width, height}; - if (!s->is_rhd) { - crop_rect.x += width - crop_rect.w; - } + for (int i = 0; i < 2; ++i) { + ds_res.face_position[i] = s->output[out_idx_offset+3+i] * REG_SCALE; + ds_res.face_position_std[i] = exp(s->output[out_idx_offset+9+i]); } - - int resized_width = MODEL_WIDTH; - int resized_height = MODEL_HEIGHT; - - auto [cropped_y, cropped_u, cropped_v] = get_yuv_buf(s->cropped_buf, crop_rect.w, crop_rect.h); - if (!s->is_rhd) { - crop_yuv((uint8_t *)stream_buf, width, height, cropped_y, cropped_u, cropped_v, crop_rect); - } else { - auto [mirror_y, mirror_u, mirror_v] = get_yuv_buf(s->premirror_cropped_buf, crop_rect.w, crop_rect.h); - crop_yuv((uint8_t *)stream_buf, width, height, mirror_y, mirror_u, mirror_v, crop_rect); - libyuv::I420Mirror(mirror_y, crop_rect.w, - mirror_u, crop_rect.w / 2, - mirror_v, crop_rect.w / 2, - cropped_y, crop_rect.w, - cropped_u, crop_rect.w / 2, - cropped_v, crop_rect.w / 2, - crop_rect.w, crop_rect.h); + for (int i = 0; i < 4; ++i) { + ds_res.ready_prob[i] = sigmoid(s->output[out_idx_offset+35+i]); } - - auto [resized_buf, resized_u, resized_v] = get_yuv_buf(s->resized_buf, resized_width, resized_height); - uint8_t *resized_y = resized_buf; - libyuv::FilterMode mode = libyuv::FilterModeEnum::kFilterBilinear; - if (Hardware::TICI()) { - libyuv::I420Scale(cropped_y, crop_rect.w, - cropped_u, crop_rect.w / 2, - cropped_v, crop_rect.w / 2, - crop_rect.w, crop_rect.h, - resized_y, resized_width, - resized_u, resized_width / 2, - resized_v, resized_width / 2, - resized_width, resized_height, - mode); - } else { - const int source_height = 0.7*resized_height; - const int extra_height = (resized_height - source_height) / 2; - const int extra_width = (resized_width - source_height / 2) / 2; - const int source_width = source_height / 2 + extra_width; - libyuv::I420Scale(cropped_y, crop_rect.w, - cropped_u, crop_rect.w / 2, - cropped_v, crop_rect.w / 2, - crop_rect.w, crop_rect.h, - resized_y + extra_height * resized_width, resized_width, - resized_u + extra_height / 2 * resized_width / 2, resized_width / 2, - resized_v + extra_height / 2 * resized_width / 2, resized_width / 2, - source_width, source_height, - mode); + for (int i = 0; i < 2; ++i) { + ds_res.not_ready_prob[i] = sigmoid(s->output[out_idx_offset+39+i]); } + ds_res.face_prob = sigmoid(s->output[out_idx_offset+12]); + ds_res.left_eye_prob = sigmoid(s->output[out_idx_offset+21]); + ds_res.right_eye_prob = sigmoid(s->output[out_idx_offset+30]); + ds_res.left_blink_prob = sigmoid(s->output[out_idx_offset+31]); + ds_res.right_blink_prob = sigmoid(s->output[out_idx_offset+32]); + ds_res.sunglasses_prob = sigmoid(s->output[out_idx_offset+33]); + ds_res.occluded_prob = sigmoid(s->output[out_idx_offset+34]); +} - int yuv_buf_len = (MODEL_WIDTH/2) * (MODEL_HEIGHT/2) * 6; // Y|u|v -> y|y|y|y|u|v - float *net_input_buf = get_buffer(s->net_input_buf, yuv_buf_len); - // one shot conversion, O(n) anyway - // yuvframe2tensor, normalize - for (int r = 0; r < MODEL_HEIGHT/2; r++) { - for (int c = 0; c < MODEL_WIDTH/2; c++) { - // Y_ul - net_input_buf[(r*MODEL_WIDTH/2) + c + (0*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = s->tensor[resized_y[(2*r)*resized_width + 2*c]]; - // Y_dl - net_input_buf[(r*MODEL_WIDTH/2) + c + (1*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = s->tensor[resized_y[(2*r+1)*resized_width + 2*c]]; - // Y_ur - net_input_buf[(r*MODEL_WIDTH/2) + c + (2*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = s->tensor[resized_y[(2*r)*resized_width + 2*c+1]]; - // Y_dr - net_input_buf[(r*MODEL_WIDTH/2) + c + (3*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = s->tensor[resized_y[(2*r+1)*resized_width + 2*c+1]]; - // U - net_input_buf[(r*MODEL_WIDTH/2) + c + (4*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = s->tensor[resized_u[r*resized_width/2 + c]]; - // V - net_input_buf[(r*MODEL_WIDTH/2) + c + (5*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = s->tensor[resized_v[r*resized_width/2 + c]]; - } - } +void fill_driver_data(cereal::DriverStateV2::DriverData::Builder ddata, const DriverStateResult &ds_res) { + ddata.setFaceOrientation(ds_res.face_orientation); + ddata.setFaceOrientationStd(ds_res.face_orientation_std); + ddata.setFacePosition(ds_res.face_position); + ddata.setFacePositionStd(ds_res.face_position_std); + ddata.setFaceProb(ds_res.face_prob); + ddata.setLeftEyeProb(ds_res.left_eye_prob); + ddata.setRightEyeProb(ds_res.right_eye_prob); + ddata.setLeftBlinkProb(ds_res.left_blink_prob); + ddata.setRightBlinkProb(ds_res.right_blink_prob); + ddata.setSunglassesProb(ds_res.sunglasses_prob); + ddata.setOccludedProb(ds_res.occluded_prob); + ddata.setReadyProb(ds_res.ready_prob); + ddata.setNotReadyProb(ds_res.not_ready_prob); +} - //printf("preprocess completed. %d \n", yuv_buf_len); - //FILE *dump_yuv_file = fopen("/tmp/rawdump.yuv", "wb"); - //fwrite(resized_buf, yuv_buf_len, sizeof(uint8_t), dump_yuv_file); - //fclose(dump_yuv_file); +DMonitoringModelResult dmonitoring_eval_frame(DMonitoringModelState* s, void* stream_buf, int width, int height, int stride, int uv_offset, float *calib) { + int v_off = height - MODEL_HEIGHT; + int h_off = (width - MODEL_WIDTH) / 2; + int yuv_buf_len = MODEL_WIDTH * MODEL_HEIGHT; - // *** testing *** - // idat = np.frombuffer(open("/tmp/inputdump.yuv", "rb").read(), np.float32).reshape(6, 160, 320) - // imshow(cv2.cvtColor(tensor_to_frames(idat[None]/0.0078125+128)[0], cv2.COLOR_YUV2RGB_I420)) + uint8_t *raw_buf = (uint8_t *) stream_buf; + // vertical crop free + uint8_t *raw_y_start = raw_buf + stride * v_off; - //FILE *dump_yuv_file2 = fopen("/tmp/inputdump.yuv", "wb"); - //fwrite(net_input_buf, MODEL_HEIGHT*MODEL_WIDTH*3/2, sizeof(float), dump_yuv_file2); - //fclose(dump_yuv_file2); + uint8_t *net_input_buf = get_buffer(s->net_input_buf, yuv_buf_len); + + // here makes a uint8 copy + for (int r = 0; r < MODEL_HEIGHT; ++r) { + memcpy(net_input_buf + r * MODEL_WIDTH, raw_y_start + r * stride + h_off, MODEL_WIDTH); + } + + // printf("preprocess completed. %d \n", yuv_buf_len); + // FILE *dump_yuv_file = fopen("/tmp/rawdump.yuv", "wb"); + // fwrite(net_input_buf, yuv_buf_len, sizeof(uint8_t), dump_yuv_file); + // fclose(dump_yuv_file); double t1 = millis_since_boot(); - s->m->addImage(net_input_buf, yuv_buf_len); + s->m->addImage((float*)net_input_buf, yuv_buf_len / 4); + for (int i = 0; i < CALIB_LEN; i++) { + s->calib[i] = calib[i]; + } s->m->execute(); double t2 = millis_since_boot(); - DMonitoringResult ret = {0}; - for (int i = 0; i < 3; ++i) { - ret.face_orientation[i] = s->output[i]; - ret.face_orientation_meta[i] = softplus(s->output[6 + i]); - } - for (int i = 0; i < 2; ++i) { - ret.face_position[i] = s->output[3 + i]; - ret.face_position_meta[i] = softplus(s->output[9 + i]); - } - ret.face_prob = s->output[12]; - ret.left_eye_prob = s->output[21]; - ret.right_eye_prob = s->output[30]; - ret.left_blink_prob = s->output[31]; - ret.right_blink_prob = s->output[32]; - ret.sg_prob = s->output[33]; - ret.poor_vision = s->output[34]; - ret.partial_face = s->output[35]; - ret.distracted_pose = s->output[36]; - ret.distracted_eyes = s->output[37]; - ret.occluded_prob = s->output[38]; - ret.dsp_execution_time = (t2 - t1) / 1000.; - return ret; + DMonitoringModelResult model_res = {0}; + parse_driver_data(model_res.driver_state_lhd, s, 0); + parse_driver_data(model_res.driver_state_rhd, s, 41); + model_res.poor_vision_prob = sigmoid(s->output[82]); + model_res.wheel_on_right_prob = sigmoid(s->output[83]); + model_res.dsp_execution_time = (t2 - t1) / 1000.; + + return model_res; } -void dmonitoring_publish(PubMaster &pm, uint32_t frame_id, const DMonitoringResult &res, float execution_time, kj::ArrayPtr raw_pred) { +void dmonitoring_publish(PubMaster &pm, uint32_t frame_id, const DMonitoringModelResult &model_res, float execution_time, kj::ArrayPtr raw_pred) { // make msg MessageBuilder msg; - auto framed = msg.initEvent().initDriverState(); + auto framed = msg.initEvent().initDriverStateV2(); framed.setFrameId(frame_id); framed.setModelExecutionTime(execution_time); - framed.setDspExecutionTime(res.dsp_execution_time); - - framed.setFaceOrientation(res.face_orientation); - framed.setFaceOrientationStd(res.face_orientation_meta); - framed.setFacePosition(res.face_position); - framed.setFacePositionStd(res.face_position_meta); - framed.setFaceProb(res.face_prob); - framed.setLeftEyeProb(res.left_eye_prob); - framed.setRightEyeProb(res.right_eye_prob); - framed.setLeftBlinkProb(res.left_blink_prob); - framed.setRightBlinkProb(res.right_blink_prob); - framed.setSunglassesProb(res.sg_prob); - framed.setPoorVision(res.poor_vision); - framed.setPartialFace(res.partial_face); - framed.setDistractedPose(res.distracted_pose); - framed.setDistractedEyes(res.distracted_eyes); - framed.setOccludedProb(res.occluded_prob); + framed.setDspExecutionTime(model_res.dsp_execution_time); + + framed.setPoorVisionProb(model_res.poor_vision_prob); + framed.setWheelOnRightProb(model_res.wheel_on_right_prob); + fill_driver_data(framed.initLeftDriverData(), model_res.driver_state_lhd); + fill_driver_data(framed.initRightDriverData(), model_res.driver_state_rhd); + if (send_raw_pred) { framed.setRawPredictions(raw_pred.asBytes()); } - pm.send("driverState", msg); + pm.send("driverStateV2", msg); } void dmonitoring_free(DMonitoringModelState* s) { diff --git a/selfdrive/modeld/models/dmonitoring.h b/selfdrive/modeld/models/dmonitoring.h index 9b3ee631f0..ae2bf05394 100644 --- a/selfdrive/modeld/models/dmonitoring.h +++ b/selfdrive/modeld/models/dmonitoring.h @@ -3,44 +3,48 @@ #include #include "cereal/messaging/messaging.h" -#include "selfdrive/common/util.h" +#include "common/util.h" #include "selfdrive/modeld/models/commonmodel.h" #include "selfdrive/modeld/runners/run.h" -#define OUTPUT_SIZE 39 +#define CALIB_LEN 3 -typedef struct DMonitoringResult { +#define OUTPUT_SIZE 84 +#define REG_SCALE 0.25f + +typedef struct DriverStateResult { float face_orientation[3]; - float face_orientation_meta[3]; + float face_orientation_std[3]; float face_position[2]; - float face_position_meta[2]; + float face_position_std[2]; float face_prob; float left_eye_prob; float right_eye_prob; float left_blink_prob; float right_blink_prob; - float sg_prob; - float poor_vision; - float partial_face; - float distracted_pose; - float distracted_eyes; + float sunglasses_prob; float occluded_prob; + float ready_prob[4]; + float not_ready_prob[2]; +} DriverStateResult; + +typedef struct DMonitoringModelResult { + DriverStateResult driver_state_lhd; + DriverStateResult driver_state_rhd; + float poor_vision_prob; + float wheel_on_right_prob; float dsp_execution_time; -} DMonitoringResult; +} DMonitoringModelResult; typedef struct DMonitoringModelState { RunModel *m; - bool is_rhd; float output[OUTPUT_SIZE]; - std::vector resized_buf; - std::vector cropped_buf; - std::vector premirror_cropped_buf; - std::vector net_input_buf; - float tensor[UINT8_MAX + 1]; + std::vector net_input_buf; + float calib[CALIB_LEN]; } DMonitoringModelState; void dmonitoring_init(DMonitoringModelState* s); -DMonitoringResult dmonitoring_eval_frame(DMonitoringModelState* s, void* stream_buf, int width, int height); -void dmonitoring_publish(PubMaster &pm, uint32_t frame_id, const DMonitoringResult &res, float execution_time, kj::ArrayPtr raw_pred); +DMonitoringModelResult dmonitoring_eval_frame(DMonitoringModelState* s, void* stream_buf, int width, int height, int stride, int uv_offset, float *calib); +void dmonitoring_publish(PubMaster &pm, uint32_t frame_id, const DMonitoringModelResult &model_res, float execution_time, kj::ArrayPtr raw_pred); void dmonitoring_free(DMonitoringModelState* s); diff --git a/selfdrive/modeld/models/dmonitoring_model.current b/selfdrive/modeld/models/dmonitoring_model.current new file mode 100644 index 0000000000..065bc7d489 --- /dev/null +++ b/selfdrive/modeld/models/dmonitoring_model.current @@ -0,0 +1,2 @@ +d1124586-761e-4e18-a771-6b5ef35124fe +6fec774f513a19e44d4316e46ad38277197d45ea \ No newline at end of file diff --git a/selfdrive/modeld/models/dmonitoring_model.onnx b/selfdrive/modeld/models/dmonitoring_model.onnx new file mode 100644 index 0000000000..f8bf94c061 --- /dev/null +++ b/selfdrive/modeld/models/dmonitoring_model.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:517262fa9f1ad3cc8049ad3722903f40356d87ea423ee5cf011226fb6cfc3d5b +size 16072278 diff --git a/selfdrive/modeld/models/dmonitoring_model_q.dlc b/selfdrive/modeld/models/dmonitoring_model_q.dlc new file mode 100644 index 0000000000..e4e6fb3347 --- /dev/null +++ b/selfdrive/modeld/models/dmonitoring_model_q.dlc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:64b94659226a1e3c6594a13c2e5d029465d5803a5c3005121ec7217acdbbef20 +size 4443461 diff --git a/selfdrive/modeld/models/driving.cc b/selfdrive/modeld/models/driving.cc index e42f2c0f46..9cb216ff19 100644 --- a/selfdrive/modeld/models/driving.cc +++ b/selfdrive/modeld/models/driving.cc @@ -8,9 +8,10 @@ #include -#include "selfdrive/common/clutil.h" -#include "selfdrive/common/params.h" -#include "selfdrive/common/timing.h" +#include "common/clutil.h" +#include "common/params.h" +#include "common/timing.h" +#include "common/swaglog.h" constexpr float FCW_THRESHOLD_5MS2_HIGH = 0.15; constexpr float FCW_THRESHOLD_5MS2_LOW = 0.05; @@ -21,73 +22,85 @@ std::array prev_brake_3ms2_probs = {0,0,0}; // #define DUMP_YUV -template -constexpr const kj::ArrayPtr to_kj_array_ptr(const std::array &arr) { - return kj::ArrayPtr(arr.data(), arr.size()); -} - -void model_init(ModelState* s, cl_device_id device_id, cl_context context, bool use_extra) { +void model_init(ModelState* s, cl_device_id device_id, cl_context context) { s->frame = new ModelFrame(device_id, context); s->wide_frame = new ModelFrame(device_id, context); #ifdef USE_THNEED - s->m = std::make_unique(use_extra ? "../../models/big_supercombo.thneed" : "../../models/supercombo.thneed", - &s->output[0], NET_OUTPUT_SIZE, USE_GPU_RUNTIME, use_extra); + s->m = std::make_unique("models/supercombo.thneed", #elif USE_ONNX_MODEL - s->m = std::make_unique(use_extra ? "../../models/big_supercombo.onnx" : "../../models/supercombo.onnx", - &s->output[0], NET_OUTPUT_SIZE, USE_GPU_RUNTIME, use_extra); + s->m = std::make_unique("models/supercombo.onnx", #else - s->m = std::make_unique(use_extra ? "../../models/big_supercombo.dlc" : "../../models/supercombo.dlc", - &s->output[0], NET_OUTPUT_SIZE, USE_GPU_RUNTIME, use_extra); + s->m = std::make_unique("models/supercombo.dlc", #endif + &s->output[0], NET_OUTPUT_SIZE, USE_GPU_RUNTIME, true, false, context); #ifdef TEMPORAL - s->m->addRecurrent(&s->output[OUTPUT_SIZE], TEMPORAL_SIZE); + s->m->addRecurrent(&s->feature_buffer[0], TEMPORAL_SIZE); #endif #ifdef DESIRE - s->m->addDesire(s->pulse_desire, DESIRE_LEN); + s->m->addDesire(s->pulse_desire, DESIRE_LEN*(HISTORY_BUFFER_LEN+1)); #endif #ifdef TRAFFIC_CONVENTION - const int idx = Params().getBool("IsRHD") ? 1 : 0; - s->traffic_convention[idx] = 1.0; s->m->addTrafficConvention(s->traffic_convention, TRAFFIC_CONVENTION_LEN); #endif } ModelOutput* model_eval_frame(ModelState* s, VisionBuf* buf, VisionBuf* wbuf, - const mat3 &transform, const mat3 &transform_wide, float *desire_in) { + const mat3 &transform, const mat3 &transform_wide, float *desire_in, bool is_rhd, bool prepare_only) { #ifdef DESIRE + std::memmove(&s->pulse_desire[0], &s->pulse_desire[DESIRE_LEN], sizeof(float) * DESIRE_LEN*HISTORY_BUFFER_LEN); if (desire_in != NULL) { for (int i = 1; i < DESIRE_LEN; i++) { // Model decides when action is completed // so desire input is just a pulse triggered on rising edge if (desire_in[i] - s->prev_desire[i] > .99) { - s->pulse_desire[i] = desire_in[i]; + s->pulse_desire[DESIRE_LEN*HISTORY_BUFFER_LEN+i] = desire_in[i]; } else { - s->pulse_desire[i] = 0.0; + s->pulse_desire[DESIRE_LEN*HISTORY_BUFFER_LEN+i] = 0.0; } s->prev_desire[i] = desire_in[i]; } } +LOGT("Desire enqueued"); #endif + int rhd_idx = is_rhd; + s->traffic_convention[rhd_idx] = 1.0; + s->traffic_convention[1-rhd_idx] = 0.0; + // if getInputBuf is not NULL, net_input_buf will be - auto net_input_buf = s->frame->prepare(buf->buf_cl, buf->width, buf->height, transform, static_cast(s->m->getInputBuf())); + auto net_input_buf = s->frame->prepare(buf->buf_cl, buf->width, buf->height, buf->stride, buf->uv_offset, transform, static_cast(s->m->getInputBuf())); s->m->addImage(net_input_buf, s->frame->buf_size); + LOGT("Image added"); if (wbuf != nullptr) { - auto net_extra_buf = s->wide_frame->prepare(wbuf->buf_cl, wbuf->width, wbuf->height, transform_wide, static_cast(s->m->getExtraBuf())); + auto net_extra_buf = s->wide_frame->prepare(wbuf->buf_cl, wbuf->width, wbuf->height, wbuf->stride, wbuf->uv_offset, transform_wide, static_cast(s->m->getExtraBuf())); s->m->addExtra(net_extra_buf, s->wide_frame->buf_size); + LOGT("Extra image added"); + } + + if (prepare_only) { + return nullptr; } + s->m->execute(); + LOGT("Execution finished"); + + #ifdef TEMPORAL + std::memmove(&s->feature_buffer[0], &s->feature_buffer[FEATURE_LEN], sizeof(float) * FEATURE_LEN*(HISTORY_BUFFER_LEN-1)); + std::memcpy(&s->feature_buffer[FEATURE_LEN*(HISTORY_BUFFER_LEN-1)], &s->output[OUTPUT_SIZE], sizeof(float) * FEATURE_LEN); + LOGT("Features enqueued"); + #endif return (ModelOutput*)&s->output; } void model_free(ModelState* s) { delete s->frame; + delete s->wide_frame; } void fill_lead(cereal::ModelDataV2::LeadDataV3::Builder lead, const ModelOutputLeads &leads, int t_idx, float prob_t) { @@ -193,6 +206,7 @@ void fill_plan(cereal::ModelDataV2::Builder &framed, const ModelOutputPlanPredic std::array pos_x_std, pos_y_std, pos_z_std; std::array vel_x, vel_y, vel_z; std::array rot_x, rot_y, rot_z; + std::array acc_x, acc_y, acc_z; std::array rot_rate_x, rot_rate_y, rot_rate_z; for(int i=0; i raw_pred, const bool valid) { const uint32_t frame_age = (frame_id > vipc_frame_id) ? (frame_id - vipc_frame_id) : 0; MessageBuilder msg; auto framed = msg.initEvent(valid).initModelV2(); framed.setFrameId(vipc_frame_id); + framed.setFrameIdExtra(vipc_frame_id_extra); framed.setFrameAge(frame_age); framed.setFrameDropPerc(frame_drop * 100); framed.setTimestampEof(timestamp_eof); @@ -339,14 +369,19 @@ void posenet_publish(PubMaster &pm, uint32_t vipc_frame_id, uint32_t vipc_droppe MessageBuilder msg; const auto &v_mean = net_outputs.pose.velocity_mean; const auto &r_mean = net_outputs.pose.rotation_mean; + const auto &t_mean = net_outputs.wide_from_device_euler.mean; const auto &v_std = net_outputs.pose.velocity_std; const auto &r_std = net_outputs.pose.rotation_std; + const auto &t_std = net_outputs.wide_from_device_euler.std; auto posenetd = msg.initEvent(valid && (vipc_dropped_frames < 1)).initCameraOdometry(); posenetd.setTrans({v_mean.x, v_mean.y, v_mean.z}); posenetd.setRot({r_mean.x, r_mean.y, r_mean.z}); + posenetd.setWideFromDeviceEuler({t_mean.x, t_mean.y, t_mean.z}); posenetd.setTransStd({exp(v_std.x), exp(v_std.y), exp(v_std.z)}); posenetd.setRotStd({exp(r_std.x), exp(r_std.y), exp(r_std.z)}); + posenetd.setWideFromDeviceEulerStd({exp(t_std.x), exp(t_std.y), exp(t_std.z)}); + posenetd.setTimestampEof(timestamp_eof); posenetd.setFrameId(vipc_frame_id); diff --git a/selfdrive/modeld/models/driving.h b/selfdrive/modeld/models/driving.h index eead06575f..b23691a56a 100644 --- a/selfdrive/modeld/models/driving.h +++ b/selfdrive/modeld/models/driving.h @@ -10,12 +10,14 @@ #include "cereal/messaging/messaging.h" #include "cereal/visionipc/visionipc_client.h" -#include "selfdrive/common/mat.h" -#include "selfdrive/common/modeldata.h" -#include "selfdrive/common/util.h" +#include "common/mat.h" +#include "common/modeldata.h" +#include "common/util.h" #include "selfdrive/modeld/models/commonmodel.h" #include "selfdrive/modeld/runners/run.h" +constexpr int FEATURE_LEN = 128; +constexpr int HISTORY_BUFFER_LEN = 99; constexpr int DESIRE_LEN = 8; constexpr int DESIRE_PRED_LEN = 4; constexpr int TRAFFIC_CONVENTION_LEN = 2; @@ -26,12 +28,13 @@ constexpr int BLINKER_LEN = 6; constexpr int META_STRIDE = 7; constexpr int PLAN_MHP_N = 5; -constexpr int STOP_LINE_MHP_N = 3; constexpr int LEAD_MHP_N = 2; constexpr int LEAD_TRAJ_LEN = 6; constexpr int LEAD_PRED_DIM = 4; constexpr int LEAD_MHP_SELECTION = 3; +// Padding to get output shape as multiple of 4 +constexpr int PAD_SIZE = 2; struct ModelOutputXYZ { float x; @@ -149,44 +152,28 @@ struct ModelOutputLeads { }; static_assert(sizeof(ModelOutputLeads) == (sizeof(ModelOutputLeadPrediction)*LEAD_MHP_N) + (sizeof(float)*LEAD_MHP_SELECTION)); -struct ModelOutputStopLineElement { - ModelOutputXYZ position; - ModelOutputXYZ rotation; - float speed; - float time; -}; -static_assert(sizeof(ModelOutputStopLineElement) == (sizeof(ModelOutputXYZ)*2 + sizeof(float)*2)); -struct ModelOutputStopLinePrediction { - ModelOutputStopLineElement mean; - ModelOutputStopLineElement std; - float prob; +struct ModelOutputPose { + ModelOutputXYZ velocity_mean; + ModelOutputXYZ rotation_mean; + ModelOutputXYZ velocity_std; + ModelOutputXYZ rotation_std; }; -static_assert(sizeof(ModelOutputStopLinePrediction) == (sizeof(ModelOutputStopLineElement)*2 + sizeof(float))); - -struct ModelOutputStopLines { - std::array prediction; - float prob; +static_assert(sizeof(ModelOutputPose) == sizeof(ModelOutputXYZ)*4); - constexpr const ModelOutputStopLinePrediction &get_best_prediction(int t_idx) const { - int max_idx = 0; - for (int i = 1; i < prediction.size(); i++) { - if (prediction[i].prob > prediction[max_idx].prob) { - max_idx = i; - } - } - return prediction[max_idx]; - } +struct ModelOutputWideFromDeviceEuler { + ModelOutputXYZ mean; + ModelOutputXYZ std; }; -static_assert(sizeof(ModelOutputStopLines) == (sizeof(ModelOutputStopLinePrediction)*STOP_LINE_MHP_N) + sizeof(float)); +static_assert(sizeof(ModelOutputWideFromDeviceEuler) == sizeof(ModelOutputXYZ)*2); -struct ModelOutputPose { +struct ModelOutputTemporalPose { ModelOutputXYZ velocity_mean; ModelOutputXYZ rotation_mean; ModelOutputXYZ velocity_std; ModelOutputXYZ rotation_std; }; -static_assert(sizeof(ModelOutputPose) == sizeof(ModelOutputXYZ)*4); +static_assert(sizeof(ModelOutputTemporalPose) == sizeof(ModelOutputXYZ)*4); struct ModelOutputDisengageProb { float gas_disengage; @@ -233,44 +220,52 @@ struct ModelOutputMeta { }; static_assert(sizeof(ModelOutputMeta) == sizeof(ModelOutputDesireProb) + sizeof(float) + (sizeof(ModelOutputDisengageProb)*DISENGAGE_LEN) + (sizeof(ModelOutputBlinkerProb)*BLINKER_LEN) + (sizeof(ModelOutputDesireProb)*DESIRE_PRED_LEN)); +struct ModelOutputFeatures { + std::array feature; +}; +static_assert(sizeof(ModelOutputFeatures) == (sizeof(float)*FEATURE_LEN)); + struct ModelOutput { const ModelOutputPlans plans; const ModelOutputLaneLines lane_lines; const ModelOutputRoadEdges road_edges; const ModelOutputLeads leads; - const ModelOutputStopLines stop_lines; const ModelOutputMeta meta; const ModelOutputPose pose; + const ModelOutputWideFromDeviceEuler wide_from_device_euler; + const ModelOutputTemporalPose temporal_pose; }; constexpr int OUTPUT_SIZE = sizeof(ModelOutput) / sizeof(float); + #ifdef TEMPORAL - constexpr int TEMPORAL_SIZE = 512; + constexpr int TEMPORAL_SIZE = HISTORY_BUFFER_LEN * FEATURE_LEN; #else constexpr int TEMPORAL_SIZE = 0; #endif -constexpr int NET_OUTPUT_SIZE = OUTPUT_SIZE + TEMPORAL_SIZE; +constexpr int NET_OUTPUT_SIZE = OUTPUT_SIZE + FEATURE_LEN + PAD_SIZE; // TODO: convert remaining arrays to std::array and update model runners struct ModelState { - ModelFrame *frame; - ModelFrame *wide_frame; + ModelFrame *frame = nullptr; + ModelFrame *wide_frame = nullptr; + std::array feature_buffer = {}; std::array output = {}; std::unique_ptr m; #ifdef DESIRE float prev_desire[DESIRE_LEN] = {}; - float pulse_desire[DESIRE_LEN] = {}; + float pulse_desire[DESIRE_LEN*(HISTORY_BUFFER_LEN+1)] = {}; #endif #ifdef TRAFFIC_CONVENTION float traffic_convention[TRAFFIC_CONVENTION_LEN] = {}; #endif }; -void model_init(ModelState* s, cl_device_id device_id, cl_context context, bool use_extra); +void model_init(ModelState* s, cl_device_id device_id, cl_context context); ModelOutput *model_eval_frame(ModelState* s, VisionBuf* buf, VisionBuf* buf_wide, - const mat3 &transform, const mat3 &transform_wide, float *desire_in); + const mat3 &transform, const mat3 &transform_wide, float *desire_in, bool is_rhd, bool prepare_only); void model_free(ModelState* s); -void model_publish(PubMaster &pm, uint32_t vipc_frame_id, uint32_t frame_id, float frame_drop, +void model_publish(PubMaster &pm, uint32_t vipc_frame_id, uint32_t vipc_frame_id_extra, uint32_t frame_id, float frame_drop, const ModelOutput &net_outputs, uint64_t timestamp_eof, float model_execution_time, kj::ArrayPtr raw_pred, const bool valid); void posenet_publish(PubMaster &pm, uint32_t vipc_frame_id, uint32_t vipc_dropped_frames, diff --git a/selfdrive/modeld/models/nav.cc b/selfdrive/modeld/models/nav.cc new file mode 100644 index 0000000000..dae87c7ce5 --- /dev/null +++ b/selfdrive/modeld/models/nav.cc @@ -0,0 +1,66 @@ +#include "selfdrive/modeld/models/nav.h" + +#include +#include + +#include "common/mat.h" +#include "common/modeldata.h" +#include "common/timing.h" + + +void navmodel_init(NavModelState* s) { +#ifdef USE_ONNX_MODEL + s->m = new ONNXModel("models/navmodel.onnx", &s->output[0], NAV_NET_OUTPUT_SIZE, USE_DSP_RUNTIME, false, true); +#else + s->m = new SNPEModel("models/navmodel_q.dlc", &s->output[0], NAV_NET_OUTPUT_SIZE, USE_DSP_RUNTIME, false, true); +#endif +} + +NavModelResult* navmodel_eval_frame(NavModelState* s, VisionBuf* buf) { + memcpy(s->net_input_buf, buf->addr, NAV_INPUT_SIZE); + + double t1 = millis_since_boot(); + s->m->addImage((float*)s->net_input_buf, NAV_INPUT_SIZE/sizeof(float)); + s->m->execute(); + double t2 = millis_since_boot(); + + NavModelResult *model_res = (NavModelResult*)&s->output; + model_res->dsp_execution_time = (t2 - t1) / 1000.; + return model_res; +} + +void fill_plan(cereal::NavModelData::Builder &framed, const NavModelOutputPlan &plan) { + std::array pos_x, pos_y; + std::array pos_x_std, pos_y_std; + + for (int i=0; im; +} diff --git a/selfdrive/modeld/models/nav.h b/selfdrive/modeld/models/nav.h new file mode 100644 index 0000000000..b469f75987 --- /dev/null +++ b/selfdrive/modeld/models/nav.h @@ -0,0 +1,73 @@ +#pragma once + +#include "cereal/messaging/messaging.h" +#include "cereal/visionipc/visionipc_client.h" +#include "common/util.h" +#include "common/modeldata.h" +#include "selfdrive/modeld/models/commonmodel.h" +#include "selfdrive/modeld/runners/run.h" + +constexpr int NAV_INPUT_SIZE = 256*256; +constexpr int NAV_FEATURE_LEN = 64; +constexpr int NAV_DESIRE_LEN = 32; +constexpr int NAV_PLAN_MHP_N = 5; + +struct NavModelOutputXY { + float x; + float y; +}; +static_assert(sizeof(NavModelOutputXY) == sizeof(float)*2); + +struct NavModelOutputPlan { + std::array mean; + std::array std; + float prob; +}; +static_assert(sizeof(NavModelOutputPlan) == sizeof(NavModelOutputXY)*TRAJECTORY_SIZE*2 + sizeof(float)); + +struct NavModelOutputPlans { + std::array predictions; + + constexpr const NavModelOutputPlan &get_best_prediction() const { + int max_idx = 0; + for (int i = 1; i < predictions.size(); i++) { + if (predictions[i].prob > predictions[max_idx].prob) { + max_idx = i; + } + } + return predictions[max_idx]; + } +}; +static_assert(sizeof(NavModelOutputPlans) == sizeof(NavModelOutputPlan)*NAV_PLAN_MHP_N); + +struct NavModelOutputDesirePrediction { + std::array values; +}; +static_assert(sizeof(NavModelOutputDesirePrediction) == sizeof(float)*NAV_DESIRE_LEN); + +struct NavModelOutputFeatures { + std::array values; +}; +static_assert(sizeof(NavModelOutputFeatures) == sizeof(float)*NAV_FEATURE_LEN); + +struct NavModelResult { + const NavModelOutputPlans plans; + const NavModelOutputDesirePrediction desire_pred; + const NavModelOutputFeatures features; + float dsp_execution_time; +}; +static_assert(sizeof(NavModelResult) == sizeof(NavModelOutputPlans) + sizeof(NavModelOutputDesirePrediction) + sizeof(NavModelOutputFeatures) + sizeof(float)); + +constexpr int NAV_OUTPUT_SIZE = sizeof(NavModelResult) / sizeof(float); +constexpr int NAV_NET_OUTPUT_SIZE = NAV_OUTPUT_SIZE - 1; + +struct NavModelState { + RunModel *m; + uint8_t net_input_buf[NAV_INPUT_SIZE]; + float output[NAV_OUTPUT_SIZE]; +}; + +void navmodel_init(NavModelState* s); +NavModelResult* navmodel_eval_frame(NavModelState* s, VisionBuf* buf); +void navmodel_publish(PubMaster &pm, uint32_t frame_id, const NavModelResult &model_res, float execution_time); +void navmodel_free(NavModelState* s); diff --git a/selfdrive/modeld/models/navmodel.onnx b/selfdrive/modeld/models/navmodel.onnx new file mode 100644 index 0000000000..60dd8c0e7f --- /dev/null +++ b/selfdrive/modeld/models/navmodel.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eab4b986e14d7d842d6d5487011c329d356fb56995b2ae7dc7188aefe6df9d97 +size 12285002 diff --git a/selfdrive/modeld/models/navmodel_q.dlc b/selfdrive/modeld/models/navmodel_q.dlc new file mode 100644 index 0000000000..7d9b36ed4d --- /dev/null +++ b/selfdrive/modeld/models/navmodel_q.dlc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:83d53efc40053b02fe7d3da4ef6213a4a5a1ae4d1bd49c121b9beb6a54ea1148 +size 3154868 diff --git a/selfdrive/modeld/models/supercombo.onnx b/selfdrive/modeld/models/supercombo.onnx new file mode 100644 index 0000000000..8805b3dce8 --- /dev/null +++ b/selfdrive/modeld/models/supercombo.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:db746e3753de84367595fedd089c2bd41b06bd401ea28e085663533d0e63d74b +size 45962473 diff --git a/selfdrive/modeld/navmodeld b/selfdrive/modeld/navmodeld new file mode 100755 index 0000000000..079afd9677 --- /dev/null +++ b/selfdrive/modeld/navmodeld @@ -0,0 +1,12 @@ +#!/bin/sh + +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" +cd $DIR + +if [ -f /TICI ]; then + export LD_LIBRARY_PATH="/usr/lib/aarch64-linux-gnu:/data/pythonpath/third_party/snpe/larch64:$LD_LIBRARY_PATH" + export ADSP_LIBRARY_PATH="/data/pythonpath/third_party/snpe/dsp/" +else + export LD_LIBRARY_PATH="$DIR/../../third_party/snpe/x86_64-linux-clang:$DIR/../../openpilot/third_party/snpe/x86_64:$LD_LIBRARY_PATH" +fi +exec ./_navmodeld diff --git a/selfdrive/modeld/navmodeld.cc b/selfdrive/modeld/navmodeld.cc new file mode 100644 index 0000000000..75f2c62ab3 --- /dev/null +++ b/selfdrive/modeld/navmodeld.cc @@ -0,0 +1,59 @@ +#include +#include + +#include +#include + +#include "cereal/visionipc/visionipc_client.h" +#include "common/swaglog.h" +#include "common/util.h" +#include "selfdrive/modeld/models/nav.h" + +ExitHandler do_exit; + +void run_model(NavModelState &model, VisionIpcClient &vipc_client) { + PubMaster pm({"navModel"}); + + double last_ts = 0; + uint32_t last_frame_id = 0; + VisionIpcBufExtra extra = {}; + + while (!do_exit) { + VisionBuf *buf = vipc_client.recv(&extra); + if (buf == nullptr) continue; + + double t1 = millis_since_boot(); + NavModelResult *model_res = navmodel_eval_frame(&model, buf); + double t2 = millis_since_boot(); + + // send navmodel packet + navmodel_publish(pm, extra.frame_id, *model_res, (t2 - t1) / 1000.0); + + //printf("navmodel process: %.2fms, from last %.2fms\n", t2 - t1, t1 - last_ts); + last_ts = t1; + last_frame_id = extra.frame_id; + } +} + +int main(int argc, char **argv) { + setpriority(PRIO_PROCESS, 0, -15); + + // init the models + NavModelState model; + navmodel_init(&model); + LOGW("models loaded, navmodeld starting"); + + VisionIpcClient vipc_client = VisionIpcClient("navd", VISION_STREAM_MAP, true); + while (!do_exit && !vipc_client.connect(false)) { + util::sleep_for(100); + } + + // run the models + if (vipc_client.connected) { + LOGW("connected with buffer size: %d", vipc_client.buffers[0].len); + run_model(model, vipc_client); + } + + navmodel_free(&model); + return 0; +} diff --git a/selfdrive/modeld/runners/onnx_runner.py b/selfdrive/modeld/runners/onnx_runner.py index 3b19550e8f..d4a11a7c0b 100755 --- a/selfdrive/modeld/runners/onnx_runner.py +++ b/selfdrive/modeld/runners/onnx_runner.py @@ -9,36 +9,49 @@ os.environ["OMP_WAIT_POLICY"] = "PASSIVE" import onnxruntime as ort # pylint: disable=import-error -def read(sz): +ORT_TYPES_TO_NP_TYPES = {'tensor(float16)': np.float16, 'tensor(float)': np.float32, 'tensor(uint8)': np.uint8} + +def read(sz, tf8=False): dd = [] gt = 0 - while gt < sz * 4: - st = os.read(0, sz * 4 - gt) + szof = 1 if tf8 else 4 + while gt < sz * szof: + st = os.read(0, sz * szof - gt) assert(len(st) > 0) dd.append(st) gt += len(st) - return np.frombuffer(b''.join(dd), dtype=np.float32) + r = np.frombuffer(b''.join(dd), dtype=np.uint8 if tf8 else np.float32) + if tf8: + r = r / 255. + return r def write(d): os.write(1, d.tobytes()) -def run_loop(m): +def run_loop(m, tf8_input=False): ishapes = [[1]+ii.shape[1:] for ii in m.get_inputs()] keys = [x.name for x in m.get_inputs()] + itypes = [ORT_TYPES_TO_NP_TYPES[x.type] for x in m.get_inputs()] + + # run once to initialize CUDA provider + if "CUDAExecutionProvider" in m.get_providers(): + m.run(None, dict(zip(keys, [np.zeros(shp, dtype=itp) for shp, itp in zip(ishapes, itypes)]))) + print("ready to run onnx model", keys, ishapes, file=sys.stderr) while 1: inputs = [] - for shp in ishapes: + for k, shp, itp in zip(keys, ishapes, itypes): ts = np.product(shp) #print("reshaping %s with offset %d" % (str(shp), offset), file=sys.stderr) - inputs.append(read(ts).reshape(shp)) + inputs.append(read(ts, (k=='input_img' and tf8_input)).reshape(shp).astype(itp)) ret = m.run(None, dict(zip(keys, inputs))) #print(ret, file=sys.stderr) for r in ret: - write(r) + write(r.astype(np.float32)) if __name__ == "__main__": + print(sys.argv, file=sys.stderr) print("Onnx available providers: ", ort.get_available_providers(), file=sys.stderr) options = ort.SessionOptions() options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_DISABLE_ALL @@ -54,7 +67,10 @@ if __name__ == "__main__": options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL provider = 'CPUExecutionProvider' - print("Onnx selected provider: ", [provider], file=sys.stderr) - ort_session = ort.InferenceSession(sys.argv[1], options, providers=[provider]) - print("Onnx using ", ort_session.get_providers(), file=sys.stderr) - run_loop(ort_session) + try: + print("Onnx selected provider: ", [provider], file=sys.stderr) + ort_session = ort.InferenceSession(sys.argv[1], options, providers=[provider]) + print("Onnx using ", ort_session.get_providers(), file=sys.stderr) + run_loop(ort_session, tf8_input=("--use_tf8" in sys.argv)) + except KeyboardInterrupt: + pass diff --git a/selfdrive/modeld/runners/onnxmodel.cc b/selfdrive/modeld/runners/onnxmodel.cc index b2de9e9a1b..447d90fd7e 100644 --- a/selfdrive/modeld/runners/onnxmodel.cc +++ b/selfdrive/modeld/runners/onnxmodel.cc @@ -11,15 +11,16 @@ #include #include -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/util.h" +#include "common/swaglog.h" +#include "common/util.h" -ONNXModel::ONNXModel(const char *path, float *_output, size_t _output_size, int runtime, bool _use_extra) { +ONNXModel::ONNXModel(const char *path, float *_output, size_t _output_size, int runtime, bool _use_extra, bool _use_tf8, cl_context context) { LOGD("loading model %s", path); output = _output; output_size = _output_size; use_extra = _use_extra; + use_tf8 = _use_tf8; int err = pipe(pipein); assert(err == 0); @@ -28,11 +29,12 @@ ONNXModel::ONNXModel(const char *path, float *_output, size_t _output_size, int std::string exe_dir = util::dir_name(util::readlink("/proc/self/exe")); std::string onnx_runner = exe_dir + "/runners/onnx_runner.py"; + std::string tf8_arg = use_tf8 ? "--use_tf8" : ""; proc_pid = fork(); if (proc_pid == 0) { LOGD("spawning onnx process %s", onnx_runner.c_str()); - char *argv[] = {(char*)onnx_runner.c_str(), (char*)path, nullptr}; + char *argv[] = {(char*)onnx_runner.c_str(), (char*)path, (char*)tf8_arg.c_str(), nullptr}; dup2(pipein[0], 0); dup2(pipeout[1], 1); close(pipein[0]); @@ -100,6 +102,11 @@ void ONNXModel::addTrafficConvention(float *state, int state_size) { traffic_convention_size = state_size; } +void ONNXModel::addCalib(float *state, int state_size) { + calib_input_buf = state; + calib_size = state_size; +} + void ONNXModel::addImage(float *image_buf, int buf_size) { image_input_buf = image_buf; image_buf_size = buf_size; @@ -124,6 +131,9 @@ void ONNXModel::execute() { if (traffic_convention_input_buf != NULL) { pwrite(traffic_convention_input_buf, traffic_convention_size); } + if (calib_input_buf != NULL) { + pwrite(calib_input_buf, calib_size); + } if (rnn_input_buf != NULL) { pwrite(rnn_input_buf, rnn_state_size); } diff --git a/selfdrive/modeld/runners/onnxmodel.h b/selfdrive/modeld/runners/onnxmodel.h index a3a6a1862a..d5b7bfecf0 100644 --- a/selfdrive/modeld/runners/onnxmodel.h +++ b/selfdrive/modeld/runners/onnxmodel.h @@ -6,11 +6,12 @@ class ONNXModel : public RunModel { public: - ONNXModel(const char *path, float *output, size_t output_size, int runtime, bool use_extra = false); + ONNXModel(const char *path, float *output, size_t output_size, int runtime, bool use_extra = false, bool _use_tf8 = false, cl_context context = NULL); ~ONNXModel(); void addRecurrent(float *state, int state_size); void addDesire(float *state, int state_size); void addTrafficConvention(float *state, int state_size); + void addCalib(float *state, int state_size); void addImage(float *image_buf, int buf_size); void addExtra(float *image_buf, int buf_size); void execute(); @@ -26,8 +27,11 @@ private: int desire_state_size; float *traffic_convention_input_buf = NULL; int traffic_convention_size; + float *calib_input_buf = NULL; + int calib_size; float *image_input_buf = NULL; int image_buf_size; + bool use_tf8; float *extra_input_buf = NULL; int extra_buf_size; bool use_extra; diff --git a/selfdrive/modeld/runners/runmodel.h b/selfdrive/modeld/runners/runmodel.h index 2d61351ebf..c607811401 100644 --- a/selfdrive/modeld/runners/runmodel.h +++ b/selfdrive/modeld/runners/runmodel.h @@ -1,10 +1,12 @@ #pragma once +#include "common/clutil.h" class RunModel { public: virtual ~RunModel() {} virtual void addRecurrent(float *state, int state_size) {} virtual void addDesire(float *state, int state_size) {} virtual void addTrafficConvention(float *state, int state_size) {} + virtual void addCalib(float *state, int state_size) {} virtual void addImage(float *image_buf, int buf_size) {} virtual void addExtra(float *image_buf, int buf_size) {} virtual void execute() {} diff --git a/selfdrive/modeld/runners/snpemodel.cc b/selfdrive/modeld/runners/snpemodel.cc index df66a9db93..ff4adcd8d3 100644 --- a/selfdrive/modeld/runners/snpemodel.cc +++ b/selfdrive/modeld/runners/snpemodel.cc @@ -6,19 +6,20 @@ #include #include -#include "selfdrive/common/util.h" -#include "selfdrive/common/timing.h" +#include "common/util.h" +#include "common/timing.h" void PrintErrorStringAndExit() { std::cerr << zdl::DlSystem::getLastErrorString() << std::endl; std::exit(EXIT_FAILURE); } -SNPEModel::SNPEModel(const char *path, float *loutput, size_t loutput_size, int runtime, bool luse_extra) { +SNPEModel::SNPEModel(const char *path, float *loutput, size_t loutput_size, int runtime, bool luse_extra, bool luse_tf8, cl_context context) { output = loutput; output_size = loutput_size; use_extra = luse_extra; -#if defined(QCOM) || defined(QCOM2) + use_tf8 = luse_tf8; +#ifdef QCOM2 if (runtime==USE_GPU_RUNTIME) { Runtime = zdl::DlSystem::Runtime_t::GPU; } else if (runtime==USE_DSP_RUNTIME) { @@ -39,7 +40,7 @@ SNPEModel::SNPEModel(const char *path, float *loutput, size_t loutput_size, int // create model runner zdl::SNPE::SNPEBuilder snpeBuilder(container.get()); while (!snpe) { -#if defined(QCOM) || defined(QCOM2) +#ifdef QCOM2 snpe = snpeBuilder.setOutputLayers({}) .setRuntimeProcessor(Runtime) .setUseUserSuppliedBuffers(true) @@ -70,14 +71,16 @@ SNPEModel::SNPEModel(const char *path, float *loutput, size_t loutput_size, int printf("model: %s -> %s\n", input_tensor_name, output_tensor_name); zdl::DlSystem::UserBufferEncodingFloat userBufferEncodingFloat; + zdl::DlSystem::UserBufferEncodingTf8 userBufferEncodingTf8(0, 1./255); // network takes 0-1 zdl::DlSystem::IUserBufferFactory& ubFactory = zdl::SNPE::SNPEFactory::getUserBufferFactory(); + size_t size_of_input = use_tf8 ? sizeof(uint8_t) : sizeof(float); // create input buffer { const auto &inputDims_opt = snpe->getInputDimensions(input_tensor_name); const zdl::DlSystem::TensorShape& bufferShape = *inputDims_opt; std::vector strides(bufferShape.rank()); - strides[strides.size() - 1] = sizeof(float); + strides[strides.size() - 1] = size_of_input; size_t product = 1; for (size_t i = 0; i < bufferShape.rank(); i++) product *= bufferShape[i]; size_t stride = strides[strides.size() - 1]; @@ -86,7 +89,10 @@ SNPEModel::SNPEModel(const char *path, float *loutput, size_t loutput_size, int strides[i-1] = stride; } printf("input product is %lu\n", product); - inputBuffer = ubFactory.createUserBuffer(NULL, product*sizeof(float), strides, &userBufferEncodingFloat); + inputBuffer = ubFactory.createUserBuffer(NULL, + product*size_of_input, + strides, + use_tf8 ? (zdl::DlSystem::UserBufferEncoding*)&userBufferEncodingTf8 : (zdl::DlSystem::UserBufferEncoding*)&userBufferEncodingFloat); inputMap.add(input_tensor_name, inputBuffer.get()); } @@ -123,6 +129,12 @@ SNPEModel::SNPEModel(const char *path, float *loutput, size_t loutput_size, int outputBuffer = ubFactory.createUserBuffer(output, output_size * sizeof(float), outputStrides, &userBufferEncodingFloat); outputMap.add(output_tensor_name, outputBuffer.get()); } + +#ifdef USE_THNEED + if (Runtime == zdl::DlSystem::Runtime_t::GPU) { + thneed.reset(new Thneed()); + } +#endif } void SNPEModel::addRecurrent(float *state, int state_size) { @@ -141,6 +153,11 @@ void SNPEModel::addDesire(float *state, int state_size) { desireBuffer = this->addExtra(state, state_size, 1); } +void SNPEModel::addCalib(float *state, int state_size) { + calib = state; + calibBuffer = this->addExtra(state, state_size, 1); +} + void SNPEModel::addImage(float *image_buf, int buf_size) { input = image_buf; input_size = buf_size; @@ -169,74 +186,14 @@ std::unique_ptr SNPEModel::addExtra(float *state, in } void SNPEModel::execute() { -#ifdef USE_THNEED - if (Runtime == zdl::DlSystem::Runtime_t::GPU) { - if (thneed == NULL) { - bool ret = inputBuffer->setBufferAddress(input); - assert(ret == true); - if (use_extra) { - assert(extra != NULL); - bool extra_ret = extraBuffer->setBufferAddress(extra); - assert(extra_ret == true); - } - if (!snpe->execute(inputMap, outputMap)) { - PrintErrorStringAndExit(); - } - memset(recurrent, 0, recurrent_size*sizeof(float)); - thneed = new Thneed(); - if (!snpe->execute(inputMap, outputMap)) { - PrintErrorStringAndExit(); - } - thneed->stop(); - printf("thneed cached\n"); - - // doing self test - float *outputs_golden = (float *)malloc(output_size*sizeof(float)); - memcpy(outputs_golden, output, output_size*sizeof(float)); - memset(output, 0, output_size*sizeof(float)); - memset(recurrent, 0, recurrent_size*sizeof(float)); - uint64_t start_time = nanos_since_boot(); - if (extra != NULL) { - float *inputs[5] = {recurrent, trafficConvention, desire, extra, input}; - thneed->execute(inputs, output); - } else { - float *inputs[4] = {recurrent, trafficConvention, desire, input}; - thneed->execute(inputs, output); - } - uint64_t elapsed_time = nanos_since_boot() - start_time; - printf("ran model in %.2f ms\n", float(elapsed_time)/1e6); - - if (memcmp(output, outputs_golden, output_size*sizeof(float)) == 0) { - printf("thneed selftest passed\n"); - } else { - for (int i = 0; i < output_size; i++) { - printf("mismatch %3d: %f %f\n", i, output[i], outputs_golden[i]); - } - assert(false); - } - free(outputs_golden); - } else { - if (use_extra) { - float *inputs[5] = {recurrent, trafficConvention, desire, extra, input}; - thneed->execute(inputs, output); - } else { - float *inputs[4] = {recurrent, trafficConvention, desire, input}; - thneed->execute(inputs, output); - } - } - } else { -#endif - bool ret = inputBuffer->setBufferAddress(input); - assert(ret == true); - if (use_extra) { - bool extra_ret = extraBuffer->setBufferAddress(extra); - assert(extra_ret == true); - } - if (!snpe->execute(inputMap, outputMap)) { - PrintErrorStringAndExit(); - } -#ifdef USE_THNEED + bool ret = inputBuffer->setBufferAddress(input); + assert(ret == true); + if (use_extra) { + bool extra_ret = extraBuffer->setBufferAddress(extra); + assert(extra_ret == true); + } + if (!snpe->execute(inputMap, outputMap)) { + PrintErrorStringAndExit(); } -#endif } diff --git a/selfdrive/modeld/runners/snpemodel.h b/selfdrive/modeld/runners/snpemodel.h index 0c927a2f42..08ae16c2b1 100644 --- a/selfdrive/modeld/runners/snpemodel.h +++ b/selfdrive/modeld/runners/snpemodel.h @@ -1,4 +1,5 @@ #pragma once +#pragma clang diagnostic ignored "-Wdeprecated-declarations" #include #include @@ -22,22 +23,24 @@ class SNPEModel : public RunModel { public: - SNPEModel(const char *path, float *loutput, size_t loutput_size, int runtime, bool luse_extra = false); + SNPEModel(const char *path, float *loutput, size_t loutput_size, int runtime, bool luse_extra = false, bool use_tf8 = false, cl_context context = NULL); void addRecurrent(float *state, int state_size); void addTrafficConvention(float *state, int state_size); + void addCalib(float *state, int state_size); void addDesire(float *state, int state_size); void addImage(float *image_buf, int buf_size); void addExtra(float *image_buf, int buf_size); void execute(); #ifdef USE_THNEED - Thneed *thneed = NULL; + std::unique_ptr thneed; + bool thneed_recorded = false; #endif private: std::string model_data; -#if defined(QCOM) || defined(QCOM2) +#ifdef QCOM2 zdl::DlSystem::Runtime_t Runtime; #endif @@ -49,6 +52,7 @@ private: std::unique_ptr inputBuffer; float *input; size_t input_size; + bool use_tf8; // snpe output stuff zdl::DlSystem::UserBufferMap outputMap; @@ -71,4 +75,6 @@ private: std::unique_ptr trafficConventionBuffer; float *desire; std::unique_ptr desireBuffer; + float *calib; + std::unique_ptr calibBuffer; }; diff --git a/selfdrive/modeld/runners/thneedmodel.cc b/selfdrive/modeld/runners/thneedmodel.cc index a85b2ac022..67db01bb95 100644 --- a/selfdrive/modeld/runners/thneedmodel.cc +++ b/selfdrive/modeld/runners/thneedmodel.cc @@ -2,12 +2,10 @@ #include -ThneedModel::ThneedModel(const char *path, float *loutput, size_t loutput_size, int runtime, bool luse_extra) { - thneed = new Thneed(true); - thneed->record = 0; +ThneedModel::ThneedModel(const char *path, float *loutput, size_t loutput_size, int runtime, bool luse_extra, bool luse_tf8, cl_context context) { + thneed = new Thneed(true, context); thneed->load(path); thneed->clexec(); - thneed->find_inputs_outputs(); recorded = false; output = loutput; @@ -47,7 +45,7 @@ void* ThneedModel::getExtraBuf() { void ThneedModel::execute() { if (!recorded) { - thneed->record = THNEED_RECORD; + thneed->record = true; if (use_extra) { float *inputs[5] = {recurrent, trafficConvention, desire, extra, input}; thneed->copy_inputs(inputs); diff --git a/selfdrive/modeld/runners/thneedmodel.h b/selfdrive/modeld/runners/thneedmodel.h index fe0f9ae44f..f3f34dc7f4 100644 --- a/selfdrive/modeld/runners/thneedmodel.h +++ b/selfdrive/modeld/runners/thneedmodel.h @@ -5,7 +5,7 @@ class ThneedModel : public RunModel { public: - ThneedModel(const char *path, float *loutput, size_t loutput_size, int runtime, bool luse_extra = false); + ThneedModel(const char *path, float *loutput, size_t loutput_size, int runtime, bool luse_extra = false, bool use_tf8 = false, cl_context context = NULL); void addRecurrent(float *state, int state_size); void addTrafficConvention(float *state, int state_size); void addDesire(float *state, int state_size); diff --git a/selfdrive/camerad/snapshot/__init__.py b/selfdrive/modeld/tests/__init__.py similarity index 100% rename from selfdrive/camerad/snapshot/__init__.py rename to selfdrive/modeld/tests/__init__.py diff --git a/selfdrive/modeld/test/dmon_lag/repro.cc b/selfdrive/modeld/tests/dmon_lag/repro.cc similarity index 100% rename from selfdrive/modeld/test/dmon_lag/repro.cc rename to selfdrive/modeld/tests/dmon_lag/repro.cc diff --git a/selfdrive/modeld/test/snpe_benchmark/.gitignore b/selfdrive/modeld/tests/snpe_benchmark/.gitignore similarity index 100% rename from selfdrive/modeld/test/snpe_benchmark/.gitignore rename to selfdrive/modeld/tests/snpe_benchmark/.gitignore diff --git a/selfdrive/modeld/test/snpe_benchmark/benchmark.cc b/selfdrive/modeld/tests/snpe_benchmark/benchmark.cc similarity index 99% rename from selfdrive/modeld/test/snpe_benchmark/benchmark.cc rename to selfdrive/modeld/tests/snpe_benchmark/benchmark.cc index 1e2072eea1..021e065d81 100644 --- a/selfdrive/modeld/test/snpe_benchmark/benchmark.cc +++ b/selfdrive/modeld/tests/snpe_benchmark/benchmark.cc @@ -102,6 +102,7 @@ void get_testframe(int index, std::unique_ptr &input) { fread(frame_buffer, length, 1, pFile); // std::cout << *(frame_buffer+length/4-1) << std::endl; std::copy(frame_buffer, frame_buffer+(length/4), input->begin()); + fclose(pFile); } void SaveITensor(const std::string& path, const zdl::DlSystem::ITensor* tensor) diff --git a/selfdrive/modeld/test/snpe_benchmark/benchmark.sh b/selfdrive/modeld/tests/snpe_benchmark/benchmark.sh similarity index 100% rename from selfdrive/modeld/test/snpe_benchmark/benchmark.sh rename to selfdrive/modeld/tests/snpe_benchmark/benchmark.sh diff --git a/selfdrive/modeld/tests/test_modeld.py b/selfdrive/modeld/tests/test_modeld.py new file mode 100755 index 0000000000..2fcff785a9 --- /dev/null +++ b/selfdrive/modeld/tests/test_modeld.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +import time +import unittest +import numpy as np +import random + +import cereal.messaging as messaging +from cereal.visionipc import VisionIpcServer, VisionStreamType +from common.transformations.camera import tici_f_frame_size +from common.realtime import DT_MDL +from selfdrive.manager.process_config import managed_processes + + +VIPC_STREAM = {"roadCameraState": VisionStreamType.VISION_STREAM_ROAD, "driverCameraState": VisionStreamType.VISION_STREAM_DRIVER, + "wideRoadCameraState": VisionStreamType.VISION_STREAM_WIDE_ROAD} + +IMG = np.zeros(int(tici_f_frame_size[0]*tici_f_frame_size[1]*(3/2)), dtype=np.uint8) +IMG_BYTES = IMG.flatten().tobytes() + +class TestModeld(unittest.TestCase): + + def setUp(self): + self.vipc_server = VisionIpcServer("camerad") + self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_ROAD, 40, False, *tici_f_frame_size) + self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_DRIVER, 40, False, *tici_f_frame_size) + self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_WIDE_ROAD, 40, False, *tici_f_frame_size) + self.vipc_server.start_listener() + + self.sm = messaging.SubMaster(['modelV2', 'cameraOdometry']) + self.pm = messaging.PubMaster(['roadCameraState', 'wideRoadCameraState', 'liveCalibration', 'lateralPlan']) + + managed_processes['modeld'].start() + time.sleep(0.2) + self.sm.update(1000) + + def tearDown(self): + managed_processes['modeld'].stop() + del self.vipc_server + + def _send_frames(self, frame_id, cams=None): + if cams is None: + cams = ('roadCameraState', 'wideRoadCameraState') + + cs = None + for cam in cams: + msg = messaging.new_message(cam) + cs = getattr(msg, cam) + cs.frameId = frame_id + cs.timestampSof = int((frame_id * DT_MDL) * 1e9) + cs.timestampEof = int(cs.timestampSof + (DT_MDL * 1e9)) + + self.pm.send(msg.which(), msg) + self.vipc_server.send(VIPC_STREAM[msg.which()], IMG_BYTES, cs.frameId, + cs.timestampSof, cs.timestampEof) + return cs + + def _wait(self): + self.sm.update(5000) + if self.sm['modelV2'].frameId != self.sm['cameraOdometry'].frameId: + self.sm.update(1000) + + def test_modeld(self): + for n in range(1, 500): + cs = self._send_frames(n) + self._wait() + + mdl = self.sm['modelV2'] + self.assertEqual(mdl.frameId, n) + self.assertEqual(mdl.frameIdExtra, n) + self.assertEqual(mdl.timestampEof, cs.timestampEof) + self.assertEqual(mdl.frameAge, 0) + self.assertEqual(mdl.frameDropPerc, 0) + + odo = self.sm['cameraOdometry'] + self.assertEqual(odo.frameId, n) + self.assertEqual(odo.timestampEof, cs.timestampEof) + + def test_dropped_frames(self): + """ + modeld should only run on consecutive road frames + """ + frame_id = -1 + road_frames = list() + for n in range(1, 50): + if (random.random() < 0.1) and n > 3: + cams = random.choice([(), ('wideRoadCameraState', )]) + self._send_frames(n, cams) + else: + self._send_frames(n) + road_frames.append(n) + self._wait() + + if len(road_frames) < 3 or road_frames[-1] - road_frames[-2] == 1: + frame_id = road_frames[-1] + + mdl = self.sm['modelV2'] + odo = self.sm['cameraOdometry'] + self.assertEqual(mdl.frameId, frame_id) + self.assertEqual(mdl.frameIdExtra, frame_id) + self.assertEqual(odo.frameId, frame_id) + if n != frame_id: + self.assertFalse(self.sm.updated['modelV2']) + self.assertFalse(self.sm.updated['cameraOdometry']) + + +if __name__ == "__main__": + unittest.main() diff --git a/selfdrive/modeld/test/tf_test/build.sh b/selfdrive/modeld/tests/tf_test/build.sh similarity index 100% rename from selfdrive/modeld/test/tf_test/build.sh rename to selfdrive/modeld/tests/tf_test/build.sh diff --git a/selfdrive/modeld/test/tf_test/main.cc b/selfdrive/modeld/tests/tf_test/main.cc similarity index 100% rename from selfdrive/modeld/test/tf_test/main.cc rename to selfdrive/modeld/tests/tf_test/main.cc diff --git a/selfdrive/modeld/test/tf_test/pb_loader.py b/selfdrive/modeld/tests/tf_test/pb_loader.py similarity index 100% rename from selfdrive/modeld/test/tf_test/pb_loader.py rename to selfdrive/modeld/tests/tf_test/pb_loader.py diff --git a/selfdrive/modeld/test/timing/benchmark.py b/selfdrive/modeld/tests/timing/benchmark.py similarity index 100% rename from selfdrive/modeld/test/timing/benchmark.py rename to selfdrive/modeld/tests/timing/benchmark.py diff --git a/selfdrive/hardware/eon/__init__.py b/selfdrive/modeld/thneed/__init__.py similarity index 100% rename from selfdrive/hardware/eon/__init__.py rename to selfdrive/modeld/thneed/__init__.py diff --git a/selfdrive/modeld/thneed/compile.cc b/selfdrive/modeld/thneed/compile.cc deleted file mode 100644 index 8e031b9ab6..0000000000 --- a/selfdrive/modeld/thneed/compile.cc +++ /dev/null @@ -1,42 +0,0 @@ -#include - -#include "selfdrive/modeld/runners/snpemodel.h" -#include "selfdrive/modeld/thneed/thneed.h" -#include "selfdrive/hardware/hw.h" - -#define TEMPORAL_SIZE 512 -#define DESIRE_LEN 8 -#define TRAFFIC_CONVENTION_LEN 2 - -// TODO: This should probably use SNPE directly. -int main(int argc, char* argv[]) { - #define OUTPUT_SIZE 0x10000 - - float *output = (float*)calloc(OUTPUT_SIZE, sizeof(float)); - SNPEModel mdl(argv[1], output, 0, USE_GPU_RUNTIME, USE_EXTRA); - - float state[TEMPORAL_SIZE] = {0}; - float desire[DESIRE_LEN] = {0}; - float traffic_convention[TRAFFIC_CONVENTION_LEN] = {0}; - float *input = (float*)calloc(0x1000000, sizeof(float)); - float *extra = (float*)calloc(0x1000000, sizeof(float)); - - mdl.addRecurrent(state, TEMPORAL_SIZE); - mdl.addDesire(desire, DESIRE_LEN); - mdl.addTrafficConvention(traffic_convention, TRAFFIC_CONVENTION_LEN); - mdl.addImage(input, 0); - if (USE_EXTRA) { - mdl.addExtra(extra, 0); - } - - // first run - printf("************** execute 1 **************\n"); - memset(output, 0, OUTPUT_SIZE * sizeof(float)); - mdl.execute(); - - // save model - bool save_binaries = (argc > 3) && (strcmp(argv[3], "--binary") == 0); - mdl.thneed->save(argv[2], save_binaries); - return 0; -} - diff --git a/selfdrive/modeld/thneed/kernels/convolution_.cl b/selfdrive/modeld/thneed/kernels/convolution_.cl deleted file mode 100644 index 1b9d74b83f..0000000000 --- a/selfdrive/modeld/thneed/kernels/convolution_.cl +++ /dev/null @@ -1,272 +0,0 @@ - read_only image2d_t input, -#ifndef DEPTHWISE - short startPackedInputChannel, - short numPackedInputChannelsForGroup, short totalNumPackedInputChannels, - // typo required for API compatibility - short packedOuputChannelOffset, short totalNumPackedOutputChannels, -#else - short totalNumPackedChannels, -#endif - read_only image2d_t weights, __constant float *biases, - short filterSizeX, short filterSizeY, - write_only image2d_t output, - short paddingX, short paddingY, short strideX, short strideY, -#ifdef SUPPORT_DILATION - short dilationX, short dilationY, -#endif - short neuron, float a, float b, float min_clamp, float max_clamp, -#ifndef DEPTHWISE - // note: these are not supported - __constant float *parameters, __constant float *batchNormBiases, -#endif - short numOutputColumns -#ifdef SUPPORT_ACCUMULATION - , short doAccumulate, read_only image2d_t accumulator -#endif - ) { - -#ifndef NUM_OUTPUTS - #define NUM_OUTPUTS 4 -#endif - - // init - const sampler_t smp = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP | CLK_FILTER_NEAREST; - short packedOutputChannel = get_global_id(0); - short startOutputColumn = mul24((short)get_global_id(1), NUM_OUTPUTS); - short outputRow = get_global_id(2); - -#ifdef DEPTHWISE - short totalNumPackedInputChannels = totalNumPackedChannels; - short totalNumPackedOutputChannels = totalNumPackedChannels; - short startPackedInputChannel = packedOutputChannel; -#endif - - short startX = mad24(mad24(startOutputColumn, strideX, -paddingX), totalNumPackedInputChannels, startPackedInputChannel); - short strideWithChannels = mul24(strideX, totalNumPackedInputChannels); - - float4 outputValues[NUM_OUTPUTS]; - for (short i = 0; i < NUM_OUTPUTS; ++i) { - outputValues[i] = (float4)(0, 0, 0, 0); - } - - int2 inputLocation; - inputLocation.y = mad24(outputRow, strideY, -paddingY); - - int2 weightLocation; - weightLocation.x = 0; - weightLocation.y = packedOutputChannel; - -#ifdef DEPTHWISE - -#ifdef SUPPORT_DILATION - - // depthwise convolution - for (short rfRow = 0; rfRow < filterSizeY; ++rfRow) { - for (short rfColumn = 0; rfColumn < filterSizeX; ++rfColumn) { - short dilatedStepX = mul24(totalNumPackedChannels, dilationX); - inputLocation.x = mad24(rfColumn, dilatedStepX, startX); - float4 inputValues[4]; - for (short i = 0; i < 4; ++i) { - inputValues[i] = read_imagef(input, smp, inputLocation); - inputLocation.x += strideWithChannels; - } - float4 weightValues = read_imagef(weights, smp, weightLocation); - ++weightLocation.x; - outputValues[0] += inputValues[0] * weightValues; - outputValues[1] += inputValues[1] * weightValues; - outputValues[2] += inputValues[2] * weightValues; - outputValues[3] += inputValues[3] * weightValues; - } - inputLocation.y += dilationY; - } - -#else - - // depthwise unstrided convolution - for (short rfRow = 0; rfRow < filterSizeY; ++rfRow) { - float4 inputValues[4]; - inputLocation.x = startX; - for (short i = 1; i < 4; ++i) { - inputValues[i] = read_imagef(input, smp, inputLocation); - inputLocation.x += totalNumPackedOutputChannels; - } - for (short rfColumn = 0; rfColumn < filterSizeX; ++rfColumn) { - inputValues[0] = inputValues[1]; - inputValues[1] = inputValues[2]; - inputValues[2] = inputValues[3]; - inputValues[3] = read_imagef(input, smp, inputLocation); - inputLocation.x += totalNumPackedChannels; - float4 weightValues = read_imagef(weights, smp, weightLocation); - ++weightLocation.x; - outputValues[0] += inputValues[0] * weightValues; - outputValues[1] += inputValues[1] * weightValues; - outputValues[2] += inputValues[2] * weightValues; - outputValues[3] += inputValues[3] * weightValues; - } - ++inputLocation.y; - } - -#endif - -#elif defined(ONLY_1X1_CONV) - - // 1x1 convolution - short endPackedInputChannel = startPackedInputChannel + numPackedInputChannelsForGroup; - for (short packedInputChannel = startPackedInputChannel; packedInputChannel < endPackedInputChannel; ++packedInputChannel) { - float4 weightValues[4]; - for (short outChIdx = 0; outChIdx < 4; ++outChIdx) { - weightValues[outChIdx] = read_imagef(weights, smp, weightLocation); - ++weightLocation.x; - } - - inputLocation.x = startX + packedInputChannel; - float4 inputValues[NUM_OUTPUTS]; - for (short i = 0; i < NUM_OUTPUTS; ++i) { - inputValues[i] = read_imagef(input, smp, inputLocation); - inputLocation.x += strideWithChannels; - } - - for (short i = 0; i < NUM_OUTPUTS; ++i) { - float4 curOutputValues = outputValues[i]; - curOutputValues.x += inputValues[i].x * weightValues[0].x; - curOutputValues.x += inputValues[i].y * weightValues[0].y; - curOutputValues.x += inputValues[i].z * weightValues[0].z; - curOutputValues.x += inputValues[i].w * weightValues[0].w; - curOutputValues.y += inputValues[i].x * weightValues[1].x; - curOutputValues.y += inputValues[i].y * weightValues[1].y; - curOutputValues.y += inputValues[i].z * weightValues[1].z; - curOutputValues.y += inputValues[i].w * weightValues[1].w; - curOutputValues.z += inputValues[i].x * weightValues[2].x; - curOutputValues.z += inputValues[i].y * weightValues[2].y; - curOutputValues.z += inputValues[i].z * weightValues[2].z; - curOutputValues.z += inputValues[i].w * weightValues[2].w; - curOutputValues.w += inputValues[i].x * weightValues[3].x; - curOutputValues.w += inputValues[i].y * weightValues[3].y; - curOutputValues.w += inputValues[i].z * weightValues[3].z; - curOutputValues.w += inputValues[i].w * weightValues[3].w; - outputValues[i] = curOutputValues; - } - } - packedOutputChannel += packedOuputChannelOffset; - -#else - - // normal convolution - for (short rfRow = 0; rfRow < filterSizeY; ++rfRow) { - for (short packedInputChannel = 0; packedInputChannel < numPackedInputChannelsForGroup; ++packedInputChannel) { - short startXForChannel = startX + packedInputChannel; - for (short rfColumn = 0; rfColumn < filterSizeX; ++rfColumn) { - - float4 weightValues[4]; - for (short outChIdx = 0; outChIdx < 4; ++outChIdx) { - weightValues[outChIdx] = read_imagef(weights, smp, weightLocation); - ++weightLocation.x; - } - -#ifdef SUPPORT_DILATION - short dilatedStepX = mul24(totalNumPackedInputChannels, dilationX); - inputLocation.x = mad24(rfColumn, dilatedStepX, startXForChannel); -#else - inputLocation.x = mad24(rfColumn, totalNumPackedInputChannels, startXForChannel); -#endif - float4 inputValues[NUM_OUTPUTS]; - for (short i = 0; i < NUM_OUTPUTS; ++i) { - inputValues[i] = read_imagef(input, smp, inputLocation); - inputLocation.x += strideWithChannels; - } - for (short i = 0; i < NUM_OUTPUTS; ++i) { - float4 curOutputValues = outputValues[i]; - curOutputValues.x += inputValues[i].x * weightValues[0].x; - curOutputValues.x += inputValues[i].y * weightValues[0].y; - curOutputValues.x += inputValues[i].z * weightValues[0].z; - curOutputValues.x += inputValues[i].w * weightValues[0].w; - curOutputValues.y += inputValues[i].x * weightValues[1].x; - curOutputValues.y += inputValues[i].y * weightValues[1].y; - curOutputValues.y += inputValues[i].z * weightValues[1].z; - curOutputValues.y += inputValues[i].w * weightValues[1].w; - curOutputValues.z += inputValues[i].x * weightValues[2].x; - curOutputValues.z += inputValues[i].y * weightValues[2].y; - curOutputValues.z += inputValues[i].z * weightValues[2].z; - curOutputValues.z += inputValues[i].w * weightValues[2].w; - curOutputValues.w += inputValues[i].x * weightValues[3].x; - curOutputValues.w += inputValues[i].y * weightValues[3].y; - curOutputValues.w += inputValues[i].z * weightValues[3].z; - curOutputValues.w += inputValues[i].w * weightValues[3].w; - outputValues[i] = curOutputValues; - } - } - } -#ifdef SUPPORT_DILATION - inputLocation.y += dilationY; -#else - ++inputLocation.y; -#endif - } - packedOutputChannel += packedOuputChannelOffset; -#endif - - // bias - short outputChannel = mul24(packedOutputChannel, 4); - float4 biasValues = vload4(0, biases + outputChannel); - for (short i = 0; i < NUM_OUTPUTS; ++i) { - outputValues[i] += biasValues; - } - -#ifdef SUPPORT_ACCUMULATION - // accumulate - if (doAccumulate) { - int2 outputLocation; - short outputColumn = startOutputColumn; - outputLocation.y = outputRow; - for (short i = 0; i < NUM_OUTPUTS; ++i) { - outputLocation.x = mad24(outputColumn, totalNumPackedOutputChannels, packedOutputChannel); - if (outputColumn < numOutputColumns) { - outputValues[i] += read_imagef(accumulator, smp, outputLocation); - } - ++outputColumn; - } - } -#endif - - // activation - switch (neuron) { - case 1: - for (short i = 0; i < NUM_OUTPUTS; ++i) { - outputValues[i] = max(outputValues[i], 0.0f); - } - break; - case 2: - for (short i = 0; i < NUM_OUTPUTS; ++i) { - outputValues[i] = a * tanh(b * outputValues[i]); - } - break; - case 3: - for (short i = 0; i < NUM_OUTPUTS; ++i) { - outputValues[i] = native_recip(1.0f + native_exp(-a * outputValues[i] + b)); - } - break; - case 4: - for (short i = 0; i < NUM_OUTPUTS; ++i) { - outputValues[i] = max(outputValues[i], min_clamp); - outputValues[i] = min(outputValues[i], max_clamp); - } - break; - case 5: - for (short i = 0; i < NUM_OUTPUTS; ++i) { - outputValues[i] = max(outputValues[i], 0.0f) + a * (native_exp(min(outputValues[i], 0.0f)) - 1.0f); - } - break; - } - - // output - int2 outputLocation; - short outputColumn = startOutputColumn; - outputLocation.y = outputRow; - for (short i = 0; i < NUM_OUTPUTS; ++i) { - outputLocation.x = mad24(outputColumn, totalNumPackedOutputChannels, packedOutputChannel); - if (outputColumn < numOutputColumns) { - write_imagef(output, outputLocation, outputValues[i]); - } - ++outputColumn; - } -} diff --git a/selfdrive/modeld/thneed/kernels/convolution_horizontal_reduced_reads.cl b/selfdrive/modeld/thneed/kernels/convolution_horizontal_reduced_reads.cl deleted file mode 100644 index bc8add79aa..0000000000 --- a/selfdrive/modeld/thneed/kernels/convolution_horizontal_reduced_reads.cl +++ /dev/null @@ -1,4 +0,0 @@ -#define SUPPORT_DILATION - -__kernel void convolution_horizontal_reduced_reads( -#include "convolution_.cl" diff --git a/selfdrive/modeld/thneed/kernels/convolution_horizontal_reduced_reads_1x1.cl b/selfdrive/modeld/thneed/kernels/convolution_horizontal_reduced_reads_1x1.cl deleted file mode 100644 index 75a090ca22..0000000000 --- a/selfdrive/modeld/thneed/kernels/convolution_horizontal_reduced_reads_1x1.cl +++ /dev/null @@ -1,5 +0,0 @@ -#define ONLY_1X1_CONV -#define SUPPORT_ACCUMULATION - -__kernel void convolution_horizontal_reduced_reads_1x1( -#include "convolution_.cl" diff --git a/selfdrive/modeld/thneed/kernels/convolution_horizontal_reduced_reads_5_outputs.cl b/selfdrive/modeld/thneed/kernels/convolution_horizontal_reduced_reads_5_outputs.cl deleted file mode 100644 index 980e7d1f67..0000000000 --- a/selfdrive/modeld/thneed/kernels/convolution_horizontal_reduced_reads_5_outputs.cl +++ /dev/null @@ -1,4 +0,0 @@ -#define NUM_OUTPUTS 5 - -__kernel void convolution_horizontal_reduced_reads_5_outputs( -#include "convolution_.cl" diff --git a/selfdrive/modeld/thneed/kernels/convolution_horizontal_reduced_reads_depthwise.cl b/selfdrive/modeld/thneed/kernels/convolution_horizontal_reduced_reads_depthwise.cl deleted file mode 100644 index 80be0da924..0000000000 --- a/selfdrive/modeld/thneed/kernels/convolution_horizontal_reduced_reads_depthwise.cl +++ /dev/null @@ -1,5 +0,0 @@ -#define DEPTHWISE -#define SUPPORT_DILATION - -__kernel void convolution_horizontal_reduced_reads_depthwise( -#include "convolution_.cl" diff --git a/selfdrive/modeld/thneed/kernels/convolution_horizontal_reduced_reads_depthwise_stride_1.cl b/selfdrive/modeld/thneed/kernels/convolution_horizontal_reduced_reads_depthwise_stride_1.cl deleted file mode 100644 index 3d651c229b..0000000000 --- a/selfdrive/modeld/thneed/kernels/convolution_horizontal_reduced_reads_depthwise_stride_1.cl +++ /dev/null @@ -1,4 +0,0 @@ -#define DEPTHWISE - -__kernel void convolution_horizontal_reduced_reads_depthwise_stride_1( -#include "convolution_.cl" diff --git a/selfdrive/modeld/thneed/lib.py b/selfdrive/modeld/thneed/lib.py new file mode 100644 index 0000000000..38ef3f4262 --- /dev/null +++ b/selfdrive/modeld/thneed/lib.py @@ -0,0 +1,31 @@ +import struct, json + +def load_thneed(fn): + with open(fn, "rb") as f: + json_len = struct.unpack("I", f.read(4))[0] + jdat = json.loads(f.read(json_len).decode('latin_1')) + weights = f.read() + ptr = 0 + for o in jdat['objects']: + if o['needs_load']: + nptr = ptr + o['size'] + o['data'] = weights[ptr:nptr] + ptr = nptr + for o in jdat['binaries']: + nptr = ptr + o['length'] + o['data'] = weights[ptr:nptr] + ptr = nptr + return jdat + +def save_thneed(jdat, fn): + new_weights = [] + for o in jdat['objects'] + jdat['binaries']: + if 'data' in o: + new_weights.append(o['data']) + del o['data'] + new_weights_bytes = b''.join(new_weights) + with open(fn, "wb") as f: + j = json.dumps(jdat, ensure_ascii=False).encode('latin_1') + f.write(struct.pack("I", len(j))) + f.write(j) + f.write(new_weights_bytes) diff --git a/selfdrive/modeld/thneed/optimizer.cc b/selfdrive/modeld/thneed/optimizer.cc deleted file mode 100644 index 3c7c41873d..0000000000 --- a/selfdrive/modeld/thneed/optimizer.cc +++ /dev/null @@ -1,266 +0,0 @@ -#include -#include -#include -#include -#include "thneed.h" - -extern map g_program_source; - -static int is_same_size_image(cl_mem a, cl_mem b) { - size_t a_width, a_height, a_depth, a_array_size, a_row_pitch, a_slice_pitch; - clGetImageInfo(a, CL_IMAGE_WIDTH, sizeof(a_width), &a_width, NULL); - clGetImageInfo(a, CL_IMAGE_HEIGHT, sizeof(a_height), &a_height, NULL); - clGetImageInfo(a, CL_IMAGE_DEPTH, sizeof(a_depth), &a_depth, NULL); - clGetImageInfo(a, CL_IMAGE_ARRAY_SIZE, sizeof(a_array_size), &a_array_size, NULL); - clGetImageInfo(a, CL_IMAGE_ROW_PITCH, sizeof(a_row_pitch), &a_row_pitch, NULL); - clGetImageInfo(a, CL_IMAGE_SLICE_PITCH, sizeof(a_slice_pitch), &a_slice_pitch, NULL); - - size_t b_width, b_height, b_depth, b_array_size, b_row_pitch, b_slice_pitch; - clGetImageInfo(b, CL_IMAGE_WIDTH, sizeof(b_width), &b_width, NULL); - clGetImageInfo(b, CL_IMAGE_HEIGHT, sizeof(b_height), &b_height, NULL); - clGetImageInfo(b, CL_IMAGE_DEPTH, sizeof(b_depth), &b_depth, NULL); - clGetImageInfo(b, CL_IMAGE_ARRAY_SIZE, sizeof(b_array_size), &b_array_size, NULL); - clGetImageInfo(b, CL_IMAGE_ROW_PITCH, sizeof(b_row_pitch), &b_row_pitch, NULL); - clGetImageInfo(b, CL_IMAGE_SLICE_PITCH, sizeof(b_slice_pitch), &b_slice_pitch, NULL); - - return (a_width == b_width) && (a_height == b_height) && - (a_depth == b_depth) && (a_array_size == b_array_size) && - (a_row_pitch == b_row_pitch) && (a_slice_pitch == b_slice_pitch); -} - -static cl_mem make_image_like(cl_context context, cl_mem val) { - cl_image_format format; - size_t width, height, row_pitch; - clGetImageInfo(val, CL_IMAGE_FORMAT, sizeof(format), &format, NULL); - assert(format.image_channel_order == CL_RGBA); - assert(format.image_channel_data_type == CL_HALF_FLOAT); - clGetImageInfo(val, CL_IMAGE_WIDTH, sizeof(width), &width, NULL); - clGetImageInfo(val, CL_IMAGE_HEIGHT, sizeof(height), &height, NULL); - clGetImageInfo(val, CL_IMAGE_ROW_PITCH, sizeof(row_pitch), &row_pitch, NULL); - - cl_image_desc desc = {0}; - desc.image_type = CL_MEM_OBJECT_IMAGE2D; - desc.image_width = width; - desc.image_height = height; - desc.image_row_pitch = row_pitch; - - cl_mem buf = clCreateBuffer(context, CL_MEM_READ_WRITE, row_pitch*height, NULL, NULL); - assert(buf != NULL); - desc.buffer = buf; - - cl_int err; - cl_mem tmp = clCreateImage(context, CL_MEM_READ_WRITE, &format, &desc, NULL, &err); - //printf("got %d for image %zux%zu %zu\n", err, width, height, row_pitch); - assert(tmp != NULL); - - return tmp; -} - -// convolution_horizontal_reduced_reads_1x1 is 66% of the model runtime -// make that faster and the model gets faster - -// this cuts ~2 ms off the model runtime right now -int Thneed::optimize() { - const char *kernel_path = getenv("KERNEL_PATH"); - if (!kernel_path) { kernel_path = "/data/openpilot/selfdrive/modeld/thneed/kernels"; printf("no KERNEL_PATH set, defaulting to %s\n", kernel_path); } - // load custom kernels - map g_programs; - for (auto &k : kq) { - // replace program? - if (g_programs.find(k->name) == g_programs.end()) { - char fn[0x100]; - snprintf(fn, sizeof(fn), "%s/%s.cl", kernel_path, k->name.c_str()); - FILE *g = fopen(fn, "rb"); - if (g != NULL) { - char *src[0x10000]; - const char *srcs[1]; srcs[0] = (const char *)src; - memset(src, 0, sizeof(src)); - size_t length = fread(src, 1, sizeof(src), g); - fclose(g); - - printf("building kernel %s\n", k->name.c_str()); - k->program = clCreateProgramWithSource(context, 1, srcs, &length, NULL); - char options[0x100]; - snprintf(options, sizeof(options)-1, "-I %s", kernel_path); - int err = clBuildProgram(k->program, 1, &device_id, options, NULL, NULL); - - if (err != 0) { - printf("got err %d\n", err); - size_t err_length; - char buffer[2048]; - clGetProgramBuildInfo(k->program, device_id, CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, &err_length); - buffer[err_length] = '\0'; - printf("%s\n", buffer); - } - assert(err == 0); - - // save in cache - g_programs[k->name] = k->program; - g_program_source[k->program] = string((char *)src, length); - } else { - g_programs[k->name] = NULL; - } - } else { - // cached replacement - if (g_programs[k->name] != NULL) { - k->program = g_programs[k->name]; - } - } - - // hack in accumulator to convolution_horizontal_reduced_reads_1x1 - if (k->name == "convolution_horizontal_reduced_reads_1x1") { - k->arg_names.push_back("doAccumulate"); - short doAccumulate = 0; - k->args.push_back(string((char *)&doAccumulate, sizeof(doAccumulate))); - k->args_size.push_back(2); - k->arg_names.push_back("accumulator"); - k->args.push_back(k->args[k->get_arg_num("output")]); - k->args_size.push_back(8); - k->num_args += 2; - } - - // assert that parameters + batchNormBiases are not used - // since they aren't supported in custom replacement kernels - if (k->name == "convolution_horizontal_reduced_reads_1x1" || - k->name == "convolution_horizontal_reduced_reads" || - k->name == "convolution_horizontal_reduced_reads_5_outputs") { - string p1 = k->args[k->get_arg_num("parameters")]; - string p2 = k->args[k->get_arg_num("batchNormBiases")]; - assert(p1.length() == 8 && *((uint64_t*)p1.data()) == 0); - assert(p2.length() == 8 && *((uint64_t*)p2.data()) == 0); - } - } - - // optimizer - size_t start_size; - do { - start_size = kq.size(); - - // get optimizations - map replacements; - for (int i = 0; i < kq.size(); i++) { - // fusing elementwise_sum + activate_image will save 3 enqueues - - // delete useless copy layers - // saves ~0.7 ms - if (kq[i]->name == "concatenation" || kq[i]->name == "flatten") { - string in = kq[i]->args[kq[i]->get_arg_num("input")]; - string out = kq[i]->args[kq[i]->get_arg_num("output")]; - if (is_same_size_image(*(cl_mem*)in.data(), *(cl_mem*)out.data())) { - cl_mem tmp = make_image_like(context, *(cl_mem *)in.data()); - replacements[in] = string((char *)&tmp, sizeof(tmp)); - replacements[out] = string((char *)&tmp, sizeof(tmp)); - - kq.erase(kq.begin()+i); --i; - } - } - - // NOTE: if activations/accumulation are done in the wrong order, this will be wrong - - // fuse activations into convs and fc_Wtx - // saves ~1.5 ms - // NOTE: this changes the outputs because of rounding, should be better now! - if (i != 0 && kq[i]->name == "activate_image") { - if (kq[i-1]->name == "convolution_horizontal_reduced_reads_1x1" || - kq[i-1]->name == "convolution_horizontal_reduced_reads_5_outputs" || - kq[i-1]->name == "convolution_horizontal_reduced_reads" || - kq[i-1]->name == "convolution_horizontal_reduced_reads_depthwise" || - kq[i-1]->name == "convolution_horizontal_reduced_reads_depthwise_stride_1" || - kq[i-1]->name == "fc_Wtx") { - string lastout = kq[i-1]->args[kq[i-1]->get_arg_num("output")]; - string in = kq[i]->args[kq[i]->get_arg_num("input")]; - string out = kq[i]->args[kq[i]->get_arg_num("output")]; - - if (lastout == in) { - short neuron = *(int*)kq[i]->args[kq[i]->get_arg_num("neuron")].data(); - assert(neuron <= 5); - - // ELU isn't supported in fc_Wtx - assert(!(kq[i-1]->name == "fc_Wtx" && neuron == 5)); - - kq[i-1]->args[kq[i-1]->get_arg_num("neuron")] = string((char *)&neuron, sizeof(neuron)); - - cl_mem tmp = make_image_like(context, *(cl_mem *)lastout.data()); - replacements[in] = string((char *)&tmp, sizeof(tmp)); - replacements[out] = string((char *)&tmp, sizeof(tmp)); - - kq.erase(kq.begin()+i); --i; - } - } - } - - // fuse accumulation into convs and fc_Wtx - if (i != 0 && kq[i]->name == "elementwise_sum") { - if (kq[i-1]->name == "convolution_horizontal_reduced_reads_1x1" || - kq[i-1]->name == "fc_Wtx") { - string lastout = kq[i-1]->args[kq[i-1]->get_arg_num("output")]; - string a = kq[i]->args[kq[i]->get_arg_num("a")]; - string b = kq[i]->args[kq[i]->get_arg_num("b")]; - string out = kq[i]->args[kq[i]->get_arg_num("output")]; - - if (lastout == a) { - kq[i-1]->args[kq[i-1]->get_arg_num("accumulator")] = b; - } else if (lastout == b) { - kq[i-1]->args[kq[i-1]->get_arg_num("accumulator")] = a; - } else { - continue; - } - - cl_mem tmp = make_image_like(context, *(cl_mem *)lastout.data()); - replacements[lastout] = string((char *)&tmp, sizeof(tmp)); - replacements[out] = string((char *)&tmp, sizeof(tmp)); - - short doAccumulate = 1; - kq[i-1]->args[kq[i-1]->get_arg_num("doAccumulate")] = string((char *)&doAccumulate, sizeof(doAccumulate)); - - kq.erase(kq.begin()+i); --i; - } - } - } - - // remap inputs and outputs, and clear the kernels - for (int i = 0; i < kq.size(); i++) { - kq[i]->kernel = NULL; - for (int j = 0; j < kq[i]->num_args; j++) { - if (replacements.find(kq[i]->args[j]) != replacements.end()) { - kq[i]->args[j] = replacements[kq[i]->args[j]]; - } - } - } - - printf("optimize %lu -> %lu\n", start_size, kq.size()); - } while (kq.size() != start_size); - - size_t work_group_size = 0; - clGetDeviceInfo(device_id, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(work_group_size), &work_group_size, NULL); - printf("max work group size %lu\n", work_group_size); - - // local work group optimizer - for (auto &k : kq) { - // only do it for convs, since others might share memory - if (k->name.rfind("convolution_", 0) == 0) { - int best = -1; - if (k->local_work_size[0] * k->local_work_size[1] * k->local_work_size[2] < work_group_size/2) { - uint64_t base_time = k->benchmark(); - uint64_t best_time = base_time; - for (int i = 0; i < 3; i++) { - k->local_work_size[i] *= 2; - uint64_t this_time = k->benchmark(); - if (this_time < best_time) { - best = i; - best_time = this_time; - } - k->local_work_size[i] /= 2; - } - if (best != -1) { - k->local_work_size[best] *= 2; - //printf("%s %.2f ms doubled %d to %.2f ms\n", k->name.c_str(), base_time/1e6, best, best_time/1e6); - } - } - - } - } - - return 0; -} - diff --git a/selfdrive/modeld/thneed/serialize.cc b/selfdrive/modeld/thneed/serialize.cc index cd5584553b..f789e5bf57 100644 --- a/selfdrive/modeld/thneed/serialize.cc +++ b/selfdrive/modeld/thneed/serialize.cc @@ -2,8 +2,8 @@ #include #include "json11.hpp" -#include "selfdrive/common/util.h" -#include "selfdrive/common/clutil.h" +#include "common/util.h" +#include "common/clutil.h" #include "selfdrive/modeld/thneed/thneed.h" using namespace json11; @@ -14,9 +14,9 @@ void Thneed::load(const char *filename) { string buf = util::read_file(filename); int jsz = *(int *)buf.data(); - string err; + string jsonerr; string jj(buf.data() + sizeof(int), jsz); - Json jdat = Json::parse(jj, err); + Json jdat = Json::parse(jj, jsonerr); map real_mem; real_mem[NULL] = NULL; @@ -33,11 +33,14 @@ void Thneed::load(const char *filename) { assert(mobj["needs_load"].bool_value() == false); } else { if (mobj["needs_load"].bool_value()) { - //printf("loading %p %d @ 0x%X\n", clbuf, sz, ptr); clbuf = clCreateBuffer(context, CL_MEM_COPY_HOST_PTR | CL_MEM_READ_WRITE, sz, &buf[ptr], NULL); + if (debug >= 1) printf("loading %p %d @ 0x%X\n", clbuf, sz, ptr); ptr += sz; } else { - clbuf = clCreateBuffer(context, CL_MEM_READ_WRITE, sz, NULL, NULL); + // TODO: is there a faster way to init zeroed out buffers? + void *host_zeros = calloc(sz, 1); + clbuf = clCreateBuffer(context, CL_MEM_COPY_HOST_PTR | CL_MEM_READ_WRITE, sz, host_zeros, NULL); + free(host_zeros); } } assert(clbuf != NULL); @@ -48,13 +51,33 @@ void Thneed::load(const char *filename) { desc.image_width = mobj["width"].int_value(); desc.image_height = mobj["height"].int_value(); desc.image_row_pitch = mobj["row_pitch"].int_value(); + assert(sz == desc.image_height*desc.image_row_pitch); +#ifdef QCOM2 desc.buffer = clbuf; - - cl_image_format format; +#else + // TODO: we are creating unused buffers on PC + clReleaseMemObject(clbuf); +#endif + cl_image_format format = {0}; format.image_channel_order = CL_RGBA; - format.image_channel_data_type = CL_HALF_FLOAT; + format.image_channel_data_type = mobj["float32"].bool_value() ? CL_FLOAT : CL_HALF_FLOAT; + + cl_int errcode; - clbuf = clCreateImage(context, CL_MEM_READ_WRITE, &format, &desc, NULL, NULL); +#ifndef QCOM2 + if (mobj["needs_load"].bool_value()) { + clbuf = clCreateImage(context, CL_MEM_COPY_HOST_PTR | CL_MEM_READ_WRITE, &format, &desc, &buf[ptr-sz], &errcode); + } else { + clbuf = clCreateImage(context, CL_MEM_READ_WRITE, &format, &desc, NULL, &errcode); + } +#else + clbuf = clCreateImage(context, CL_MEM_READ_WRITE, &format, &desc, NULL, &errcode); +#endif + if (clbuf == NULL) { + printf("clError: %s create image %zux%zu rp %zu with buffer %p\n", cl_get_error_string(errcode), + desc.image_width, desc.image_height, desc.image_row_pitch, desc.buffer + ); + } assert(clbuf != NULL); } @@ -63,14 +86,38 @@ void Thneed::load(const char *filename) { map g_programs; for (const auto &[name, source] : jdat["programs"].object_items()) { - if (record & THNEED_DEBUG) printf("building %s with size %zu\n", name.c_str(), source.string_value().size()); + if (debug >= 1) printf("building %s with size %zu\n", name.c_str(), source.string_value().size()); g_programs[name] = cl_program_from_source(context, device_id, source.string_value()); } + for (auto &obj : jdat["inputs"].array_items()) { + auto mobj = obj.object_items(); + int sz = mobj["size"].int_value(); + cl_mem aa = real_mem[*(cl_mem*)(mobj["buffer_id"].string_value().data())]; + input_clmem.push_back(aa); + input_sizes.push_back(sz); + printf("Thneed::load: adding input %s with size %d\n", mobj["name"].string_value().data(), sz); + + cl_int cl_err; + void *ret = clEnqueueMapBuffer(command_queue, aa, CL_TRUE, CL_MAP_WRITE, 0, sz, 0, NULL, NULL, &cl_err); + if (cl_err != CL_SUCCESS) printf("clError: %s map %p %d\n", cl_get_error_string(cl_err), aa, sz); + assert(cl_err == CL_SUCCESS); + inputs.push_back(ret); + } + + for (auto &obj : jdat["outputs"].array_items()) { + auto mobj = obj.object_items(); + int sz = mobj["size"].int_value(); + printf("Thneed::save: adding output with size %d\n", sz); + // TODO: support multiple outputs + output = real_mem[*(cl_mem*)(mobj["buffer_id"].string_value().data())]; + assert(output != NULL); + } + for (auto &obj : jdat["binaries"].array_items()) { string name = obj["name"].string_value(); size_t length = obj["length"].int_value(); - if (record & THNEED_DEBUG) printf("binary %s with size %zu\n", name.c_str(), length); + if (debug >= 1) printf("binary %s with size %zu\n", name.c_str(), length); g_programs[name] = cl_program_from_binary(context, device_id, (const uint8_t*)&buf[ptr], length); ptr += length; } @@ -105,154 +152,3 @@ void Thneed::load(const char *filename) { clFinish(command_queue); } - -void Thneed::save(const char *filename, bool save_binaries) { - printf("Thneed::save: saving to %s\n", filename); - - // get kernels - std::vector kernels; - std::set saved_objects; - std::vector objects; - std::map programs; - std::map binaries; - - for (auto &k : kq) { - kernels.push_back(k->to_json()); - - // check args for objects - int i = 0; - for (auto &a : k->args) { - if (a.size() == 8) { - if (saved_objects.find(a) == saved_objects.end()) { - saved_objects.insert(a); - cl_mem val = *(cl_mem*)(a.data()); - if (val != NULL) { - bool needs_load = k->arg_names[i] == "weights" || k->arg_names[i] == "biases"; - - auto jj = Json::object({ - {"id", a}, - {"arg_type", k->arg_types[i]}, - }); - - if (k->arg_types[i] == "image2d_t" || k->arg_types[i] == "image1d_t") { - cl_mem buf; - clGetImageInfo(val, CL_IMAGE_BUFFER, sizeof(buf), &buf, NULL); - string aa = string((char *)&buf, sizeof(buf)); - jj["buffer_id"] = aa; - - size_t width, height, row_pitch; - clGetImageInfo(val, CL_IMAGE_WIDTH, sizeof(width), &width, NULL); - clGetImageInfo(val, CL_IMAGE_HEIGHT, sizeof(height), &height, NULL); - clGetImageInfo(val, CL_IMAGE_ROW_PITCH, sizeof(row_pitch), &row_pitch, NULL); - jj["width"] = (int)width; - jj["height"] = (int)height; - jj["row_pitch"] = (int)row_pitch; - jj["size"] = (int)(height * row_pitch); - jj["needs_load"] = false; - - if (saved_objects.find(aa) == saved_objects.end()) { - saved_objects.insert(aa); - size_t sz; - clGetMemObjectInfo(buf, CL_MEM_SIZE, sizeof(sz), &sz, NULL); - // save the buffer - objects.push_back(Json::object({ - {"id", aa}, - {"arg_type", ""}, - {"needs_load", needs_load}, - {"size", (int)sz} - })); - if (needs_load) assert(sz == height * row_pitch); - } - } else { - size_t sz = 0; - clGetMemObjectInfo(val, CL_MEM_SIZE, sizeof(sz), &sz, NULL); - jj["size"] = (int)sz; - jj["needs_load"] = needs_load; - } - - objects.push_back(jj); - } - } - } - i++; - } - - if (save_binaries) { - int err; - size_t binary_size = 0; - err = clGetProgramInfo(k->program, CL_PROGRAM_BINARY_SIZES, sizeof(binary_size), &binary_size, NULL); - assert(err == 0); - assert(binary_size > 0); - string sv(binary_size, '\x00'); - - uint8_t* bufs[1] = { (uint8_t*)sv.data(), }; - err = clGetProgramInfo(k->program, CL_PROGRAM_BINARIES, sizeof(bufs), &bufs, NULL); - assert(err == 0); - - binaries[k->name] = sv; - } else { - programs[k->name] = g_program_source[k->program]; - } - } - - vector saved_buffers; - for (auto &obj : objects) { - auto mobj = obj.object_items(); - cl_mem val = *(cl_mem*)(mobj["id"].string_value().data()); - int sz = mobj["size"].int_value(); - if (mobj["needs_load"].bool_value()) { - char *buf = (char *)malloc(sz); - if (mobj["arg_type"] == "image2d_t" || mobj["arg_type"] == "image1d_t") { - assert(false); - } else { - // buffers allocated with CL_MEM_HOST_WRITE_ONLY, hence this hack - //hexdump((uint32_t*)val, 0x100); - - // the worst hack in thneed, the flags are at 0x14 - ((uint32_t*)val)[0x14] &= ~CL_MEM_HOST_WRITE_ONLY; - cl_int ret = clEnqueueReadBuffer(command_queue, val, CL_TRUE, 0, sz, buf, 0, NULL, NULL); - assert(ret == CL_SUCCESS); - } - //printf("saving buffer: %d %p %s\n", sz, buf, mobj["arg_type"].string_value().c_str()); - saved_buffers.push_back(string(buf, sz)); - free(buf); - } - } - - std::vector jbinaries; - for (auto &obj : binaries) { - jbinaries.push_back(Json::object({{"name", obj.first}, {"length", (int)obj.second.size()}})); - saved_buffers.push_back(obj.second); - } - - Json jdat = Json::object({ - {"kernels", kernels}, - {"objects", objects}, - {"programs", programs}, - {"binaries", jbinaries}, - }); - - string str = jdat.dump(); - int jsz = str.length(); - - FILE *f = fopen(filename, "wb"); - fwrite(&jsz, 1, sizeof(jsz), f); - fwrite(str.data(), 1, jsz, f); - for (auto &s : saved_buffers) { - fwrite(s.data(), 1, s.length(), f); - } - fclose(f); -} - -Json CLQueuedKernel::to_json() const { - return Json::object { - { "name", name }, - { "work_dim", (int)work_dim }, - { "global_work_size", Json::array { (int)global_work_size[0], (int)global_work_size[1], (int)global_work_size[2] } }, - { "local_work_size", Json::array { (int)local_work_size[0], (int)local_work_size[1], (int)local_work_size[2] } }, - { "num_args", (int)num_args }, - { "args", args }, - { "args_size", args_size }, - }; -} - diff --git a/selfdrive/modeld/thneed/thneed.cc b/selfdrive/modeld/thneed/thneed.cc deleted file mode 100644 index 31bfa3e2f3..0000000000 --- a/selfdrive/modeld/thneed/thneed.cc +++ /dev/null @@ -1,612 +0,0 @@ -#include "selfdrive/modeld/thneed/thneed.h" - -#include -#include - -#include -#include -#include -#include -#include - -#include "selfdrive/common/clutil.h" -#include "selfdrive/common/timing.h" -//#define RUN_DISASSEMBLER -#define RUN_OPTIMIZER - -Thneed *g_thneed = NULL; -int g_fd = -1; -map, string> g_args; -map, int> g_args_size; -map g_program_source; - -void hexdump(uint8_t *d, int len) { - assert((len%4) == 0); - printf(" dumping %p len 0x%x\n", d, len); - for (int i = 0; i < len/4; i++) { - if (i != 0 && (i%0x10) == 0) printf("\n"); - printf("%8x ", d[i]); - } - printf("\n"); -} - -// *********** ioctl interceptor *********** - -extern "C" { - -int (*my_ioctl)(int filedes, unsigned long request, void *argp) = NULL; -#undef ioctl -int ioctl(int filedes, unsigned long request, void *argp) { - request &= 0xFFFFFFFF; // needed on QCOM2 - if (my_ioctl == NULL) my_ioctl = reinterpret_cast(dlsym(RTLD_NEXT, "ioctl")); - Thneed *thneed = g_thneed; - - // save the fd - if (request == IOCTL_KGSL_GPUOBJ_ALLOC) g_fd = filedes; - - // note that this runs always, even without a thneed object - if (request == IOCTL_KGSL_DRAWCTXT_CREATE) { - struct kgsl_drawctxt_create *create = (struct kgsl_drawctxt_create *)argp; - create->flags &= ~KGSL_CONTEXT_PRIORITY_MASK; - create->flags |= 1 << KGSL_CONTEXT_PRIORITY_SHIFT; // priority from 1-15, 1 is max priority - printf("IOCTL_KGSL_DRAWCTXT_CREATE: creating context with flags 0x%x\n", create->flags); - } - - if (thneed != NULL) { - if (request == IOCTL_KGSL_GPU_COMMAND) { - struct kgsl_gpu_command *cmd = (struct kgsl_gpu_command *)argp; - if (thneed->record & THNEED_RECORD) { - thneed->timestamp = cmd->timestamp; - thneed->context_id = cmd->context_id; - thneed->cmds.push_back(unique_ptr(new CachedCommand(thneed, cmd))); - } - if (thneed->record & THNEED_DEBUG) { - printf("IOCTL_KGSL_GPU_COMMAND(%2zu): flags: 0x%lx context_id: %u timestamp: %u numcmds: %d numobjs: %d\n", - thneed->cmds.size(), - cmd->flags, - cmd->context_id, cmd->timestamp, cmd->numcmds, cmd->numobjs); - } - } else if (request == IOCTL_KGSL_GPUOBJ_SYNC) { - struct kgsl_gpuobj_sync *cmd = (struct kgsl_gpuobj_sync *)argp; - struct kgsl_gpuobj_sync_obj *objs = (struct kgsl_gpuobj_sync_obj *)(cmd->objs); - - if (thneed->record & THNEED_DEBUG) { - printf("IOCTL_KGSL_GPUOBJ_SYNC count:%d ", cmd->count); - for (int i = 0; i < cmd->count; i++) { - printf(" -- offset:0x%lx len:0x%lx id:%d op:%d ", objs[i].offset, objs[i].length, objs[i].id, objs[i].op); - } - printf("\n"); - } - - if (thneed->record & THNEED_RECORD) { - thneed->cmds.push_back(unique_ptr(new - CachedSync(thneed, string((char *)objs, sizeof(struct kgsl_gpuobj_sync_obj)*cmd->count)))); - } - } else if (request == IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID) { - struct kgsl_device_waittimestamp_ctxtid *cmd = (struct kgsl_device_waittimestamp_ctxtid *)argp; - if (thneed->record & THNEED_DEBUG) { - printf("IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID: context_id: %d timestamp: %d timeout: %d\n", - cmd->context_id, cmd->timestamp, cmd->timeout); - } - } else if (request == IOCTL_KGSL_SETPROPERTY) { - if (thneed->record & THNEED_DEBUG) { - struct kgsl_device_getproperty *prop = (struct kgsl_device_getproperty *)argp; - printf("IOCTL_KGSL_SETPROPERTY: 0x%x sizebytes:%zu\n", prop->type, prop->sizebytes); - if (thneed->record & THNEED_VERBOSE_DEBUG) { - hexdump((uint8_t *)prop->value, prop->sizebytes); - if (prop->type == KGSL_PROP_PWR_CONSTRAINT) { - struct kgsl_device_constraint *constraint = (struct kgsl_device_constraint *)prop->value; - hexdump((uint8_t *)constraint->data, constraint->size); - } - } - } - } else if (request == IOCTL_KGSL_DRAWCTXT_CREATE || request == IOCTL_KGSL_DRAWCTXT_DESTROY) { - // this happens - } else if (request == IOCTL_KGSL_GPUOBJ_ALLOC || request == IOCTL_KGSL_GPUOBJ_FREE) { - // this happens - } else { - if (thneed->record & THNEED_DEBUG) { - printf("other ioctl %lx\n", request); - } - } - } - - int ret = my_ioctl(filedes, request, argp); - if (ret != 0) printf("ioctl returned %d with errno %d\n", ret, errno); - return ret; -} - -} - -// *********** GPUMalloc *********** - -GPUMalloc::GPUMalloc(int size, int fd) { - struct kgsl_gpuobj_alloc alloc; - memset(&alloc, 0, sizeof(alloc)); - alloc.size = size; - alloc.flags = 0x10000a00; - ioctl(fd, IOCTL_KGSL_GPUOBJ_ALLOC, &alloc); - void *addr = mmap64(NULL, alloc.mmapsize, 0x3, 0x1, fd, alloc.id*0x1000); - assert(addr != MAP_FAILED); - - base = (uint64_t)addr; - remaining = size; -} - -GPUMalloc::~GPUMalloc() { - // TODO: free the GPU malloced area -} - -void *GPUMalloc::alloc(int size) { - void *ret = (void*)base; - size = (size+0xff) & (~0xFF); - assert(size <= remaining); - remaining -= size; - base += size; - return ret; -} - -// *********** CachedSync, at the ioctl layer *********** - -void CachedSync::exec() { - struct kgsl_gpuobj_sync cmd; - - cmd.objs = (uint64_t)data.data(); - cmd.obj_len = data.length(); - cmd.count = data.length() / sizeof(struct kgsl_gpuobj_sync_obj); - - int ret = ioctl(thneed->fd, IOCTL_KGSL_GPUOBJ_SYNC, &cmd); - assert(ret == 0); -} - -// *********** CachedCommand, at the ioctl layer *********** - -CachedCommand::CachedCommand(Thneed *lthneed, struct kgsl_gpu_command *cmd) { - thneed = lthneed; - assert(cmd->numsyncs == 0); - - memcpy(&cache, cmd, sizeof(cache)); - - if (cmd->numcmds > 0) { - cmds = make_unique(cmd->numcmds); - memcpy(cmds.get(), (void *)cmd->cmdlist, sizeof(struct kgsl_command_object)*cmd->numcmds); - cache.cmdlist = (uint64_t)cmds.get(); - for (int i = 0; i < cmd->numcmds; i++) { - void *nn = thneed->ram->alloc(cmds[i].size); - memcpy(nn, (void*)cmds[i].gpuaddr, cmds[i].size); - cmds[i].gpuaddr = (uint64_t)nn; - } - } - - if (cmd->numobjs > 0) { - objs = make_unique(cmd->numobjs); - memcpy(objs.get(), (void *)cmd->objlist, sizeof(struct kgsl_command_object)*cmd->numobjs); - cache.objlist = (uint64_t)objs.get(); - for (int i = 0; i < cmd->numobjs; i++) { - void *nn = thneed->ram->alloc(objs[i].size); - memset(nn, 0, objs[i].size); - objs[i].gpuaddr = (uint64_t)nn; - } - } - - kq = thneed->ckq; - thneed->ckq.clear(); -} - -void CachedCommand::exec() { - cache.timestamp = ++thneed->timestamp; - int ret = ioctl(thneed->fd, IOCTL_KGSL_GPU_COMMAND, &cache); - - if (thneed->record & THNEED_DEBUG) printf("CachedCommand::exec got %d\n", ret); - - if (thneed->record & THNEED_VERBOSE_DEBUG) { - for (auto &it : kq) { - it->debug_print(false); - } - #ifdef RUN_DISASSEMBLER - // assuming 2 commands - disassemble(0); - disassemble(1); - #endif - } - - assert(ret == 0); -} - -// *********** Thneed *********** - -Thneed::Thneed(bool do_clinit) { - if (do_clinit) clinit(); - assert(g_fd != -1); - fd = g_fd; - ram = make_unique(0x80000, fd); - record = THNEED_RECORD; - timestamp = -1; - g_thneed = this; -} - -void Thneed::stop() { - find_inputs_outputs(); - printf("Thneed::stop: recorded %lu commands\n", cmds.size()); - record = 0; -} - -void Thneed::find_inputs_outputs() { - cl_int err; - if (inputs.size() > 0) return; - - // save the global inputs/outputs - for (auto &k : kq) { - for (int i = 0; i < k->num_args; i++) { - if (k->name == "zero_pad_image_float" && k->arg_names[i] == "input") { - cl_mem aa = *(cl_mem*)(k->args[i].data()); - input_clmem.push_back(aa); - - size_t sz; - clGetMemObjectInfo(aa, CL_MEM_SIZE, sizeof(sz), &sz, NULL); - input_sizes.push_back(sz); - - void *ret = clEnqueueMapBuffer(command_queue, aa, CL_TRUE, CL_MAP_WRITE, 0, sz, 0, NULL, NULL, &err); - assert(err == CL_SUCCESS); - inputs.push_back(ret); - } - - if (k->name == "image2d_to_buffer_float" && k->arg_names[i] == "output") { - output = *(cl_mem*)(k->args[i].data()); - } - } - } -} - -void Thneed::copy_inputs(float **finputs) { - //cl_int ret; - for (int idx = 0; idx < inputs.size(); ++idx) { - if (record & THNEED_DEBUG) printf("copying %lu -- %p -> %p\n", input_sizes[idx], finputs[idx], inputs[idx]); - if (finputs[idx] != NULL) memcpy(inputs[idx], finputs[idx], input_sizes[idx]); - } -} - -void Thneed::copy_output(float *foutput) { - if (output != NULL) { - size_t sz; - clGetMemObjectInfo(output, CL_MEM_SIZE, sizeof(sz), &sz, NULL); - if (record & THNEED_DEBUG) printf("copying %lu for output %p -> %p\n", sz, output, foutput); - clEnqueueReadBuffer(command_queue, output, CL_TRUE, 0, sz, foutput, 0, NULL, NULL); - } else { - printf("CAUTION: model output is NULL, does it have no outputs?\n"); - } -} - -void Thneed::wait() { - struct kgsl_device_waittimestamp_ctxtid wait; - wait.context_id = context_id; - wait.timestamp = timestamp; - wait.timeout = -1; - - uint64_t tb = nanos_since_boot(); - int wret = ioctl(fd, IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID, &wait); - uint64_t te = nanos_since_boot(); - - if (record & THNEED_DEBUG) printf("wait %d after %lu us\n", wret, (te-tb)/1000); -} - -void Thneed::execute(float **finputs, float *foutput, bool slow) { - uint64_t tb, te; - if (record & THNEED_DEBUG) tb = nanos_since_boot(); - - // ****** copy inputs - copy_inputs(finputs); - - // ****** set power constraint - int ret; - struct kgsl_device_constraint_pwrlevel pwrlevel; - pwrlevel.level = KGSL_CONSTRAINT_PWR_MAX; - - struct kgsl_device_constraint constraint; - constraint.type = KGSL_CONSTRAINT_PWRLEVEL; - constraint.context_id = context_id; - constraint.data = (void*)&pwrlevel; - constraint.size = sizeof(pwrlevel); - - struct kgsl_device_getproperty prop; - prop.type = KGSL_PROP_PWR_CONSTRAINT; - prop.value = (void*)&constraint; - prop.sizebytes = sizeof(constraint); - ret = ioctl(fd, IOCTL_KGSL_SETPROPERTY, &prop); - assert(ret == 0); - - // ****** run commands - int i = 0; - for (auto &it : cmds) { - ++i; - if (record & THNEED_DEBUG) printf("run %2d @ %7lu us: ", i, (nanos_since_boot()-tb)/1000); - it->exec(); - if ((i == cmds.size()) || slow) wait(); - } - - // ****** copy outputs - copy_output(foutput); - - // ****** unset power constraint - constraint.type = KGSL_CONSTRAINT_NONE; - constraint.data = NULL; - constraint.size = 0; - - ret = ioctl(fd, IOCTL_KGSL_SETPROPERTY, &prop); - assert(ret == 0); - - if (record & THNEED_DEBUG) { - te = nanos_since_boot(); - printf("model exec in %lu us\n", (te-tb)/1000); - } -} - -void Thneed::clinit() { - device_id = cl_get_device_id(CL_DEVICE_TYPE_DEFAULT); - context = CL_CHECK_ERR(clCreateContext(NULL, 1, &device_id, NULL, NULL, &err)); - //cl_command_queue_properties props[3] = {CL_QUEUE_PROPERTIES, CL_QUEUE_PROFILING_ENABLE, 0}; - cl_command_queue_properties props[3] = {CL_QUEUE_PROPERTIES, 0, 0}; - command_queue = CL_CHECK_ERR(clCreateCommandQueueWithProperties(context, device_id, props, &err)); - printf("Thneed::clinit done\n"); -} - -cl_int Thneed::clexec() { - printf("Thneed::clexec: running %lu queued kernels\n", kq.size()); - for (auto &k : kq) { - if (record & THNEED_RECORD) ckq.push_back(k); - cl_int ret = k->exec(); - assert(ret == CL_SUCCESS); - } - return clFinish(command_queue); -} - -// *********** OpenCL interceptor *********** - -cl_int thneed_clSetKernelArg(cl_kernel kernel, cl_uint arg_index, size_t arg_size, const void *arg_value) { - g_args_size[make_pair(kernel, arg_index)] = arg_size; - if (arg_value != NULL) { - g_args[make_pair(kernel, arg_index)] = string((char*)arg_value, arg_size); - } else { - g_args[make_pair(kernel, arg_index)] = string(""); - } - cl_int ret = clSetKernelArg(kernel, arg_index, arg_size, arg_value); - return ret; -} - -cl_int thneed_clEnqueueNDRangeKernel(cl_command_queue command_queue, - cl_kernel kernel, - cl_uint work_dim, - const size_t *global_work_offset, - const size_t *global_work_size, - const size_t *local_work_size, - cl_uint num_events_in_wait_list, - const cl_event *event_wait_list, - cl_event *event) { - - Thneed *thneed = g_thneed; - - // SNPE doesn't use these - assert(num_events_in_wait_list == 0); - assert(global_work_offset == NULL); - assert(event_wait_list == NULL); - - cl_int ret = 0; - if (thneed != NULL && thneed->record & THNEED_RECORD) { - if (thneed->context == NULL) { - thneed->command_queue = command_queue; - clGetKernelInfo(kernel, CL_KERNEL_CONTEXT, sizeof(thneed->context), &thneed->context, NULL); - clGetContextInfo(thneed->context, CL_CONTEXT_DEVICES, sizeof(thneed->device_id), &thneed->device_id, NULL); - } - - // if we are recording, we don't actually enqueue the kernel - thneed->kq.push_back(unique_ptr(new CLQueuedKernel(thneed, kernel, work_dim, global_work_size, local_work_size))); - *event = NULL; - } else { - ret = clEnqueueNDRangeKernel(command_queue, kernel, work_dim, - global_work_offset, global_work_size, local_work_size, - num_events_in_wait_list, event_wait_list, event); - } - - return ret; -} - -cl_int thneed_clFinish(cl_command_queue command_queue) { - Thneed *thneed = g_thneed; - - if (thneed != NULL && thneed->record & THNEED_RECORD) { - #ifdef RUN_OPTIMIZER - thneed->optimize(); - #endif - return thneed->clexec(); - } else { - return clFinish(command_queue); - } -} - -cl_program thneed_clCreateProgramWithSource(cl_context context, cl_uint count, const char **strings, const size_t *lengths, cl_int *errcode_ret) { - assert(count == 1); - cl_program ret = clCreateProgramWithSource(context, count, strings, lengths, errcode_ret); - g_program_source[ret] = strings[0]; - return ret; -} - -void *dlsym(void *handle, const char *symbol) { -#if defined(QCOM) || defined(QCOM2) - void *(*my_dlsym)(void *handle, const char *symbol) = (void *(*)(void *handle, const char *symbol))((uintptr_t)dlopen + DLSYM_OFFSET); -#else - #error "Unsupported platform for thneed" -#endif - if (memcmp("REAL_", symbol, 5) == 0) { - return my_dlsym(handle, symbol+5); - } else if (strcmp("clFinish", symbol) == 0) { - return (void*)thneed_clFinish; - } else if (strcmp("clEnqueueNDRangeKernel", symbol) == 0) { - return (void*)thneed_clEnqueueNDRangeKernel; - } else if (strcmp("clSetKernelArg", symbol) == 0) { - return (void*)thneed_clSetKernelArg; - } else if (strcmp("clCreateProgramWithSource", symbol) == 0) { - return (void*)thneed_clCreateProgramWithSource; - } else { - return my_dlsym(handle, symbol); - } -} - -// *********** CLQueuedKernel *********** - -CLQueuedKernel::CLQueuedKernel(Thneed *lthneed, - cl_kernel _kernel, - cl_uint _work_dim, - const size_t *_global_work_size, - const size_t *_local_work_size) { - thneed = lthneed; - kernel = _kernel; - work_dim = _work_dim; - assert(work_dim <= 3); - for (int i = 0; i < work_dim; i++) { - global_work_size[i] = _global_work_size[i]; - local_work_size[i] = _local_work_size[i]; - } - - char _name[0x100]; - clGetKernelInfo(kernel, CL_KERNEL_FUNCTION_NAME, sizeof(_name), _name, NULL); - name = string(_name); - clGetKernelInfo(kernel, CL_KERNEL_NUM_ARGS, sizeof(num_args), &num_args, NULL); - - // get args - for (int i = 0; i < num_args; i++) { - char arg_name[0x100]; - clGetKernelArgInfo(kernel, i, CL_KERNEL_ARG_NAME, sizeof(arg_name), arg_name, NULL); - arg_names.push_back(string(arg_name)); - clGetKernelArgInfo(kernel, i, CL_KERNEL_ARG_TYPE_NAME, sizeof(arg_name), arg_name, NULL); - arg_types.push_back(string(arg_name)); - - args.push_back(g_args[make_pair(kernel, i)]); - args_size.push_back(g_args_size[make_pair(kernel, i)]); - } - - // get program - clGetKernelInfo(kernel, CL_KERNEL_PROGRAM, sizeof(program), &program, NULL); -} - -int CLQueuedKernel::get_arg_num(const char *search_arg_name) { - for (int i = 0; i < num_args; i++) { - if (arg_names[i] == search_arg_name) return i; - } - printf("failed to find %s in %s\n", search_arg_name, name.c_str()); - assert(false); -} - -cl_int CLQueuedKernel::exec() { - if (kernel == NULL) { - kernel = clCreateKernel(program, name.c_str(), NULL); - arg_names.clear(); - arg_types.clear(); - - for (int j = 0; j < num_args; j++) { - char arg_name[0x100]; - clGetKernelArgInfo(kernel, j, CL_KERNEL_ARG_NAME, sizeof(arg_name), arg_name, NULL); - arg_names.push_back(string(arg_name)); - clGetKernelArgInfo(kernel, j, CL_KERNEL_ARG_TYPE_NAME, sizeof(arg_name), arg_name, NULL); - arg_types.push_back(string(arg_name)); - - cl_int ret; - if (args[j].size() != 0) { - assert(args[j].size() == args_size[j]); - ret = thneed_clSetKernelArg(kernel, j, args[j].size(), args[j].data()); - } else { - ret = thneed_clSetKernelArg(kernel, j, args_size[j], NULL); - } - assert(ret == CL_SUCCESS); - } - } - - if (thneed->record & THNEED_DEBUG) { - debug_print(thneed->record & THNEED_VERBOSE_DEBUG); - } - - return clEnqueueNDRangeKernel(thneed->command_queue, - kernel, work_dim, NULL, global_work_size, local_work_size, 0, NULL, NULL); -} - -uint64_t CLQueuedKernel::benchmark() { - uint64_t ret = 0; - int old_record = thneed->record; - thneed->record = 0; - clFinish(thneed->command_queue); - // TODO: benchmarking at a lower level will make this more accurate - for (int i = 0; i < 10; i++) { - uint64_t sb = nanos_since_boot(); - exec(); - clFinish(thneed->command_queue); - uint64_t et = nanos_since_boot() - sb; - if (ret == 0 || et < ret) ret = et; - } - thneed->record = old_record; - return ret; -} - -void CLQueuedKernel::debug_print(bool verbose) { - printf("%p %56s -- ", kernel, name.c_str()); - for (int i = 0; i < work_dim; i++) { - printf("%4zu ", global_work_size[i]); - } - printf(" -- "); - for (int i = 0; i < work_dim; i++) { - printf("%4zu ", local_work_size[i]); - } - printf("\n"); - - if (verbose) { - for (int i = 0; i < num_args; i++) { - string arg = args[i]; - printf(" %s %s", arg_types[i].c_str(), arg_names[i].c_str()); - void *arg_value = (void*)arg.data(); - int arg_size = arg.size(); - if (arg_size == 0) { - printf(" (size) %d", args_size[i]); - } else if (arg_size == 1) { - printf(" = %d", *((char*)arg_value)); - } else if (arg_size == 2) { - printf(" = %d", *((short*)arg_value)); - } else if (arg_size == 4) { - if (arg_types[i] == "float") { - printf(" = %f", *((float*)arg_value)); - } else { - printf(" = %d", *((int*)arg_value)); - } - } else if (arg_size == 8) { - cl_mem val = (cl_mem)(*((uintptr_t*)arg_value)); - printf(" = %p", val); - if (val != NULL) { - if (arg_types[i] == "image2d_t" || arg_types[i] == "image1d_t") { - cl_image_format format; - size_t width, height, depth, array_size, row_pitch, slice_pitch; - cl_mem buf; - clGetImageInfo(val, CL_IMAGE_FORMAT, sizeof(format), &format, NULL); - assert(format.image_channel_order == CL_RGBA); - assert(format.image_channel_data_type == CL_HALF_FLOAT); - clGetImageInfo(val, CL_IMAGE_WIDTH, sizeof(width), &width, NULL); - clGetImageInfo(val, CL_IMAGE_HEIGHT, sizeof(height), &height, NULL); - clGetImageInfo(val, CL_IMAGE_ROW_PITCH, sizeof(row_pitch), &row_pitch, NULL); - clGetImageInfo(val, CL_IMAGE_DEPTH, sizeof(depth), &depth, NULL); - clGetImageInfo(val, CL_IMAGE_ARRAY_SIZE, sizeof(array_size), &array_size, NULL); - clGetImageInfo(val, CL_IMAGE_SLICE_PITCH, sizeof(slice_pitch), &slice_pitch, NULL); - assert(depth == 0); - assert(array_size == 0); - assert(slice_pitch == 0); - - clGetImageInfo(val, CL_IMAGE_BUFFER, sizeof(buf), &buf, NULL); - size_t sz; - clGetMemObjectInfo(buf, CL_MEM_SIZE, sizeof(sz), &sz, NULL); - printf(" image %zu x %zu rp %zu @ %p buffer %zu", width, height, row_pitch, buf, sz); - } else { - size_t sz; - clGetMemObjectInfo(val, CL_MEM_SIZE, sizeof(sz), &sz, NULL); - printf(" buffer %zu", sz); - } - } - } - printf("\n"); - } - } -} diff --git a/selfdrive/modeld/thneed/thneed.h b/selfdrive/modeld/thneed/thneed.h index 1197e4c5ed..65475ccf7f 100644 --- a/selfdrive/modeld/thneed/thneed.h +++ b/selfdrive/modeld/thneed/thneed.h @@ -14,12 +14,10 @@ #include "selfdrive/modeld/thneed/include/msm_kgsl.h" -#define THNEED_RECORD 1 -#define THNEED_DEBUG 2 -#define THNEED_VERBOSE_DEBUG 4 - using namespace std; +cl_int thneed_clSetKernelArg(cl_kernel kernel, cl_uint arg_index, size_t arg_size, const void *arg_value); + namespace json11 { class Json; } @@ -44,7 +42,6 @@ class CLQueuedKernel { const size_t *_global_work_size, const size_t *_local_work_size); cl_int exec(); - uint64_t benchmark(); void debug_print(bool verbose); int get_arg_num(const char *search_arg_name); cl_program program; @@ -93,11 +90,10 @@ class CachedCommand: public CachedIoctl { class Thneed { public: - Thneed(bool do_clinit=false); + Thneed(bool do_clinit=false, cl_context _context = NULL); void stop(); void execute(float **finputs, float *foutput, bool slow=false); void wait(); - int optimize(); vector input_clmem; vector inputs; @@ -110,15 +106,18 @@ class Thneed { int context_id; // protected? - int record; + bool record = false; + int debug; int timestamp; + +#ifdef QCOM2 unique_ptr ram; vector > cmds; int fd; +#endif // all CL kernels - void find_inputs_outputs(); - void copy_inputs(float **finputs); + void copy_inputs(float **finputs, bool internal=false); void copy_output(float *foutput); cl_int clexec(); vector > kq; @@ -126,9 +125,8 @@ class Thneed { // pending CL kernels vector > ckq; - // loading and saving + // loading void load(const char *filename); - void save(const char *filename, bool save_binaries=false); private: void clinit(); }; diff --git a/selfdrive/modeld/thneed/thneed_common.cc b/selfdrive/modeld/thneed/thneed_common.cc new file mode 100644 index 0000000000..ecdf1237e3 --- /dev/null +++ b/selfdrive/modeld/thneed/thneed_common.cc @@ -0,0 +1,216 @@ +#include "selfdrive/modeld/thneed/thneed.h" + +#include +#include +#include + +#include "common/clutil.h" +#include "common/timing.h" + +map, string> g_args; +map, int> g_args_size; +map g_program_source; + +void Thneed::stop() { + //printf("Thneed::stop: recorded %lu commands\n", cmds.size()); + record = false; +} + +void Thneed::clinit() { + device_id = cl_get_device_id(CL_DEVICE_TYPE_DEFAULT); + if (context == NULL) context = CL_CHECK_ERR(clCreateContext(NULL, 1, &device_id, NULL, NULL, &err)); + //cl_command_queue_properties props[3] = {CL_QUEUE_PROPERTIES, CL_QUEUE_PROFILING_ENABLE, 0}; + cl_command_queue_properties props[3] = {CL_QUEUE_PROPERTIES, 0, 0}; + command_queue = CL_CHECK_ERR(clCreateCommandQueueWithProperties(context, device_id, props, &err)); + printf("Thneed::clinit done\n"); +} + +cl_int Thneed::clexec() { + if (debug >= 1) printf("Thneed::clexec: running %lu queued kernels\n", kq.size()); + for (auto &k : kq) { + if (record) ckq.push_back(k); + cl_int ret = k->exec(); + assert(ret == CL_SUCCESS); + } + return clFinish(command_queue); +} + +void Thneed::copy_inputs(float **finputs, bool internal) { + for (int idx = 0; idx < inputs.size(); ++idx) { + if (debug >= 1) printf("copying %lu -- %p -> %p (cl %p)\n", input_sizes[idx], finputs[idx], inputs[idx], input_clmem[idx]); + + if (internal) { + // if it's internal, using memcpy is fine since the buffer sync is cached in the ioctl layer + if (finputs[idx] != NULL) memcpy(inputs[idx], finputs[idx], input_sizes[idx]); + } else { + if (finputs[idx] != NULL) CL_CHECK(clEnqueueWriteBuffer(command_queue, input_clmem[idx], CL_TRUE, 0, input_sizes[idx], finputs[idx], 0, NULL, NULL)); + } + } +} + +void Thneed::copy_output(float *foutput) { + if (output != NULL) { + size_t sz; + clGetMemObjectInfo(output, CL_MEM_SIZE, sizeof(sz), &sz, NULL); + if (debug >= 1) printf("copying %lu for output %p -> %p\n", sz, output, foutput); + CL_CHECK(clEnqueueReadBuffer(command_queue, output, CL_TRUE, 0, sz, foutput, 0, NULL, NULL)); + } else { + printf("CAUTION: model output is NULL, does it have no outputs?\n"); + } +} + +// *********** CLQueuedKernel *********** + +CLQueuedKernel::CLQueuedKernel(Thneed *lthneed, + cl_kernel _kernel, + cl_uint _work_dim, + const size_t *_global_work_size, + const size_t *_local_work_size) { + thneed = lthneed; + kernel = _kernel; + work_dim = _work_dim; + assert(work_dim <= 3); + for (int i = 0; i < work_dim; i++) { + global_work_size[i] = _global_work_size[i]; + local_work_size[i] = _local_work_size[i]; + } + + char _name[0x100]; + clGetKernelInfo(kernel, CL_KERNEL_FUNCTION_NAME, sizeof(_name), _name, NULL); + name = string(_name); + clGetKernelInfo(kernel, CL_KERNEL_NUM_ARGS, sizeof(num_args), &num_args, NULL); + + // get args + for (int i = 0; i < num_args; i++) { + char arg_name[0x100] = {0}; + clGetKernelArgInfo(kernel, i, CL_KERNEL_ARG_NAME, sizeof(arg_name), arg_name, NULL); + arg_names.push_back(string(arg_name)); + clGetKernelArgInfo(kernel, i, CL_KERNEL_ARG_TYPE_NAME, sizeof(arg_name), arg_name, NULL); + arg_types.push_back(string(arg_name)); + + args.push_back(g_args[make_pair(kernel, i)]); + args_size.push_back(g_args_size[make_pair(kernel, i)]); + } + + // get program + clGetKernelInfo(kernel, CL_KERNEL_PROGRAM, sizeof(program), &program, NULL); +} + +int CLQueuedKernel::get_arg_num(const char *search_arg_name) { + for (int i = 0; i < num_args; i++) { + if (arg_names[i] == search_arg_name) return i; + } + printf("failed to find %s in %s\n", search_arg_name, name.c_str()); + assert(false); +} + +cl_int CLQueuedKernel::exec() { + if (kernel == NULL) { + kernel = clCreateKernel(program, name.c_str(), NULL); + arg_names.clear(); + arg_types.clear(); + + for (int j = 0; j < num_args; j++) { + char arg_name[0x100] = {0}; + clGetKernelArgInfo(kernel, j, CL_KERNEL_ARG_NAME, sizeof(arg_name), arg_name, NULL); + arg_names.push_back(string(arg_name)); + clGetKernelArgInfo(kernel, j, CL_KERNEL_ARG_TYPE_NAME, sizeof(arg_name), arg_name, NULL); + arg_types.push_back(string(arg_name)); + + cl_int ret; + if (args[j].size() != 0) { + assert(args[j].size() == args_size[j]); + ret = thneed_clSetKernelArg(kernel, j, args[j].size(), args[j].data()); + } else { + ret = thneed_clSetKernelArg(kernel, j, args_size[j], NULL); + } + assert(ret == CL_SUCCESS); + } + } + + if (thneed->debug >= 1) { + debug_print(thneed->debug >= 2); + } + + return clEnqueueNDRangeKernel(thneed->command_queue, + kernel, work_dim, NULL, global_work_size, local_work_size, 0, NULL, NULL); +} + +void CLQueuedKernel::debug_print(bool verbose) { + printf("%p %56s -- ", kernel, name.c_str()); + for (int i = 0; i < work_dim; i++) { + printf("%4zu ", global_work_size[i]); + } + printf(" -- "); + for (int i = 0; i < work_dim; i++) { + printf("%4zu ", local_work_size[i]); + } + printf("\n"); + + if (verbose) { + for (int i = 0; i < num_args; i++) { + string arg = args[i]; + printf(" %s %s", arg_types[i].c_str(), arg_names[i].c_str()); + void *arg_value = (void*)arg.data(); + int arg_size = arg.size(); + if (arg_size == 0) { + printf(" (size) %d", args_size[i]); + } else if (arg_size == 1) { + printf(" = %d", *((char*)arg_value)); + } else if (arg_size == 2) { + printf(" = %d", *((short*)arg_value)); + } else if (arg_size == 4) { + if (arg_types[i] == "float") { + printf(" = %f", *((float*)arg_value)); + } else { + printf(" = %d", *((int*)arg_value)); + } + } else if (arg_size == 8) { + cl_mem val = (cl_mem)(*((uintptr_t*)arg_value)); + printf(" = %p", val); + if (val != NULL) { + cl_mem_object_type obj_type; + clGetMemObjectInfo(val, CL_MEM_TYPE, sizeof(obj_type), &obj_type, NULL); + if (arg_types[i] == "image2d_t" || arg_types[i] == "image1d_t" || obj_type == CL_MEM_OBJECT_IMAGE2D) { + cl_image_format format; + size_t width, height, depth, array_size, row_pitch, slice_pitch; + cl_mem buf; + clGetImageInfo(val, CL_IMAGE_FORMAT, sizeof(format), &format, NULL); + assert(format.image_channel_order == CL_RGBA); + assert(format.image_channel_data_type == CL_HALF_FLOAT || format.image_channel_data_type == CL_FLOAT); + clGetImageInfo(val, CL_IMAGE_WIDTH, sizeof(width), &width, NULL); + clGetImageInfo(val, CL_IMAGE_HEIGHT, sizeof(height), &height, NULL); + clGetImageInfo(val, CL_IMAGE_ROW_PITCH, sizeof(row_pitch), &row_pitch, NULL); + clGetImageInfo(val, CL_IMAGE_DEPTH, sizeof(depth), &depth, NULL); + clGetImageInfo(val, CL_IMAGE_ARRAY_SIZE, sizeof(array_size), &array_size, NULL); + clGetImageInfo(val, CL_IMAGE_SLICE_PITCH, sizeof(slice_pitch), &slice_pitch, NULL); + assert(depth == 0); + assert(array_size == 0); + assert(slice_pitch == 0); + + clGetImageInfo(val, CL_IMAGE_BUFFER, sizeof(buf), &buf, NULL); + size_t sz = 0; + if (buf != NULL) clGetMemObjectInfo(buf, CL_MEM_SIZE, sizeof(sz), &sz, NULL); + printf(" image %zu x %zu rp %zu @ %p buffer %zu", width, height, row_pitch, buf, sz); + } else { + size_t sz; + clGetMemObjectInfo(val, CL_MEM_SIZE, sizeof(sz), &sz, NULL); + printf(" buffer %zu", sz); + } + } + } + printf("\n"); + } + } +} + +cl_int thneed_clSetKernelArg(cl_kernel kernel, cl_uint arg_index, size_t arg_size, const void *arg_value) { + g_args_size[make_pair(kernel, arg_index)] = arg_size; + if (arg_value != NULL) { + g_args[make_pair(kernel, arg_index)] = string((char*)arg_value, arg_size); + } else { + g_args[make_pair(kernel, arg_index)] = string(""); + } + cl_int ret = clSetKernelArg(kernel, arg_index, arg_size, arg_value); + return ret; +} diff --git a/selfdrive/modeld/thneed/thneed_pc.cc b/selfdrive/modeld/thneed/thneed_pc.cc new file mode 100644 index 0000000000..8d0037628e --- /dev/null +++ b/selfdrive/modeld/thneed/thneed_pc.cc @@ -0,0 +1,32 @@ +#include "selfdrive/modeld/thneed/thneed.h" + +#include + +#include "common/clutil.h" +#include "common/timing.h" + +Thneed::Thneed(bool do_clinit, cl_context _context) { + context = _context; + if (do_clinit) clinit(); + char *thneed_debug_env = getenv("THNEED_DEBUG"); + debug = (thneed_debug_env != NULL) ? atoi(thneed_debug_env) : 0; +} + +void Thneed::execute(float **finputs, float *foutput, bool slow) { + uint64_t tb, te; + if (debug >= 1) tb = nanos_since_boot(); + + // ****** copy inputs + copy_inputs(finputs); + + // ****** run commands + clexec(); + + // ****** copy outputs + copy_output(foutput); + + if (debug >= 1) { + te = nanos_since_boot(); + printf("model exec in %lu us\n", (te-tb)/1000); + } +} diff --git a/selfdrive/modeld/thneed/thneed_qcom2.cc b/selfdrive/modeld/thneed/thneed_qcom2.cc new file mode 100644 index 0000000000..a29a82c8c8 --- /dev/null +++ b/selfdrive/modeld/thneed/thneed_qcom2.cc @@ -0,0 +1,283 @@ +#include "selfdrive/modeld/thneed/thneed.h" + +#include +#include + +#include +#include +#include +#include +#include + +#include "common/clutil.h" +#include "common/timing.h" + +Thneed *g_thneed = NULL; +int g_fd = -1; + +void hexdump(uint8_t *d, int len) { + assert((len%4) == 0); + printf(" dumping %p len 0x%x\n", d, len); + for (int i = 0; i < len/4; i++) { + if (i != 0 && (i%0x10) == 0) printf("\n"); + printf("%8x ", d[i]); + } + printf("\n"); +} + +// *********** ioctl interceptor *********** + +extern "C" { + +int (*my_ioctl)(int filedes, unsigned long request, void *argp) = NULL; +#undef ioctl +int ioctl(int filedes, unsigned long request, void *argp) { + request &= 0xFFFFFFFF; // needed on QCOM2 + if (my_ioctl == NULL) my_ioctl = reinterpret_cast(dlsym(RTLD_NEXT, "ioctl")); + Thneed *thneed = g_thneed; + + // save the fd + if (request == IOCTL_KGSL_GPUOBJ_ALLOC) g_fd = filedes; + + // note that this runs always, even without a thneed object + if (request == IOCTL_KGSL_DRAWCTXT_CREATE) { + struct kgsl_drawctxt_create *create = (struct kgsl_drawctxt_create *)argp; + create->flags &= ~KGSL_CONTEXT_PRIORITY_MASK; + create->flags |= 1 << KGSL_CONTEXT_PRIORITY_SHIFT; // priority from 1-15, 1 is max priority + printf("IOCTL_KGSL_DRAWCTXT_CREATE: creating context with flags 0x%x\n", create->flags); + } + + if (thneed != NULL) { + if (request == IOCTL_KGSL_GPU_COMMAND) { + struct kgsl_gpu_command *cmd = (struct kgsl_gpu_command *)argp; + if (thneed->record) { + thneed->timestamp = cmd->timestamp; + thneed->context_id = cmd->context_id; + thneed->cmds.push_back(unique_ptr(new CachedCommand(thneed, cmd))); + } + if (thneed->debug >= 1) { + printf("IOCTL_KGSL_GPU_COMMAND(%2zu): flags: 0x%lx context_id: %u timestamp: %u numcmds: %d numobjs: %d\n", + thneed->cmds.size(), + cmd->flags, + cmd->context_id, cmd->timestamp, cmd->numcmds, cmd->numobjs); + } + } else if (request == IOCTL_KGSL_GPUOBJ_SYNC) { + struct kgsl_gpuobj_sync *cmd = (struct kgsl_gpuobj_sync *)argp; + struct kgsl_gpuobj_sync_obj *objs = (struct kgsl_gpuobj_sync_obj *)(cmd->objs); + + if (thneed->debug >= 2) { + printf("IOCTL_KGSL_GPUOBJ_SYNC count:%d ", cmd->count); + for (int i = 0; i < cmd->count; i++) { + printf(" -- offset:0x%lx len:0x%lx id:%d op:%d ", objs[i].offset, objs[i].length, objs[i].id, objs[i].op); + } + printf("\n"); + } + + if (thneed->record) { + thneed->cmds.push_back(unique_ptr(new + CachedSync(thneed, string((char *)objs, sizeof(struct kgsl_gpuobj_sync_obj)*cmd->count)))); + } + } else if (request == IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID) { + struct kgsl_device_waittimestamp_ctxtid *cmd = (struct kgsl_device_waittimestamp_ctxtid *)argp; + if (thneed->debug >= 1) { + printf("IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID: context_id: %d timestamp: %d timeout: %d\n", + cmd->context_id, cmd->timestamp, cmd->timeout); + } + } else if (request == IOCTL_KGSL_SETPROPERTY) { + if (thneed->debug >= 1) { + struct kgsl_device_getproperty *prop = (struct kgsl_device_getproperty *)argp; + printf("IOCTL_KGSL_SETPROPERTY: 0x%x sizebytes:%zu\n", prop->type, prop->sizebytes); + if (thneed->debug >= 2) { + hexdump((uint8_t *)prop->value, prop->sizebytes); + if (prop->type == KGSL_PROP_PWR_CONSTRAINT) { + struct kgsl_device_constraint *constraint = (struct kgsl_device_constraint *)prop->value; + hexdump((uint8_t *)constraint->data, constraint->size); + } + } + } + } else if (request == IOCTL_KGSL_DRAWCTXT_CREATE || request == IOCTL_KGSL_DRAWCTXT_DESTROY) { + // this happens + } else if (request == IOCTL_KGSL_GPUOBJ_ALLOC || request == IOCTL_KGSL_GPUOBJ_FREE) { + // this happens + } else { + if (thneed->debug >= 1) { + printf("other ioctl %lx\n", request); + } + } + } + + int ret = my_ioctl(filedes, request, argp); + if (ret != 0) printf("ioctl returned %d with errno %d\n", ret, errno); + return ret; +} + +} + +// *********** GPUMalloc *********** + +GPUMalloc::GPUMalloc(int size, int fd) { + struct kgsl_gpuobj_alloc alloc; + memset(&alloc, 0, sizeof(alloc)); + alloc.size = size; + alloc.flags = 0x10000a00; + ioctl(fd, IOCTL_KGSL_GPUOBJ_ALLOC, &alloc); + void *addr = mmap64(NULL, alloc.mmapsize, 0x3, 0x1, fd, alloc.id*0x1000); + assert(addr != MAP_FAILED); + + base = (uint64_t)addr; + remaining = size; +} + +GPUMalloc::~GPUMalloc() { + // TODO: free the GPU malloced area +} + +void *GPUMalloc::alloc(int size) { + void *ret = (void*)base; + size = (size+0xff) & (~0xFF); + assert(size <= remaining); + remaining -= size; + base += size; + return ret; +} + +// *********** CachedSync, at the ioctl layer *********** + +void CachedSync::exec() { + struct kgsl_gpuobj_sync cmd; + + cmd.objs = (uint64_t)data.data(); + cmd.obj_len = data.length(); + cmd.count = data.length() / sizeof(struct kgsl_gpuobj_sync_obj); + + int ret = ioctl(thneed->fd, IOCTL_KGSL_GPUOBJ_SYNC, &cmd); + assert(ret == 0); +} + +// *********** CachedCommand, at the ioctl layer *********** + +CachedCommand::CachedCommand(Thneed *lthneed, struct kgsl_gpu_command *cmd) { + thneed = lthneed; + assert(cmd->numsyncs == 0); + + memcpy(&cache, cmd, sizeof(cache)); + + if (cmd->numcmds > 0) { + cmds = make_unique(cmd->numcmds); + memcpy(cmds.get(), (void *)cmd->cmdlist, sizeof(struct kgsl_command_object)*cmd->numcmds); + cache.cmdlist = (uint64_t)cmds.get(); + for (int i = 0; i < cmd->numcmds; i++) { + void *nn = thneed->ram->alloc(cmds[i].size); + memcpy(nn, (void*)cmds[i].gpuaddr, cmds[i].size); + cmds[i].gpuaddr = (uint64_t)nn; + } + } + + if (cmd->numobjs > 0) { + objs = make_unique(cmd->numobjs); + memcpy(objs.get(), (void *)cmd->objlist, sizeof(struct kgsl_command_object)*cmd->numobjs); + cache.objlist = (uint64_t)objs.get(); + for (int i = 0; i < cmd->numobjs; i++) { + void *nn = thneed->ram->alloc(objs[i].size); + memset(nn, 0, objs[i].size); + objs[i].gpuaddr = (uint64_t)nn; + } + } + + kq = thneed->ckq; + thneed->ckq.clear(); +} + +void CachedCommand::exec() { + cache.timestamp = ++thneed->timestamp; + int ret = ioctl(thneed->fd, IOCTL_KGSL_GPU_COMMAND, &cache); + + if (thneed->debug >= 1) printf("CachedCommand::exec got %d\n", ret); + + if (thneed->debug >= 2) { + for (auto &it : kq) { + it->debug_print(false); + } + } + + assert(ret == 0); +} + +// *********** Thneed *********** + +Thneed::Thneed(bool do_clinit, cl_context _context) { + // TODO: QCOM2 actually requires a different context + //context = _context; + if (do_clinit) clinit(); + assert(g_fd != -1); + fd = g_fd; + ram = make_unique(0x80000, fd); + timestamp = -1; + g_thneed = this; + char *thneed_debug_env = getenv("THNEED_DEBUG"); + debug = (thneed_debug_env != NULL) ? atoi(thneed_debug_env) : 0; +} + +void Thneed::wait() { + struct kgsl_device_waittimestamp_ctxtid wait; + wait.context_id = context_id; + wait.timestamp = timestamp; + wait.timeout = -1; + + uint64_t tb = nanos_since_boot(); + int wret = ioctl(fd, IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID, &wait); + uint64_t te = nanos_since_boot(); + + if (debug >= 1) printf("wait %d after %lu us\n", wret, (te-tb)/1000); +} + +void Thneed::execute(float **finputs, float *foutput, bool slow) { + uint64_t tb, te; + if (debug >= 1) tb = nanos_since_boot(); + + // ****** copy inputs + copy_inputs(finputs, true); + + // ****** set power constraint + int ret; + struct kgsl_device_constraint_pwrlevel pwrlevel; + pwrlevel.level = KGSL_CONSTRAINT_PWR_MAX; + + struct kgsl_device_constraint constraint; + constraint.type = KGSL_CONSTRAINT_PWRLEVEL; + constraint.context_id = context_id; + constraint.data = (void*)&pwrlevel; + constraint.size = sizeof(pwrlevel); + + struct kgsl_device_getproperty prop; + prop.type = KGSL_PROP_PWR_CONSTRAINT; + prop.value = (void*)&constraint; + prop.sizebytes = sizeof(constraint); + ret = ioctl(fd, IOCTL_KGSL_SETPROPERTY, &prop); + assert(ret == 0); + + // ****** run commands + int i = 0; + for (auto &it : cmds) { + ++i; + if (debug >= 1) printf("run %2d @ %7lu us: ", i, (nanos_since_boot()-tb)/1000); + it->exec(); + if ((i == cmds.size()) || slow) wait(); + } + + // ****** copy outputs + copy_output(foutput); + + // ****** unset power constraint + constraint.type = KGSL_CONSTRAINT_NONE; + constraint.data = NULL; + constraint.size = 0; + + ret = ioctl(fd, IOCTL_KGSL_SETPROPERTY, &prop); + assert(ret == 0); + + if (debug >= 1) { + te = nanos_since_boot(); + printf("model exec in %lu us\n", (te-tb)/1000); + } +} diff --git a/selfdrive/modeld/transforms/loadyuv.h b/selfdrive/modeld/transforms/loadyuv.h index a3161b2935..7d27ef5d46 100644 --- a/selfdrive/modeld/transforms/loadyuv.h +++ b/selfdrive/modeld/transforms/loadyuv.h @@ -1,6 +1,6 @@ #pragma once -#include "selfdrive/common/clutil.h" +#include "common/clutil.h" typedef struct { int width, height; diff --git a/selfdrive/modeld/transforms/transform.cc b/selfdrive/modeld/transforms/transform.cc index 5f4929bab3..f341314144 100644 --- a/selfdrive/modeld/transforms/transform.cc +++ b/selfdrive/modeld/transforms/transform.cc @@ -3,7 +3,7 @@ #include #include -#include "selfdrive/common/clutil.h" +#include "common/clutil.h" void transform_init(Transform* s, cl_context ctx, cl_device_id device_id) { memset(s, 0, sizeof(*s)); @@ -25,14 +25,14 @@ void transform_destroy(Transform* s) { void transform_queue(Transform* s, cl_command_queue q, - cl_mem in_yuv, int in_width, int in_height, + cl_mem in_yuv, int in_width, int in_height, int in_stride, int in_uv_offset, cl_mem out_y, cl_mem out_u, cl_mem out_v, int out_width, int out_height, const mat3& projection) { const int zero = 0; // sampled using pixel center origin - // (because thats how fastcv and opencv does it) + // (because that's how fastcv and opencv does it) mat3 projection_y = projection; @@ -44,28 +44,30 @@ void transform_queue(Transform* s, const int in_y_width = in_width; const int in_y_height = in_height; + const int in_y_px_stride = 1; const int in_uv_width = in_width/2; const int in_uv_height = in_height/2; - const int in_y_offset = 0; - const int in_u_offset = in_y_offset + in_y_width*in_y_height; - const int in_v_offset = in_u_offset + in_uv_width*in_uv_height; + const int in_uv_px_stride = 2; + const int in_u_offset = in_uv_offset; + const int in_v_offset = in_uv_offset + 1; const int out_y_width = out_width; const int out_y_height = out_height; const int out_uv_width = out_width/2; const int out_uv_height = out_height/2; - CL_CHECK(clSetKernelArg(s->krnl, 0, sizeof(cl_mem), &in_yuv)); - CL_CHECK(clSetKernelArg(s->krnl, 1, sizeof(cl_int), &in_y_width)); - CL_CHECK(clSetKernelArg(s->krnl, 2, sizeof(cl_int), &in_y_offset)); - CL_CHECK(clSetKernelArg(s->krnl, 3, sizeof(cl_int), &in_y_height)); - CL_CHECK(clSetKernelArg(s->krnl, 4, sizeof(cl_int), &in_y_width)); - CL_CHECK(clSetKernelArg(s->krnl, 5, sizeof(cl_mem), &out_y)); - CL_CHECK(clSetKernelArg(s->krnl, 6, sizeof(cl_int), &out_y_width)); - CL_CHECK(clSetKernelArg(s->krnl, 7, sizeof(cl_int), &zero)); - CL_CHECK(clSetKernelArg(s->krnl, 8, sizeof(cl_int), &out_y_height)); - CL_CHECK(clSetKernelArg(s->krnl, 9, sizeof(cl_int), &out_y_width)); - CL_CHECK(clSetKernelArg(s->krnl, 10, sizeof(cl_mem), &s->m_y_cl)); + CL_CHECK(clSetKernelArg(s->krnl, 0, sizeof(cl_mem), &in_yuv)); // src + CL_CHECK(clSetKernelArg(s->krnl, 1, sizeof(cl_int), &in_stride)); // src_row_stride + CL_CHECK(clSetKernelArg(s->krnl, 2, sizeof(cl_int), &in_y_px_stride)); // src_px_stride + CL_CHECK(clSetKernelArg(s->krnl, 3, sizeof(cl_int), &zero)); // src_offset + CL_CHECK(clSetKernelArg(s->krnl, 4, sizeof(cl_int), &in_y_height)); // src_rows + CL_CHECK(clSetKernelArg(s->krnl, 5, sizeof(cl_int), &in_y_width)); // src_cols + CL_CHECK(clSetKernelArg(s->krnl, 6, sizeof(cl_mem), &out_y)); // dst + CL_CHECK(clSetKernelArg(s->krnl, 7, sizeof(cl_int), &out_y_width)); // dst_row_stride + CL_CHECK(clSetKernelArg(s->krnl, 8, sizeof(cl_int), &zero)); // dst_offset + CL_CHECK(clSetKernelArg(s->krnl, 9, sizeof(cl_int), &out_y_height)); // dst_rows + CL_CHECK(clSetKernelArg(s->krnl, 10, sizeof(cl_int), &out_y_width)); // dst_cols + CL_CHECK(clSetKernelArg(s->krnl, 11, sizeof(cl_mem), &s->m_y_cl)); // M const size_t work_size_y[2] = {(size_t)out_y_width, (size_t)out_y_height}; @@ -74,21 +76,21 @@ void transform_queue(Transform* s, const size_t work_size_uv[2] = {(size_t)out_uv_width, (size_t)out_uv_height}; - CL_CHECK(clSetKernelArg(s->krnl, 1, sizeof(cl_int), &in_uv_width)); - CL_CHECK(clSetKernelArg(s->krnl, 2, sizeof(cl_int), &in_u_offset)); - CL_CHECK(clSetKernelArg(s->krnl, 3, sizeof(cl_int), &in_uv_height)); - CL_CHECK(clSetKernelArg(s->krnl, 4, sizeof(cl_int), &in_uv_width)); - CL_CHECK(clSetKernelArg(s->krnl, 5, sizeof(cl_mem), &out_u)); - CL_CHECK(clSetKernelArg(s->krnl, 6, sizeof(cl_int), &out_uv_width)); - CL_CHECK(clSetKernelArg(s->krnl, 7, sizeof(cl_int), &zero)); - CL_CHECK(clSetKernelArg(s->krnl, 8, sizeof(cl_int), &out_uv_height)); - CL_CHECK(clSetKernelArg(s->krnl, 9, sizeof(cl_int), &out_uv_width)); - CL_CHECK(clSetKernelArg(s->krnl, 10, sizeof(cl_mem), &s->m_uv_cl)); - + CL_CHECK(clSetKernelArg(s->krnl, 2, sizeof(cl_int), &in_uv_px_stride)); // src_px_stride + CL_CHECK(clSetKernelArg(s->krnl, 3, sizeof(cl_int), &in_u_offset)); // src_offset + CL_CHECK(clSetKernelArg(s->krnl, 4, sizeof(cl_int), &in_uv_height)); // src_rows + CL_CHECK(clSetKernelArg(s->krnl, 5, sizeof(cl_int), &in_uv_width)); // src_cols + CL_CHECK(clSetKernelArg(s->krnl, 6, sizeof(cl_mem), &out_u)); // dst + CL_CHECK(clSetKernelArg(s->krnl, 7, sizeof(cl_int), &out_uv_width)); // dst_row_stride + CL_CHECK(clSetKernelArg(s->krnl, 8, sizeof(cl_int), &zero)); // dst_offset + CL_CHECK(clSetKernelArg(s->krnl, 9, sizeof(cl_int), &out_uv_height)); // dst_rows + CL_CHECK(clSetKernelArg(s->krnl, 10, sizeof(cl_int), &out_uv_width)); // dst_cols + CL_CHECK(clSetKernelArg(s->krnl, 11, sizeof(cl_mem), &s->m_uv_cl)); // M + CL_CHECK(clEnqueueNDRangeKernel(q, s->krnl, 2, NULL, (const size_t*)&work_size_uv, NULL, 0, 0, NULL)); - CL_CHECK(clSetKernelArg(s->krnl, 2, sizeof(cl_int), &in_v_offset)); - CL_CHECK(clSetKernelArg(s->krnl, 5, sizeof(cl_mem), &out_v)); + CL_CHECK(clSetKernelArg(s->krnl, 3, sizeof(cl_int), &in_v_offset)); // src_ofset + CL_CHECK(clSetKernelArg(s->krnl, 6, sizeof(cl_mem), &out_v)); // dst CL_CHECK(clEnqueueNDRangeKernel(q, s->krnl, 2, NULL, (const size_t*)&work_size_uv, NULL, 0, 0, NULL)); diff --git a/selfdrive/modeld/transforms/transform.cl b/selfdrive/modeld/transforms/transform.cl index 8ad1869351..357ef87321 100644 --- a/selfdrive/modeld/transforms/transform.cl +++ b/selfdrive/modeld/transforms/transform.cl @@ -6,9 +6,9 @@ #define INTER_REMAP_COEF_SCALE (1 << INTER_REMAP_COEF_BITS) __kernel void warpPerspective(__global const uchar * src, - int src_step, int src_offset, int src_rows, int src_cols, + int src_row_stride, int src_px_stride, int src_offset, int src_rows, int src_cols, __global uchar * dst, - int dst_step, int dst_offset, int dst_rows, int dst_cols, + int dst_row_stride, int dst_offset, int dst_rows, int dst_cols, __constant float * M) { int dx = get_global_id(0); @@ -28,18 +28,18 @@ __kernel void warpPerspective(__global const uchar * src, short ax = (short)(X & (INTER_TAB_SIZE - 1)); int v0 = (sx >= 0 && sx < src_cols && sy >= 0 && sy < src_rows) ? - convert_int(src[mad24(sy, src_step, src_offset + sx)]) : 0; + convert_int(src[mad24(sy, src_row_stride, src_offset + sx*src_px_stride)]) : 0; int v1 = (sx+1 >= 0 && sx+1 < src_cols && sy >= 0 && sy < src_rows) ? - convert_int(src[mad24(sy, src_step, src_offset + (sx+1))]) : 0; + convert_int(src[mad24(sy, src_row_stride, src_offset + (sx+1)*src_px_stride)]) : 0; int v2 = (sx >= 0 && sx < src_cols && sy+1 >= 0 && sy+1 < src_rows) ? - convert_int(src[mad24(sy+1, src_step, src_offset + sx)]) : 0; + convert_int(src[mad24(sy+1, src_row_stride, src_offset + sx*src_px_stride)]) : 0; int v3 = (sx+1 >= 0 && sx+1 < src_cols && sy+1 >= 0 && sy+1 < src_rows) ? - convert_int(src[mad24(sy+1, src_step, src_offset + (sx+1))]) : 0; + convert_int(src[mad24(sy+1, src_row_stride, src_offset + (sx+1)*src_px_stride)]) : 0; float taby = 1.f/INTER_TAB_SIZE*ay; float tabx = 1.f/INTER_TAB_SIZE*ax; - int dst_index = mad24(dy, dst_step, dst_offset + dx); + int dst_index = mad24(dy, dst_row_stride, dst_offset + dx); int itab0 = convert_short_sat_rte( (1.0f-taby)*(1.0f-tabx) * INTER_REMAP_COEF_SCALE ); int itab1 = convert_short_sat_rte( (1.0f-taby)*tabx * INTER_REMAP_COEF_SCALE ); diff --git a/selfdrive/modeld/transforms/transform.h b/selfdrive/modeld/transforms/transform.h index f34613684c..771a7054b3 100644 --- a/selfdrive/modeld/transforms/transform.h +++ b/selfdrive/modeld/transforms/transform.h @@ -7,7 +7,7 @@ #include #endif -#include "selfdrive/common/mat.h" +#include "common/mat.h" typedef struct { cl_kernel krnl; @@ -19,7 +19,7 @@ void transform_init(Transform* s, cl_context ctx, cl_device_id device_id); void transform_destroy(Transform* transform); void transform_queue(Transform* s, cl_command_queue q, - cl_mem yuv, int in_width, int in_height, + cl_mem yuv, int in_width, int in_height, int in_stride, int in_uv_offset, cl_mem out_y, cl_mem out_u, cl_mem out_v, int out_width, int out_height, const mat3& projection); diff --git a/selfdrive/modeld/visiontest.c b/selfdrive/modeld/visiontest.c deleted file mode 100644 index fcc3539040..0000000000 --- a/selfdrive/modeld/visiontest.c +++ /dev/null @@ -1,111 +0,0 @@ -#include -#include -#include - -#define CL_USE_DEPRECATED_OPENCL_1_2_APIS -#ifdef __APPLE__ -#include -#else -#include -#endif - -#include "selfdrive/common/clutil.h" -#include "selfdrive/modeld/transforms/transform.h" - -typedef struct { - int disable_model; - Transform transform; - - int in_width; - int in_height; - int out_width; - int out_height; - - cl_context context; - cl_command_queue command_queue; - cl_device_id device_id; - - size_t in_yuv_size; - cl_mem in_yuv_cl; - - cl_mem out_y_cl, out_u_cl, out_v_cl; -} VisionTest; - -void initialize_opencl(VisionTest* visiontest) { - // init cl - cl_device_id device_id = cl_get_device_id(CL_DEVICE_TYPE_CPU); - visiontest->context = CL_CHECK_ERR(clCreateContext(NULL, 1, &device_id, NULL, NULL, &err)); - visiontest->device_id = device_id; -} - -VisionTest* visiontest_create(int temporal_model, int disable_model, - int input_width, int input_height, - int model_input_width, int model_input_height) { - VisionTest* const vt = calloc(1, sizeof(*vt)); - assert(vt); - - vt->disable_model = disable_model; - vt->in_width = input_width; - vt->in_height = input_height; - vt->out_width = model_input_width; - vt->out_height = model_input_height; - - initialize_opencl(vt); - - transform_init(&vt->transform, vt->context, vt->device_id); - - - assert((vt->in_width%2) == 0 && (vt->in_height%2) == 0); - vt->in_yuv_size = vt->in_width*vt->in_height*3/2; - vt->in_yuv_cl = CL_CHECK_ERR(clCreateBuffer(vt->context, CL_MEM_READ_WRITE, - vt->in_yuv_size, NULL, &err)); - vt->out_y_cl = CL_CHECK_ERR(clCreateBuffer(vt->context, CL_MEM_READ_WRITE, - vt->out_width*vt->out_width, NULL, &err)); - vt->out_u_cl = CL_CHECK_ERR(clCreateBuffer(vt->context, CL_MEM_READ_WRITE, - vt->out_width*vt->out_width/4, NULL, &err)); - vt->out_v_cl = CL_CHECK_ERR(clCreateBuffer(vt->context, CL_MEM_READ_WRITE, - vt->out_width*vt->out_width/4, NULL, &err)); - vt->command_queue = CL_CHECK_ERR(clCreateCommandQueue(vt->context, vt->device_id, 0, &err)); - return vt; -} - -void visiontest_destroy(VisionTest* vt) { - transform_destroy(&vt->transform); - - CL_CHECK(clReleaseMemObject(vt->in_yuv_cl)); - CL_CHECK(clReleaseMemObject(vt->out_y_cl)); - CL_CHECK(clReleaseMemObject(vt->out_u_cl)); - CL_CHECK(clReleaseMemObject(vt->out_v_cl)); - CL_CHECK(clReleaseCommandQueue(vt->command_queue)); - CL_CHECK(clReleaseContext(vt->context)); - - free(vt); -} - -void visiontest_transform(VisionTest* vt, const uint8_t* yuv_data, - uint8_t* out_y, uint8_t* out_u, uint8_t* out_v, - const float* transform) { - CL_CHECK(clEnqueueWriteBuffer(vt->command_queue, vt->in_yuv_cl, CL_FALSE, - 0, vt->in_yuv_size, yuv_data, 0, NULL, NULL)); - - mat3 transform_m = *(const mat3*)transform; - - transform_queue(&vt->transform, vt->command_queue, - vt->in_yuv_cl, vt->in_width, vt->in_height, - vt->out_y_cl, vt->out_u_cl, vt->out_v_cl, - vt->out_width, vt->out_height, - transform_m); - - CL_CHECK(clEnqueueReadBuffer(vt->command_queue, vt->out_y_cl, CL_FALSE, - 0, vt->out_width*vt->out_height, out_y, - 0, NULL, NULL)); - CL_CHECK(clEnqueueReadBuffer(vt->command_queue, vt->out_u_cl, CL_FALSE, - 0, vt->out_width*vt->out_height/4, out_u, - 0, NULL, NULL)); - CL_CHECK(clEnqueueReadBuffer(vt->command_queue, vt->out_v_cl, CL_FALSE, - 0, vt->out_width*vt->out_height/4, out_v, - 0, NULL, NULL)); - - clFinish(vt->command_queue); -} - diff --git a/selfdrive/modeld/visiontest.mk b/selfdrive/modeld/visiontest.mk deleted file mode 100644 index 1df504e93a..0000000000 --- a/selfdrive/modeld/visiontest.mk +++ /dev/null @@ -1,104 +0,0 @@ -CC:=clang -CXX:=clang++ -OPT_FLAGS:=-O2 -g -ggdb3 - -UNAME_S := $(shell uname -s) -ifeq ($(UNAME_S),Linux) - SHARED_FLAGS=-Wl,--whole-archive $^ -Wl,--no-whole-archive -endif -ifeq ($(UNAME_S),Darwin) - SHARED_FLAGS=-Wl,-force_load $^ -endif - -PHONELIBS := ../../third_party -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 $(OPT_FLAGS) $(WARN_FLAGS) -CXXFLAGS = -std=c++1z -fPIC $(OPT_FLAGS) $(WARN_FLAGS) - -EIGEN_FLAGS = -I$(PHONELIBS)/eigen - -CEREAL_LIBS = $(BASEDIR)/cereal/libmessaging.a - -OPENCV_LIBS = -lopencv_video -lopencv_core -lopencv_imgproc - -ifeq ($(UNAME_S),Darwin) - VT_LDFLAGS += $(PHONELIBS)/capnp-c/mac/lib/libcapnp_c.a \ - $(PHONELIBS)/zmq/mac/lib/libzmq.a \ - -framework OpenCL - - OPENCV_LIBS += -L/usr/local/opt/opencv@2/lib - OPENCV_FLAGS += -I/usr/local/opt/opencv@2/include - -else - VT_LDFLAGS += $(CEREAL_LIBS) \ - -L/system/vendor/lib64 \ - -L$(BASEDIR)/external/zmq/lib/ \ - -l:libzmq.a \ - -lOpenCL -endif - -.PHONY: all visiontest clean test -all: visiontest - -libvisiontest_inputs := visiontest.c \ - transforms/transform.cc \ - transforms/loadyuv.cc \ - ../common/clutil.cc \ - $(BASEDIR)/selfdrive/common/util.c \ - $(CEREAL_OBJS) - -visiontest: libvisiontest.so -all-tests := $(addsuffix .test, $(basename $(wildcard test_*))) - -%.o: %.cc - @echo "[ CXX ] $@" - $(CXX) $(CXXFLAGS) -MMD \ - -I. -I.. -I../.. \ - -Wall \ - -I$(BASEDIR)/ -I$(BASEDIR)/selfdrive -I$(BASEDIR)/selfdrive/common \ - $(EIGEN_FLAGS) \ - $(OPENCV_FLAGS) \ - $(CEREAL_CXXFLAGS) \ - -c -o '$@' '$<' - -%.o: %.c - @echo "[ CXX ] $@" - $(CC) $(CFLAGS) -MMD \ - -I. -I.. -I../.. \ - -Wall \ - -I$(BASEDIR)/ -I$(BASEDIR)/selfdrive -I$(BASEDIR)/selfdrive/common \ - $(CEREAL_CFLAGS) \ - -c -o '$@' '$<' - -libvisiontest.so: $(libvisiontest_inputs) - $(eval $@_TMP := $(shell mktemp)) - $(CC) -std=gnu11 -shared -fPIC -O2 -g \ - -Werror=implicit-function-declaration -Werror=incompatible-pointer-types \ - -Werror=int-conversion -Wno-pointer-to-int-cast \ - -I. \ - $^ -o $($@_TMP) \ - -I$(PHONELIBS)/opencl/include \ - -I$(BASEDIR)/selfdrive/common \ - $(CEREAL_CXXFLAGS) \ - $(CEREAL_CFLAGS) \ - -I$(BASEDIR)/external/zmq/include \ - -I$(BASEDIR)/ -I$(BASEDIR)/selfdrive \ - -lstdc++ \ - $(VT_LDFLAGS) \ - -lm -lpthread - mv $($@_TMP) $@ - -test : $(all-tests) - -test_%.test : test_% - @./'$<' || echo FAIL - -clean: - rm -rf *.o *.so *.a diff --git a/selfdrive/modeld/visiontest.py b/selfdrive/modeld/visiontest.py deleted file mode 100644 index 1e30c05449..0000000000 --- a/selfdrive/modeld/visiontest.py +++ /dev/null @@ -1,135 +0,0 @@ -import os -import subprocess -from cffi import FFI -from common.basedir import BASEDIR - -# Initialize visiontest. Ignore output. -_visiond_dir = os.path.dirname(os.path.abspath(__file__)) -_libvisiontest = "libvisiontest.so" -try: # because this crashes sometimes when running pipeline - subprocess.check_output(["make", "-C", _visiond_dir, "-f", - os.path.join(_visiond_dir, "visiontest.mk"), - _libvisiontest]) -except Exception: - pass - - -class VisionTest(): - """A version of the vision model that can be run on a desktop. - - WARNING: This class is not thread safe. VisionTest objects cannot be - created or used on multiple threads simultaneously. - """ - - ffi = FFI() - ffi.cdef(""" - typedef unsigned char uint8_t; - - struct VisionTest; - typedef struct VisionTest VisionTest; - - VisionTest* visiontest_create(int temporal_model, int disable_model, - int input_width, int input_height, - int model_input_width, int model_input_height); - void visiontest_destroy(VisionTest* visiontest); - - void visiontest_transform(VisionTest* vt, const uint8_t* yuv_data, - uint8_t* out_y, uint8_t* out_u, uint8_t* out_v, - const float* transform); - """) - - clib = ffi.dlopen(os.path.join(_visiond_dir, _libvisiontest)) - - def __init__(self, input_size, model_input_size, model): - """Create a wrapper around visiond for off-device python code. - - Inputs: - input_size: The size of YUV images passed to transform. - model_input_size: The size of YUV images passed to the model. - model: The name of the model to use. "temporal", "yuv", or None to disable the - model (used to disable OpenCL). - """ - self._input_size = input_size - self._model_input_size = model_input_size - - if model is None: - disable_model = 1 - temporal_model = 0 - elif model == "yuv": - disable_model = 0 - temporal_model = 0 - elif model == "temporal": - disable_model = 0 - temporal_model = 1 - else: - raise ValueError(f"Bad model name: {model}") - - prevdir = os.getcwd() - os.chdir(_visiond_dir) # tmp hack to find kernels - os.environ['BASEDIR'] = BASEDIR - self._visiontest_c = self.clib.visiontest_create( - temporal_model, disable_model, self._input_size[0], self._input_size[1], - self._model_input_size[0], self._model_input_size[1]) - os.chdir(prevdir) - - @property - def input_size(self): - return self._input_size - - @property - def model_input_size(self): - return self._model_input_size - - def transform(self, yuv_data, transform): - y_len = self.model_input_size[0] * self.model_input_size[1] - t_y_ptr = bytearray(y_len) - t_u_ptr = bytearray(y_len // 4) - t_v_ptr = bytearray(y_len // 4) - - self.transform_output_buffer(yuv_data, t_y_ptr, t_u_ptr, t_v_ptr, - transform) - - return t_y_ptr, t_u_ptr, t_v_ptr - - def transform_contiguous(self, yuv_data, transform): - y_ol = self.model_input_size[0] * self.model_input_size[1] - uv_ol = y_ol // 4 - result = bytearray(y_ol * 3 // 2) - result_view = memoryview(result) - t_y_ptr = result_view[:y_ol] - t_u_ptr = result_view[y_ol:y_ol + uv_ol] - t_v_ptr = result_view[y_ol + uv_ol:] - - self.transform_output_buffer(yuv_data, t_y_ptr, t_u_ptr, t_v_ptr, - transform) - return result - - def transform_output_buffer(self, yuv_data, y_out, u_out, v_out, - transform): - assert len(yuv_data) == self.input_size[0] * self.input_size[1] * 3 / 2 - - cast = self.ffi.cast - from_buffer = self.ffi.from_buffer - yuv_ptr = cast("unsigned char*", from_buffer(yuv_data)) - transform_ptr = self.ffi.new("float[]", transform) - - y_out_ptr = cast("unsigned char*", from_buffer(y_out)) - u_out_ptr = cast("unsigned char*", from_buffer(u_out)) - v_out_ptr = cast("unsigned char*", from_buffer(v_out)) - - self.clib.visiontest_transform(self._visiontest_c, yuv_ptr, y_out_ptr, - u_out_ptr, v_out_ptr, transform_ptr) - - def close(self): - self.clib.visiontest_destroy(self._visiontest_c) - self._visiontest_c = None - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_value, traceback): - self.close() - - -if __name__ == "__main__": - VisionTest((560, 304), (320, 160), "temporal") diff --git a/selfdrive/monitoring/dmonitoringd.py b/selfdrive/monitoring/dmonitoringd.py index f1b0c42bd9..35eee5b035 100755 --- a/selfdrive/monitoring/dmonitoringd.py +++ b/selfdrive/monitoring/dmonitoringd.py @@ -3,7 +3,7 @@ import gc import cereal.messaging as messaging from cereal import car -from common.params import Params +from common.params import Params, put_bool_nonblocking from common.realtime import set_realtime_priority from selfdrive.controls.lib.events import Events from selfdrive.locationd.calibrationd import Calibration @@ -18,9 +18,9 @@ def dmonitoringd_thread(sm=None, pm=None): pm = messaging.PubMaster(['driverMonitoringState']) if sm is None: - sm = messaging.SubMaster(['driverState', 'liveCalibration', 'carState', 'controlsState', 'modelV2'], poll=['driverState']) + sm = messaging.SubMaster(['driverStateV2', 'liveCalibration', 'carState', 'controlsState', 'modelV2'], poll=['driverStateV2']) - driver_status = DriverStatus(rhd=Params().get_bool("IsRHD")) + driver_status = DriverStatus(rhd_saved=Params().get_bool("IsRhdDetected")) sm['liveCalibration'].calStatus = Calibration.INVALID sm['liveCalibration'].rpyCalib = [0, 0, 0] @@ -34,7 +34,7 @@ def dmonitoringd_thread(sm=None, pm=None): while True: sm.update() - if not sm.updated['driverState']: + if not sm.updated['driverStateV2']: continue # Get interaction @@ -51,7 +51,7 @@ def dmonitoringd_thread(sm=None, pm=None): # Get data from dmonitoringmodeld events = Events() - driver_status.get_pose(sm['driverState'], sm['liveCalibration'].rpyCalib, sm['carState'].vEgo, sm['controlsState'].enabled) + driver_status.update_states(sm['driverStateV2'], sm['liveCalibration'].rpyCalib, sm['carState'].vEgo, sm['controlsState'].enabled) # Block engaging after max number of distrations if driver_status.terminal_alert_cnt >= driver_status.settings._MAX_TERMINAL_ALERTS or \ @@ -59,7 +59,7 @@ def dmonitoringd_thread(sm=None, pm=None): events.add(car.CarEvent.EventName.tooDistracted) # Update events from driver state - driver_status.update(events, driver_engaged, sm['controlsState'].enabled, sm['carState'].standstill) + driver_status.update_events(events, driver_engaged, sm['controlsState'].enabled, sm['carState'].standstill) # build driverMonitoringState packet dat = messaging.new_message('driverMonitoringState') @@ -67,6 +67,7 @@ def dmonitoringd_thread(sm=None, pm=None): "events": events.to_msg(), "faceDetected": driver_status.face_detected, "isDistracted": driver_status.driver_distracted, + "distractedType": sum(driver_status.distracted_types), "awarenessStatus": driver_status.awareness, "posePitchOffset": driver_status.pose.pitch_offseter.filtered_stat.mean(), "posePitchValidCount": driver_status.pose.pitch_offseter.filtered_stat.n, @@ -78,9 +79,15 @@ def dmonitoringd_thread(sm=None, pm=None): "isLowStd": driver_status.pose.low_std, "hiStdCount": driver_status.hi_stds, "isActiveMode": driver_status.active_monitoring_mode, + "isRHD": driver_status.wheel_on_right, } pm.send('driverMonitoringState', dat) + # save rhd virtual toggle every 5 mins + if (sm['driverStateV2'].frameId % 6000 == 0 and + driver_status.wheelpos_learner.filtered_stat.n > driver_status.settings._WHEELPOS_FILTER_MIN_COUNT and + driver_status.wheel_on_right == (driver_status.wheelpos_learner.filtered_stat.M > driver_status.settings._WHEELPOS_THRESHOLD)): + put_bool_nonblocking("IsRhdDetected", driver_status.wheel_on_right) def main(sm=None, pm=None): dmonitoringd_thread(sm, pm) diff --git a/selfdrive/monitoring/driver_monitor.py b/selfdrive/monitoring/driver_monitor.py index efb00ecb77..a2cddc2462 100644 --- a/selfdrive/monitoring/driver_monitor.py +++ b/selfdrive/monitoring/driver_monitor.py @@ -3,9 +3,9 @@ from math import atan2 from cereal import car from common.numpy_fast import interp from common.realtime import DT_DMON -from selfdrive.hardware import TICI from common.filter_simple import FirstOrderFilter from common.stat_live import RunningStatFilter +from common.transformations.camera import tici_d_frame_size EventName = car.CarEvent.EventName @@ -16,37 +16,43 @@ EventName = car.CarEvent.EventName # ****************************************************************************************** class DRIVER_MONITOR_SETTINGS(): - def __init__(self, TICI=TICI, DT_DMON=DT_DMON): + def __init__(self): self._DT_DMON = DT_DMON - self._AWARENESS_TIME = 35. # passive wheeltouch total timeout - self._AWARENESS_PRE_TIME_TILL_TERMINAL = 12. + # ref (page15-16): https://eur-lex.europa.eu/legal-content/EN/TXT/PDF/?uri=CELEX:42018X1947&rid=2 + self._AWARENESS_TIME = 30. # passive wheeltouch total timeout + self._AWARENESS_PRE_TIME_TILL_TERMINAL = 15. self._AWARENESS_PROMPT_TIME_TILL_TERMINAL = 6. self._DISTRACTED_TIME = 11. # active monitoring total timeout self._DISTRACTED_PRE_TIME_TILL_TERMINAL = 8. self._DISTRACTED_PROMPT_TIME_TILL_TERMINAL = 6. - self._FACE_THRESHOLD = 0.5 - self._PARTIAL_FACE_THRESHOLD = 0.765 if TICI else 0.43 - self._EYE_THRESHOLD = 0.61 if TICI else 0.55 - self._SG_THRESHOLD = 0.89 if TICI else 0.86 - self._BLINK_THRESHOLD = 0.82 if TICI else 0.588 - self._BLINK_THRESHOLD_SLACK = 0.9 if TICI else 0.77 - self._BLINK_THRESHOLD_STRICT = self._BLINK_THRESHOLD + self._FACE_THRESHOLD = 0.7 + self._EYE_THRESHOLD = 0.65 + self._SG_THRESHOLD = 0.9 + self._BLINK_THRESHOLD = 0.895 + + self._EE_THRESH11 = 0.275 + self._EE_THRESH12 = 5.5 + self._EE_MAX_OFFSET1 = 0.06 + self._EE_MIN_OFFSET1 = 0.025 + self._EE_THRESH21 = 0.01 + self._EE_THRESH22 = 0.35 - self._POSE_PITCH_THRESHOLD = 0.3237 - self._POSE_PITCH_THRESHOLD_SLACK = 0.3657 + self._POSE_PITCH_THRESHOLD = 0.3133 + self._POSE_PITCH_THRESHOLD_SLACK = 0.3237 self._POSE_PITCH_THRESHOLD_STRICT = self._POSE_PITCH_THRESHOLD - self._POSE_YAW_THRESHOLD = 0.3109 - self._POSE_YAW_THRESHOLD_SLACK = 0.4294 + self._POSE_YAW_THRESHOLD = 0.4020 + self._POSE_YAW_THRESHOLD_SLACK = 0.5042 self._POSE_YAW_THRESHOLD_STRICT = self._POSE_YAW_THRESHOLD - self._PITCH_NATURAL_OFFSET = 0.057 # initial value before offset is learned - self._YAW_NATURAL_OFFSET = 0.11 # initial value before offset is learned + self._PITCH_NATURAL_OFFSET = 0.029 # initial value before offset is learned + self._PITCH_NATURAL_THRESHOLD = 0.449 + self._YAW_NATURAL_OFFSET = 0.097 # initial value before offset is learned self._PITCH_MAX_OFFSET = 0.124 self._PITCH_MIN_OFFSET = -0.0881 self._YAW_MAX_OFFSET = 0.289 self._YAW_MIN_OFFSET = -0.0246 - self._POSESTD_THRESHOLD = 0.38 if TICI else 0.3 + self._POSESTD_THRESHOLD = 0.3 self._HI_STD_FALLBACK_TIME = int(10 / self._DT_DMON) # fall back to wheel touch if model is uncertain for 10s self._DISTRACTED_FILTER_TS = 0.25 # 0.6Hz @@ -54,6 +60,10 @@ class DRIVER_MONITOR_SETTINGS(): self._POSE_OFFSET_MIN_COUNT = int(60 / self._DT_DMON) # valid data counts before calibration completes, 1min cumulative self._POSE_OFFSET_MAX_COUNT = int(360 / self._DT_DMON) # stop deweighting new data after 6 min, aka "short term memory" + self._WHEELPOS_CALIB_MIN_SPEED = 11 + self._WHEELPOS_THRESHOLD = 0.5 + self._WHEELPOS_FILTER_MIN_COUNT = int(15 / self._DT_DMON) # allow 15 seconds to converge wheel side + self._RECOVERY_FACTOR_MAX = 5. # relative to minus step change self._RECOVERY_FACTOR_MIN = 1.25 # relative to minus step change @@ -61,31 +71,32 @@ class DRIVER_MONITOR_SETTINGS(): self._MAX_TERMINAL_DURATION = int(30 / self._DT_DMON) # not allowed to engage after 30s of terminal alerts -# model output refers to center of cropped image, so need to apply the x displacement offset -RESIZED_FOCAL = 320.0 -H, W, FULL_W = 320, 160, 426 +# model output refers to center of undistorted+leveled image +EFL = 598.0 # focal length in K +W, H = tici_d_frame_size # corrected image has same size as raw class DistractedType: NOT_DISTRACTED = 0 - BAD_POSE = 1 - BAD_BLINK = 2 + DISTRACTED_POSE = 1 + DISTRACTED_BLINK = 2 + DISTRACTED_E2E = 4 -def face_orientation_from_net(angles_desc, pos_desc, rpy_calib, is_rhd): +def face_orientation_from_net(angles_desc, pos_desc, rpy_calib): # the output of these angles are in device frame # so from driver's perspective, pitch is up and yaw is right pitch_net, yaw_net, roll_net = angles_desc - face_pixel_position = ((pos_desc[0] + .5)*W - W + FULL_W, (pos_desc[1]+.5)*H) - yaw_focal_angle = atan2(face_pixel_position[0] - FULL_W//2, RESIZED_FOCAL) - pitch_focal_angle = atan2(face_pixel_position[1] - H//2, RESIZED_FOCAL) + face_pixel_position = ((pos_desc[0]+0.5)*W, (pos_desc[1]+0.5)*H) + yaw_focal_angle = atan2(face_pixel_position[0] - W//2, EFL) + pitch_focal_angle = atan2(face_pixel_position[1] - H//2, EFL) pitch = pitch_net + pitch_focal_angle yaw = -yaw_net + yaw_focal_angle # no calib for roll pitch -= rpy_calib[1] - yaw -= rpy_calib[2] * (1 - 2 * int(is_rhd)) # lhd -> -=, rhd -> += + yaw -= rpy_calib[2] return roll_net, pitch, yaw class DriverPose(): @@ -106,25 +117,34 @@ class DriverBlink(): def __init__(self): self.left_blink = 0. self.right_blink = 0. - self.cfactor = 1. class DriverStatus(): - def __init__(self, rhd=False, settings=DRIVER_MONITOR_SETTINGS()): + def __init__(self, rhd_saved=False, settings=DRIVER_MONITOR_SETTINGS()): # init policy settings self.settings = settings # init driver status - self.is_rhd_region = rhd + self.wheelpos_learner = RunningStatFilter() self.pose = DriverPose(self.settings._POSE_OFFSET_MAX_COUNT) self.pose_calibrated = False self.blink = DriverBlink() + self.eev1 = 0. + self.eev2 = 1. + self.ee1_offseter = RunningStatFilter(max_trackable=self.settings._POSE_OFFSET_MAX_COUNT) + self.ee2_offseter = RunningStatFilter(max_trackable=self.settings._POSE_OFFSET_MAX_COUNT) + self.ee1_calibrated = False + self.ee2_calibrated = False + self.awareness = 1. self.awareness_active = 1. self.awareness_passive = 1. + self.distracted_types = [] self.driver_distracted = False self.driver_distraction_filter = FirstOrderFilter(0., self.settings._DISTRACTED_FILTER_TS, self.settings._DT_DMON) + self.wheel_on_right = False + self.wheel_on_right_last = None + self.wheel_on_right_default = rhd_saved self.face_detected = False - self.face_partial = False self.terminal_alert_cnt = 0 self.terminal_time = 0 self.step_change = 0. @@ -136,6 +156,11 @@ class DriverStatus(): self._set_timers(active_monitoring=True) + def _reset_awareness(self): + self.awareness = 1. + self.awareness_active = 1. + self.awareness_passive = 1. + def _set_timers(self, active_monitoring): if self.active_monitoring_mode and self.awareness <= self.threshold_prompt: if active_monitoring: @@ -166,35 +191,41 @@ class DriverStatus(): self.step_change = self.settings._DT_DMON / self.settings._AWARENESS_TIME self.active_monitoring_mode = False - def _is_driver_distracted(self, pose, blink): + def _get_distracted_types(self): + distracted_types = [] + if not self.pose_calibrated: - pitch_error = pose.pitch - self.settings._PITCH_NATURAL_OFFSET - yaw_error = pose.yaw - self.settings._YAW_NATURAL_OFFSET + pitch_error = self.pose.pitch - self.settings._PITCH_NATURAL_OFFSET + yaw_error = self.pose.yaw - self.settings._YAW_NATURAL_OFFSET else: - pitch_error = pose.pitch - min(max(self.pose.pitch_offseter.filtered_stat.mean(), + pitch_error = self.pose.pitch - min(max(self.pose.pitch_offseter.filtered_stat.mean(), self.settings._PITCH_MIN_OFFSET), self.settings._PITCH_MAX_OFFSET) - yaw_error = pose.yaw - min(max(self.pose.yaw_offseter.filtered_stat.mean(), + yaw_error = self.pose.yaw - min(max(self.pose.yaw_offseter.filtered_stat.mean(), self.settings._YAW_MIN_OFFSET), self.settings._YAW_MAX_OFFSET) - pitch_error = 0 if pitch_error > 0 else abs(pitch_error) # no positive pitch limit yaw_error = abs(yaw_error) + if pitch_error > (self.settings._POSE_PITCH_THRESHOLD*self.pose.cfactor_pitch if self.pose_calibrated else self.settings._PITCH_NATURAL_THRESHOLD) or \ + yaw_error > self.settings._POSE_YAW_THRESHOLD*self.pose.cfactor_yaw: + distracted_types.append(DistractedType.DISTRACTED_POSE) - if pitch_error > self.settings._POSE_PITCH_THRESHOLD*pose.cfactor_pitch or \ - yaw_error > self.settings._POSE_YAW_THRESHOLD*pose.cfactor_yaw: - return DistractedType.BAD_POSE - elif (blink.left_blink + blink.right_blink)*0.5 > self.settings._BLINK_THRESHOLD*blink.cfactor: - return DistractedType.BAD_BLINK + if (self.blink.left_blink + self.blink.right_blink)*0.5 > self.settings._BLINK_THRESHOLD: + distracted_types.append(DistractedType.DISTRACTED_BLINK) + + if self.ee1_calibrated: + ee1_dist = self.eev1 > max(min(self.ee1_offseter.filtered_stat.M, self.settings._EE_MAX_OFFSET1), self.settings._EE_MIN_OFFSET1) * self.settings._EE_THRESH12 else: - return DistractedType.NOT_DISTRACTED + ee1_dist = self.eev1 > self.settings._EE_THRESH11 + # if self.ee2_calibrated: + # ee2_dist = self.eev2 < self.ee2_offseter.filtered_stat.M * self.settings._EE_THRESH22 + # else: + # ee2_dist = self.eev2 < self.settings._EE_THRESH21 + if ee1_dist: + distracted_types.append(DistractedType.DISTRACTED_E2E) + + return distracted_types def set_policy(self, model_data, car_speed): - ep = min(model_data.meta.engagedProb, 0.8) / 0.8 # engaged prob bp = model_data.meta.disengagePredictions.brakeDisengageProbs[0] # brake disengage prob in next 2s - # TODO: retune adaptive blink - self.blink.cfactor = interp(ep, [0, 0.5, 1], - [self.settings._BLINK_THRESHOLD_STRICT, - self.settings._BLINK_THRESHOLD, - self.settings._BLINK_THRESHOLD_SLACK]) / self.settings._BLINK_THRESHOLD k1 = max(-0.00156*((car_speed-16)**2)+0.6, 0.2) bp_normal = max(min(bp / k1, 0.5),0) self.pose.cfactor_pitch = interp(bp_normal, [0, 0.5], @@ -204,24 +235,42 @@ class DriverStatus(): [self.settings._POSE_YAW_THRESHOLD_SLACK, self.settings._POSE_YAW_THRESHOLD_STRICT]) / self.settings._POSE_YAW_THRESHOLD - def get_pose(self, driver_state, cal_rpy, car_speed, op_engaged): - if not all(len(x) > 0 for x in (driver_state.faceOrientation, driver_state.facePosition, - driver_state.faceOrientationStd, driver_state.facePositionStd)): + def update_states(self, driver_state, cal_rpy, car_speed, op_engaged): + rhd_pred = driver_state.wheelOnRightProb + # calibrates only when there's movement and either face detected + if car_speed > self.settings._WHEELPOS_CALIB_MIN_SPEED and (driver_state.leftDriverData.faceProb > self.settings._FACE_THRESHOLD or + driver_state.rightDriverData.faceProb > self.settings._FACE_THRESHOLD): + self.wheelpos_learner.push_and_update(rhd_pred) + if self.wheelpos_learner.filtered_stat.n > self.settings._WHEELPOS_FILTER_MIN_COUNT: + self.wheel_on_right = self.wheelpos_learner.filtered_stat.M > self.settings._WHEELPOS_THRESHOLD + else: + self.wheel_on_right = self.wheel_on_right_default # use default/saved if calibration is unfinished + # make sure no switching when engaged + if op_engaged and self.wheel_on_right_last is not None and self.wheel_on_right_last != self.wheel_on_right: + self.wheel_on_right = self.wheel_on_right_last + driver_data = driver_state.rightDriverData if self.wheel_on_right else driver_state.leftDriverData + if not all(len(x) > 0 for x in (driver_data.faceOrientation, driver_data.facePosition, + driver_data.faceOrientationStd, driver_data.facePositionStd, + driver_data.readyProb, driver_data.notReadyProb)): return - self.face_partial = driver_state.partialFace > self.settings._PARTIAL_FACE_THRESHOLD - self.face_detected = driver_state.faceProb > self.settings._FACE_THRESHOLD or self.face_partial - self.pose.roll, self.pose.pitch, self.pose.yaw = face_orientation_from_net(driver_state.faceOrientation, driver_state.facePosition, cal_rpy, self.is_rhd_region) - self.pose.pitch_std = driver_state.faceOrientationStd[0] - self.pose.yaw_std = driver_state.faceOrientationStd[1] - # self.pose.roll_std = driver_state.faceOrientationStd[2] + self.face_detected = driver_data.faceProb > self.settings._FACE_THRESHOLD + self.pose.roll, self.pose.pitch, self.pose.yaw = face_orientation_from_net(driver_data.faceOrientation, driver_data.facePosition, cal_rpy) + if self.wheel_on_right: + self.pose.yaw *= -1 + self.wheel_on_right_last = self.wheel_on_right + self.pose.pitch_std = driver_data.faceOrientationStd[0] + self.pose.yaw_std = driver_data.faceOrientationStd[1] model_std_max = max(self.pose.pitch_std, self.pose.yaw_std) - self.pose.low_std = model_std_max < self.settings._POSESTD_THRESHOLD and not self.face_partial - self.blink.left_blink = driver_state.leftBlinkProb * (driver_state.leftEyeProb > self.settings._EYE_THRESHOLD) * (driver_state.sunglassesProb < self.settings._SG_THRESHOLD) - self.blink.right_blink = driver_state.rightBlinkProb * (driver_state.rightEyeProb > self.settings._EYE_THRESHOLD) * (driver_state.sunglassesProb < self.settings._SG_THRESHOLD) - - self.driver_distracted = self._is_driver_distracted(self.pose, self.blink) > 0 and \ - driver_state.faceProb > self.settings._FACE_THRESHOLD and self.pose.low_std + self.pose.low_std = model_std_max < self.settings._POSESTD_THRESHOLD + self.blink.left_blink = driver_data.leftBlinkProb * (driver_data.leftEyeProb > self.settings._EYE_THRESHOLD) * (driver_data.sunglassesProb < self.settings._SG_THRESHOLD) + self.blink.right_blink = driver_data.rightBlinkProb * (driver_data.rightEyeProb > self.settings._EYE_THRESHOLD) * (driver_data.sunglassesProb < self.settings._SG_THRESHOLD) + self.eev1 = driver_data.notReadyProb[0] + self.eev2 = driver_data.readyProb[0] + + self.distracted_types = self._get_distracted_types() + self.driver_distracted = (DistractedType.DISTRACTED_E2E in self.distracted_types or DistractedType.DISTRACTED_POSE in self.distracted_types or DistractedType.DISTRACTED_BLINK in self.distracted_types) and \ + driver_data.faceProb > self.settings._FACE_THRESHOLD and self.pose.low_std self.driver_distraction_filter.update(self.driver_distracted) # update offseter @@ -229,9 +278,13 @@ class DriverStatus(): if self.face_detected and car_speed > self.settings._POSE_CALIB_MIN_SPEED and self.pose.low_std and (not op_engaged or not self.driver_distracted): self.pose.pitch_offseter.push_and_update(self.pose.pitch) self.pose.yaw_offseter.push_and_update(self.pose.yaw) + self.ee1_offseter.push_and_update(self.eev1) + self.ee2_offseter.push_and_update(self.eev2) self.pose_calibrated = self.pose.pitch_offseter.filtered_stat.n > self.settings._POSE_OFFSET_MIN_COUNT and \ self.pose.yaw_offseter.filtered_stat.n > self.settings._POSE_OFFSET_MIN_COUNT + self.ee1_calibrated = self.ee1_offseter.filtered_stat.n > self.settings._POSE_OFFSET_MIN_COUNT + self.ee2_calibrated = self.ee2_offseter.filtered_stat.n > self.settings._POSE_OFFSET_MIN_COUNT self.is_model_uncertain = self.hi_stds > self.settings._HI_STD_FALLBACK_TIME self._set_timers(self.face_detected and not self.is_model_uncertain) @@ -240,18 +293,18 @@ class DriverStatus(): elif self.face_detected and self.pose.low_std: self.hi_stds = 0 - def update(self, events, driver_engaged, ctrl_active, standstill): - if (driver_engaged and self.awareness > 0) or not ctrl_active: - # reset only when on disengagement if red reached - self.awareness = 1. - self.awareness_active = 1. - self.awareness_passive = 1. + def update_events(self, events, driver_engaged, ctrl_active, standstill): + if (driver_engaged and self.awareness > 0 and not self.active_monitoring_mode) or not ctrl_active: # reset only when on disengagement if red reached + self._reset_awareness() return driver_attentive = self.driver_distraction_filter.x < 0.37 awareness_prev = self.awareness if (driver_attentive and self.face_detected and self.pose.low_std and self.awareness > 0): + if driver_engaged: + self._reset_awareness() + return # only restore awareness when paying attention and alert is not red self.awareness = min(self.awareness + ((self.settings._RECOVERY_FACTOR_MAX-self.settings._RECOVERY_FACTOR_MIN)*(1.-self.awareness)+self.settings._RECOVERY_FACTOR_MIN)*self.step_change, 1.) if self.awareness == 1.: diff --git a/selfdrive/monitoring/test_monitoring.py b/selfdrive/monitoring/test_monitoring.py index 4079e34132..f72b4a3aaa 100755 --- a/selfdrive/monitoring/test_monitoring.py +++ b/selfdrive/monitoring/test_monitoring.py @@ -17,16 +17,19 @@ INVISIBLE_SECONDS_TO_ORANGE = dm_settings._AWARENESS_TIME - dm_settings._AWARENE INVISIBLE_SECONDS_TO_RED = dm_settings._AWARENESS_TIME + 1 def make_msg(face_detected, distracted=False, model_uncertain=False): - ds = log.DriverState.new_message() - ds.faceOrientation = [0., 0., 0.] - ds.facePosition = [0., 0.] - ds.faceProb = 1. * face_detected - ds.leftEyeProb = 1. - ds.rightEyeProb = 1. - ds.leftBlinkProb = 1. * distracted - ds.rightBlinkProb = 1. * distracted - ds.faceOrientationStd = [1.*model_uncertain, 1.*model_uncertain, 1.*model_uncertain] - ds.facePositionStd = [1.*model_uncertain, 1.*model_uncertain] + ds = log.DriverStateV2.new_message() + ds.leftDriverData.faceOrientation = [0., 0., 0.] + ds.leftDriverData.facePosition = [0., 0.] + ds.leftDriverData.faceProb = 1. * face_detected + ds.leftDriverData.leftEyeProb = 1. + ds.leftDriverData.rightEyeProb = 1. + ds.leftDriverData.leftBlinkProb = 1. * distracted + ds.leftDriverData.rightBlinkProb = 1. * distracted + ds.leftDriverData.faceOrientationStd = [1.*model_uncertain, 1.*model_uncertain, 1.*model_uncertain] + ds.leftDriverData.facePositionStd = [1.*model_uncertain, 1.*model_uncertain] + # TODO: test both separately when e2e is used + ds.leftDriverData.readyProb = [0., 0., 0., 0.] + ds.leftDriverData.notReadyProb = [0., 0.] return ds @@ -57,11 +60,11 @@ class TestMonitoring(unittest.TestCase): events = [] for idx in range(len(msgs)): e = Events() - DS.get_pose(msgs[idx], [0, 0, 0], 0, engaged[idx]) + DS.update_states(msgs[idx], [0, 0, 0], 0, engaged[idx]) # cal_rpy and car_speed don't matter here # evaluate events at 10Hz for tests - DS.update(e, interaction[idx], engaged[idx], standstill[idx]) + DS.update_events(e, interaction[idx], engaged[idx], standstill[idx]) events.append(e) assert len(events) == len(msgs), f"got {len(events)} for {len(msgs)} driverState input msgs" return events, DS @@ -98,11 +101,12 @@ class TestMonitoring(unittest.TestCase): ((TEST_TIMESPAN-10-d_status.settings._AWARENESS_TIME)/2))/DT_DMON)].names[0], EventName.driverUnresponsive) # engaged, down to orange, driver pays attention, back to normal; then down to orange, driver touches wheel - # - should have short orange recovery time and no green afterwards; should recover rightaway on wheel touch + # - should have short orange recovery time and no green afterwards; wheel touch only recovers when paying attention def test_normal_driver(self): ds_vector = [msg_DISTRACTED] * int(DISTRACTED_SECONDS_TO_ORANGE/DT_DMON) + \ [msg_ATTENTIVE] * int(DISTRACTED_SECONDS_TO_ORANGE/DT_DMON) + \ - [msg_DISTRACTED] * (int(TEST_TIMESPAN/DT_DMON)-int(DISTRACTED_SECONDS_TO_ORANGE*2/DT_DMON)) + [msg_DISTRACTED] * int((DISTRACTED_SECONDS_TO_ORANGE+2)/DT_DMON) + \ + [msg_ATTENTIVE] * (int(TEST_TIMESPAN/DT_DMON)-int((DISTRACTED_SECONDS_TO_ORANGE*3+2)/DT_DMON)) interaction_vector = [car_interaction_NOT_DETECTED] * int(DISTRACTED_SECONDS_TO_ORANGE*3/DT_DMON) + \ [car_interaction_DETECTED] * (int(TEST_TIMESPAN/DT_DMON)-int(DISTRACTED_SECONDS_TO_ORANGE*3/DT_DMON)) events, _ = self._run_seq(ds_vector, interaction_vector, always_true, always_false) @@ -110,7 +114,8 @@ class TestMonitoring(unittest.TestCase): self.assertEqual(events[int((DISTRACTED_SECONDS_TO_ORANGE-0.1)/DT_DMON)].names[0], EventName.promptDriverDistracted) self.assertEqual(len(events[int(DISTRACTED_SECONDS_TO_ORANGE*1.5/DT_DMON)]), 0) self.assertEqual(events[int((DISTRACTED_SECONDS_TO_ORANGE*3-0.1)/DT_DMON)].names[0], EventName.promptDriverDistracted) - self.assertEqual(len(events[int((DISTRACTED_SECONDS_TO_ORANGE*3+0.1)/DT_DMON)]), 0) + self.assertEqual(events[int((DISTRACTED_SECONDS_TO_ORANGE*3+0.1)/DT_DMON)].names[0], EventName.promptDriverDistracted) + self.assertEqual(len(events[int((DISTRACTED_SECONDS_TO_ORANGE*3+2.5)/DT_DMON)]), 0) # engaged, down to orange, driver dodges camera, then comes back still distracted, down to red, \ # driver dodges, and then touches wheel to no avail, disengages and reengages @@ -133,21 +138,21 @@ class TestMonitoring(unittest.TestCase): # engaged, invisible driver, down to orange, driver touches wheel; then down to orange again, driver appears # - both actions should clear the alert, but momentary appearance should not def test_sometimes_transparent_commuter(self): - _visible_time = np.random.choice([0.5, 10]) - ds_vector = always_no_face[:]*2 - interaction_vector = always_false[:]*2 - ds_vector[int((2*INVISIBLE_SECONDS_TO_ORANGE+1)/DT_DMON):int((2*INVISIBLE_SECONDS_TO_ORANGE+1+_visible_time)/DT_DMON)] = [msg_ATTENTIVE] * int(_visible_time/DT_DMON) - interaction_vector[int((INVISIBLE_SECONDS_TO_ORANGE)/DT_DMON):int((INVISIBLE_SECONDS_TO_ORANGE+1)/DT_DMON)] = [True] * int(1/DT_DMON) - events, _ = self._run_seq(ds_vector, interaction_vector, 2*always_true, 2*always_false) - self.assertTrue(len(events[int(INVISIBLE_SECONDS_TO_ORANGE*0.5/DT_DMON)]) == 0) - self.assertEqual(events[int((INVISIBLE_SECONDS_TO_ORANGE-0.1)/DT_DMON)].names[0], EventName.promptDriverUnresponsive) - self.assertTrue(len(events[int((INVISIBLE_SECONDS_TO_ORANGE+0.1)/DT_DMON)]) == 0) - if _visible_time == 0.5: - self.assertEqual(events[int((INVISIBLE_SECONDS_TO_ORANGE*2+1-0.1)/DT_DMON)].names[0], EventName.promptDriverUnresponsive) - self.assertEqual(events[int((INVISIBLE_SECONDS_TO_ORANGE*2+1+0.1+_visible_time)/DT_DMON)].names[0], EventName.preDriverUnresponsive) - elif _visible_time == 10: - self.assertEqual(events[int((INVISIBLE_SECONDS_TO_ORANGE*2+1-0.1)/DT_DMON)].names[0], EventName.promptDriverUnresponsive) - self.assertTrue(len(events[int((INVISIBLE_SECONDS_TO_ORANGE*2+1+0.1+_visible_time)/DT_DMON)]) == 0) + _visible_time = np.random.choice([0.5, 10]) + ds_vector = always_no_face[:]*2 + interaction_vector = always_false[:]*2 + ds_vector[int((2*INVISIBLE_SECONDS_TO_ORANGE+1)/DT_DMON):int((2*INVISIBLE_SECONDS_TO_ORANGE+1+_visible_time)/DT_DMON)] = [msg_ATTENTIVE] * int(_visible_time/DT_DMON) + interaction_vector[int((INVISIBLE_SECONDS_TO_ORANGE)/DT_DMON):int((INVISIBLE_SECONDS_TO_ORANGE+1)/DT_DMON)] = [True] * int(1/DT_DMON) + events, _ = self._run_seq(ds_vector, interaction_vector, 2*always_true, 2*always_false) + self.assertTrue(len(events[int(INVISIBLE_SECONDS_TO_ORANGE*0.5/DT_DMON)]) == 0) + self.assertEqual(events[int((INVISIBLE_SECONDS_TO_ORANGE-0.1)/DT_DMON)].names[0], EventName.promptDriverUnresponsive) + self.assertTrue(len(events[int((INVISIBLE_SECONDS_TO_ORANGE+0.1)/DT_DMON)]) == 0) + if _visible_time == 0.5: + self.assertEqual(events[int((INVISIBLE_SECONDS_TO_ORANGE*2+1-0.1)/DT_DMON)].names[0], EventName.promptDriverUnresponsive) + self.assertEqual(events[int((INVISIBLE_SECONDS_TO_ORANGE*2+1+0.1+_visible_time)/DT_DMON)].names[0], EventName.preDriverUnresponsive) + elif _visible_time == 10: + self.assertEqual(events[int((INVISIBLE_SECONDS_TO_ORANGE*2+1-0.1)/DT_DMON)].names[0], EventName.promptDriverUnresponsive) + self.assertTrue(len(events[int((INVISIBLE_SECONDS_TO_ORANGE*2+1+0.1+_visible_time)/DT_DMON)]) == 0) # engaged, invisible driver, down to red, driver appears and then touches wheel, then disengages/reengages # - only disengage will clear the alert diff --git a/selfdrive/navd/.gitignore b/selfdrive/navd/.gitignore new file mode 100644 index 0000000000..a070fe32bb --- /dev/null +++ b/selfdrive/navd/.gitignore @@ -0,0 +1,5 @@ +moc_* +*.moc + +map_renderer +libmap_renderer.so diff --git a/selfdrive/navd/SConscript b/selfdrive/navd/SConscript new file mode 100644 index 0000000000..b10684eef3 --- /dev/null +++ b/selfdrive/navd/SConscript @@ -0,0 +1,22 @@ +Import('qt_env', 'arch', 'common', 'messaging', 'visionipc', 'cereal', 'transformations') + +base_libs = [common, messaging, cereal, visionipc, transformations, 'zmq', + 'capnp', 'kj', 'm', 'OpenCL', 'ssl', 'crypto', 'pthread'] + qt_env["LIBS"] + +if arch == 'larch64': + base_libs.append('EGL') + +if arch in ['larch64', 'x86_64']: + if arch == 'x86_64': + rpath = [Dir(f"#third_party/mapbox-gl-native-qt/{arch}").srcnode().abspath] + qt_env["RPATH"] += rpath + + style_path = File("style.json").abspath + qt_env['CXXFLAGS'].append(f'-DSTYLE_PATH=\\"{style_path}\\"') + qt_libs = ["qt_widgets", "qt_util", "qmapboxgl"] + base_libs + + nav_src = ["main.cc", "map_renderer.cc"] + qt_env.Program("map_renderer", nav_src, LIBS=qt_libs + ['common', 'json11']) + + if GetOption('extras'): + qt_env.SharedLibrary("map_renderer", ["map_renderer.cc"], LIBS=qt_libs + ['common', 'messaging']) diff --git a/selfdrive/hardware/pc/__init__.py b/selfdrive/navd/__init__.py similarity index 100% rename from selfdrive/hardware/pc/__init__.py rename to selfdrive/navd/__init__.py diff --git a/selfdrive/navd/helpers.py b/selfdrive/navd/helpers.py new file mode 100644 index 0000000000..eda813154a --- /dev/null +++ b/selfdrive/navd/helpers.py @@ -0,0 +1,174 @@ +from __future__ import annotations + +import json +import math +from typing import Any, Dict, List, Optional, Tuple, Union, cast + +from common.conversions import Conversions +from common.numpy_fast import clip +from common.params import Params + +EARTH_MEAN_RADIUS = 6371007.2 +SPEED_CONVERSIONS = { + 'km/h': Conversions.KPH_TO_MS, + 'mph': Conversions.MPH_TO_MS, + } + + +class Coordinate: + def __init__(self, latitude: float, longitude: float) -> None: + self.latitude = latitude + self.longitude = longitude + self.annotations: Dict[str, float] = {} + + @classmethod + def from_mapbox_tuple(cls, t: Tuple[float, float]) -> Coordinate: + return cls(t[1], t[0]) + + def as_dict(self) -> Dict[str, float]: + return {'latitude': self.latitude, 'longitude': self.longitude} + + def __str__(self) -> str: + return f"({self.latitude}, {self.longitude})" + + def __eq__(self, other) -> bool: + if not isinstance(other, Coordinate): + return False + return (self.latitude == other.latitude) and (self.longitude == other.longitude) + + def __sub__(self, other: Coordinate) -> Coordinate: + return Coordinate(self.latitude - other.latitude, self.longitude - other.longitude) + + def __add__(self, other: Coordinate) -> Coordinate: + return Coordinate(self.latitude + other.latitude, self.longitude + other.longitude) + + def __mul__(self, c: float) -> Coordinate: + return Coordinate(self.latitude * c, self.longitude * c) + + def dot(self, other: Coordinate) -> float: + return self.latitude * other.latitude + self.longitude * other.longitude + + def distance_to(self, other: Coordinate) -> float: + # Haversine formula + dlat = math.radians(other.latitude - self.latitude) + dlon = math.radians(other.longitude - self.longitude) + + haversine_dlat = math.sin(dlat / 2.0) + haversine_dlat *= haversine_dlat + haversine_dlon = math.sin(dlon / 2.0) + haversine_dlon *= haversine_dlon + + y = haversine_dlat \ + + math.cos(math.radians(self.latitude)) \ + * math.cos(math.radians(other.latitude)) \ + * haversine_dlon + x = 2 * math.asin(math.sqrt(y)) + return x * EARTH_MEAN_RADIUS + + +def minimum_distance(a: Coordinate, b: Coordinate, p: Coordinate): + if a.distance_to(b) < 0.01: + return a.distance_to(p) + + ap = p - a + ab = b - a + t = clip(ap.dot(ab) / ab.dot(ab), 0.0, 1.0) + projection = a + ab * t + return projection.distance_to(p) + + +def distance_along_geometry(geometry: List[Coordinate], pos: Coordinate) -> float: + if len(geometry) <= 2: + return geometry[0].distance_to(pos) + + # 1. Find segment that is closest to current position + # 2. Total distance is sum of distance to start of closest segment + # + all previous segments + total_distance = 0.0 + total_distance_closest = 0.0 + closest_distance = 1e9 + + for i in range(len(geometry) - 1): + d = minimum_distance(geometry[i], geometry[i + 1], pos) + + if d < closest_distance: + closest_distance = d + total_distance_closest = total_distance + geometry[i].distance_to(pos) + + total_distance += geometry[i].distance_to(geometry[i + 1]) + + return total_distance_closest + + +def coordinate_from_param(param: str, params: Optional[Params] = None) -> Optional[Coordinate]: + if params is None: + params = Params() + + json_str = params.get(param) + if json_str is None: + return None + + pos = json.loads(json_str) + if 'latitude' not in pos or 'longitude' not in pos: + return None + + return Coordinate(pos['latitude'], pos['longitude']) + + +def string_to_direction(direction: str) -> str: + for d in ['left', 'right', 'straight']: + if d in direction: + return d + return 'none' + + +def maxspeed_to_ms(maxspeed: Dict[str, Union[str, float]]) -> float: + unit = cast(str, maxspeed['unit']) + speed = cast(float, maxspeed['speed']) + return SPEED_CONVERSIONS[unit] * speed + + +def parse_banner_instructions(instruction: Any, banners: Any, distance_to_maneuver: float = 0.0) -> None: + if not len(banners): + return + + current_banner = banners[0] + + # A segment can contain multiple banners, find one that we need to show now + for banner in banners: + if distance_to_maneuver < banner['distanceAlongGeometry']: + current_banner = banner + + # Only show banner when close enough to maneuver + instruction.showFull = distance_to_maneuver < current_banner['distanceAlongGeometry'] + + # Primary + p = current_banner['primary'] + if 'text' in p: + instruction.maneuverPrimaryText = p['text'] + if 'type' in p: + instruction.maneuverType = p['type'] + if 'modifier' in p: + instruction.maneuverModifier = p['modifier'] + + # Secondary + if 'secondary' in current_banner: + instruction.maneuverSecondaryText = current_banner['secondary']['text'] + + # Lane lines + if 'sub' in current_banner: + lanes = [] + for component in current_banner['sub']['components']: + if component['type'] != 'lane': + continue + + lane = { + 'active': component['active'], + 'directions': [string_to_direction(d) for d in component['directions']], + } + + if 'active_direction' in component: + lane['activeDirection'] = string_to_direction(component['active_direction']) + + lanes.append(lane) + instruction.lanes = lanes diff --git a/selfdrive/navd/main.cc b/selfdrive/navd/main.cc new file mode 100644 index 0000000000..b6eec10328 --- /dev/null +++ b/selfdrive/navd/main.cc @@ -0,0 +1,31 @@ +#include +#include +#include + +#include "selfdrive/ui/qt/util.h" +#include "selfdrive/ui/qt/maps/map_helpers.h" +#include "selfdrive/navd/map_renderer.h" +#include "system/hardware/hw.h" + + + +void sigHandler(int s) { + qInfo() << "Shutting down"; + std::signal(s, SIG_DFL); + + qApp->quit(); +} + + +int main(int argc, char *argv[]) { + qInstallMessageHandler(swagLogMessageHandler); + + QApplication app(argc, argv); + std::signal(SIGINT, sigHandler); + std::signal(SIGTERM, sigHandler); + + MapRenderer * m = new MapRenderer(get_mapbox_settings()); + assert(m); + + return app.exec(); +} diff --git a/selfdrive/ui/navd/map_renderer.cc b/selfdrive/navd/map_renderer.cc similarity index 61% rename from selfdrive/ui/navd/map_renderer.cc rename to selfdrive/navd/map_renderer.cc index 1d78d68dfe..6a19f45fed 100644 --- a/selfdrive/ui/navd/map_renderer.cc +++ b/selfdrive/navd/map_renderer.cc @@ -1,19 +1,30 @@ -#include "selfdrive/ui/navd/map_renderer.h" +#include "selfdrive/navd/map_renderer.h" +#include +#include #include #include #include +#include "common/util.h" +#include "common/timing.h" #include "selfdrive/ui/qt/maps/map_helpers.h" -#include "selfdrive/common/timing.h" - -const float ZOOM = 13.5; // Don't go below 13 or features will start to disappear -const int WIDTH = 256; -const int HEIGHT = WIDTH; +const float DEFAULT_ZOOM = 13.5; // Don't go below 13 or features will start to disappear +const int HEIGHT = 512, WIDTH = 512; const int NUM_VIPC_BUFFERS = 4; -MapRenderer::MapRenderer(const QMapboxGLSettings &settings, bool enable_vipc) : m_settings(settings) { +const int EARTH_CIRCUMFERENCE_METERS = 40075000; +const int PIXELS_PER_TILE = 256; + +float get_zoom_level_for_scale(float lat, float meters_per_pixel) { + float meters_per_tile = meters_per_pixel * PIXELS_PER_TILE; + float num_tiles = cos(DEG2RAD(lat)) * EARTH_CIRCUMFERENCE_METERS / meters_per_tile; + return log2(num_tiles) - 1; +} + + +MapRenderer::MapRenderer(const QMapboxGLSettings &settings, bool online) : m_settings(settings) { QSurfaceFormat fmt; fmt.setRenderableType(QSurfaceFormat::OpenGLES); @@ -35,22 +46,51 @@ MapRenderer::MapRenderer(const QMapboxGLSettings &settings, bool enable_vipc) : QOpenGLFramebufferObjectFormat fbo_format; fbo.reset(new QOpenGLFramebufferObject(WIDTH, HEIGHT, fbo_format)); + std::string style = util::read_file(STYLE_PATH); m_map.reset(new QMapboxGL(nullptr, m_settings, fbo->size(), 1)); - m_map->setCoordinateZoom(QMapbox::Coordinate(0, 0), ZOOM); - m_map->setStyleUrl("mapbox://styles/commaai/ckvmksrpd4n0a14pfdo5heqzr"); + m_map->setCoordinateZoom(QMapbox::Coordinate(0, 0), DEFAULT_ZOOM); + m_map->setStyleJson(style.c_str()); m_map->createRenderer(); m_map->resize(fbo->size()); m_map->setFramebufferObject(fbo->handle(), fbo->size()); gl_functions->glViewport(0, 0, WIDTH, HEIGHT); - if (enable_vipc) { - qWarning() << "Enabling navd map rendering"; + if (online) { vipc_server.reset(new VisionIpcServer("navd")); - vipc_server->create_buffers(VisionStreamType::VISION_STREAM_RGB_MAP, NUM_VIPC_BUFFERS, true, WIDTH, HEIGHT); + vipc_server->create_buffers(VisionStreamType::VISION_STREAM_MAP, NUM_VIPC_BUFFERS, false, WIDTH, HEIGHT); vipc_server->start_listener(); pm.reset(new PubMaster({"navThumbnail"})); + sm.reset(new SubMaster({"liveLocationKalman", "navRoute"})); + + timer = new QTimer(this); + QObject::connect(timer, SIGNAL(timeout()), this, SLOT(msgUpdate())); + timer->start(50); + } +} + +void MapRenderer::msgUpdate() { + sm->update(0); + + if (sm->updated("liveLocationKalman")) { + auto location = (*sm)["liveLocationKalman"].getLiveLocationKalman(); + auto pos = location.getPositionGeodetic(); + auto orientation = location.getCalibratedOrientationNED(); + + bool localizer_valid = (location.getStatus() == cereal::LiveLocationKalman::Status::VALID) && pos.getValid(); + if (localizer_valid && (sm->rcv_frame("liveLocationKalman") % 10) == 0) { + updatePosition(QMapbox::Coordinate(pos.getValue()[0], pos.getValue()[1]), RAD2DEG(orientation.getValue()[2])); + } + } + + if (sm->updated("navRoute")) { + QList route; + auto coords = (*sm)["navRoute"].getNavRoute().getCoordinates(); + for (auto const &c : coords) { + route.push_back(QGeoCoordinate(c.getLatitude(), c.getLongitude())); + } + updateRoute(route); } } @@ -59,8 +99,13 @@ void MapRenderer::updatePosition(QMapbox::Coordinate position, float bearing) { return; } + // Choose a scale that ensures above 13 zoom level up to and above 75deg of lat + float meters_per_pixel = 2; + float zoom = get_zoom_level_for_scale(position.first, meters_per_pixel); + m_map->setCoordinate(position); m_map->setBearing(bearing); + m_map->setZoom(zoom); update(); } @@ -83,15 +128,23 @@ void MapRenderer::sendVipc() { QImage cap = fbo->toImage().convertToFormat(QImage::Format_RGB888, Qt::AutoColor); uint64_t ts = nanos_since_boot(); - VisionBuf* buf = vipc_server->get_buffer(VisionStreamType::VISION_STREAM_RGB_MAP); + VisionBuf* buf = vipc_server->get_buffer(VisionStreamType::VISION_STREAM_MAP); VisionIpcBufExtra extra = { .frame_id = frame_id, .timestamp_sof = ts, .timestamp_eof = ts, }; - assert(cap.sizeInBytes() == buf->len); - memcpy(buf->addr, cap.bits(), buf->len); + assert(cap.sizeInBytes() >= buf->len); + uint8_t* dst = (uint8_t*)buf->addr; + uint8_t* src = cap.bits(); + + // RGB to greyscale + memset(dst, 128, buf->len); + for (int i = 0; i < WIDTH * HEIGHT; i++) { + dst[i] = src[i * 3]; + } + vipc_server->send(buf, &extra); if (frame_id % 100 == 0) { @@ -117,10 +170,16 @@ void MapRenderer::sendVipc() { uint8_t* MapRenderer::getImage() { QImage cap = fbo->toImage().convertToFormat(QImage::Format_RGB888, Qt::AutoColor); - uint8_t* buf = new uint8_t[cap.sizeInBytes()]; - memcpy(buf, cap.bits(), cap.sizeInBytes()); - return buf; + uint8_t* src = cap.bits(); + uint8_t* dst = new uint8_t[WIDTH * HEIGHT]; + + // RGB to greyscale + for (int i = 0; i < WIDTH * HEIGHT; i++) { + dst[i] = src[i * 3]; + } + + return dst; } void MapRenderer::updateRoute(QList coordinates) { @@ -143,8 +202,8 @@ void MapRenderer::initLayers() { nav["type"] = "line"; nav["source"] = "navSource"; m_map->addLayer(nav, "road-intersection"); - m_map->setPaintProperty("navLayer", "line-color", QColor("blue")); - m_map->setPaintProperty("navLayer", "line-width", 3); + m_map->setPaintProperty("navLayer", "line-color", QColor("grey")); + m_map->setPaintProperty("navLayer", "line-width", 5); m_map->setLayoutProperty("navLayer", "line-cap", "round"); } } @@ -153,7 +212,7 @@ MapRenderer::~MapRenderer() { } extern "C" { - MapRenderer* map_renderer_init() { + MapRenderer* map_renderer_init(char *maps_host = nullptr, char *token = nullptr) { char *argv[] = { (char*)"navd", nullptr @@ -163,8 +222,8 @@ extern "C" { assert(app); QMapboxGLSettings settings; - settings.setApiBaseUrl(MAPS_HOST); - settings.setAccessToken(get_mapbox_token()); + settings.setApiBaseUrl(maps_host == nullptr ? MAPS_HOST : maps_host); + settings.setAccessToken(token == nullptr ? get_mapbox_token() : token); return new MapRenderer(settings, false); } diff --git a/selfdrive/ui/navd/map_renderer.h b/selfdrive/navd/map_renderer.h similarity index 88% rename from selfdrive/ui/navd/map_renderer.h rename to selfdrive/navd/map_renderer.h index 1746e76695..855dc91894 100644 --- a/selfdrive/ui/navd/map_renderer.h +++ b/selfdrive/navd/map_renderer.h @@ -19,7 +19,7 @@ class MapRenderer : public QObject { Q_OBJECT public: - MapRenderer(const QMapboxGLSettings &, bool enable_vipc=true); + MapRenderer(const QMapboxGLSettings &, bool online=true); uint8_t* getImage(); void update(); bool loaded(); @@ -34,6 +34,7 @@ private: std::unique_ptr vipc_server; std::unique_ptr pm; + std::unique_ptr sm; void sendVipc(); QMapboxGLSettings m_settings; @@ -43,7 +44,10 @@ private: uint32_t frame_id = 0; + QTimer* timer; + public slots: void updatePosition(QMapbox::Coordinate position, float bearing); void updateRoute(QList coordinates); + void msgUpdate(); }; diff --git a/selfdrive/ui/navd/map_renderer.py b/selfdrive/navd/map_renderer.py similarity index 87% rename from selfdrive/ui/navd/map_renderer.py rename to selfdrive/navd/map_renderer.py index 28d006841b..868307bb63 100755 --- a/selfdrive/ui/navd/map_renderer.py +++ b/selfdrive/navd/map_renderer.py @@ -3,20 +3,22 @@ import os import time +import numpy as np from cffi import FFI from common.ffi_wrapper import suffix from common.basedir import BASEDIR -HEIGHT = WIDTH = 256 +HEIGHT = WIDTH = SIZE = 512 +METERS_PER_PIXEL = 2 def get_ffi(): - lib = os.path.join(BASEDIR, "selfdrive", "ui", "navd", "libmap_renderer" + suffix()) + lib = os.path.join(BASEDIR, "selfdrive", "navd", "libmap_renderer" + suffix()) ffi = FFI() ffi.cdef(""" -void* map_renderer_init(); +void* map_renderer_init(char *maps_host, char *token); void map_renderer_update_position(void *inst, float lat, float lon, float bearing); void map_renderer_update_route(void *inst, char *polyline); void map_renderer_update(void *inst); @@ -40,20 +42,19 @@ def wait_ready(lib, renderer): def get_image(lib, renderer): buf = lib.map_renderer_get_image(renderer) - r = list(buf[0:3 * WIDTH * HEIGHT]) + r = list(buf[0:WIDTH * HEIGHT]) lib.map_renderer_free_image(renderer, buf) # Convert to numpy r = np.asarray(r) - return r.reshape((WIDTH, HEIGHT, 3)) + return r.reshape((WIDTH, HEIGHT)) if __name__ == "__main__": import matplotlib.pyplot as plt - import numpy as np ffi, lib = get_ffi() - renderer = lib.map_renderer_init() + renderer = lib.map_renderer_init(ffi.NULL, ffi.NULL) wait_ready(lib, renderer) geometry = r"{yxk}@|obn~Eg@@eCFqc@J{RFw@?kA@gA?q|@Riu@NuJBgi@ZqVNcRBaPBkG@iSD{I@_H@cH?gG@mG@gG?aD@{LDgDDkVVyQLiGDgX@q_@@qI@qKhS{R~[}NtYaDbGoIvLwNfP_b@|f@oFnF_JxHel@bf@{JlIuxAlpAkNnLmZrWqFhFoh@jd@kX|TkJxH_RnPy^|[uKtHoZ~Um`DlkCorC``CuShQogCtwB_ThQcr@fk@sVrWgRhVmSb\\oj@jxA{Qvg@u]tbAyHzSos@xjBeKbWszAbgEc~@~jCuTrl@cYfo@mRn\\_m@v}@ij@jp@om@lk@y|A`pAiXbVmWzUod@xj@wNlTw}@|uAwSn\\kRfYqOdS_IdJuK`KmKvJoOhLuLbHaMzGwO~GoOzFiSrEsOhD}PhCqw@vJmnAxSczA`Vyb@bHk[fFgl@pJeoDdl@}}@zIyr@hG}X`BmUdBcM^aRR}Oe@iZc@mR_@{FScHxAn_@vz@zCzH~GjPxAhDlB~DhEdJlIbMhFfG|F~GlHrGjNjItLnGvQ~EhLnBfOn@p`@AzAAvn@CfC?fc@`@lUrArStCfSxEtSzGxM|ElFlBrOzJlEbDnC~BfDtCnHjHlLvMdTnZzHpObOf^pKla@~G|a@dErg@rCbj@zArYlj@ttJ~AfZh@r]LzYg@`TkDbj@gIdv@oE|i@kKzhA{CdNsEfOiGlPsEvMiDpLgBpHyB`MkB|MmArPg@|N?|P^rUvFz~AWpOCdAkB|PuB`KeFfHkCfGy@tAqC~AsBPkDs@uAiAcJwMe@s@eKkPMoXQux@EuuCoH?eI?Kas@}Dy@wAUkMOgDL" @@ -73,6 +74,6 @@ if __name__ == "__main__": print(f"{pos} took {time.time() - t:.2f} s") plt.subplot(2, 2, i + 1) - plt.imshow(get_image(lib, renderer)) + plt.imshow(get_image(lib, renderer), cmap='gray') plt.show() diff --git a/selfdrive/navd/navd.py b/selfdrive/navd/navd.py new file mode 100755 index 0000000000..4855b63594 --- /dev/null +++ b/selfdrive/navd/navd.py @@ -0,0 +1,307 @@ +#!/usr/bin/env python3 +import math +import os +import threading + +import requests +import numpy as np + +import cereal.messaging as messaging +from cereal import log +from common.api import Api +from common.params import Params +from common.realtime import Ratekeeper +from common.transformations.coordinates import ecef2geodetic +from selfdrive.navd.helpers import (Coordinate, coordinate_from_param, + distance_along_geometry, maxspeed_to_ms, + minimum_distance, + parse_banner_instructions) +from system.swaglog import cloudlog + +REROUTE_DISTANCE = 25 +MANEUVER_TRANSITION_THRESHOLD = 10 +VALID_POS_STD = 50.0 + + +class RouteEngine: + def __init__(self, sm, pm): + self.sm = sm + self.pm = pm + + self.params = Params() + + # Get last gps position from params + self.last_position = coordinate_from_param("LastGPSPosition", self.params) + self.last_bearing = None + + self.gps_ok = False + self.localizer_valid = False + + self.nav_destination = None + self.step_idx = None + self.route = None + self.route_geometry = None + + self.recompute_backoff = 0 + self.recompute_countdown = 0 + + self.ui_pid = None + + if "MAPBOX_TOKEN" in os.environ: + self.mapbox_token = os.environ["MAPBOX_TOKEN"] + self.mapbox_host = "https://api.mapbox.com" + else: + try: + self.mapbox_token = Api(self.params.get("DongleId", encoding='utf8')).get_token(expiry_hours=4 * 7 * 24) + except FileNotFoundError: + cloudlog.exception("Failed to generate mapbox token due to missing private key. Ensure device is registered.") + self.mapbox_token = "" + self.mapbox_host = "https://maps.comma.ai" + + def update(self): + self.sm.update(0) + + if self.sm.updated["managerState"]: + ui_pid = [p.pid for p in self.sm["managerState"].processes if p.name == "ui" and p.running] + if ui_pid: + if self.ui_pid and self.ui_pid != ui_pid[0]: + cloudlog.warning("UI restarting, sending route") + threading.Timer(5.0, self.send_route).start() + self.ui_pid = ui_pid[0] + + self.update_location() + self.recompute_route() + self.send_instruction() + + def update_location(self): + location = self.sm['liveLocationKalman'] + laikad = self.sm['gnssMeasurements'] + + locationd_valid = (location.status == log.LiveLocationKalman.Status.valid) and location.positionGeodetic.valid + laikad_valid = laikad.positionECEF.valid and np.linalg.norm(laikad.positionECEF.std) < VALID_POS_STD + + self.localizer_valid = locationd_valid or laikad_valid + self.gps_ok = location.gpsOK or laikad_valid + + if locationd_valid: + self.last_bearing = math.degrees(location.calibratedOrientationNED.value[2]) + self.last_position = Coordinate(location.positionGeodetic.value[0], location.positionGeodetic.value[1]) + elif laikad_valid: + geodetic = ecef2geodetic(laikad.positionECEF.value) + self.last_position = Coordinate(geodetic[0], geodetic[1]) + self.last_bearing = None + + def recompute_route(self): + if self.last_position is None: + return + + new_destination = coordinate_from_param("NavDestination", self.params) + if new_destination is None: + self.clear_route() + return + + should_recompute = self.should_recompute() + if new_destination != self.nav_destination: + cloudlog.warning(f"Got new destination from NavDestination param {new_destination}") + should_recompute = True + + # Don't recompute when GPS drifts in tunnels + if not self.gps_ok and self.step_idx is not None: + return + + if self.recompute_countdown == 0 and should_recompute: + self.recompute_countdown = 2**self.recompute_backoff + self.recompute_backoff = min(6, self.recompute_backoff + 1) + self.calculate_route(new_destination) + else: + self.recompute_countdown = max(0, self.recompute_countdown - 1) + + def calculate_route(self, destination): + cloudlog.warning(f"Calculating route {self.last_position} -> {destination}") + self.nav_destination = destination + + lang = self.params.get('LanguageSetting', encoding='utf8') + if lang is not None: + lang = lang.replace('main_', '') + + params = { + 'access_token': self.mapbox_token, + 'annotations': 'maxspeed', + 'geometries': 'geojson', + 'overview': 'full', + 'steps': 'true', + 'banner_instructions': 'true', + 'alternatives': 'false', + 'language': lang, + } + + if self.last_bearing is not None: + params['bearings'] = f"{(self.last_bearing + 360) % 360:.0f},90;" + + url = self.mapbox_host + f'/directions/v5/mapbox/driving-traffic/{self.last_position.longitude},{self.last_position.latitude};{destination.longitude},{destination.latitude}' + try: + resp = requests.get(url, params=params, timeout=10) + resp.raise_for_status() + + r = resp.json() + if len(r['routes']): + self.route = r['routes'][0]['legs'][0]['steps'] + self.route_geometry = [] + + maxspeed_idx = 0 + maxspeeds = r['routes'][0]['legs'][0]['annotation']['maxspeed'] + + # Convert coordinates + for step in self.route: + coords = [] + + for c in step['geometry']['coordinates']: + coord = Coordinate.from_mapbox_tuple(c) + + # Last step does not have maxspeed + if (maxspeed_idx < len(maxspeeds)): + maxspeed = maxspeeds[maxspeed_idx] + if ('unknown' not in maxspeed) and ('none' not in maxspeed): + coord.annotations['maxspeed'] = maxspeed_to_ms(maxspeed) + + coords.append(coord) + maxspeed_idx += 1 + + self.route_geometry.append(coords) + maxspeed_idx -= 1 # Every segment ends with the same coordinate as the start of the next + + self.step_idx = 0 + else: + cloudlog.warning("Got empty route response") + self.clear_route() + + except requests.exceptions.RequestException: + cloudlog.exception("failed to get route") + self.clear_route() + + self.send_route() + + def send_instruction(self): + msg = messaging.new_message('navInstruction') + + if self.step_idx is None: + msg.valid = False + self.pm.send('navInstruction', msg) + return + + step = self.route[self.step_idx] + geometry = self.route_geometry[self.step_idx] + along_geometry = distance_along_geometry(geometry, self.last_position) + distance_to_maneuver_along_geometry = step['distance'] - along_geometry + + # Current instruction + msg.navInstruction.maneuverDistance = distance_to_maneuver_along_geometry + parse_banner_instructions(msg.navInstruction, step['bannerInstructions'], distance_to_maneuver_along_geometry) + + # Compute total remaining time and distance + remaining = 1.0 - along_geometry / max(step['distance'], 1) + total_distance = step['distance'] * remaining + total_time = step['duration'] * remaining + total_time_typical = step['duration_typical'] * remaining + + # Add up totals for future steps + for i in range(self.step_idx + 1, len(self.route)): + total_distance += self.route[i]['distance'] + total_time += self.route[i]['duration'] + total_time_typical += self.route[i]['duration_typical'] + + msg.navInstruction.distanceRemaining = total_distance + msg.navInstruction.timeRemaining = total_time + msg.navInstruction.timeRemainingTypical = total_time_typical + + # Speed limit + closest_idx, closest = min(enumerate(geometry), key=lambda p: p[1].distance_to(self.last_position)) + if closest_idx > 0: + # If we are not past the closest point, show previous + if along_geometry < distance_along_geometry(geometry, geometry[closest_idx]): + closest = geometry[closest_idx - 1] + + if ('maxspeed' in closest.annotations) and self.localizer_valid: + msg.navInstruction.speedLimit = closest.annotations['maxspeed'] + + # Speed limit sign type + if 'speedLimitSign' in step: + if step['speedLimitSign'] == 'mutcd': + msg.navInstruction.speedLimitSign = log.NavInstruction.SpeedLimitSign.mutcd + elif step['speedLimitSign'] == 'vienna': + msg.navInstruction.speedLimitSign = log.NavInstruction.SpeedLimitSign.vienna + + self.pm.send('navInstruction', msg) + + # Transition to next route segment + if distance_to_maneuver_along_geometry < -MANEUVER_TRANSITION_THRESHOLD: + if self.step_idx + 1 < len(self.route): + self.step_idx += 1 + self.recompute_backoff = 0 + self.recompute_countdown = 0 + else: + cloudlog.warning("Destination reached") + Params().remove("NavDestination") + + # Clear route if driving away from destination + dist = self.nav_destination.distance_to(self.last_position) + if dist > REROUTE_DISTANCE: + self.clear_route() + + def send_route(self): + coords = [] + + if self.route is not None: + for path in self.route_geometry: + coords += [c.as_dict() for c in path] + + msg = messaging.new_message('navRoute') + msg.navRoute.coordinates = coords + self.pm.send('navRoute', msg) + + def clear_route(self): + self.route = None + self.route_geometry = None + self.step_idx = None + self.nav_destination = None + + def should_recompute(self): + if self.step_idx is None or self.route is None: + return True + + # Don't recompute in last segment, assume destination is reached + if self.step_idx == len(self.route) - 1: + return False + + # Compute closest distance to all line segments in the current path + min_d = REROUTE_DISTANCE + 1 + path = self.route_geometry[self.step_idx] + for i in range(len(path) - 1): + a = path[i] + b = path[i + 1] + + if a.distance_to(b) < 1.0: + continue + + min_d = min(min_d, minimum_distance(a, b, self.last_position)) + + return min_d > REROUTE_DISTANCE + + # TODO: Check for going wrong way in segment + + +def main(sm=None, pm=None): + if sm is None: + sm = messaging.SubMaster(['liveLocationKalman', 'gnssMeasurements', 'managerState']) + if pm is None: + pm = messaging.PubMaster(['navInstruction', 'navRoute']) + + rk = Ratekeeper(1.0) + route_engine = RouteEngine(sm, pm) + while True: + route_engine.update() + rk.keep_time() + + +if __name__ == "__main__": + main() diff --git a/selfdrive/navd/style.json b/selfdrive/navd/style.json new file mode 100644 index 0000000000..06bb750d1f --- /dev/null +++ b/selfdrive/navd/style.json @@ -0,0 +1 @@ +{"version": 8, "name": "Navigation Model", "metadata": {"mapbox:type": "default", "mapbox:origin": "monochrome-dark-v1", "mapbox:sdk-support": {"android": "10.0.0", "ios": "10.0.0", "js": "2.3.0"}, "mapbox:autocomposite": true, "mapbox:groups": {"Transit, transit-labels": {"name": "Transit, transit-labels", "collapsed": true}, "Administrative boundaries, admin": {"name": "Administrative boundaries, admin", "collapsed": true}, "Transit, bridges": {"name": "Transit, bridges", "collapsed": true}, "Transit, surface": {"name": "Transit, surface", "collapsed": true}, "Road network, bridges": {"name": "Road network, bridges", "collapsed": false}, "Land, water, & sky, water": {"name": "Land, water, & sky, water", "collapsed": true}, "Road network, tunnels": {"name": "Road network, tunnels", "collapsed": false}, "Road network, road-labels": {"name": "Road network, road-labels", "collapsed": true}, "Buildings, built": {"name": "Buildings, built", "collapsed": true}, "Natural features, natural-labels": {"name": "Natural features, natural-labels", "collapsed": true}, "Road network, surface": {"name": "Road network, surface", "collapsed": false}, "Land, water, & sky, built": {"name": "Land, water, & sky, built", "collapsed": true}, "Place labels, place-labels": {"name": "Place labels, place-labels", "collapsed": true}, "Point of interest labels, poi-labels": {"name": "Point of interest labels, poi-labels", "collapsed": true}, "Road network, tunnels-case": {"name": "Road network, tunnels-case", "collapsed": true}, "Transit, built": {"name": "Transit, built", "collapsed": true}, "Road network, surface-icons": {"name": "Road network, surface-icons", "collapsed": false}, "Land, water, & sky, land": {"name": "Land, water, & sky, land", "collapsed": true}}}, "center": [-117.19189443261149, 32.756553679559985], "zoom": 12.932776547838778, "bearing": 0, "pitch": 0.5017568344510897, "sources": {"composite": {"url": "mapbox://mapbox.mapbox-streets-v8", "type": "vector", "maxzoom": 13}}, "sprite": "mapbox://sprites/commaai/ckvmksrpd4n0a14pfdo5heqzr/bkx9h9tjdf3xedbnjvfo5xnbv", "glyphs": "mapbox://fonts/mapbox/{fontstack}/{range}.pbf", "layers": [{"id": "land", "type": "background", "layout": {"visibility": "none"}, "paint": {"background-color": "rgb(252, 252, 252)"}, "metadata": {"mapbox:featureComponent": "land-and-water", "mapbox:group": "Land, water, & sky, land"}}, {"minzoom": 5, "layout": {"visibility": "none"}, "metadata": {"mapbox:featureComponent": "land-and-water", "mapbox:group": "Land, water, & sky, land"}, "filter": ["==", ["get", "class"], "national_park"], "type": "fill", "source": "composite", "id": "national-park", "paint": {"fill-color": "rgb(240, 240, 240)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, 0.5, 10, 0.5]}, "source-layer": "landuse_overlay"}, {"minzoom": 5, "layout": {"visibility": "none"}, "metadata": {"mapbox:featureComponent": "land-and-water", "mapbox:group": "Land, water, & sky, land"}, "filter": ["match", ["get", "class"], ["park", "airport", "glacier", "pitch", "sand", "facility"], true, false], "type": "fill", "source": "composite", "id": "landuse", "paint": {"fill-color": "rgb(240, 240, 240)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 5, 0, 6, ["match", ["get", "class"], "glacier", 0.5, 1]]}, "source-layer": "landuse"}, {"id": "waterway-shadow", "type": "line", "source": "composite", "source-layer": "waterway", "minzoom": 8, "layout": {"line-cap": ["step", ["zoom"], "butt", 11, "round"], "line-join": "round", "visibility": "none"}, "paint": {"line-color": "rgb(204, 204, 204)", "line-width": ["interpolate", ["exponential", 1.3], ["zoom"], 9, ["match", ["get", "class"], ["canal", "river"], 0.1, 0], 20, ["match", ["get", "class"], ["canal", "river"], 8, 3]], "line-translate": ["interpolate", ["exponential", 1.2], ["zoom"], 7, ["literal", [0, 0]], 16, ["literal", [-1, -1]]], "line-translate-anchor": "viewport", "line-opacity": ["interpolate", ["linear"], ["zoom"], 8, 0, 8.5, 1]}, "metadata": {"mapbox:featureComponent": "land-and-water", "mapbox:group": "Land, water, & sky, water"}}, {"id": "water-shadow", "type": "fill", "source": "composite", "source-layer": "water", "layout": {"visibility": "none"}, "paint": {"fill-color": "rgb(204, 204, 204)", "fill-translate": ["interpolate", ["exponential", 1.2], ["zoom"], 7, ["literal", [0, 0]], 16, ["literal", [-1, -1]]], "fill-translate-anchor": "viewport"}, "metadata": {"mapbox:featureComponent": "land-and-water", "mapbox:group": "Land, water, & sky, water"}}, {"id": "waterway", "type": "line", "source": "composite", "source-layer": "waterway", "minzoom": 8, "layout": {"line-cap": ["step", ["zoom"], "butt", 11, "round"], "line-join": "round", "visibility": "none"}, "paint": {"line-color": "rgb(224, 224, 224)", "line-width": ["interpolate", ["exponential", 1.3], ["zoom"], 9, ["match", ["get", "class"], ["canal", "river"], 0.1, 0], 20, ["match", ["get", "class"], ["canal", "river"], 8, 3]], "line-opacity": ["interpolate", ["linear"], ["zoom"], 8, 0, 8.5, 1]}, "metadata": {"mapbox:featureComponent": "land-and-water", "mapbox:group": "Land, water, & sky, water"}}, {"id": "water", "type": "fill", "source": "composite", "source-layer": "water", "layout": {"visibility": "none"}, "paint": {"fill-color": "rgb(224, 224, 224)"}, "metadata": {"mapbox:featureComponent": "land-and-water", "mapbox:group": "Land, water, & sky, water"}}, {"minzoom": 13, "layout": {"visibility": "none"}, "metadata": {"mapbox:featureComponent": "land-and-water", "mapbox:group": "Land, water, & sky, built"}, "filter": ["all", ["==", ["geometry-type"], "Polygon"], ["==", ["get", "class"], "land"]], "type": "fill", "source": "composite", "id": "land-structure-polygon", "paint": {"fill-color": "rgb(252, 252, 252)"}, "source-layer": "structure"}, {"minzoom": 13, "layout": {"line-cap": "round", "visibility": "none"}, "metadata": {"mapbox:featureComponent": "land-and-water", "mapbox:group": "Land, water, & sky, built"}, "filter": ["all", ["==", ["geometry-type"], "LineString"], ["==", ["get", "class"], "land"]], "type": "line", "source": "composite", "id": "land-structure-line", "paint": {"line-width": ["interpolate", ["exponential", 1.99], ["zoom"], 14, 0.75, 20, 40], "line-color": "rgb(252, 252, 252)"}, "source-layer": "structure"}, {"minzoom": 11, "layout": {"visibility": "none"}, "metadata": {"mapbox:featureComponent": "transit", "mapbox:group": "Transit, built"}, "filter": ["all", ["==", ["geometry-type"], "Polygon"], ["match", ["get", "type"], ["runway", "taxiway", "helipad"], true, false]], "type": "fill", "source": "composite", "id": "aeroway-polygon", "paint": {"fill-color": "rgb(255, 255, 255)", "fill-opacity": ["interpolate", ["linear"], ["zoom"], 11, 0, 11.5, 1]}, "source-layer": "aeroway"}, {"minzoom": 9, "layout": {"visibility": "none"}, "metadata": {"mapbox:featureComponent": "transit", "mapbox:group": "Transit, built"}, "filter": ["==", ["geometry-type"], "LineString"], "type": "line", "source": "composite", "id": "aeroway-line", "paint": {"line-color": "rgb(255, 255, 255)", "line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 9, ["match", ["get", "type"], "runway", 1, 0.5], 18, ["match", ["get", "type"], "runway", 80, 20]]}, "source-layer": "aeroway"}, {"minzoom": 13, "layout": {"visibility": "none"}, "metadata": {"mapbox:featureComponent": "buildings", "mapbox:group": "Buildings, built"}, "filter": ["all", ["!=", ["get", "type"], "building:part"], ["==", ["get", "underground"], "false"]], "type": "line", "source": "composite", "id": "building-outline", "paint": {"line-color": "rgb(227, 227, 227)", "line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 15, 0.75, 20, 3], "line-opacity": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 1]}, "source-layer": "building"}, {"minzoom": 13, "layout": {"visibility": "none"}, "metadata": {"mapbox:featureComponent": "buildings", "mapbox:group": "Buildings, built"}, "filter": ["all", ["!=", ["get", "type"], "building:part"], ["==", ["get", "underground"], "false"]], "type": "fill", "source": "composite", "id": "building", "paint": {"fill-color": ["interpolate", ["linear"], ["zoom"], 15, "rgb(242, 242, 242)", 16, "rgb(242, 242, 242)"], "fill-opacity": ["interpolate", ["linear"], ["zoom"], 15, 0, 16, 1], "fill-outline-color": "rgb(227, 227, 227)"}, "source-layer": "building"}, {"minzoom": 13, "layout": {}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, tunnels-case"}, "filter": ["all", ["==", ["get", "structure"], "tunnel"], ["step", ["zoom"], ["match", ["get", "class"], ["street", "street_limited", "primary_link", "track"], true, false], 1, ["match", ["get", "class"], ["street", "street_limited", "track", "primary_link", "secondary_link", "tertiary_link", "service"], true, false]], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "tunnel-street-minor-low", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 12, 0.5, 14, ["match", ["get", "class"], ["street", "street_limited", "primary_link"], 2, "track", 1, 0.5], 18, ["match", ["get", "class"], ["street", "street_limited", "primary_link"], 18, 12]], "line-color": "rgb(235, 235, 235)", "line-opacity": ["step", ["zoom"], 1, 14, 0]}, "source-layer": "road"}, {"minzoom": 13, "layout": {}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, tunnels-case"}, "filter": ["all", ["==", ["get", "structure"], "tunnel"], ["step", ["zoom"], ["match", ["get", "class"], ["street", "street_limited", "primary_link", "track"], true, false], 1, ["match", ["get", "class"], ["street", "street_limited", "track", "primary_link", "secondary_link", "tertiary_link", "service"], true, false]], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "tunnel-street-minor-case", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 12, 0.75, 20, 2], "line-color": "rgb(255, 255, 255)", "line-gap-width": ["interpolate", ["exponential", 1.5], ["zoom"], 12, 0.5, 14, ["match", ["get", "class"], ["street", "street_limited", "primary_link"], 2, "track", 1, 0.5], 18, ["match", ["get", "class"], ["street", "street_limited", "primary_link"], 18, 12]], "line-opacity": ["step", ["zoom"], 0, 14, 1], "line-dasharray": [3, 3]}, "source-layer": "road"}, {"minzoom": 13, "layout": {}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, tunnels-case"}, "filter": ["all", ["==", ["get", "structure"], "tunnel"], ["match", ["get", "class"], ["primary", "secondary", "tertiary"], true, false], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "tunnel-primary-secondary-tertiary-case", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 10, ["match", ["get", "class"], "primary", 1, 0.75], 18, 2], "line-color": "rgb(255, 255, 255)", "line-gap-width": ["interpolate", ["exponential", 1.5], ["zoom"], 5, ["match", ["get", "class"], "primary", 0.75, 0.1], 18, ["match", ["get", "class"], "primary", 32, 26]], "line-dasharray": [3, 3]}, "source-layer": "road"}, {"minzoom": 13, "layout": {}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, tunnels-case"}, "filter": ["all", ["==", ["get", "structure"], "tunnel"], ["match", ["get", "class"], ["motorway_link", "trunk_link"], true, false], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "tunnel-major-link-case", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 12, 0.75, 20, 2], "line-color": "rgb(255, 255, 255)", "line-gap-width": ["interpolate", ["exponential", 1.5], ["zoom"], 12, 0.5, 14, 2, 18, 18], "line-dasharray": [3, 3]}, "source-layer": "road"}, {"minzoom": 13, "layout": {}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, tunnels-case"}, "filter": ["all", ["==", ["get", "structure"], "tunnel"], ["match", ["get", "class"], ["motorway", "trunk"], true, false], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "tunnel-motorway-trunk-case", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 10, 1, 18, 2], "line-color": "rgb(255, 255, 255)", "line-gap-width": ["interpolate", ["exponential", 1.5], ["zoom"], 5, 0.75, 18, 32], "line-dasharray": [3, 3]}, "source-layer": "road"}, {"minzoom": 13, "layout": {}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, tunnels-case"}, "filter": ["all", ["==", ["get", "structure"], "tunnel"], ["==", ["get", "class"], "construction"], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "tunnel-construction", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 14, 2, 18, 18], "line-color": "rgb(235, 235, 235)", "line-dasharray": ["step", ["zoom"], ["literal", [0.4, 0.8]], 15, ["literal", [0.3, 0.6]], 16, ["literal", [0.2, 0.3]], 17, ["literal", [0.2, 0.25]], 18, ["literal", [0.15, 0.15]]]}, "source-layer": "road"}, {"minzoom": 13, "layout": {}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, tunnels"}, "filter": ["all", ["==", ["get", "structure"], "tunnel"], ["match", ["get", "class"], ["motorway_link", "trunk_link"], true, false], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "tunnel-major-link", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 12, 0.5, 14, 2, 18, 18], "line-color": "rgb(235, 235, 235)"}, "source-layer": "road"}, {"minzoom": 13, "layout": {}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, tunnels"}, "filter": ["all", ["==", ["get", "structure"], "tunnel"], ["step", ["zoom"], ["match", ["get", "class"], ["street", "street_limited", "primary_link", "track"], true, false], 1, ["match", ["get", "class"], ["street", "street_limited", "track", "primary_link", "secondary_link", "tertiary_link", "service"], true, false]], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "tunnel-street-minor", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 12, 0.5, 14, ["match", ["get", "class"], ["street", "street_limited", "primary_link"], 2, "track", 1, 0.5], 18, ["match", ["get", "class"], ["street", "street_limited", "primary_link"], 18, 12]], "line-color": "rgb(235, 235, 235)", "line-opacity": ["step", ["zoom"], 0, 14, 1]}, "source-layer": "road"}, {"minzoom": 13, "layout": {}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, tunnels"}, "filter": ["all", ["==", ["get", "structure"], "tunnel"], ["match", ["get", "class"], ["primary", "secondary", "tertiary"], true, false], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "tunnel-primary-secondary-tertiary", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 5, ["match", ["get", "class"], "primary", 0.75, 0.1], 18, ["match", ["get", "class"], "primary", 32, 26]], "line-color": "rgb(235, 235, 235)"}, "source-layer": "road"}, {"minzoom": 13, "layout": {}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, tunnels"}, "filter": ["all", ["==", ["get", "structure"], "tunnel"], ["match", ["get", "class"], ["motorway", "trunk"], true, false], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "tunnel-motorway-trunk", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 5, 0.75, 18, 32], "line-color": "rgb(235, 235, 235)"}, "source-layer": "road"}, {"minzoom": 13, "layout": {"icon-image": "turning-circle-outline", "icon-size": ["interpolate", ["exponential", 1.5], ["zoom"], 14, 0.122, 18, 0.969, 20, 1], "icon-allow-overlap": true, "icon-ignore-placement": true, "icon-padding": 0, "icon-rotation-alignment": "map", "visibility": "none"}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, surface"}, "filter": ["all", ["==", ["geometry-type"], "Point"], ["match", ["get", "class"], ["turning_circle", "turning_loop"], true, false]], "type": "symbol", "source": "composite", "id": "turning-feature-outline", "paint": {}, "source-layer": "road"}, {"minzoom": 13, "layout": {"line-cap": ["step", ["zoom"], "butt", 14, "round"], "line-join": ["step", ["zoom"], "miter", 14, "round"]}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, surface"}, "filter": ["all", ["step", ["zoom"], ["==", ["get", "class"], "track"], 1, ["match", ["get", "class"], ["track", "secondary_link", "tertiary_link", "service"], true, false]], ["match", ["get", "structure"], ["none", "ford"], true, false], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "road-minor-low", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 14, ["match", ["get", "class"], "track", 1, 0.5], 18, 12], "line-color": "rgb(255, 255, 255)", "line-opacity": ["step", ["zoom"], 1, 14, 0]}, "source-layer": "road"}, {"minzoom": 13, "layout": {"line-cap": ["step", ["zoom"], "butt", 14, "round"], "line-join": ["step", ["zoom"], "miter", 14, "round"]}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, surface"}, "filter": ["all", ["step", ["zoom"], ["==", ["get", "class"], "track"], 1, ["match", ["get", "class"], ["track", "secondary_link", "tertiary_link", "service"], true, false]], ["match", ["get", "structure"], ["none", "ford"], true, false], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "road-minor-case", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 12, 0.75, 20, 2], "line-color": "rgb(242, 242, 242)", "line-gap-width": ["interpolate", ["exponential", 1.5], ["zoom"], 14, ["match", ["get", "class"], "track", 1, 0.5], 18, 12], "line-opacity": ["step", ["zoom"], 0, 14, 1]}, "source-layer": "road"}, {"minzoom": 11, "layout": {"line-cap": ["step", ["zoom"], "butt", 14, "round"], "line-join": ["step", ["zoom"], "miter", 14, "round"]}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, surface"}, "filter": ["all", ["match", ["get", "class"], ["street", "street_limited", "primary_link"], true, false], ["match", ["get", "structure"], ["none", "ford"], true, false], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "road-street-low", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 12, 0.5, 14, 2, 18, 18], "line-color": "rgb(255, 255, 255)", "line-opacity": ["step", ["zoom"], 1, 14, 0]}, "source-layer": "road"}, {"minzoom": 11, "layout": {"line-cap": ["step", ["zoom"], "butt", 14, "round"], "line-join": ["step", ["zoom"], "miter", 14, "round"]}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, surface"}, "filter": ["all", ["match", ["get", "class"], ["street", "street_limited", "primary_link"], true, false], ["match", ["get", "structure"], ["none", "ford"], true, false], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "road-street-case", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 12, 0.75, 20, 2], "line-color": "rgb(242, 242, 242)", "line-gap-width": ["interpolate", ["exponential", 1.5], ["zoom"], 12, 0.5, 14, 2, 18, 18], "line-opacity": ["step", ["zoom"], 0, 14, 1]}, "source-layer": "road"}, {"minzoom": 8, "layout": {"line-cap": ["step", ["zoom"], "butt", 14, "round"], "line-join": ["step", ["zoom"], "miter", 14, "round"]}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, surface"}, "filter": ["all", ["match", ["get", "class"], ["secondary", "tertiary"], true, false], ["match", ["get", "structure"], ["none", "ford"], true, false], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "road-secondary-tertiary-case", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 10, 0.75, 18, 2], "line-color": "rgb(242, 242, 242)", "line-gap-width": ["interpolate", ["exponential", 1.5], ["zoom"], 5, 0.1, 18, 26], "line-opacity": ["step", ["zoom"], 0, 10, 1]}, "source-layer": "road"}, {"minzoom": 7, "layout": {"line-cap": ["step", ["zoom"], "butt", 14, "round"], "line-join": ["step", ["zoom"], "miter", 14, "round"]}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, surface"}, "filter": ["all", ["==", ["get", "class"], "primary"], ["match", ["get", "structure"], ["none", "ford"], true, false], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "road-primary-case", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 10, 1, 18, 2], "line-color": "rgb(242, 242, 242)", "line-gap-width": ["interpolate", ["exponential", 1.5], ["zoom"], 5, 0.75, 18, 32], "line-opacity": ["step", ["zoom"], 0, 10, 1]}, "source-layer": "road"}, {"minzoom": 10, "layout": {"line-cap": ["step", ["zoom"], "butt", 14, "round"], "line-join": ["step", ["zoom"], "miter", 14, "round"]}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, surface"}, "filter": ["all", ["match", ["get", "class"], ["motorway_link", "trunk_link"], true, false], ["match", ["get", "structure"], ["none", "ford"], true, false], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "road-major-link-case", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 12, 0.75, 20, 2], "line-color": "rgb(242, 242, 242)", "line-gap-width": ["interpolate", ["exponential", 1.5], ["zoom"], 12, 0.5, 14, 2, 18, 18], "line-opacity": ["step", ["zoom"], 0, 11, 1]}, "source-layer": "road"}, {"minzoom": 5, "layout": {"line-cap": ["step", ["zoom"], "butt", 14, "round"], "line-join": ["step", ["zoom"], "miter", 14, "round"]}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, surface"}, "filter": ["all", ["match", ["get", "class"], ["motorway", "trunk"], true, false], ["match", ["get", "structure"], ["none", "ford"], true, false], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "road-motorway-trunk-case", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 10, 1, 18, 2], "line-color": "rgb(242, 242, 242)", "line-gap-width": ["interpolate", ["exponential", 1.5], ["zoom"], 5, 0.75, 18, 32], "line-opacity": ["step", ["zoom"], ["match", ["get", "class"], "motorway", 1, 0], 6, 1]}, "source-layer": "road"}, {"minzoom": 13, "layout": {}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, surface"}, "filter": ["all", ["==", ["get", "class"], "construction"], ["match", ["get", "structure"], ["none", "ford"], true, false], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "road-construction", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 14, 2, 18, 18], "line-color": "rgb(255, 255, 255)", "line-dasharray": ["step", ["zoom"], ["literal", [0.4, 0.8]], 15, ["literal", [0.3, 0.6]], 16, ["literal", [0.2, 0.3]], 17, ["literal", [0.2, 0.25]], 18, ["literal", [0.15, 0.15]]]}, "source-layer": "road"}, {"minzoom": 10, "layout": {"line-cap": ["step", ["zoom"], "butt", 13, "round"], "line-join": ["step", ["zoom"], "miter", 13, "round"]}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, surface"}, "filter": ["all", ["match", ["get", "class"], ["motorway_link", "trunk_link"], true, false], ["match", ["get", "structure"], ["none", "ford"], true, false], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "road-major-link", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 12, 0.5, 14, 2, 18, 18], "line-color": "rgb(255, 255, 255)"}, "source-layer": "road"}, {"minzoom": 13, "layout": {"line-cap": ["step", ["zoom"], "butt", 14, "round"], "line-join": ["step", ["zoom"], "miter", 14, "round"]}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, surface"}, "filter": ["all", ["step", ["zoom"], ["==", ["get", "class"], "track"], 1, ["match", ["get", "class"], ["track", "secondary_link", "tertiary_link", "service"], true, false]], ["match", ["get", "structure"], ["none", "ford"], true, false], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "road-minor", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 14, ["match", ["get", "class"], "track", 1, 0.5], 18, 12], "line-color": "rgb(255, 255, 255)", "line-opacity": ["step", ["zoom"], 0, 14, 1]}, "source-layer": "road"}, {"minzoom": 11, "layout": {"line-cap": ["step", ["zoom"], "butt", 14, "round"], "line-join": ["step", ["zoom"], "miter", 14, "round"]}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, surface"}, "filter": ["all", ["match", ["get", "class"], ["street", "street_limited", "primary_link"], true, false], ["match", ["get", "structure"], ["none", "ford"], true, false], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "road-street", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 12, 0.5, 14, 2, 18, 18], "line-color": "rgb(255, 255, 255)", "line-opacity": ["step", ["zoom"], 0, 14, 1]}, "source-layer": "road"}, {"minzoom": 8, "layout": {"line-cap": ["step", ["zoom"], "butt", 14, "round"], "line-join": ["step", ["zoom"], "miter", 14, "round"]}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, surface"}, "filter": ["all", ["match", ["get", "class"], ["secondary", "tertiary"], true, false], ["match", ["get", "structure"], ["none", "ford"], true, false], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "road-secondary-tertiary", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 5, 0.1, 18, 26], "line-color": "rgb(255, 255, 255)"}, "source-layer": "road"}, {"minzoom": 6, "layout": {"line-cap": ["step", ["zoom"], "butt", 14, "round"], "line-join": ["step", ["zoom"], "miter", 14, "round"]}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, surface"}, "filter": ["all", ["==", ["get", "class"], "primary"], ["match", ["get", "structure"], ["none", "ford"], true, false], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "road-primary", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 5, 0.75, 18, 32], "line-color": "rgb(255, 255, 255)"}, "source-layer": "road"}, {"id": "road-motorway-trunk", "type": "line", "source": "composite", "source-layer": "road", "filter": ["all", ["match", ["get", "class"], ["motorway", "trunk"], true, false], ["match", ["get", "structure"], ["none", "ford"], true, false], ["==", ["geometry-type"], "LineString"]], "layout": {"line-cap": ["step", ["zoom"], "butt", 13, "round"], "line-join": ["step", ["zoom"], "miter", 13, "round"]}, "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 5, 0.75, 18, 32], "line-color": "rgb(255, 255, 255)"}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, surface"}}, {"minzoom": 13, "layout": {"line-join": "round", "visibility": "none"}, "metadata": {"mapbox:featureComponent": "transit", "mapbox:group": "Transit, surface"}, "filter": ["all", ["match", ["get", "class"], ["major_rail", "minor_rail"], true, false], ["match", ["get", "structure"], ["none", "ford"], true, false]], "type": "line", "source": "composite", "id": "road-rail", "paint": {"line-color": ["interpolate", ["linear"], ["zoom"], 13, "rgb(242, 242, 242)", 17, "rgb(227, 227, 227)"], "line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 14, 0.5, 20, 1]}, "source-layer": "road"}, {"minzoom": 13, "layout": {"icon-image": "turning-circle", "icon-size": ["interpolate", ["exponential", 1.5], ["zoom"], 14, 0.095, 18, 1], "icon-allow-overlap": true, "icon-ignore-placement": true, "icon-padding": 0, "icon-rotation-alignment": "map", "visibility": "none"}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, surface-icons"}, "filter": ["all", ["==", ["geometry-type"], "Point"], ["match", ["get", "class"], ["turning_circle", "turning_loop"], true, false]], "type": "symbol", "source": "composite", "id": "turning-feature", "paint": {}, "source-layer": "road"}, {"minzoom": 13, "layout": {"line-cap": ["step", ["zoom"], "butt", 14, "round"], "line-join": ["step", ["zoom"], "miter", 14, "round"]}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, bridges"}, "filter": ["all", ["==", ["get", "structure"], "bridge"], ["step", ["zoom"], ["match", ["get", "class"], ["street", "street_limited", "primary_link", "track"], true, false], 1, ["match", ["get", "class"], ["street", "street_limited", "track", "primary_link", "secondary_link", "tertiary_link", "service"], true, false]], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "bridge-street-minor-low", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 12, 0.5, 14, ["match", ["get", "class"], ["street", "street_limited", "primary_link"], 2, "track", 1, 0.5], 18, ["match", ["get", "class"], ["street", "street_limited", "primary_link"], 18, 12]], "line-color": "rgb(255, 255, 255)", "line-opacity": ["step", ["zoom"], 1, 14, 0]}, "source-layer": "road"}, {"minzoom": 13, "layout": {"line-join": "round"}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, bridges"}, "filter": ["all", ["==", ["get", "structure"], "bridge"], ["step", ["zoom"], ["match", ["get", "class"], ["street", "street_limited", "primary_link", "track"], true, false], 1, ["match", ["get", "class"], ["street", "street_limited", "track", "primary_link", "secondary_link", "tertiary_link", "service"], true, false]], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "bridge-street-minor-case", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 12, 0.75, 20, 2], "line-color": "rgb(242, 242, 242)", "line-gap-width": ["interpolate", ["exponential", 1.5], ["zoom"], 12, 0.5, 14, ["match", ["get", "class"], ["street", "street_limited", "primary_link"], 2, "track", 1, 0.5], 18, ["match", ["get", "class"], ["street", "street_limited", "primary_link"], 18, 12]], "line-opacity": ["step", ["zoom"], 0, 14, 1]}, "source-layer": "road"}, {"minzoom": 13, "layout": {"line-join": "round"}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, bridges"}, "filter": ["all", ["==", ["get", "structure"], "bridge"], ["match", ["get", "class"], ["primary", "secondary", "tertiary"], true, false], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "bridge-primary-secondary-tertiary-case", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 10, ["match", ["get", "class"], "primary", 1, 0.75], 18, 2], "line-color": "rgb(242, 242, 242)", "line-gap-width": ["interpolate", ["exponential", 1.5], ["zoom"], 5, ["match", ["get", "class"], "primary", 0.75, 0.1], 18, ["match", ["get", "class"], "primary", 32, 26]], "line-opacity": ["step", ["zoom"], 0, 10, 1]}, "source-layer": "road"}, {"minzoom": 13, "layout": {"line-join": "round"}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, bridges"}, "filter": ["all", ["==", ["get", "structure"], "bridge"], ["match", ["get", "class"], ["motorway_link", "trunk_link"], true, false], ["<=", ["get", "layer"], 1], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "bridge-major-link-case", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 12, 0.75, 20, 2], "line-color": "rgb(242, 242, 242)", "line-gap-width": ["interpolate", ["exponential", 1.5], ["zoom"], 12, 0.5, 14, 2, 18, 18]}, "source-layer": "road"}, {"minzoom": 13, "layout": {"line-join": "round"}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, bridges"}, "filter": ["all", ["==", ["get", "structure"], "bridge"], ["match", ["get", "class"], ["motorway", "trunk"], true, false], ["<=", ["get", "layer"], 1], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "bridge-motorway-trunk-case", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 10, 1, 18, 2], "line-color": "rgb(242, 242, 242)", "line-gap-width": ["interpolate", ["exponential", 1.5], ["zoom"], 5, 0.75, 18, 32]}, "source-layer": "road"}, {"minzoom": 13, "layout": {}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, bridges"}, "filter": ["all", ["==", ["get", "structure"], "bridge"], ["==", ["get", "class"], "construction"], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "bridge-construction", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 14, 2, 18, 18], "line-color": "rgb(255, 255, 255)", "line-dasharray": ["step", ["zoom"], ["literal", [0.4, 0.8]], 15, ["literal", [0.3, 0.6]], 16, ["literal", [0.2, 0.3]], 17, ["literal", [0.2, 0.25]], 18, ["literal", [0.15, 0.15]]]}, "source-layer": "road"}, {"minzoom": 13, "layout": {"line-cap": "round", "line-join": "round"}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, bridges"}, "filter": ["all", ["==", ["get", "structure"], "bridge"], ["match", ["get", "class"], ["motorway_link", "trunk_link"], true, false], ["<=", ["get", "layer"], 1], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "bridge-major-link", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 12, 0.5, 14, 2, 18, 18], "line-color": "rgb(255, 255, 255)"}, "source-layer": "road"}, {"minzoom": 13, "layout": {"line-cap": ["step", ["zoom"], "butt", 14, "round"], "line-join": ["step", ["zoom"], "miter", 14, "round"]}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, bridges"}, "filter": ["all", ["==", ["get", "structure"], "bridge"], ["step", ["zoom"], ["match", ["get", "class"], ["street", "street_limited", "primary_link", "track"], true, false], 1, ["match", ["get", "class"], ["street", "street_limited", "track", "primary_link", "secondary_link", "tertiary_link", "service"], true, false]], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "bridge-street-minor", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 12, 0.5, 14, ["match", ["get", "class"], ["street", "street_limited", "primary_link"], 2, "track", 1, 0.5], 18, ["match", ["get", "class"], ["street", "street_limited", "primary_link"], 18, 12]], "line-color": "rgb(255, 255, 255)", "line-opacity": ["step", ["zoom"], 0, 14, 1]}, "source-layer": "road"}, {"minzoom": 13, "layout": {"line-cap": ["step", ["zoom"], "butt", 14, "round"], "line-join": ["step", ["zoom"], "miter", 14, "round"]}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, bridges"}, "filter": ["all", ["==", ["get", "structure"], "bridge"], ["match", ["get", "class"], ["primary", "secondary", "tertiary"], true, false], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "bridge-primary-secondary-tertiary", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 5, ["match", ["get", "class"], "primary", 0.75, 0.1], 18, ["match", ["get", "class"], "primary", 32, 26]], "line-color": "rgb(255, 255, 255)"}, "source-layer": "road"}, {"minzoom": 13, "layout": {"line-cap": "round", "line-join": "round"}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, bridges"}, "filter": ["all", ["==", ["get", "structure"], "bridge"], ["match", ["get", "class"], ["motorway", "trunk"], true, false], ["<=", ["get", "layer"], 1], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "bridge-motorway-trunk", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 5, 0.75, 18, 32], "line-color": "rgb(255, 255, 255)"}, "source-layer": "road"}, {"minzoom": 13, "layout": {"line-join": "round"}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, bridges"}, "filter": ["all", ["==", ["get", "structure"], "bridge"], [">=", ["get", "layer"], 2], ["match", ["get", "class"], ["motorway_link", "trunk_link"], true, false], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "bridge-major-link-2-case", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 12, 0.75, 20, 2], "line-color": "rgb(242, 242, 242)", "line-gap-width": ["interpolate", ["exponential", 1.5], ["zoom"], 12, 0.5, 14, 2, 18, 18]}, "source-layer": "road"}, {"minzoom": 13, "layout": {"line-join": "round"}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, bridges"}, "filter": ["all", ["==", ["get", "structure"], "bridge"], [">=", ["get", "layer"], 2], ["match", ["get", "class"], ["motorway", "trunk"], true, false], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "bridge-motorway-trunk-2-case", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 10, 1, 18, 2], "line-color": "rgb(242, 242, 242)", "line-gap-width": ["interpolate", ["exponential", 1.5], ["zoom"], 5, 0.75, 18, 32]}, "source-layer": "road"}, {"minzoom": 13, "layout": {"line-cap": "round", "line-join": "round"}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, bridges"}, "filter": ["all", ["==", ["get", "structure"], "bridge"], [">=", ["get", "layer"], 2], ["match", ["get", "class"], ["motorway_link", "trunk_link"], true, false], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "bridge-major-link-2", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 12, 0.5, 14, 2, 18, 18], "line-color": "rgb(255, 255, 255)"}, "source-layer": "road"}, {"minzoom": 13, "layout": {"line-cap": ["step", ["zoom"], "butt", 14, "round"], "line-join": ["step", ["zoom"], "miter", 14, "round"]}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, bridges"}, "filter": ["all", ["==", ["get", "structure"], "bridge"], [">=", ["get", "layer"], 2], ["match", ["get", "class"], ["motorway", "trunk"], true, false], ["==", ["geometry-type"], "LineString"]], "type": "line", "source": "composite", "id": "bridge-motorway-trunk-2", "paint": {"line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 5, 0.75, 18, 32], "line-color": "rgb(255, 255, 255)"}, "source-layer": "road"}, {"minzoom": 13, "layout": {"line-join": "round", "visibility": "none"}, "metadata": {"mapbox:featureComponent": "transit", "mapbox:group": "Transit, bridges"}, "filter": ["all", ["==", ["get", "structure"], "bridge"], ["match", ["get", "class"], ["major_rail", "minor_rail"], true, false]], "type": "line", "source": "composite", "id": "bridge-rail", "paint": {"line-color": "rgb(227, 227, 227)", "line-width": ["interpolate", ["exponential", 1.5], ["zoom"], 14, 0.5, 20, 1]}, "source-layer": "road"}, {"minzoom": 7, "layout": {"line-join": "bevel", "visibility": "none"}, "metadata": {"mapbox:featureComponent": "admin-boundaries", "mapbox:group": "Administrative boundaries, admin"}, "filter": ["all", ["==", ["get", "admin_level"], 1], ["==", ["get", "maritime"], "false"], ["match", ["get", "worldview"], ["all", "US"], true, false]], "type": "line", "source": "composite", "id": "admin-1-boundary-bg", "paint": {"line-color": ["interpolate", ["linear"], ["zoom"], 8, "rgb(227, 227, 227)", 16, "rgb(227, 227, 227)"], "line-width": ["interpolate", ["linear"], ["zoom"], 7, 3.75, 12, 5.5], "line-opacity": ["interpolate", ["linear"], ["zoom"], 7, 0, 8, 0.75], "line-dasharray": [1, 0], "line-blur": ["interpolate", ["linear"], ["zoom"], 3, 0, 8, 3]}, "source-layer": "admin"}, {"minzoom": 1, "layout": {"visibility": "none"}, "metadata": {"mapbox:featureComponent": "admin-boundaries", "mapbox:group": "Administrative boundaries, admin"}, "filter": ["all", ["==", ["get", "admin_level"], 0], ["==", ["get", "maritime"], "false"], ["match", ["get", "worldview"], ["all", "US"], true, false]], "type": "line", "source": "composite", "id": "admin-0-boundary-bg", "paint": {"line-width": ["interpolate", ["linear"], ["zoom"], 3, 3.5, 10, 8], "line-color": "rgb(227, 227, 227)", "line-opacity": ["interpolate", ["linear"], ["zoom"], 3, 0, 4, 0.5], "line-blur": ["interpolate", ["linear"], ["zoom"], 3, 0, 10, 2]}, "source-layer": "admin"}, {"minzoom": 2, "layout": {"line-join": "round", "line-cap": "round", "visibility": "none"}, "metadata": {"mapbox:featureComponent": "admin-boundaries", "mapbox:group": "Administrative boundaries, admin"}, "filter": ["all", ["==", ["get", "admin_level"], 1], ["==", ["get", "maritime"], "false"], ["match", ["get", "worldview"], ["all", "US"], true, false]], "type": "line", "source": "composite", "id": "admin-1-boundary", "paint": {"line-dasharray": ["step", ["zoom"], ["literal", [2, 0]], 7, ["literal", [2, 2, 6, 2]]], "line-width": ["interpolate", ["linear"], ["zoom"], 7, 0.75, 12, 1.5], "line-opacity": ["interpolate", ["linear"], ["zoom"], 2, 0, 3, 1], "line-color": ["interpolate", ["linear"], ["zoom"], 3, "rgb(224, 224, 224)", 7, "rgb(184, 184, 184)"]}, "source-layer": "admin"}, {"minzoom": 1, "layout": {"line-join": "round", "line-cap": "round", "visibility": "none"}, "metadata": {"mapbox:featureComponent": "admin-boundaries", "mapbox:group": "Administrative boundaries, admin"}, "filter": ["all", ["==", ["get", "admin_level"], 0], ["==", ["get", "disputed"], "false"], ["==", ["get", "maritime"], "false"], ["match", ["get", "worldview"], ["all", "US"], true, false]], "type": "line", "source": "composite", "id": "admin-0-boundary", "paint": {"line-color": "rgb(184, 184, 184)", "line-width": ["interpolate", ["linear"], ["zoom"], 3, 0.5, 10, 2], "line-dasharray": [10, 0]}, "source-layer": "admin"}, {"minzoom": 1, "layout": {"line-join": "round", "visibility": "none"}, "metadata": {"mapbox:featureComponent": "admin-boundaries", "mapbox:group": "Administrative boundaries, admin"}, "filter": ["all", ["==", ["get", "disputed"], "true"], ["==", ["get", "admin_level"], 0], ["==", ["get", "maritime"], "false"], ["match", ["get", "worldview"], ["all", "US"], true, false]], "type": "line", "source": "composite", "id": "admin-0-boundary-disputed", "paint": {"line-color": "rgb(184, 184, 184)", "line-width": ["interpolate", ["linear"], ["zoom"], 3, 0.5, 10, 2], "line-dasharray": ["step", ["zoom"], ["literal", [3.25, 3.25]], 6, ["literal", [2.5, 2.5]], 7, ["literal", [2, 2.25]], 8, ["literal", [1.75, 2]]]}, "source-layer": "admin"}, {"minzoom": 10, "layout": {"text-size": ["interpolate", ["linear"], ["zoom"], 10, ["match", ["get", "class"], ["motorway", "trunk", "primary", "secondary", "tertiary"], 10, ["motorway_link", "trunk_link", "primary_link", "secondary_link", "tertiary_link", "street", "street_limited"], 9, 6.5], 18, ["match", ["get", "class"], ["motorway", "trunk", "primary", "secondary", "tertiary"], 16, ["motorway_link", "trunk_link", "primary_link", "secondary_link", "tertiary_link", "street", "street_limited"], 14, 13]], "text-max-angle": 30, "text-font": ["DIN Pro Regular", "Arial Unicode MS Regular"], "symbol-placement": "line", "text-padding": 1, "visibility": "none", "text-rotation-alignment": "map", "text-pitch-alignment": "viewport", "text-field": ["coalesce", ["get", "name_en"], ["get", "name"]], "text-letter-spacing": 0.01}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, road-labels"}, "filter": ["step", ["zoom"], ["match", ["get", "class"], ["motorway", "trunk", "primary", "secondary", "tertiary"], true, false], 1, ["match", ["get", "class"], ["motorway", "trunk", "primary", "secondary", "tertiary", "street", "street_limited"], true, false], 2, ["match", ["get", "class"], ["path", "pedestrian", "golf", "ferry", "aerialway"], false, true]], "type": "symbol", "source": "composite", "id": "road-label", "paint": {"text-color": "rgb(128, 128, 128)", "text-halo-color": "rgb(255, 255, 255)", "text-halo-width": 1, "text-halo-blur": 1}, "source-layer": "road"}, {"minzoom": 13, "layout": {"text-field": ["coalesce", ["get", "name_en"], ["get", "name"]], "icon-image": "intersection", "icon-text-fit": "both", "icon-text-fit-padding": [1, 2, 1, 2], "text-size": ["interpolate", ["exponential", 1.2], ["zoom"], 15, 9, 18, 12], "text-font": ["DIN Pro Bold", "Arial Unicode MS Bold"], "visibility": "none"}, "metadata": {"mapbox:featureComponent": "road-network", "mapbox:group": "Road network, road-labels"}, "filter": ["all", ["==", ["get", "class"], "intersection"], ["has", "name"]], "type": "symbol", "source": "composite", "id": "road-intersection", "paint": {"text-color": "rgb(153, 153, 153)"}, "source-layer": "road"}, {"minzoom": 13, "layout": {"text-font": ["DIN Pro Italic", "Arial Unicode MS Regular"], "text-max-angle": 30, "symbol-spacing": ["interpolate", ["linear", 1], ["zoom"], 15, 250, 17, 400], "text-size": ["interpolate", ["linear"], ["zoom"], 13, 12, 18, 16], "symbol-placement": "line", "text-pitch-alignment": "viewport", "text-field": ["coalesce", ["get", "name_en"], ["get", "name"]], "visibility": "none"}, "metadata": {"mapbox:featureComponent": "natural-features", "mapbox:group": "Natural features, natural-labels"}, "filter": ["all", ["match", ["get", "class"], ["canal", "river", "stream"], ["match", ["get", "worldview"], ["all", "US"], true, false], ["disputed_canal", "disputed_river", "disputed_stream"], ["all", ["==", ["get", "disputed"], "true"], ["match", ["get", "worldview"], ["all", "US"], true, false]], false], ["==", ["geometry-type"], "LineString"]], "type": "symbol", "source": "composite", "id": "waterway-label", "paint": {"text-color": "rgb(150, 150, 150)"}, "source-layer": "natural_label"}, {"minzoom": 4, "layout": {"text-size": ["step", ["zoom"], ["step", ["get", "sizerank"], 18, 5, 12], 17, ["step", ["get", "sizerank"], 18, 13, 12]], "text-max-angle": 30, "text-field": ["coalesce", ["get", "name_en"], ["get", "name"]], "text-font": ["DIN Pro Medium", "Arial Unicode MS Regular"], "symbol-placement": "line-center", "text-pitch-alignment": "viewport", "visibility": "none"}, "metadata": {"mapbox:featureComponent": "natural-features", "mapbox:group": "Natural features, natural-labels"}, "filter": ["all", ["match", ["get", "class"], ["glacier", "landform"], ["match", ["get", "worldview"], ["all", "US"], true, false], ["disputed_glacier", "disputed_landform"], ["all", ["==", ["get", "disputed"], "true"], ["match", ["get", "worldview"], ["all", "US"], true, false]], false], ["==", ["geometry-type"], "LineString"], ["<=", ["get", "filterrank"], 1]], "type": "symbol", "source": "composite", "id": "natural-line-label", "paint": {"text-halo-width": 0.5, "text-halo-color": "rgb(255, 255, 255)", "text-halo-blur": 0.5, "text-color": "rgb(128, 128, 128)"}, "source-layer": "natural_label"}, {"minzoom": 4, "layout": {"text-size": ["step", ["zoom"], ["step", ["get", "sizerank"], 18, 5, 12], 17, ["step", ["get", "sizerank"], 18, 13, 12]], "icon-image": "", "text-font": ["DIN Pro Medium", "Arial Unicode MS Regular"], "text-offset": ["literal", [0, 0]], "text-field": ["coalesce", ["get", "name_en"], ["get", "name"]], "visibility": "none"}, "metadata": {"mapbox:featureComponent": "natural-features", "mapbox:group": "Natural features, natural-labels"}, "filter": ["all", ["match", ["get", "class"], ["dock", "glacier", "landform", "water_feature", "wetland"], ["match", ["get", "worldview"], ["all", "US"], true, false], ["disputed_dock", "disputed_glacier", "disputed_landform", "disputed_water_feature", "disputed_wetland"], ["all", ["==", ["get", "disputed"], "true"], ["match", ["get", "worldview"], ["all", "US"], true, false]], false], ["==", ["geometry-type"], "Point"], ["<=", ["get", "filterrank"], 1]], "type": "symbol", "source": "composite", "id": "natural-point-label", "paint": {"icon-opacity": ["step", ["zoom"], ["step", ["get", "sizerank"], 0, 5, 1], 17, ["step", ["get", "sizerank"], 0, 13, 1]], "text-halo-color": "rgb(255, 255, 255)", "text-halo-width": 0.5, "text-halo-blur": 0.5, "text-color": "rgb(128, 128, 128)"}, "source-layer": "natural_label"}, {"id": "water-line-label", "type": "symbol", "metadata": {"mapbox:featureComponent": "natural-features", "mapbox:group": "Natural features, natural-labels"}, "source": "composite", "source-layer": "natural_label", "filter": ["all", ["match", ["get", "class"], ["bay", "ocean", "reservoir", "sea", "water"], ["match", ["get", "worldview"], ["all", "US"], true, false], ["disputed_bay", "disputed_ocean", "disputed_reservoir", "disputed_sea", "disputed_water"], ["all", ["==", ["get", "disputed"], "true"], ["match", ["get", "worldview"], ["all", "US"], true, false]], false], ["==", ["geometry-type"], "LineString"]], "layout": {"text-size": ["interpolate", ["linear"], ["zoom"], 7, ["step", ["get", "sizerank"], 20, 6, 18, 12, 12], 10, ["step", ["get", "sizerank"], 15, 9, 12], 18, ["step", ["get", "sizerank"], 15, 9, 14]], "text-max-angle": 30, "text-letter-spacing": ["match", ["get", "class"], "ocean", 0.25, ["sea", "bay"], 0.15, 0], "text-font": ["DIN Pro Italic", "Arial Unicode MS Regular"], "symbol-placement": "line-center", "text-pitch-alignment": "viewport", "text-field": ["coalesce", ["get", "name_en"], ["get", "name"]], "visibility": "none"}, "paint": {"text-color": "rgb(150, 150, 150)"}}, {"id": "water-point-label", "type": "symbol", "source": "composite", "source-layer": "natural_label", "filter": ["all", ["match", ["get", "class"], ["bay", "ocean", "reservoir", "sea", "water"], ["match", ["get", "worldview"], ["all", "US"], true, false], ["disputed_bay", "disputed_ocean", "disputed_reservoir", "disputed_sea", "disputed_water"], ["all", ["==", ["get", "disputed"], "true"], ["match", ["get", "worldview"], ["all", "US"], true, false]], false], ["==", ["geometry-type"], "Point"]], "layout": {"text-line-height": 1.3, "text-size": ["interpolate", ["linear"], ["zoom"], 7, ["step", ["get", "sizerank"], 20, 6, 15, 12, 12], 10, ["step", ["get", "sizerank"], 15, 9, 12]], "text-font": ["DIN Pro Italic", "Arial Unicode MS Regular"], "text-field": ["coalesce", ["get", "name_en"], ["get", "name"]], "text-letter-spacing": ["match", ["get", "class"], "ocean", 0.25, ["bay", "sea"], 0.15, 0.01], "text-max-width": ["match", ["get", "class"], "ocean", 4, "sea", 5, ["bay", "water"], 7, 10], "visibility": "none"}, "paint": {"text-color": "rgb(150, 150, 150)"}, "metadata": {"mapbox:featureComponent": "natural-features", "mapbox:group": "Natural features, natural-labels"}}, {"minzoom": 6, "layout": {"text-size": ["step", ["zoom"], ["step", ["get", "sizerank"], 18, 5, 12], 17, ["step", ["get", "sizerank"], 18, 13, 12]], "icon-image": "", "text-font": ["DIN Pro Medium", "Arial Unicode MS Regular"], "text-offset": [0, 0], "text-anchor": ["step", ["zoom"], ["step", ["get", "sizerank"], "center", 5, "top"], 17, ["step", ["get", "sizerank"], "center", 13, "top"]], "text-field": ["coalesce", ["get", "name_en"], ["get", "name"]], "visibility": "none"}, "metadata": {"mapbox:featureComponent": "point-of-interest-labels", "mapbox:group": "Point of interest labels, poi-labels"}, "filter": ["<=", ["get", "filterrank"], ["+", ["step", ["zoom"], 1, 2, 3, 4, 5], 1]], "type": "symbol", "source": "composite", "id": "poi-label", "paint": {"text-halo-color": "rgb(255, 255, 255)", "text-halo-width": 0.5, "text-halo-blur": 0.5, "text-color": ["step", ["zoom"], ["step", ["get", "sizerank"], "rgb(184, 184, 184)", 5, "rgb(161, 161, 161)"], 17, ["step", ["get", "sizerank"], "rgb(184, 184, 184)", 13, "rgb(161, 161, 161)"]]}, "source-layer": "poi_label"}, {"minzoom": 8, "layout": {"text-line-height": 1.1, "text-size": ["step", ["get", "sizerank"], 18, 9, 12], "icon-image": ["get", "maki"], "text-font": ["DIN Pro Medium", "Arial Unicode MS Regular"], "visibility": "none", "text-offset": [0, 0.75], "text-rotation-alignment": "viewport", "text-anchor": "top", "text-field": ["step", ["get", "sizerank"], ["coalesce", ["get", "name_en"], ["get", "name"]], 15, ["get", "ref"]], "text-letter-spacing": 0.01, "text-max-width": 9}, "metadata": {"mapbox:featureComponent": "transit", "mapbox:group": "Transit, transit-labels"}, "filter": ["match", ["get", "class"], ["military", "civil"], ["match", ["get", "worldview"], ["all", "US"], true, false], ["disputed_military", "disputed_civil"], ["all", ["==", ["get", "disputed"], "true"], ["match", ["get", "worldview"], ["all", "US"], true, false]], false], "type": "symbol", "source": "composite", "id": "airport-label", "paint": {"text-color": "rgb(128, 128, 128)", "text-halo-color": "rgb(255, 255, 255)", "text-halo-width": 1}, "source-layer": "airport_label"}, {"minzoom": 10, "layout": {"text-field": ["coalesce", ["get", "name_en"], ["get", "name"]], "text-transform": "uppercase", "text-font": ["DIN Pro Regular", "Arial Unicode MS Regular"], "text-letter-spacing": ["match", ["get", "type"], "suburb", 0.15, 0.1], "text-max-width": 7, "text-padding": 3, "text-size": ["interpolate", ["cubic-bezier", 0.5, 0, 1, 1], ["zoom"], 11, ["match", ["get", "type"], "suburb", 11, 10.5], 15, ["match", ["get", "type"], "suburb", 15, 14]], "visibility": "none"}, "metadata": {"mapbox:featureComponent": "place-labels", "mapbox:group": "Place labels, place-labels"}, "maxzoom": 15, "filter": ["all", ["match", ["get", "class"], "settlement_subdivision", ["match", ["get", "worldview"], ["all", "US"], true, false], "disputed_settlement_subdivision", ["all", ["==", ["get", "disputed"], "true"], ["match", ["get", "worldview"], ["all", "US"], true, false]], false], ["<=", ["get", "filterrank"], 4]], "type": "symbol", "source": "composite", "id": "settlement-subdivision-label", "paint": {"text-halo-color": "rgb(255, 255, 255)", "text-halo-width": 1, "text-color": "rgb(179, 179, 179)", "text-halo-blur": 0.5}, "source-layer": "place_label"}, {"minzoom": 3, "layout": {"text-line-height": 1.1, "text-size": ["interpolate", ["cubic-bezier", 0.2, 0, 0.9, 1], ["zoom"], 3, ["step", ["get", "symbolrank"], 12, 9, 11, 10, 10.5, 12, 9.5, 14, 8.5, 16, 6.5, 17, 4], 13, ["step", ["get", "symbolrank"], 23, 9, 21, 10, 19, 11, 17, 12, 16, 13, 15, 15, 13]], "text-radial-offset": ["step", ["zoom"], ["match", ["get", "capital"], 2, 0.6, 0.55], 8, 0], "icon-image": ["step", ["zoom"], ["case", ["==", ["get", "capital"], 2], "border-dot-13", ["step", ["get", "symbolrank"], "dot-11", 9, "dot-10", 11, "dot-9"]], 8, ""], "text-font": ["DIN Pro Regular", "Arial Unicode MS Regular"], "text-justify": "auto", "visibility": "none", "text-anchor": ["step", ["zoom"], ["get", "text_anchor"], 8, "center"], "text-field": ["coalesce", ["get", "name_en"], ["get", "name"]], "text-max-width": 7}, "metadata": {"mapbox:featureComponent": "place-labels", "mapbox:group": "Place labels, place-labels"}, "maxzoom": 13, "filter": ["all", ["<=", ["get", "filterrank"], 3], ["match", ["get", "class"], "settlement", ["match", ["get", "worldview"], ["all", "US"], true, false], "disputed_settlement", ["all", ["==", ["get", "disputed"], "true"], ["match", ["get", "worldview"], ["all", "US"], true, false]], false], ["step", ["zoom"], [">", ["get", "symbolrank"], 6], 1, [">=", ["get", "symbolrank"], 7], 2, [">=", ["get", "symbolrank"], 8], 3, [">=", ["get", "symbolrank"], 10], 4, [">=", ["get", "symbolrank"], 11], 5, [">=", ["get", "symbolrank"], 13], 6, [">=", ["get", "symbolrank"], 15]]], "type": "symbol", "source": "composite", "id": "settlement-minor-label", "paint": {"text-color": ["step", ["get", "symbolrank"], "rgb(128, 128, 128)", 11, "rgb(161, 161, 161)", 16, "rgb(184, 184, 184)"], "text-halo-color": "rgb(255, 255, 255)", "text-halo-width": 1, "text-halo-blur": 1}, "source-layer": "place_label"}, {"minzoom": 3, "layout": {"text-line-height": 1.1, "text-size": ["interpolate", ["cubic-bezier", 0.2, 0, 0.9, 1], ["zoom"], 3, ["step", ["get", "symbolrank"], 13, 6, 12], 6, ["step", ["get", "symbolrank"], 16, 6, 15, 7, 14], 8, ["step", ["get", "symbolrank"], 18, 9, 17, 10, 15], 15, ["step", ["get", "symbolrank"], 23, 9, 22, 10, 20, 11, 18, 12, 16, 13, 15, 15, 13]], "text-radial-offset": ["step", ["zoom"], ["match", ["get", "capital"], 2, 0.6, 0.55], 8, 0], "icon-image": ["step", ["zoom"], ["case", ["==", ["get", "capital"], 2], "border-dot-13", ["step", ["get", "symbolrank"], "dot-11", 9, "dot-10", 11, "dot-9"]], 8, ""], "text-font": ["DIN Pro Medium", "Arial Unicode MS Regular"], "text-justify": ["step", ["zoom"], ["match", ["get", "text_anchor"], ["left", "bottom-left", "top-left"], "left", ["right", "bottom-right", "top-right"], "right", "center"], 8, "center"], "visibility": "none", "text-anchor": ["step", ["zoom"], ["get", "text_anchor"], 8, "center"], "text-field": ["coalesce", ["get", "name_en"], ["get", "name"]], "text-max-width": 7}, "metadata": {"mapbox:featureComponent": "place-labels", "mapbox:group": "Place labels, place-labels"}, "maxzoom": 15, "filter": ["all", ["<=", ["get", "filterrank"], 3], ["match", ["get", "class"], "settlement", ["match", ["get", "worldview"], ["all", "US"], true, false], "disputed_settlement", ["all", ["==", ["get", "disputed"], "true"], ["match", ["get", "worldview"], ["all", "US"], true, false]], false], ["step", ["zoom"], false, 1, ["<=", ["get", "symbolrank"], 6], 2, ["<", ["get", "symbolrank"], 7], 3, ["<", ["get", "symbolrank"], 8], 4, ["<", ["get", "symbolrank"], 10], 5, ["<", ["get", "symbolrank"], 11], 6, ["<", ["get", "symbolrank"], 13], 7, ["<", ["get", "symbolrank"], 15], 8, [">=", ["get", "symbolrank"], 11], 9, [">=", ["get", "symbolrank"], 15]]], "type": "symbol", "source": "composite", "id": "settlement-major-label", "paint": {"text-color": ["step", ["get", "symbolrank"], "rgb(128, 128, 128)", 11, "rgb(161, 161, 161)", 16, "rgb(184, 184, 184)"], "text-halo-color": "rgb(255, 255, 255)", "text-halo-width": 1, "text-halo-blur": 1}, "source-layer": "place_label"}, {"minzoom": 3, "layout": {"text-size": ["interpolate", ["cubic-bezier", 0.85, 0.7, 0.65, 1], ["zoom"], 4, ["step", ["get", "symbolrank"], 10, 6, 9.5, 7, 9], 9, ["step", ["get", "symbolrank"], 21, 6, 16, 7, 13]], "text-transform": "uppercase", "text-font": ["DIN Pro Bold", "Arial Unicode MS Bold"], "text-field": ["step", ["zoom"], ["step", ["get", "symbolrank"], ["coalesce", ["get", "name_en"], ["get", "name"]], 5, ["coalesce", ["get", "abbr"], ["get", "name_en"], ["get", "name"]]], 5, ["coalesce", ["get", "name_en"], ["get", "name"]]], "text-letter-spacing": 0.15, "text-max-width": 6, "visibility": "none"}, "metadata": {"mapbox:featureComponent": "place-labels", "mapbox:group": "Place labels, place-labels"}, "maxzoom": 9, "filter": ["match", ["get", "class"], "state", ["match", ["get", "worldview"], ["all", "US"], true, false], "disputed_state", ["all", ["==", ["get", "disputed"], "true"], ["match", ["get", "worldview"], ["all", "US"], true, false]], false], "type": "symbol", "source": "composite", "id": "state-label", "paint": {"text-color": "rgb(184, 184, 184)", "text-halo-color": "rgb(255, 255, 255)", "text-halo-width": 1}, "source-layer": "place_label"}, {"minzoom": 1, "layout": {"text-line-height": 1.1, "text-size": ["interpolate", ["cubic-bezier", 0.2, 0, 0.7, 1], ["zoom"], 1, ["step", ["get", "symbolrank"], 11, 4, 9, 5, 8], 9, ["step", ["get", "symbolrank"], 22, 4, 19, 5, 17]], "text-radial-offset": ["step", ["zoom"], 0.6, 8, 0], "icon-image": "", "text-font": ["DIN Pro Medium", "Arial Unicode MS Regular"], "text-justify": ["step", ["zoom"], ["match", ["get", "text_anchor"], ["left", "bottom-left", "top-left"], "left", ["right", "bottom-right", "top-right"], "right", "center"], 7, "auto"], "visibility": "none", "text-field": ["coalesce", ["get", "name_en"], ["get", "name"]], "text-max-width": 6}, "metadata": {"mapbox:featureComponent": "place-labels", "mapbox:group": "Place labels, place-labels"}, "maxzoom": 10, "filter": ["match", ["get", "class"], "country", ["match", ["get", "worldview"], ["all", "US"], true, false], "disputed_country", ["all", ["==", ["get", "disputed"], "true"], ["match", ["get", "worldview"], ["all", "US"], true, false]], false], "type": "symbol", "source": "composite", "id": "country-label", "paint": {"icon-opacity": ["step", ["zoom"], ["case", ["has", "text_anchor"], 1, 0], 7, 0], "text-color": "rgb(128, 128, 128)", "text-halo-color": "rgb(255, 255, 255)", "text-halo-width": 1.25}, "source-layer": "place_label"}], "created": "2021-11-05T16:12:04.822Z", "modified": "2021-11-25T13:58:04.167Z", "id": "ckvmksrpd4n0a14pfdo5heqzr", "owner": "commaai", "visibility": "private", "protected": false, "draft": false} \ No newline at end of file diff --git a/selfdrive/rtshield.py b/selfdrive/rtshield.py index ad7538d7a8..45571fe2db 100755 --- a/selfdrive/rtshield.py +++ b/selfdrive/rtshield.py @@ -11,7 +11,7 @@ from common.realtime import set_core_affinity, set_realtime_priority # openpilot processes def main() -> NoReturn: - set_core_affinity(int(os.getenv("CORE", "3"))) + set_core_affinity([int(os.getenv("CORE", "3")), ]) set_realtime_priority(1) while True: diff --git a/selfdrive/sensord/SConscript b/selfdrive/sensord/SConscript index 186e302bc3..8f26c00853 100644 --- a/selfdrive/sensord/SConscript +++ b/selfdrive/sensord/SConscript @@ -1,22 +1,19 @@ Import('env', 'arch', 'common', 'cereal', 'messaging') -if arch == "aarch64": - env.Program('_sensord', 'sensors_qcom.cc', LIBS=['hardware', common, cereal, messaging, 'capnp', 'zmq', 'kj']) -else: - sensors = [ - 'sensors/file_sensor.cc', - 'sensors/i2c_sensor.cc', - 'sensors/light_sensor.cc', - 'sensors/bmx055_accel.cc', - 'sensors/bmx055_gyro.cc', - 'sensors/bmx055_magn.cc', - 'sensors/bmx055_temp.cc', - 'sensors/lsm6ds3_accel.cc', - 'sensors/lsm6ds3_gyro.cc', - 'sensors/lsm6ds3_temp.cc', - 'sensors/mmc5603nj_magn.cc', - ] - libs = [common, cereal, messaging, 'capnp', 'zmq', 'kj'] - if arch == "larch64": - libs.append('i2c') - env.Program('_sensord', ['sensors_qcom2.cc'] + sensors, LIBS=libs) +sensors = [ + 'sensors/file_sensor.cc', + 'sensors/i2c_sensor.cc', + 'sensors/light_sensor.cc', + 'sensors/bmx055_accel.cc', + 'sensors/bmx055_gyro.cc', + 'sensors/bmx055_magn.cc', + 'sensors/bmx055_temp.cc', + 'sensors/lsm6ds3_accel.cc', + 'sensors/lsm6ds3_gyro.cc', + 'sensors/lsm6ds3_temp.cc', + 'sensors/mmc5603nj_magn.cc', +] +libs = [common, cereal, messaging, 'capnp', 'zmq', 'kj', 'pthread'] +if arch == "larch64": + libs.append('i2c') +env.Program('_sensord', ['sensors_qcom2.cc'] + sensors, LIBS=libs) diff --git a/selfdrive/hardware/tici/__init__.py b/selfdrive/sensord/__init__.py similarity index 100% rename from selfdrive/hardware/tici/__init__.py rename to selfdrive/sensord/__init__.py diff --git a/selfdrive/sensord/pigeond.py b/selfdrive/sensord/pigeond.py new file mode 100755 index 0000000000..f56af1c705 --- /dev/null +++ b/selfdrive/sensord/pigeond.py @@ -0,0 +1,313 @@ +#!/usr/bin/env python3 +import sys +import time +import signal +import serial +import struct +import requests +import urllib.parse +from datetime import datetime +from typing import List, Optional, Tuple + +from cereal import messaging +from common.params import Params +from system.swaglog import cloudlog +from system.hardware import TICI +from common.gpio import gpio_init, gpio_set +from system.hardware.tici.pins import GPIO + +UBLOX_TTY = "/dev/ttyHS0" + +UBLOX_ACK = b"\xb5\x62\x05\x01\x02\x00" +UBLOX_NACK = b"\xb5\x62\x05\x00\x02\x00" +UBLOX_SOS_ACK = b"\xb5\x62\x09\x14\x08\x00\x02\x00\x00\x00\x01\x00\x00\x00" +UBLOX_SOS_NACK = b"\xb5\x62\x09\x14\x08\x00\x02\x00\x00\x00\x00\x00\x00\x00" +UBLOX_BACKUP_RESTORE_MSG = b"\xb5\x62\x09\x14\x08\x00\x03" +UBLOX_ASSIST_ACK = b"\xb5\x62\x13\x60\x08\x00" + +def set_power(enabled: bool) -> None: + gpio_init(GPIO.UBLOX_SAFEBOOT_N, True) + gpio_init(GPIO.UBLOX_PWR_EN, True) + gpio_init(GPIO.UBLOX_RST_N, True) + + gpio_set(GPIO.UBLOX_SAFEBOOT_N, True) + gpio_set(GPIO.UBLOX_PWR_EN, enabled) + gpio_set(GPIO.UBLOX_RST_N, enabled) + +def add_ubx_checksum(msg: bytes) -> bytes: + A = B = 0 + for b in msg[2:]: + A = (A + b) % 256 + B = (B + A) % 256 + return msg + bytes([A, B]) + +def get_assistnow_messages(token: bytes) -> List[bytes]: + # make request + # TODO: implement adding the last known location + r = requests.get("https://online-live2.services.u-blox.com/GetOnlineData.ashx", params=urllib.parse.urlencode({ + 'token': token, + 'gnss': 'gps,glo', + 'datatype': 'eph,alm,aux', + }, safe=':,'), timeout=5) + assert r.status_code == 200, "Got invalid status code" + dat = r.content + + # split up messages + msgs = [] + while len(dat) > 0: + assert dat[:2] == b"\xB5\x62" + msg_len = 6 + (dat[5] << 8 | dat[4]) + 2 + msgs.append(dat[:msg_len]) + dat = dat[msg_len:] + return msgs + + +class TTYPigeon(): + def __init__(self): + self.tty = serial.VTIMESerial(UBLOX_TTY, baudrate=9600, timeout=0) + + def send(self, dat: bytes) -> None: + self.tty.write(dat) + + def receive(self) -> bytes: + dat = b'' + while len(dat) < 0x1000: + d = self.tty.read(0x40) + dat += d + if len(d) == 0: + break + return dat + + def set_baud(self, baud: int) -> None: + self.tty.baudrate = baud + + def wait_for_ack(self, ack: bytes = UBLOX_ACK, nack: bytes = UBLOX_NACK, timeout: float = 0.5) -> bool: + dat = b'' + st = time.monotonic() + while True: + dat += self.receive() + if ack in dat: + cloudlog.debug("Received ACK from ublox") + return True + elif nack in dat: + cloudlog.error("Received NACK from ublox") + return False + elif time.monotonic() - st > timeout: + cloudlog.error("No response from ublox") + raise TimeoutError('No response from ublox') + time.sleep(0.001) + + def send_with_ack(self, dat: bytes, ack: bytes = UBLOX_ACK, nack: bytes = UBLOX_NACK) -> None: + self.send(dat) + self.wait_for_ack(ack, nack) + + def wait_for_backup_restore_status(self, timeout: float = 1.) -> int: + dat = b'' + st = time.monotonic() + while True: + dat += self.receive() + position = dat.find(UBLOX_BACKUP_RESTORE_MSG) + if position >= 0 and len(dat) >= position + 11: + return dat[position + 10] + elif time.monotonic() - st > timeout: + cloudlog.error("No backup restore response from ublox") + raise TimeoutError('No response from ublox') + time.sleep(0.001) + + def reset_device(self) -> bool: + # deleting the backup does not always work on first try (mostly on second try) + for _ in range(5): + # device cold start + self.send(b"\xb5\x62\x06\x04\x04\x00\xff\xff\x00\x00\x0c\x5d") + time.sleep(1) # wait for cold start + init_baudrate(self) + + # clear configuration + self.send_with_ack(b"\xb5\x62\x06\x09\x0d\x00\x00\x00\x1f\x1f\x00\x00\x00\x00\x00\x00\x00\x00\x17\x71\x5b") + + # clear flash memory (almanac backup) + self.send_with_ack(b"\xB5\x62\x09\x14\x04\x00\x01\x00\x00\x00\x22\xf0") + + # try restoring backup to verify it got deleted + self.send(b"\xB5\x62\x09\x14\x00\x00\x1D\x60") + # 1: failed to restore, 2: could restore, 3: no backup + status = self.wait_for_backup_restore_status() + if status == 1 or status == 3: + return True + return False + +def init_baudrate(pigeon: TTYPigeon): + # ublox default setting on startup is 9600 baudrate + pigeon.set_baud(9600) + + # $PUBX,41,1,0007,0003,460800,0*15\r\n + pigeon.send(b"\x24\x50\x55\x42\x58\x2C\x34\x31\x2C\x31\x2C\x30\x30\x30\x37\x2C\x30\x30\x30\x33\x2C\x34\x36\x30\x38\x30\x30\x2C\x30\x2A\x31\x35\x0D\x0A") + time.sleep(0.1) + pigeon.set_baud(460800) + + +def initialize_pigeon(pigeon: TTYPigeon) -> bool: + # try initializing a few times + for _ in range(10): + try: + + # setup port config + pigeon.send_with_ack(b"\xb5\x62\x06\x00\x14\x00\x03\xFF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x01\x00\x00\x00\x00\x00\x1E\x7F") + pigeon.send_with_ack(b"\xb5\x62\x06\x00\x14\x00\x00\xFF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x19\x35") + pigeon.send_with_ack(b"\xb5\x62\x06\x00\x14\x00\x01\x00\x00\x00\xC0\x08\x00\x00\x00\x08\x07\x00\x01\x00\x01\x00\x00\x00\x00\x00\xF4\x80") + pigeon.send_with_ack(b"\xb5\x62\x06\x00\x14\x00\x04\xFF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x1D\x85") + pigeon.send_with_ack(b"\xb5\x62\x06\x00\x00\x00\x06\x18") + pigeon.send_with_ack(b"\xb5\x62\x06\x00\x01\x00\x01\x08\x22") + pigeon.send_with_ack(b"\xb5\x62\x06\x00\x01\x00\x03\x0A\x24") + + # UBX-CFG-RATE (0x06 0x08) + pigeon.send_with_ack(b"\xB5\x62\x06\x08\x06\x00\x64\x00\x01\x00\x00\x00\x79\x10") + + # UBX-CFG-NAV5 (0x06 0x24) + pigeon.send_with_ack(b"\xB5\x62\x06\x24\x24\x00\x05\x00\x04\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x5A\x63") + + # UBX-CFG-ODO (0x06 0x1E) + pigeon.send_with_ack(b"\xB5\x62\x06\x1E\x14\x00\x00\x00\x00\x00\x01\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x3C\x37") + pigeon.send_with_ack(b"\xB5\x62\x06\x39\x08\x00\xFF\xAD\x62\xAD\x1E\x63\x00\x00\x83\x0C") + pigeon.send_with_ack(b"\xB5\x62\x06\x23\x28\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x56\x24") + + # UBX-CFG-NAV5 (0x06 0x24) + pigeon.send_with_ack(b"\xB5\x62\x06\x24\x00\x00\x2A\x84") + pigeon.send_with_ack(b"\xB5\x62\x06\x23\x00\x00\x29\x81") + pigeon.send_with_ack(b"\xB5\x62\x06\x1E\x00\x00\x24\x72") + pigeon.send_with_ack(b"\xB5\x62\x06\x39\x00\x00\x3F\xC3") + + # UBX-CFG-MSG (set message rate) + pigeon.send_with_ack(b"\xB5\x62\x06\x01\x03\x00\x01\x07\x01\x13\x51") + pigeon.send_with_ack(b"\xB5\x62\x06\x01\x03\x00\x02\x15\x01\x22\x70") + pigeon.send_with_ack(b"\xB5\x62\x06\x01\x03\x00\x02\x13\x01\x20\x6C") + pigeon.send_with_ack(b"\xB5\x62\x06\x01\x03\x00\x0A\x09\x01\x1E\x70") + pigeon.send_with_ack(b"\xB5\x62\x06\x01\x03\x00\x0A\x0B\x01\x20\x74") + cloudlog.debug("pigeon configured") + + # try restoring almanac backup + pigeon.send(b"\xB5\x62\x09\x14\x00\x00\x1D\x60") + restore_status = pigeon.wait_for_backup_restore_status() + if restore_status == 2: + cloudlog.warning("almanac backup restored") + elif restore_status == 3: + cloudlog.warning("no almanac backup found") + else: + cloudlog.error(f"failed to restore almanac backup, status: {restore_status}") + + # sending time to ublox + t_now = datetime.utcnow() + if t_now >= datetime(2021, 6, 1): + cloudlog.warning("Sending current time to ublox") + + # UBX-MGA-INI-TIME_UTC + msg = add_ubx_checksum(b"\xB5\x62\x13\x40\x18\x00" + struct.pack(" Tuple[TTYPigeon, messaging.PubMaster]: + pigeon = None + + # register exit handler + signal.signal(signal.SIGINT, lambda sig, frame: deinitialize_and_exit(pigeon)) + pm = messaging.PubMaster(['ubloxRaw']) + + # power cycle ublox + set_power(False) + time.sleep(0.1) + set_power(True) + time.sleep(0.5) + + pigeon = TTYPigeon() + return pigeon, pm + +def run_receiving(pigeon: TTYPigeon, pm: messaging.PubMaster, duration: int = 0): + + start_time = time.monotonic() + def end_condition(): + return True if duration == 0 else time.monotonic() - start_time < duration + + while end_condition(): + dat = pigeon.receive() + if len(dat) > 0: + if dat[0] == 0x00: + cloudlog.warning("received invalid data from ublox, re-initing!") + init_baudrate(pigeon) + initialize_pigeon(pigeon) + continue + + # send out to socket + msg = messaging.new_message('ubloxRaw', len(dat)) + msg.ubloxRaw = dat[:] + pm.send('ubloxRaw', msg) + else: + # prevent locking up a CPU core if ublox disconnects + time.sleep(0.001) + + +def main(): + assert TICI, "unsupported hardware for pigeond" + + pigeon, pm = create_pigeon() + init_baudrate(pigeon) + r = initialize_pigeon(pigeon) + Params().put_bool("UbloxAvailable", r) + + # start receiving data + run_receiving(pigeon, pm) + +if __name__ == "__main__": + main() diff --git a/selfdrive/sensord/rawgps/compare.py b/selfdrive/sensord/rawgps/compare.py new file mode 100755 index 0000000000..0ec15b81fb --- /dev/null +++ b/selfdrive/sensord/rawgps/compare.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +import cereal.messaging as messaging +from laika import constants + +if __name__ == "__main__": + sm = messaging.SubMaster(['ubloxGnss', 'qcomGnss']) + + meas = None + while 1: + sm.update() + if sm['ubloxGnss'].which() == "measurementReport": + meas = sm['ubloxGnss'].measurementReport.measurements + if not sm.updated['qcomGnss'] or meas is None: + continue + report = sm['qcomGnss'].measurementReport + if report.source not in [0, 1]: + continue + GLONASS = report.source == 1 + recv_time = report.milliseconds / 1000 + + car = [] + print("qcom has ", list(sorted([x.svId for x in report.sv]))) + print("ublox has", list(sorted([x.svId for x in meas if x.gnssId == (6 if GLONASS else 0)]))) + for i in report.sv: + # match to ublox + tm = None + for m in meas: + if i.svId == m.svId and m.gnssId == 0 and m.sigId == 0 and not GLONASS: + tm = m + if (i.svId-64) == m.svId and m.gnssId == 6 and m.sigId == 0 and GLONASS: + tm = m + if tm is None: + continue + + if not i.measurementStatus.measurementNotUsable and i.measurementStatus.satelliteTimeIsKnown: + sat_time = (i.unfilteredMeasurementIntegral + i.unfilteredMeasurementFraction + i.latency) / 1000 + ublox_psuedorange = tm.pseudorange + qcom_psuedorange = (recv_time - sat_time)*constants.SPEED_OF_LIGHT + if GLONASS: + glonass_freq = tm.glonassFrequencyIndex - 7 + ublox_speed = -(constants.SPEED_OF_LIGHT / (constants.GLONASS_L1 + glonass_freq*constants.GLONASS_L1_DELTA)) * (tm.doppler) + else: + ublox_speed = -(constants.SPEED_OF_LIGHT / constants.GPS_L1) * tm.doppler + qcom_speed = i.unfilteredSpeed + car.append((i.svId, tm.pseudorange, ublox_speed, qcom_psuedorange, qcom_speed, tm.cno)) + + if len(car) == 0: + print("nothing to compare") + continue + + pr_err, speed_err = 0., 0. + for c in car: + ublox_psuedorange, ublox_speed, qcom_psuedorange, qcom_speed = c[1:5] + pr_err += ublox_psuedorange - qcom_psuedorange + speed_err += ublox_speed - qcom_speed + pr_err /= len(car) + speed_err /= len(car) + print("avg psuedorange err %f avg speed err %f" % (pr_err, speed_err)) + for c in sorted(car, key=lambda x: abs(x[1] - x[3] - pr_err)): # type: ignore + svid, ublox_psuedorange, ublox_speed, qcom_psuedorange, qcom_speed, cno = c + print("svid: %3d pseudorange: %10.2f m speed: %8.2f m/s meas: %12.2f speed: %10.2f meas_err: %10.3f speed_err: %8.3f cno: %d" % + (svid, ublox_psuedorange, ublox_speed, qcom_psuedorange, qcom_speed, + ublox_psuedorange - qcom_psuedorange - pr_err, ublox_speed - qcom_speed - speed_err, cno)) + + + diff --git a/selfdrive/sensord/rawgps/modemdiag.py b/selfdrive/sensord/rawgps/modemdiag.py new file mode 100644 index 0000000000..5d72aeba9e --- /dev/null +++ b/selfdrive/sensord/rawgps/modemdiag.py @@ -0,0 +1,94 @@ +import select +from serial import Serial +from crcmod import mkCrcFun +from struct import pack, unpack_from, calcsize + +class ModemDiag: + def __init__(self): + self.serial = self.open_serial() + self.pend = b'' + + def open_serial(self): + serial = Serial("/dev/ttyUSB0", baudrate=115200, rtscts=True, dsrdtr=True, timeout=0, exclusive=True) + serial.flush() + serial.reset_input_buffer() + serial.reset_output_buffer() + return serial + + ccitt_crc16 = mkCrcFun(0x11021, initCrc=0, xorOut=0xffff) + ESCAPE_CHAR = b'\x7d' + TRAILER_CHAR = b'\x7e' + + def hdlc_encapsulate(self, payload): + payload += pack('= 3 + assert payload[-1:] == self.TRAILER_CHAR + payload = payload[:-1] + payload = payload.replace(bytes([self.ESCAPE_CHAR[0], self.TRAILER_CHAR[0] ^ 0x20]), self.TRAILER_CHAR) + payload = payload.replace(bytes([self.ESCAPE_CHAR[0], self.ESCAPE_CHAR[0] ^ 0x20]), self.ESCAPE_CHAR) + assert payload[-2:] == pack(' None: + for _ in range(5): + try: + subprocess.check_call(f"mmcli -m any --timeout 30 --command='{cmd}'", shell=True) + break + except subprocess.CalledProcessError: + cloudlog.exception("rawgps.mmcli_command_failed") + else: + raise Exception(f"failed to execute mmcli command {cmd=}") + + +def gps_enabled() -> bool: + try: + p = subprocess.check_output("mmcli -m any --command=\"AT+QGPS?\"", shell=True) + return b"QGPS: 1" in p + except subprocess.CalledProcessError as exc: + raise Exception("failed to execute QGPS mmcli command") from exc + +def setup_quectel(diag: ModemDiag): + # enable OEMDRE in the NV + # TODO: it has to reboot for this to take effect + DIAG_NV_READ_F = 38 + DIAG_NV_WRITE_F = 39 + NV_GNSS_OEM_FEATURE_MASK = 7165 + send_recv(diag, DIAG_NV_WRITE_F, pack(' NoReturn: + unpack_gps_meas, size_gps_meas = dict_unpacker(gps_measurement_report, True) + unpack_gps_meas_sv, size_gps_meas_sv = dict_unpacker(gps_measurement_report_sv, True) + + unpack_glonass_meas, size_glonass_meas = dict_unpacker(glonass_measurement_report, True) + unpack_glonass_meas_sv, size_glonass_meas_sv = dict_unpacker(glonass_measurement_report_sv, True) + + unpack_oemdre_meas, size_oemdre_meas = dict_unpacker(oemdre_measurement_report, True) + unpack_oemdre_meas_sv, size_oemdre_meas_sv = dict_unpacker(oemdre_measurement_report_sv, True) + + unpack_svpoly, _ = dict_unpacker(oemdre_svpoly_report, True) + unpack_position, _ = dict_unpacker(position_report) + + unpack_position, _ = dict_unpacker(position_report) + + # wait for ModemManager to come up + cloudlog.warning("waiting for modem to come up") + while True: + ret = subprocess.call("mmcli -m any --timeout 10 --command=\"AT+QGPS?\"", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, shell=True) + if ret == 0: + break + time.sleep(0.1) + + # connect to modem + diag = ModemDiag() + + def cleanup(sig, frame): + cloudlog.warning(f"caught sig {sig}, disabling quectel gps") + teardown_quectel(diag) + cloudlog.warning("quectel cleanup done") + sys.exit(0) + signal.signal(signal.SIGINT, cleanup) + signal.signal(signal.SIGTERM, cleanup) + + setup_quectel(diag) + cloudlog.warning("quectel setup done") + + pm = messaging.PubMaster(['qcomGnss', 'gpsLocation']) + + while 1: + opcode, payload = diag.recv() + if opcode != DIAG_LOG_F: + cloudlog.error(f"Unhandled opcode: {opcode}") + continue + + (pending_msgs, log_outer_length), inner_log_packet = unpack_from(' 0: + cloudlog.debug("have %d pending messages" % pending_msgs) + assert log_outer_length == len(inner_log_packet) + + (log_inner_length, log_type, log_time), log_payload = unpack_from(' 0: + assert len(sats)//dat['svCount'] == size_meas_sv + for i in range(dat['svCount']): + sv = report.sv[i] + sv.init('measurementStatus') + sat = unpack_meas_sv(sats[size_meas_sv*i:size_meas_sv*(i+1)]) + for k,v in sat.items(): + if k == "parityErrorCount": + sv.gpsParityErrorCount = v + elif k == "frequencyIndex": + sv.glonassFrequencyIndex = v + elif k == "hemmingErrorCount": + sv.glonassHemmingErrorCount = v + elif k == "measurementStatus": + for kk,vv in itertools.chain(*measurement_status_fields): + setattr(sv.measurementStatus, kk, bool(v & (1< Accelerometer BIT[1] 0x00000002 <96> Gyro 0x0000FFFC - Reserved A bit set to 1 indicates that certain fields as defined by the SENSOR_AIDING_MASK were aided with sensor data*/ + uint32 q_SensorAidMask; /* Denotes which component of the position report was assisted with additional sensors defined in SENSOR_DATA_USAGE_MASK BIT[0] 0x00000001 <96> Heading aided with sensor data BIT[1] 0x00000002 <96> Speed aided with sensor data BIT[2] 0x00000004 <96> Position aided with sensor data BIT[3] 0x00000008 <96> Velocity aided with sensor data 0xFFFFFFF0 <96> Reserved */ + uint8 u_NumGpsSvsUsed; /* The number of GPS SVs used in the fix */ + uint8 u_TotalGpsSvs; /* Total number of GPS SVs detected by searcher, including ones not used in position calculation */ + uint8 u_NumGloSvsUsed; /* The number of Glonass SVs used in the fix */ + uint8 u_TotalGloSvs; /* Total number of Glonass SVs detected by searcher, including ones not used in position calculation */ + uint8 u_NumBdsSvsUsed; /* The number of BeiDou SVs used in the fix */ + uint8 u_TotalBdsSvs; /* Total number of BeiDou SVs detected by searcher, including ones not used in position calculation */ +""" + +def name_to_camelcase(nam): + ret = [] + i = 0 + while i < len(nam): + if nam[i] == "_": + ret.append(nam[i+1].upper()) + i += 2 + else: + ret.append(nam[i]) + i += 1 + return ''.join(ret) + +def parse_struct(ss): + st = "<" + nams = [] + for l in ss.strip().split("\n"): + if len(l.strip()) == 0: + continue + typ, nam = l.split(";")[0].split() + #print(typ, nam) + if typ == "float" or '_Flt' in nam: + st += "f" + elif typ == "double" or '_Dbl' in nam: + st += "d" + elif typ in ["uint8", "uint8_t"]: + st += "B" + elif typ in ["int8", "int8_t"]: + st += "b" + elif typ in ["uint32", "uint32_t"]: + st += "I" + elif typ in ["int32", "int32_t"]: + st += "i" + elif typ in ["uint16", "uint16_t"]: + st += "H" + elif typ in ["int16", "int16_t"]: + st += "h" + elif typ in ["uint64", "uint64_t"]: + st += "Q" + else: + print("unknown type", typ) + assert False + if '[' in nam: + cnt = int(nam.split("[")[1].split("]")[0]) + st += st[-1]*(cnt-1) + for i in range(cnt): + nams.append("%s[%d]" % (nam.split("[")[0], i)) + else: + nams.append(nam) + return st, nams + +def dict_unpacker(ss, camelcase = False): + st, nams = parse_struct(ss) + if camelcase: + nams = [name_to_camelcase(x) for x in nams] + sz = calcsize(st) + return lambda x: dict(zip(nams, unpack_from(st, x))), sz + +def relist(dat): + list_keys = set() + for key in dat.keys(): + if '[' in key: + list_keys.add(key.split('[')[0]) + list_dict = {} + for list_key in list_keys: + list_dict[list_key] = [] + i = 0 + while True: + key = list_key + f'[{i}]' + if key not in dat: + break + list_dict[list_key].append(dat[key]) + del dat[key] + i += 1 + return {**dat, **list_dict} diff --git a/selfdrive/sensord/rawgps/test_rawgps.py b/selfdrive/sensord/rawgps/test_rawgps.py new file mode 100755 index 0000000000..5bd0833955 --- /dev/null +++ b/selfdrive/sensord/rawgps/test_rawgps.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +import json +import time +import unittest +import subprocess + +import cereal.messaging as messaging +from system.hardware import TICI +from selfdrive.manager.process_config import managed_processes + + +class TestRawgpsd(unittest.TestCase): + @classmethod + def setUpClass(cls): + if not TICI: + raise unittest.SkipTest + + def tearDown(self): + managed_processes['rawgpsd'].stop() + + def test_startup_time(self): + for _ in range(5): + sm = messaging.SubMaster(['qcomGnss']) + managed_processes['rawgpsd'].start() + + start_time = time.monotonic() + for __ in range(10): + sm.update(1 * 1000) + if sm.updated['qcomGnss']: + break + assert sm.rcv_frame['qcomGnss'] > 0, "rawgpsd didn't start outputting messages in time" + + et = time.monotonic() - start_time + assert et < 5, f"rawgpsd took {et:.1f}s to start" + managed_processes['rawgpsd'].stop() + + def test_turns_off_gnss(self): + for s in (0.1, 0.5, 1, 5): + managed_processes['rawgpsd'].start() + time.sleep(s) + managed_processes['rawgpsd'].stop() + + ls = subprocess.check_output("mmcli -m any --location-status --output-json", shell=True, encoding='utf-8') + loc_status = json.loads(ls) + assert set(loc_status['modem']['location']['enabled']) <= {'3gpp-lac-ci'} + + +if __name__ == "__main__": + unittest.main() diff --git a/selfdrive/sensord/sensors/bmx055_accel.cc b/selfdrive/sensord/sensors/bmx055_accel.cc index f5d68bdee5..78b3ac526d 100644 --- a/selfdrive/sensord/sensors/bmx055_accel.cc +++ b/selfdrive/sensord/sensors/bmx055_accel.cc @@ -2,8 +2,9 @@ #include -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/timing.h" +#include "common/swaglog.h" +#include "common/timing.h" +#include "common/util.h" BMX055_Accel::BMX055_Accel(I2CBus *bus) : I2CSensor(bus) {} @@ -23,6 +24,13 @@ int BMX055_Accel::init() { goto fail; } + ret = set_register(BMX055_ACCEL_I2C_REG_PMU, BMX055_ACCEL_NORMAL_MODE); + if (ret < 0) { + goto fail; + } + // bmx055 accel has a 1.3ms wakeup time from deep suspend mode + util::sleep_for(10); + // High bandwidth // ret = set_register(BMX055_ACCEL_I2C_REG_HBW, BMX055_ACCEL_HBW_ENABLE); // if (ret < 0) { @@ -34,6 +42,7 @@ int BMX055_Accel::init() { if (ret < 0) { goto fail; } + ret = set_register(BMX055_ACCEL_I2C_REG_BW, BMX055_ACCEL_BW_125HZ); if (ret < 0) { goto fail; @@ -43,7 +52,17 @@ fail: return ret; } -void BMX055_Accel::get_event(cereal::SensorEventData::Builder &event) { +int BMX055_Accel::shutdown() { + // enter deep suspend mode (lowest power mode) + int ret = set_register(BMX055_ACCEL_I2C_REG_PMU, BMX055_ACCEL_DEEP_SUSPEND); + if (ret < 0) { + LOGE("Could not move BMX055 ACCEL in deep suspend mode!") + } + + return ret; +} + +bool BMX055_Accel::get_event(MessageBuilder &msg, uint64_t ts) { uint64_t start_time = nanos_since_boot(); uint8_t buffer[6]; int len = read_register(BMX055_ACCEL_I2C_REG_X_LSB, buffer, sizeof(buffer)); @@ -55,6 +74,7 @@ void BMX055_Accel::get_event(cereal::SensorEventData::Builder &event) { float y = -read_12_bit(buffer[2], buffer[3]) * scale; float z = read_12_bit(buffer[4], buffer[5]) * scale; + auto event = msg.initEvent().initAccelerometer2(); event.setSource(cereal::SensorEventData::SensorSource::BMX055); event.setVersion(1); event.setSensor(SENSOR_ACCELEROMETER); @@ -66,4 +86,5 @@ void BMX055_Accel::get_event(cereal::SensorEventData::Builder &event) { svec.setV(xyz); svec.setStatus(true); + return true; } diff --git a/selfdrive/sensord/sensors/bmx055_accel.h b/selfdrive/sensord/sensors/bmx055_accel.h index 86ec419cde..8ef660a99f 100644 --- a/selfdrive/sensord/sensors/bmx055_accel.h +++ b/selfdrive/sensord/sensors/bmx055_accel.h @@ -10,6 +10,7 @@ #define BMX055_ACCEL_I2C_REG_X_LSB 0x02 #define BMX055_ACCEL_I2C_REG_TEMP 0x08 #define BMX055_ACCEL_I2C_REG_BW 0x10 +#define BMX055_ACCEL_I2C_REG_PMU 0x11 #define BMX055_ACCEL_I2C_REG_HBW 0x13 #define BMX055_ACCEL_I2C_REG_FIFO 0x3F @@ -18,6 +19,8 @@ #define BMX055_ACCEL_HBW_ENABLE 0b10000000 #define BMX055_ACCEL_HBW_DISABLE 0b00000000 +#define BMX055_ACCEL_DEEP_SUSPEND 0b00100000 +#define BMX055_ACCEL_NORMAL_MODE 0b00000000 #define BMX055_ACCEL_BW_7_81HZ 0b01000 #define BMX055_ACCEL_BW_15_63HZ 0b01001 @@ -33,5 +36,6 @@ class BMX055_Accel : public I2CSensor { public: BMX055_Accel(I2CBus *bus); int init(); - void get_event(cereal::SensorEventData::Builder &event); + bool get_event(MessageBuilder &msg, uint64_t ts = 0); + int shutdown(); }; diff --git a/selfdrive/sensord/sensors/bmx055_gyro.cc b/selfdrive/sensord/sensors/bmx055_gyro.cc index f0e3034e3f..9d70b9e431 100644 --- a/selfdrive/sensord/sensors/bmx055_gyro.cc +++ b/selfdrive/sensord/sensors/bmx055_gyro.cc @@ -3,7 +3,8 @@ #include #include -#include "selfdrive/common/swaglog.h" +#include "common/swaglog.h" +#include "common/util.h" #define DEG2RAD(x) ((x) * M_PI / 180.0) @@ -26,6 +27,13 @@ int BMX055_Gyro::init() { goto fail; } + ret = set_register(BMX055_GYRO_I2C_REG_LPM1, BMX055_GYRO_NORMAL_MODE); + if (ret < 0) { + goto fail; + } + // bmx055 gyro has a 30ms wakeup time from deep suspend mode + util::sleep_for(50); + // High bandwidth // ret = set_register(BMX055_GYRO_I2C_REG_HBW, BMX055_GYRO_HBW_ENABLE); // if (ret < 0) { @@ -54,7 +62,17 @@ fail: return ret; } -void BMX055_Gyro::get_event(cereal::SensorEventData::Builder &event) { +int BMX055_Gyro::shutdown() { + // enter deep suspend mode (lowest power mode) + int ret = set_register(BMX055_GYRO_I2C_REG_LPM1, BMX055_GYRO_DEEP_SUSPEND); + if (ret < 0) { + LOGE("Could not move BMX055 GYRO in deep suspend mode!") + } + + return ret; +} + +bool BMX055_Gyro::get_event(MessageBuilder &msg, uint64_t ts) { uint64_t start_time = nanos_since_boot(); uint8_t buffer[6]; int len = read_register(BMX055_GYRO_I2C_REG_RATE_X_LSB, buffer, sizeof(buffer)); @@ -66,6 +84,7 @@ void BMX055_Gyro::get_event(cereal::SensorEventData::Builder &event) { float y = -DEG2RAD(read_16_bit(buffer[2], buffer[3]) * scale); float z = DEG2RAD(read_16_bit(buffer[4], buffer[5]) * scale); + auto event = msg.initEvent().initGyroscope2(); event.setSource(cereal::SensorEventData::SensorSource::BMX055); event.setVersion(1); event.setSensor(SENSOR_GYRO_UNCALIBRATED); @@ -77,4 +96,5 @@ void BMX055_Gyro::get_event(cereal::SensorEventData::Builder &event) { svec.setV(xyz); svec.setStatus(true); + return true; } diff --git a/selfdrive/sensord/sensors/bmx055_gyro.h b/selfdrive/sensord/sensors/bmx055_gyro.h index ed0c16ff05..80b93f128c 100644 --- a/selfdrive/sensord/sensors/bmx055_gyro.h +++ b/selfdrive/sensord/sensors/bmx055_gyro.h @@ -10,6 +10,7 @@ #define BMX055_GYRO_I2C_REG_RATE_X_LSB 0x02 #define BMX055_GYRO_I2C_REG_RANGE 0x0F #define BMX055_GYRO_I2C_REG_BW 0x10 +#define BMX055_GYRO_I2C_REG_LPM1 0x11 #define BMX055_GYRO_I2C_REG_HBW 0x13 #define BMX055_GYRO_I2C_REG_FIFO 0x3F @@ -18,6 +19,8 @@ #define BMX055_GYRO_HBW_ENABLE 0b10000000 #define BMX055_GYRO_HBW_DISABLE 0b00000000 +#define BMX055_GYRO_DEEP_SUSPEND 0b00100000 +#define BMX055_GYRO_NORMAL_MODE 0b00000000 #define BMX055_GYRO_RANGE_2000 0b000 #define BMX055_GYRO_RANGE_1000 0b001 @@ -33,5 +36,6 @@ class BMX055_Gyro : public I2CSensor { public: BMX055_Gyro(I2CBus *bus); int init(); - void get_event(cereal::SensorEventData::Builder &event); + bool get_event(MessageBuilder &msg, uint64_t ts = 0); + int shutdown(); }; diff --git a/selfdrive/sensord/sensors/bmx055_magn.cc b/selfdrive/sensord/sensors/bmx055_magn.cc index 29e0d809d8..394b1e83d3 100644 --- a/selfdrive/sensord/sensors/bmx055_magn.cc +++ b/selfdrive/sensord/sensors/bmx055_magn.cc @@ -6,8 +6,8 @@ #include #include -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/util.h" +#include "common/swaglog.h" +#include "common/util.h" static int16_t compensate_x(trim_data_t trim_data, int16_t mag_data_x, uint16_t data_rhall) { uint16_t process_comp_x0 = data_rhall; @@ -155,6 +155,16 @@ int BMX055_Magn::init() { return ret; } +int BMX055_Magn::shutdown() { + // move to suspend mode + int ret = set_register(BMX055_MAGN_I2C_REG_PWR_0, 0); + if (ret < 0) { + LOGE("Could not move BMX055 MAGN in suspend mode!") + } + + return ret; +} + bool BMX055_Magn::perform_self_test() { uint8_t buffer[8]; int16_t x, y; @@ -213,7 +223,7 @@ bool BMX055_Magn::parse_xyz(uint8_t buffer[8], int16_t *x, int16_t *y, int16_t * } -void BMX055_Magn::get_event(cereal::SensorEventData::Builder &event) { +bool BMX055_Magn::get_event(MessageBuilder &msg, uint64_t ts) { uint64_t start_time = nanos_since_boot(); uint8_t buffer[8]; int16_t _x, _y, x, y, z; @@ -221,7 +231,10 @@ void BMX055_Magn::get_event(cereal::SensorEventData::Builder &event) { int len = read_register(BMX055_MAGN_I2C_REG_DATAX_LSB, buffer, sizeof(buffer)); assert(len == sizeof(buffer)); - if (parse_xyz(buffer, &_x, &_y, &z)) { + bool parsed = parse_xyz(buffer, &_x, &_y, &z); + if (parsed) { + + auto event = msg.initEvent().initMagnetometer(); event.setSource(cereal::SensorEventData::SensorSource::BMX055); event.setVersion(2); event.setSensor(SENSOR_MAGNETOMETER_UNCALIBRATED); @@ -247,4 +260,6 @@ void BMX055_Magn::get_event(cereal::SensorEventData::Builder &event) { // at a 100 Hz. When reading the registers we have to check the ready bit // To verify the measurement was completed this cycle. set_register(BMX055_MAGN_I2C_REG_MAG, BMX055_MAGN_FORCED); + + return parsed; } diff --git a/selfdrive/sensord/sensors/bmx055_magn.h b/selfdrive/sensord/sensors/bmx055_magn.h index d60fd5515c..e4a79bc7e0 100644 --- a/selfdrive/sensord/sensors/bmx055_magn.h +++ b/selfdrive/sensord/sensors/bmx055_magn.h @@ -59,5 +59,6 @@ class BMX055_Magn : public I2CSensor{ public: BMX055_Magn(I2CBus *bus); int init(); - void get_event(cereal::SensorEventData::Builder &event); + bool get_event(MessageBuilder &msg, uint64_t ts = 0); + int shutdown(); }; diff --git a/selfdrive/sensord/sensors/bmx055_temp.cc b/selfdrive/sensord/sensors/bmx055_temp.cc index 339a987ce0..bdb34f1508 100644 --- a/selfdrive/sensord/sensors/bmx055_temp.cc +++ b/selfdrive/sensord/sensors/bmx055_temp.cc @@ -3,8 +3,8 @@ #include #include "selfdrive/sensord/sensors/bmx055_accel.h" -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/timing.h" +#include "common/swaglog.h" +#include "common/timing.h" BMX055_Temp::BMX055_Temp(I2CBus *bus) : I2CSensor(bus) {} @@ -28,7 +28,7 @@ fail: return ret; } -void BMX055_Temp::get_event(cereal::SensorEventData::Builder &event) { +bool BMX055_Temp::get_event(MessageBuilder &msg, uint64_t ts) { uint64_t start_time = nanos_since_boot(); uint8_t buffer[1]; int len = read_register(BMX055_ACCEL_I2C_REG_TEMP, buffer, sizeof(buffer)); @@ -36,9 +36,12 @@ void BMX055_Temp::get_event(cereal::SensorEventData::Builder &event) { float temp = 23.0f + int8_t(buffer[0]) / 2.0f; + auto event = msg.initEvent().initTemperatureSensor(); event.setSource(cereal::SensorEventData::SensorSource::BMX055); event.setVersion(1); event.setType(SENSOR_TYPE_AMBIENT_TEMPERATURE); event.setTimestamp(start_time); event.setTemperature(temp); + + return true; } diff --git a/selfdrive/sensord/sensors/bmx055_temp.h b/selfdrive/sensord/sensors/bmx055_temp.h index 5ffaa8fb6b..0b6802deaa 100644 --- a/selfdrive/sensord/sensors/bmx055_temp.h +++ b/selfdrive/sensord/sensors/bmx055_temp.h @@ -8,5 +8,6 @@ class BMX055_Temp : public I2CSensor { public: BMX055_Temp(I2CBus *bus); int init(); - void get_event(cereal::SensorEventData::Builder &event); + bool get_event(MessageBuilder &msg, uint64_t ts = 0); + int shutdown() { return 0; } }; diff --git a/selfdrive/sensord/sensors/file_sensor.cc b/selfdrive/sensord/sensors/file_sensor.cc index 812a41fa8a..a74ae1ae1e 100644 --- a/selfdrive/sensord/sensors/file_sensor.cc +++ b/selfdrive/sensord/sensors/file_sensor.cc @@ -2,8 +2,7 @@ #include -FileSensor::FileSensor(std::string filename) : file(filename) { -} +FileSensor::FileSensor(std::string filename) : file(filename) {} int FileSensor::init() { return file.is_open() ? 0 : 1; @@ -12,3 +11,7 @@ int FileSensor::init() { FileSensor::~FileSensor() { file.close(); } + +bool FileSensor::has_interrupt_enabled() { + return false; +} \ No newline at end of file diff --git a/selfdrive/sensord/sensors/file_sensor.h b/selfdrive/sensord/sensors/file_sensor.h index c5b4643e16..39d695167d 100644 --- a/selfdrive/sensord/sensors/file_sensor.h +++ b/selfdrive/sensord/sensors/file_sensor.h @@ -14,5 +14,6 @@ public: FileSensor(std::string filename); ~FileSensor(); int init(); - virtual void get_event(cereal::SensorEventData::Builder &event) = 0; + bool has_interrupt_enabled(); + virtual bool get_event(MessageBuilder &msg, uint64_t ts = 0) = 0; }; diff --git a/selfdrive/sensord/sensors/i2c_sensor.cc b/selfdrive/sensord/sensors/i2c_sensor.cc index 40dfa4a736..f563f93d2b 100644 --- a/selfdrive/sensord/sensors/i2c_sensor.cc +++ b/selfdrive/sensord/sensors/i2c_sensor.cc @@ -15,8 +15,13 @@ int32_t read_20_bit(uint8_t b2, uint8_t b1, uint8_t b0) { return int32_t(combined) / (1 << 4); } +I2CSensor::I2CSensor(I2CBus *bus, int gpio_nr, bool shared_gpio) : + bus(bus), gpio_nr(gpio_nr), shared_gpio(shared_gpio) {} -I2CSensor::I2CSensor(I2CBus *bus) : bus(bus) { +I2CSensor::~I2CSensor() { + if (gpio_fd != -1) { + close(gpio_fd); + } } int I2CSensor::read_register(uint register_address, uint8_t *buffer, uint8_t len) { @@ -26,3 +31,20 @@ int I2CSensor::read_register(uint register_address, uint8_t *buffer, uint8_t len int I2CSensor::set_register(uint register_address, uint8_t data) { return bus->set_register(get_device_address(), register_address, data); } + +int I2CSensor::init_gpio() { + if (shared_gpio || gpio_nr == 0) { + return 0; + } + + gpio_fd = gpiochip_get_ro_value_fd("sensord", GPIOCHIP_INT, gpio_nr); + if (gpio_fd < 0) { + return -1; + } + + return 0; +} + +bool I2CSensor::has_interrupt_enabled() { + return gpio_nr != 0; +} diff --git a/selfdrive/sensord/sensors/i2c_sensor.h b/selfdrive/sensord/sensors/i2c_sensor.h index 83c66eac87..0de2a98738 100644 --- a/selfdrive/sensord/sensors/i2c_sensor.h +++ b/selfdrive/sensord/sensors/i2c_sensor.h @@ -1,9 +1,13 @@ #pragma once #include +#include #include "cereal/gen/cpp/log.capnp.h" -#include "selfdrive/common/i2c.h" + +#include "common/i2c.h" +#include "common/gpio.h" + #include "selfdrive/sensord/sensors/constants.h" #include "selfdrive/sensord/sensors/sensor.h" @@ -15,12 +19,18 @@ int32_t read_20_bit(uint8_t b2, uint8_t b1, uint8_t b0); class I2CSensor : public Sensor { private: I2CBus *bus; + int gpio_nr; + bool shared_gpio; virtual uint8_t get_device_address() = 0; public: - I2CSensor(I2CBus *bus); + I2CSensor(I2CBus *bus, int gpio_nr = 0, bool shared_gpio = false); + ~I2CSensor(); int read_register(uint register_address, uint8_t *buffer, uint8_t len); int set_register(uint register_address, uint8_t data); + int init_gpio(); + bool has_interrupt_enabled(); virtual int init() = 0; - virtual void get_event(cereal::SensorEventData::Builder &event) = 0; + virtual bool get_event(MessageBuilder &msg, uint64_t ts = 0) = 0; + virtual int shutdown() = 0; }; diff --git a/selfdrive/sensord/sensors/light_sensor.cc b/selfdrive/sensord/sensors/light_sensor.cc index 4d00d37bda..58c602ea39 100644 --- a/selfdrive/sensord/sensors/light_sensor.cc +++ b/selfdrive/sensord/sensors/light_sensor.cc @@ -2,10 +2,12 @@ #include -#include "selfdrive/common/timing.h" +#include "common/timing.h" #include "selfdrive/sensord/sensors/constants.h" -void LightSensor::get_event(cereal::SensorEventData::Builder &event) { +LightSensor::LightSensor(std::string filename) : FileSensor(filename) {} + +bool LightSensor::get_event(MessageBuilder &msg, uint64_t ts) { uint64_t start_time = nanos_since_boot(); file.clear(); file.seekg(0); @@ -13,10 +15,13 @@ void LightSensor::get_event(cereal::SensorEventData::Builder &event) { int value; file >> value; + auto event = msg.initEvent().initLightSensor(); event.setSource(cereal::SensorEventData::SensorSource::RPR0521); event.setVersion(1); event.setSensor(SENSOR_LIGHT); event.setType(SENSOR_TYPE_LIGHT); event.setTimestamp(start_time); event.setLight(value); + + return true; } diff --git a/selfdrive/sensord/sensors/light_sensor.h b/selfdrive/sensord/sensors/light_sensor.h index faf901d41c..7ed1c1f70c 100644 --- a/selfdrive/sensord/sensors/light_sensor.h +++ b/selfdrive/sensord/sensors/light_sensor.h @@ -3,6 +3,7 @@ class LightSensor : public FileSensor { public: - LightSensor(std::string filename) : FileSensor(filename){}; - void get_event(cereal::SensorEventData::Builder &event); + LightSensor(std::string filename); + bool get_event(MessageBuilder &msg, uint64_t ts = 0); + int shutdown() { return 0; } }; diff --git a/selfdrive/sensord/sensors/lsm6ds3_accel.cc b/selfdrive/sensord/sensors/lsm6ds3_accel.cc index 83222858e7..c19e3de7ed 100644 --- a/selfdrive/sensord/sensors/lsm6ds3_accel.cc +++ b/selfdrive/sensord/sensors/lsm6ds3_accel.cc @@ -1,15 +1,132 @@ #include "lsm6ds3_accel.h" #include +#include +#include -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/timing.h" +#include "common/swaglog.h" +#include "common/timing.h" +#include "common/util.h" -LSM6DS3_Accel::LSM6DS3_Accel(I2CBus *bus) : I2CSensor(bus) {} +LSM6DS3_Accel::LSM6DS3_Accel(I2CBus *bus, int gpio_nr, bool shared_gpio) : + I2CSensor(bus, gpio_nr, shared_gpio) {} + +void LSM6DS3_Accel::wait_for_data_ready() { + uint8_t drdy = 0; + uint8_t buffer[6]; + + do { + read_register(LSM6DS3_ACCEL_I2C_REG_STAT_REG, &drdy, sizeof(drdy)); + drdy &= LSM6DS3_ACCEL_DRDY_XLDA; + } while (drdy == 0); + + read_register(LSM6DS3_ACCEL_I2C_REG_OUTX_L_XL, buffer, sizeof(buffer)); +} + +void LSM6DS3_Accel::read_and_avg_data(float* out_buf) { + uint8_t drdy = 0; + uint8_t buffer[6]; + + float scaling = 0.061f; + if (source == cereal::SensorEventData::SensorSource::LSM6DS3TRC) { + scaling = 0.122f; + } + + for (int i = 0; i < 5; i++) { + do { + read_register(LSM6DS3_ACCEL_I2C_REG_STAT_REG, &drdy, sizeof(drdy)); + drdy &= LSM6DS3_ACCEL_DRDY_XLDA; + } while (drdy == 0); + + int len = read_register(LSM6DS3_ACCEL_I2C_REG_OUTX_L_XL, buffer, sizeof(buffer)); + assert(len == sizeof(buffer)); + + for (int j = 0; j < 3; j++) { + out_buf[j] += (float)read_16_bit(buffer[j*2], buffer[j*2+1]) * scaling; + } + } + + for (int i = 0; i < 3; i++) { + out_buf[i] /= 5.0f; + } +} + +int LSM6DS3_Accel::self_test(int test_type) { + float val_st_off[3] = {0}; + float val_st_on[3] = {0}; + float test_val[3] = {0}; + uint8_t ODR_FS_MO = LSM6DS3_ACCEL_ODR_52HZ; // full scale: +-2g, ODR: 52Hz + + // prepare sensor for self-test + + // enable block data update and automatic increment + int ret = set_register(LSM6DS3_ACCEL_I2C_REG_CTRL3_C, LSM6DS3_ACCEL_IF_INC_BDU); + if (ret < 0) { + return ret; + } + + if (source == cereal::SensorEventData::SensorSource::LSM6DS3TRC) { + ODR_FS_MO = LSM6DS3_ACCEL_FS_4G | LSM6DS3_ACCEL_ODR_52HZ; + } + ret = set_register(LSM6DS3_ACCEL_I2C_REG_CTRL1_XL, ODR_FS_MO); + if (ret < 0) { + return ret; + } + + // wait for stable output, and discard first values + util::sleep_for(100); + wait_for_data_ready(); + read_and_avg_data(val_st_off); + + // enable Self Test positive (or negative) + ret = set_register(LSM6DS3_ACCEL_I2C_REG_CTRL5_C, test_type); + if (ret < 0) { + return ret; + } + + // wait for stable output, and discard first values + util::sleep_for(100); + wait_for_data_ready(); + read_and_avg_data(val_st_on); + + // disable sensor + ret = set_register(LSM6DS3_ACCEL_I2C_REG_CTRL1_XL, 0); + if (ret < 0) { + return ret; + } + + // disable self test + ret = set_register(LSM6DS3_ACCEL_I2C_REG_CTRL5_C, 0); + if (ret < 0) { + return ret; + } + + // calculate the mg values for self test + for (int i = 0; i < 3; i++) { + test_val[i] = fabs(val_st_on[i] - val_st_off[i]); + } + + // verify test result + for (int i = 0; i < 3; i++) { + if ((LSM6DS3_ACCEL_MIN_ST_LIMIT_mg > test_val[i]) || + (test_val[i] > LSM6DS3_ACCEL_MAX_ST_LIMIT_mg)) { + return -1; + } + } + + return ret; +} int LSM6DS3_Accel::init() { int ret = 0; uint8_t buffer[1]; + uint8_t value = 0; + bool do_self_test = false; + + const char* env_lsm_selftest =env_lsm_selftest = std::getenv("LSM_SELF_TEST"); + if (env_lsm_selftest != nullptr && strncmp(env_lsm_selftest, "1", 1) == 0) { + do_self_test = true; + } ret = read_register(LSM6DS3_ACCEL_I2C_REG_ID, buffer, 1); if(ret < 0) { @@ -27,20 +144,98 @@ int LSM6DS3_Accel::init() { source = cereal::SensorEventData::SensorSource::LSM6DS3TRC; } - // TODO: set scale and bandwith. Default is +- 2G, 50 Hz + ret = self_test(LSM6DS3_ACCEL_POSITIVE_TEST); + if (ret < 0) { + LOGE("LSM6DS3 accel positive self-test failed!"); + if (do_self_test) goto fail; + } + + ret = self_test(LSM6DS3_ACCEL_NEGATIVE_TEST); + if (ret < 0) { + LOGE("LSM6DS3 accel negative self-test failed!"); + if (do_self_test) goto fail; + } + + ret = init_gpio(); + if (ret < 0) { + goto fail; + } + + // enable continuous update, and automatic increase + ret = set_register(LSM6DS3_ACCEL_I2C_REG_CTRL3_C, LSM6DS3_ACCEL_IF_INC); + if (ret < 0) { + goto fail; + } + + // TODO: set scale and bandwidth. Default is +- 2G, 50 Hz ret = set_register(LSM6DS3_ACCEL_I2C_REG_CTRL1_XL, LSM6DS3_ACCEL_ODR_104HZ); if (ret < 0) { goto fail; } + ret = set_register(LSM6DS3_ACCEL_I2C_REG_DRDY_CFG, LSM6DS3_ACCEL_DRDY_PULSE_MODE); + if (ret < 0) { + goto fail; + } + + // enable data ready interrupt for accel on INT1 + // (without resetting existing interrupts) + ret = read_register(LSM6DS3_ACCEL_I2C_REG_INT1_CTRL, &value, 1); + if (ret < 0) { + goto fail; + } + + value |= LSM6DS3_ACCEL_INT1_DRDY_XL; + ret = set_register(LSM6DS3_ACCEL_I2C_REG_INT1_CTRL, value); fail: return ret; } -void LSM6DS3_Accel::get_event(cereal::SensorEventData::Builder &event) { +int LSM6DS3_Accel::shutdown() { + int ret = 0; + + // disable data ready interrupt for accel on INT1 + uint8_t value = 0; + ret = read_register(LSM6DS3_ACCEL_I2C_REG_INT1_CTRL, &value, 1); + if (ret < 0) { + goto fail; + } + + value &= ~(LSM6DS3_ACCEL_INT1_DRDY_XL); + ret = set_register(LSM6DS3_ACCEL_I2C_REG_INT1_CTRL, value); + if (ret < 0) { + LOGE("Could not disable lsm6ds3 acceleration interrupt!") + goto fail; + } + + // enable power-down mode + value = 0; + ret = read_register(LSM6DS3_ACCEL_I2C_REG_CTRL1_XL, &value, 1); + if (ret < 0) { + goto fail; + } + + value &= 0x0F; + ret = set_register(LSM6DS3_ACCEL_I2C_REG_CTRL1_XL, value); + if (ret < 0) { + LOGE("Could not power-down lsm6ds3 accelerometer!") + goto fail; + } + +fail: + return ret; +} + +bool LSM6DS3_Accel::get_event(MessageBuilder &msg, uint64_t ts) { + + // INT1 shared with gyro, check STATUS_REG who triggered + uint8_t status_reg = 0; + read_register(LSM6DS3_ACCEL_I2C_REG_STAT_REG, &status_reg, sizeof(status_reg)); + if ((status_reg & LSM6DS3_ACCEL_DRDY_XLDA) == 0) { + return false; + } - uint64_t start_time = nanos_since_boot(); uint8_t buffer[6]; int len = read_register(LSM6DS3_ACCEL_I2C_REG_OUTX_L_XL, buffer, sizeof(buffer)); assert(len == sizeof(buffer)); @@ -50,15 +245,17 @@ void LSM6DS3_Accel::get_event(cereal::SensorEventData::Builder &event) { float y = read_16_bit(buffer[2], buffer[3]) * scale; float z = read_16_bit(buffer[4], buffer[5]) * scale; + auto event = msg.initEvent().initAccelerometer(); event.setSource(source); event.setVersion(1); event.setSensor(SENSOR_ACCELEROMETER); event.setType(SENSOR_TYPE_ACCELEROMETER); - event.setTimestamp(start_time); + event.setTimestamp(ts); float xyz[] = {y, -x, z}; auto svec = event.initAcceleration(); svec.setV(xyz); svec.setStatus(true); + return true; } diff --git a/selfdrive/sensord/sensors/lsm6ds3_accel.h b/selfdrive/sensord/sensors/lsm6ds3_accel.h index 4a6b687445..c3f66f5803 100644 --- a/selfdrive/sensord/sensors/lsm6ds3_accel.h +++ b/selfdrive/sensord/sensors/lsm6ds3_accel.h @@ -6,21 +6,44 @@ #define LSM6DS3_ACCEL_I2C_ADDR 0x6A // Registers of the chip +#define LSM6DS3_ACCEL_I2C_REG_DRDY_CFG 0x0B #define LSM6DS3_ACCEL_I2C_REG_ID 0x0F +#define LSM6DS3_ACCEL_I2C_REG_INT1_CTRL 0x0D #define LSM6DS3_ACCEL_I2C_REG_CTRL1_XL 0x10 +#define LSM6DS3_ACCEL_I2C_REG_CTRL3_C 0x12 +#define LSM6DS3_ACCEL_I2C_REG_CTRL5_C 0x14 +#define LSM6DS3_ACCEL_I2C_REG_CTR9_XL 0x18 +#define LSM6DS3_ACCEL_I2C_REG_STAT_REG 0x1E #define LSM6DS3_ACCEL_I2C_REG_OUTX_L_XL 0x28 // Constants -#define LSM6DS3_ACCEL_CHIP_ID 0x69 -#define LSM6DS3TRC_ACCEL_CHIP_ID 0x6A -#define LSM6DS3_ACCEL_ODR_104HZ (0b0100 << 4) - +#define LSM6DS3_ACCEL_CHIP_ID 0x69 +#define LSM6DS3TRC_ACCEL_CHIP_ID 0x6A +#define LSM6DS3_ACCEL_FS_4G (0b10 << 2) +#define LSM6DS3_ACCEL_ODR_52HZ (0b0011 << 4) +#define LSM6DS3_ACCEL_ODR_104HZ (0b0100 << 4) +#define LSM6DS3_ACCEL_INT1_DRDY_XL 0b1 +#define LSM6DS3_ACCEL_DRDY_XLDA 0b1 +#define LSM6DS3_ACCEL_DRDY_PULSE_MODE (1 << 7) +#define LSM6DS3_ACCEL_IF_INC 0b00000100 +#define LSM6DS3_ACCEL_IF_INC_BDU 0b01000100 +#define LSM6DS3_ACCEL_XYZ_DEN 0b11100000 +#define LSM6DS3_ACCEL_POSITIVE_TEST 0b01 +#define LSM6DS3_ACCEL_NEGATIVE_TEST 0b10 +#define LSM6DS3_ACCEL_MIN_ST_LIMIT_mg 90.0f +#define LSM6DS3_ACCEL_MAX_ST_LIMIT_mg 1700.0f class LSM6DS3_Accel : public I2CSensor { uint8_t get_device_address() {return LSM6DS3_ACCEL_I2C_ADDR;} cereal::SensorEventData::SensorSource source = cereal::SensorEventData::SensorSource::LSM6DS3; + + // self test functions + int self_test(int test_type); + void wait_for_data_ready(); + void read_and_avg_data(float* val_st_off); public: - LSM6DS3_Accel(I2CBus *bus); + LSM6DS3_Accel(I2CBus *bus, int gpio_nr = 0, bool shared_gpio = false); int init(); - void get_event(cereal::SensorEventData::Builder &event); + bool get_event(MessageBuilder &msg, uint64_t ts = 0); + int shutdown(); }; diff --git a/selfdrive/sensord/sensors/lsm6ds3_gyro.cc b/selfdrive/sensord/sensors/lsm6ds3_gyro.cc index 6732ead0f1..f306be0fe8 100644 --- a/selfdrive/sensord/sensors/lsm6ds3_gyro.cc +++ b/selfdrive/sensord/sensors/lsm6ds3_gyro.cc @@ -2,18 +2,120 @@ #include #include +#include -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/timing.h" +#include "common/swaglog.h" +#include "common/timing.h" +#include "common/util.h" #define DEG2RAD(x) ((x) * M_PI / 180.0) +LSM6DS3_Gyro::LSM6DS3_Gyro(I2CBus *bus, int gpio_nr, bool shared_gpio) : + I2CSensor(bus, gpio_nr, shared_gpio) {} -LSM6DS3_Gyro::LSM6DS3_Gyro(I2CBus *bus) : I2CSensor(bus) {} +void LSM6DS3_Gyro::wait_for_data_ready() { + uint8_t drdy = 0; + uint8_t buffer[6]; + + do { + read_register(LSM6DS3_GYRO_I2C_REG_STAT_REG, &drdy, sizeof(drdy)); + drdy &= LSM6DS3_GYRO_DRDY_GDA; + } while (drdy == 0); + + read_register(LSM6DS3_GYRO_I2C_REG_OUTX_L_G, buffer, sizeof(buffer)); +} + +void LSM6DS3_Gyro::read_and_avg_data(float* out_buf) { + uint8_t drdy = 0; + uint8_t buffer[6]; + + for (int i = 0; i < 5; i++) { + do { + read_register(LSM6DS3_GYRO_I2C_REG_STAT_REG, &drdy, sizeof(drdy)); + drdy &= LSM6DS3_GYRO_DRDY_GDA; + } while (drdy == 0); + + int len = read_register(LSM6DS3_GYRO_I2C_REG_OUTX_L_G, buffer, sizeof(buffer)); + assert(len == sizeof(buffer)); + + for (int j = 0; j < 3; j++) { + out_buf[j] += (float)read_16_bit(buffer[j*2], buffer[j*2+1]) * 70.0f; + } + } + + // calculate the mg average values + for (int i = 0; i < 3; i++) { + out_buf[i] /= 5.0f; + } +} + +int LSM6DS3_Gyro::self_test(int test_type) { + float val_st_off[3] = {0}; + float val_st_on[3] = {0}; + float test_val[3] = {0}; + + // prepare sensor for self-test + + // full scale: 2000dps, ODR: 208Hz + int ret = set_register(LSM6DS3_GYRO_I2C_REG_CTRL2_G, LSM6DS3_GYRO_ODR_208HZ | LSM6DS3_GYRO_FS_2000dps); + if (ret < 0) { + return ret; + } + + // wait for stable output, and discard first values + util::sleep_for(150); + wait_for_data_ready(); + read_and_avg_data(val_st_off); + + // enable Self Test positive (or negative) + ret = set_register(LSM6DS3_GYRO_I2C_REG_CTRL5_C, test_type); + if (ret < 0) { + return ret; + } + + // wait for stable output, and discard first values + util::sleep_for(50); + wait_for_data_ready(); + read_and_avg_data(val_st_on); + + // disable sensor + ret = set_register(LSM6DS3_GYRO_I2C_REG_CTRL2_G, 0); + if (ret < 0) { + return ret; + } + + // disable self test + ret = set_register(LSM6DS3_GYRO_I2C_REG_CTRL5_C, 0); + if (ret < 0) { + return ret; + } + + // calculate the mg values for self test + for (int i = 0; i < 3; i++) { + test_val[i] = fabs(val_st_on[i] - val_st_off[i]); + } + + // verify test result + for (int i = 0; i < 3; i++) { + if ((LSM6DS3_GYRO_MIN_ST_LIMIT_mdps > test_val[i]) || + (test_val[i] > LSM6DS3_GYRO_MAX_ST_LIMIT_mdps)) { + return -1; + } + } + + return ret; +} int LSM6DS3_Gyro::init() { int ret = 0; uint8_t buffer[1]; + uint8_t value = 0; + bool do_self_test = false; + + const char* env_lsm_selftest =env_lsm_selftest = std::getenv("LSM_SELF_TEST"); + if (env_lsm_selftest != nullptr && strncmp(env_lsm_selftest, "1", 1) == 0) { + do_self_test = true; + } ret = read_register(LSM6DS3_GYRO_I2C_REG_ID, buffer, 1); if(ret < 0) { @@ -31,20 +133,92 @@ int LSM6DS3_Gyro::init() { source = cereal::SensorEventData::SensorSource::LSM6DS3TRC; } + ret = init_gpio(); + if (ret < 0) { + goto fail; + } + + ret = self_test(LSM6DS3_GYRO_POSITIVE_TEST); + if (ret < 0 ) { + LOGE("LSM6DS3 gyro positive self-test failed!"); + if (do_self_test) goto fail; + } + + ret = self_test(LSM6DS3_GYRO_NEGATIVE_TEST); + if (ret < 0) { + LOGE("LSM6DS3 gyro negative self-test failed!"); + if (do_self_test) goto fail; + } + // TODO: set scale. Default is +- 250 deg/s ret = set_register(LSM6DS3_GYRO_I2C_REG_CTRL2_G, LSM6DS3_GYRO_ODR_104HZ); if (ret < 0) { goto fail; } + ret = set_register(LSM6DS3_GYRO_I2C_REG_DRDY_CFG, LSM6DS3_GYRO_DRDY_PULSE_MODE); + if (ret < 0) { + goto fail; + } + + // enable data ready interrupt for gyro on INT1 + // (without resetting existing interrupts) + ret = read_register(LSM6DS3_GYRO_I2C_REG_INT1_CTRL, &value, 1); + if (ret < 0) { + goto fail; + } + + value |= LSM6DS3_GYRO_INT1_DRDY_G; + ret = set_register(LSM6DS3_GYRO_I2C_REG_INT1_CTRL, value); fail: return ret; } -void LSM6DS3_Gyro::get_event(cereal::SensorEventData::Builder &event) { +int LSM6DS3_Gyro::shutdown() { + int ret = 0; + + // disable data ready interrupt for gyro on INT1 + uint8_t value = 0; + ret = read_register(LSM6DS3_GYRO_I2C_REG_INT1_CTRL, &value, 1); + if (ret < 0) { + goto fail; + } + + value &= ~(LSM6DS3_GYRO_INT1_DRDY_G); + ret = set_register(LSM6DS3_GYRO_I2C_REG_INT1_CTRL, value); + if (ret < 0) { + LOGE("Could not disable lsm6ds3 gyroscope interrupt!") + goto fail; + } + + // enable power-down mode + value = 0; + ret = read_register(LSM6DS3_GYRO_I2C_REG_CTRL2_G, &value, 1); + if (ret < 0) { + goto fail; + } + + value &= 0x0F; + ret = set_register(LSM6DS3_GYRO_I2C_REG_CTRL2_G, value); + if (ret < 0) { + LOGE("Could not power-down lsm6ds3 gyroscope!") + goto fail; + } + +fail: + return ret; +} + +bool LSM6DS3_Gyro::get_event(MessageBuilder &msg, uint64_t ts) { + + // INT1 shared with accel, check STATUS_REG who triggered + uint8_t status_reg = 0; + read_register(LSM6DS3_GYRO_I2C_REG_STAT_REG, &status_reg, sizeof(status_reg)); + if ((status_reg & LSM6DS3_GYRO_DRDY_GDA) == 0) { + return false; + } - uint64_t start_time = nanos_since_boot(); uint8_t buffer[6]; int len = read_register(LSM6DS3_GYRO_I2C_REG_OUTX_L_G, buffer, sizeof(buffer)); assert(len == sizeof(buffer)); @@ -54,15 +228,17 @@ void LSM6DS3_Gyro::get_event(cereal::SensorEventData::Builder &event) { float y = DEG2RAD(read_16_bit(buffer[2], buffer[3]) * scale); float z = DEG2RAD(read_16_bit(buffer[4], buffer[5]) * scale); + auto event = msg.initEvent().initGyroscope(); event.setSource(source); event.setVersion(2); event.setSensor(SENSOR_GYRO_UNCALIBRATED); event.setType(SENSOR_TYPE_GYROSCOPE_UNCALIBRATED); - event.setTimestamp(start_time); + event.setTimestamp(ts); float xyz[] = {y, -x, z}; auto svec = event.initGyroUncalibrated(); svec.setV(xyz); svec.setStatus(true); + return true; } diff --git a/selfdrive/sensord/sensors/lsm6ds3_gyro.h b/selfdrive/sensord/sensors/lsm6ds3_gyro.h index d7e8f0025a..220e6b0cec 100644 --- a/selfdrive/sensord/sensors/lsm6ds3_gyro.h +++ b/selfdrive/sensord/sensors/lsm6ds3_gyro.h @@ -6,21 +6,40 @@ #define LSM6DS3_GYRO_I2C_ADDR 0x6A // Registers of the chip +#define LSM6DS3_GYRO_I2C_REG_DRDY_CFG 0x0B #define LSM6DS3_GYRO_I2C_REG_ID 0x0F +#define LSM6DS3_GYRO_I2C_REG_INT1_CTRL 0x0D #define LSM6DS3_GYRO_I2C_REG_CTRL2_G 0x11 +#define LSM6DS3_GYRO_I2C_REG_CTRL5_C 0x14 +#define LSM6DS3_GYRO_I2C_REG_STAT_REG 0x1E #define LSM6DS3_GYRO_I2C_REG_OUTX_L_G 0x22 +#define LSM6DS3_GYRO_POSITIVE_TEST (0b01 << 2) +#define LSM6DS3_GYRO_NEGATIVE_TEST (0b11 << 2) // Constants -#define LSM6DS3_GYRO_CHIP_ID 0x69 -#define LSM6DS3TRC_GYRO_CHIP_ID 0x6A -#define LSM6DS3_GYRO_ODR_104HZ (0b0100 << 4) +#define LSM6DS3_GYRO_CHIP_ID 0x69 +#define LSM6DS3TRC_GYRO_CHIP_ID 0x6A +#define LSM6DS3_GYRO_FS_2000dps (0b11 << 2) +#define LSM6DS3_GYRO_ODR_104HZ (0b0100 << 4) +#define LSM6DS3_GYRO_ODR_208HZ (0b0101 << 4) +#define LSM6DS3_GYRO_INT1_DRDY_G 0b10 +#define LSM6DS3_GYRO_DRDY_GDA 0b10 +#define LSM6DS3_GYRO_DRDY_PULSE_MODE (1 << 7) +#define LSM6DS3_GYRO_MIN_ST_LIMIT_mdps 150000.0f +#define LSM6DS3_GYRO_MAX_ST_LIMIT_mdps 700000.0f class LSM6DS3_Gyro : public I2CSensor { uint8_t get_device_address() {return LSM6DS3_GYRO_I2C_ADDR;} cereal::SensorEventData::SensorSource source = cereal::SensorEventData::SensorSource::LSM6DS3; + + // self test functions + int self_test(int test_type); + void wait_for_data_ready(); + void read_and_avg_data(float* val_st_off); public: - LSM6DS3_Gyro(I2CBus *bus); + LSM6DS3_Gyro(I2CBus *bus, int gpio_nr = 0, bool shared_gpio = false); int init(); - void get_event(cereal::SensorEventData::Builder &event); + bool get_event(MessageBuilder &msg, uint64_t ts = 0); + int shutdown(); }; diff --git a/selfdrive/sensord/sensors/lsm6ds3_temp.cc b/selfdrive/sensord/sensors/lsm6ds3_temp.cc index 6b093fce05..7e1c4d4c81 100644 --- a/selfdrive/sensord/sensors/lsm6ds3_temp.cc +++ b/selfdrive/sensord/sensors/lsm6ds3_temp.cc @@ -2,8 +2,8 @@ #include -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/timing.h" +#include "common/swaglog.h" +#include "common/timing.h" LSM6DS3_Temp::LSM6DS3_Temp(I2CBus *bus) : I2CSensor(bus) {} @@ -31,8 +31,7 @@ fail: return ret; } -void LSM6DS3_Temp::get_event(cereal::SensorEventData::Builder &event) { - +bool LSM6DS3_Temp::get_event(MessageBuilder &msg, uint64_t ts) { uint64_t start_time = nanos_since_boot(); uint8_t buffer[2]; int len = read_register(LSM6DS3_TEMP_I2C_REG_OUT_TEMP_L, buffer, sizeof(buffer)); @@ -41,10 +40,12 @@ void LSM6DS3_Temp::get_event(cereal::SensorEventData::Builder &event) { float scale = (source == cereal::SensorEventData::SensorSource::LSM6DS3TRC) ? 256.0f : 16.0f; float temp = 25.0f + read_16_bit(buffer[0], buffer[1]) / scale; + auto event = msg.initEvent().initTemperatureSensor(); event.setSource(source); event.setVersion(1); event.setType(SENSOR_TYPE_AMBIENT_TEMPERATURE); event.setTimestamp(start_time); event.setTemperature(temp); + return true; } diff --git a/selfdrive/sensord/sensors/lsm6ds3_temp.h b/selfdrive/sensord/sensors/lsm6ds3_temp.h index 8188f46700..1d6bcc228a 100644 --- a/selfdrive/sensord/sensors/lsm6ds3_temp.h +++ b/selfdrive/sensord/sensors/lsm6ds3_temp.h @@ -21,5 +21,6 @@ class LSM6DS3_Temp : public I2CSensor { public: LSM6DS3_Temp(I2CBus *bus); int init(); - void get_event(cereal::SensorEventData::Builder &event); + bool get_event(MessageBuilder &msg, uint64_t ts = 0); + int shutdown() { return 0; } }; diff --git a/selfdrive/sensord/sensors/mmc5603nj_magn.cc b/selfdrive/sensord/sensors/mmc5603nj_magn.cc index 68878867e4..7a9b7a298b 100644 --- a/selfdrive/sensord/sensors/mmc5603nj_magn.cc +++ b/selfdrive/sensord/sensors/mmc5603nj_magn.cc @@ -2,8 +2,8 @@ #include -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/timing.h" +#include "common/swaglog.h" +#include "common/timing.h" MMC5603NJ_Magn::MMC5603NJ_Magn(I2CBus *bus) : I2CSensor(bus) {} @@ -51,8 +51,35 @@ fail: return ret; } -void MMC5603NJ_Magn::get_event(cereal::SensorEventData::Builder &event) { +int MMC5603NJ_Magn::shutdown() { + int ret = 0; + + // disable auto reset of measurements + uint8_t value = 0; + ret = read_register(MMC5603NJ_I2C_REG_INTERNAL_0, &value, 1); + if (ret < 0) { + goto fail; + } + + value &= ~(MMC5603NJ_CMM_FREQ_EN | MMC5603NJ_AUTO_SR_EN); + ret = set_register(MMC5603NJ_I2C_REG_INTERNAL_0, value); + if (ret < 0) { + goto fail; + } + + // set ODR to 0 to leave continuous mode + ret = set_register(MMC5603NJ_I2C_REG_ODR, 0); + if (ret < 0) { + goto fail; + } + return ret; + +fail: + LOGE("Could not disable mmc5603nj auto set reset") + return ret; +} +bool MMC5603NJ_Magn::get_event(MessageBuilder &msg, uint64_t ts) { uint64_t start_time = nanos_since_boot(); uint8_t buffer[9]; int len = read_register(MMC5603NJ_I2C_REG_XOUT0, buffer, sizeof(buffer)); @@ -63,6 +90,7 @@ void MMC5603NJ_Magn::get_event(cereal::SensorEventData::Builder &event) { float y = read_20_bit(buffer[7], buffer[3], buffer[2]) * scale; float z = read_20_bit(buffer[8], buffer[5], buffer[4]) * scale; + auto event = msg.initEvent().initMagnetometer(); event.setSource(cereal::SensorEventData::SensorSource::MMC5603NJ); event.setVersion(1); event.setSensor(SENSOR_MAGNETOMETER_UNCALIBRATED); @@ -74,4 +102,5 @@ void MMC5603NJ_Magn::get_event(cereal::SensorEventData::Builder &event) { svec.setV(xyz); svec.setStatus(true); + return true; } diff --git a/selfdrive/sensord/sensors/mmc5603nj_magn.h b/selfdrive/sensord/sensors/mmc5603nj_magn.h index 58840bbf27..a364c7c37a 100644 --- a/selfdrive/sensord/sensors/mmc5603nj_magn.h +++ b/selfdrive/sensord/sensors/mmc5603nj_magn.h @@ -25,5 +25,6 @@ class MMC5603NJ_Magn : public I2CSensor { public: MMC5603NJ_Magn(I2CBus *bus); int init(); - void get_event(cereal::SensorEventData::Builder &event); + bool get_event(MessageBuilder &msg, uint64_t ts = 0); + int shutdown(); }; diff --git a/selfdrive/sensord/sensors/sensor.h b/selfdrive/sensord/sensors/sensor.h index 3fb58ad2ae..603aa3586e 100644 --- a/selfdrive/sensord/sensors/sensor.h +++ b/selfdrive/sensord/sensors/sensor.h @@ -1,10 +1,18 @@ #pragma once -#include "cereal/gen/cpp/log.capnp.h" +#include "cereal/messaging/messaging.h" class Sensor { public: + int gpio_fd = -1; + uint64_t init_delay = 500e6; // default dealy 500ms virtual ~Sensor() {}; virtual int init() = 0; - virtual void get_event(cereal::SensorEventData::Builder &event) = 0; + virtual bool get_event(MessageBuilder &msg, uint64_t ts = 0) = 0; + virtual bool has_interrupt_enabled() = 0; + virtual int shutdown() = 0; + + virtual bool is_data_valid(uint64_t st, uint64_t ct) { + return (ct - st) > init_delay; + } }; diff --git a/selfdrive/sensord/sensors_qcom.cc b/selfdrive/sensord/sensors_qcom.cc deleted file mode 100644 index fcdb9a72d7..0000000000 --- a/selfdrive/sensord/sensors_qcom.cc +++ /dev/null @@ -1,228 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include "cereal/messaging/messaging.h" -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/timing.h" -#include "selfdrive/common/util.h" - -// ACCELEROMETER_UNCALIBRATED is only in Android O -// https://developer.android.com/reference/android/hardware/Sensor.html#STRING_TYPE_ACCELEROMETER_UNCALIBRATED - -#define SENSOR_ACCELEROMETER 1 -#define SENSOR_MAGNETOMETER 2 -#define SENSOR_GYRO 4 -#define SENSOR_MAGNETOMETER_UNCALIBRATED 3 -#define SENSOR_GYRO_UNCALIBRATED 5 -#define SENSOR_PROXIMITY 6 -#define SENSOR_LIGHT 7 - -ExitHandler do_exit; -volatile sig_atomic_t re_init_sensors = 0; - -namespace { - -void sigpipe_handler(int sig) { - LOGE("SIGPIPE received"); - re_init_sensors = true; -} - -void sensor_loop() { - LOG("*** sensor loop"); - - uint64_t frame = 0; - bool low_power_mode = false; - - while (!do_exit) { - SubMaster sm({"deviceState"}); - PubMaster pm({"sensorEvents"}); - - 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); - } - - std::set sensor_types = { - SENSOR_TYPE_ACCELEROMETER, - SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED, - SENSOR_TYPE_MAGNETIC_FIELD, - SENSOR_TYPE_GYROSCOPE_UNCALIBRATED, - SENSOR_TYPE_GYROSCOPE, - SENSOR_TYPE_PROXIMITY, - SENSOR_TYPE_LIGHT, - }; - - std::map sensors = { - {SENSOR_GYRO_UNCALIBRATED, ms2ns(10)}, - {SENSOR_MAGNETOMETER_UNCALIBRATED, ms2ns(100)}, - {SENSOR_ACCELEROMETER, ms2ns(10)}, - {SENSOR_GYRO, ms2ns(10)}, - {SENSOR_MAGNETOMETER, ms2ns(100)}, - {SENSOR_PROXIMITY, ms2ns(100)}, - {SENSOR_LIGHT, ms2ns(100)} - }; - - // sensors needed while offroad - std::set offroad_sensors = { - SENSOR_LIGHT, - SENSOR_ACCELEROMETER, - SENSOR_GYRO_UNCALIBRATED, - }; - - // init all the sensors - for (auto &s : sensors) { - device->activate(device, s.first, 0); - device->activate(device, s.first, 1); - device->setDelay(device, s.first, s.second); - } - - // TODO: why is this 16? - static const size_t numEvents = 16; - sensors_event_t buffer[numEvents]; - - 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++) { - if (sensor_types.find(buffer[i].type) != sensor_types.end()) { - log_events++; - } - } - - MessageBuilder msg; - auto sensor_events = msg.initEvent().initSensorEvents(log_events); - - int log_i = 0; - for (int i = 0; i < n; i++) { - - const sensors_event_t& data = buffer[i]; - - if (sensor_types.find(data.type) == sensor_types.end()) { - 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(); - svec.setV(data.acceleration.v); - 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(); - svec.setV(data.magnetic.v); - 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(); - svec.setV(data.gyro.v); - 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++; - } - - pm.send("sensorEvents", msg); - - if (re_init_sensors) { - LOGE("Resetting sensors"); - re_init_sensors = false; - break; - } - - // Check whether to go into low power mode at 5Hz - if (frame % 20 == 0) { - sm.update(0); - bool offroad = !sm["deviceState"].getDeviceState().getStarted(); - if (low_power_mode != offroad) { - for (auto &s : sensors) { - device->activate(device, s.first, 0); - if (!offroad || offroad_sensors.find(s.first) != offroad_sensors.end()) { - device->activate(device, s.first, 1); - } - } - low_power_mode = offroad; - } - } - - frame++; - } - sensors_close(device); - } -} - -}// Namespace end - -int main(int argc, char *argv[]) { - setpriority(PRIO_PROCESS, 0, -18); - signal(SIGPIPE, (sighandler_t)sigpipe_handler); - - sensor_loop(); - - return 0; -} diff --git a/selfdrive/sensord/sensors_qcom2.cc b/selfdrive/sensord/sensors_qcom2.cc index c3e5bbcdfa..fc8dc8620b 100644 --- a/selfdrive/sensord/sensors_qcom2.cc +++ b/selfdrive/sensord/sensors_qcom2.cc @@ -3,12 +3,15 @@ #include #include #include +#include +#include +#include #include "cereal/messaging/messaging.h" -#include "selfdrive/common/i2c.h" -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/timing.h" -#include "selfdrive/common/util.h" +#include "common/i2c.h" +#include "common/swaglog.h" +#include "common/timing.h" +#include "common/util.h" #include "selfdrive/sensord/sensors/bmx055_accel.h" #include "selfdrive/sensord/sensors/bmx055_gyro.h" #include "selfdrive/sensord/sensors/bmx055_magn.h" @@ -24,30 +27,95 @@ #define I2C_BUS_IMU 1 ExitHandler do_exit; +uint64_t init_ts = 0; -int sensor_loop() { - I2CBus *i2c_bus_imu; +void interrupt_loop(std::vector& sensors, + std::map& sensor_service) +{ + PubMaster pm_int({"gyroscope", "accelerometer"}); - try { - i2c_bus_imu = new I2CBus(I2C_BUS_IMU); - } catch (std::exception &e) { - LOGE("I2CBus init failed"); - return -1; + int fd = sensors[0]->gpio_fd; + struct pollfd fd_list[1] = {0}; + fd_list[0].fd = fd; + fd_list[0].events = POLLIN | POLLPRI; + + while (!do_exit) { + int err = poll(fd_list, 1, 100); + if (err == -1) { + if (errno == EINTR) { + continue; + } + return; + } else if (err == 0) { + LOGE("poll timed out"); + continue; + } + + if ((fd_list[0].revents & (POLLIN | POLLPRI)) == 0) { + LOGE("no poll events set"); + continue; + } + + // Read all events + struct gpioevent_data evdata[16]; + err = read(fd, evdata, sizeof(evdata)); + if (err < 0 || err % sizeof(*evdata) != 0) { + LOGE("error reading event data %d", err); + continue; + } + + int num_events = err / sizeof(*evdata); + uint64_t offset = nanos_since_epoch() - nanos_since_boot(); + uint64_t ts = evdata[num_events - 1].timestamp - offset; + + for (Sensor *sensor : sensors) { + MessageBuilder msg; + if (!sensor->get_event(msg, ts)) { + continue; + } + + if (!sensor->is_data_valid(init_ts, ts)) { + continue; + } + + pm_int.send(sensor_service[sensor].c_str(), msg); + } } + // poweroff sensors, disable interrupts + for (Sensor *sensor : sensors) { + sensor->shutdown(); + } +} + +int sensor_loop(I2CBus *i2c_bus_imu) { BMX055_Accel bmx055_accel(i2c_bus_imu); BMX055_Gyro bmx055_gyro(i2c_bus_imu); BMX055_Magn bmx055_magn(i2c_bus_imu); BMX055_Temp bmx055_temp(i2c_bus_imu); - LSM6DS3_Accel lsm6ds3_accel(i2c_bus_imu); - LSM6DS3_Gyro lsm6ds3_gyro(i2c_bus_imu); + LSM6DS3_Accel lsm6ds3_accel(i2c_bus_imu, GPIO_LSM_INT); + LSM6DS3_Gyro lsm6ds3_gyro(i2c_bus_imu, GPIO_LSM_INT, true); // GPIO shared with accel LSM6DS3_Temp lsm6ds3_temp(i2c_bus_imu); MMC5603NJ_Magn mmc5603nj_magn(i2c_bus_imu); LightSensor light("/sys/class/i2c-adapter/i2c-2/2-0038/iio:device1/in_intensity_both_raw"); + std::map sensor_service = { + {&bmx055_accel, "accelerometer2"}, + {&bmx055_gyro, "gyroscope2"}, + {&bmx055_magn, "magnetometer"}, + {&bmx055_temp, "temperatureSensor"}, + + {&lsm6ds3_accel, "accelerometer"}, + {&lsm6ds3_gyro, "gyroscope"}, + {&lsm6ds3_temp, "temperatureSensor"}, + + {&mmc5603nj_magn, "magnetometer"}, + {&light, "lightSensor"} + }; + // Sensor init std::vector> sensors_init; // Sensor, required sensors_init.push_back({&bmx055_accel, false}); @@ -67,19 +135,22 @@ int sensor_loop() { // Initialize sensors std::vector sensors; - for (auto &sensor : sensors_init) { - int err = sensor.first->init(); + for (auto &[sensor, required] : sensors_init) { + int err = sensor->init(); if (err < 0) { - // Fail on required sensors - if (sensor.second) { + if (required) { LOGE("Error initializing sensors"); return -1; } } else { - if (sensor.first == &bmx055_magn || sensor.first == &mmc5603nj_magn) { + + if (sensor == &bmx055_magn || sensor == &mmc5603nj_magn) { has_magnetometer = true; } - sensors.push_back(sensor.first); + + if (!sensor->has_interrupt_enabled()) { + sensors.push_back(sensor); + } } } @@ -88,29 +159,55 @@ int sensor_loop() { return -1; } - PubMaster pm({"sensorEvents"}); + // increase interrupt quality by pinning interrupt and process to core 1 + setpriority(PRIO_PROCESS, 0, -18); + util::set_core_affinity({1}); + std::system("sudo su -c 'echo 1 > /proc/irq/336/smp_affinity_list'"); + + PubMaster pm_non_int({"gyroscope2", "accelerometer2", "temperatureSensor", + "lightSensor", "magnetometer"}); + init_ts = nanos_since_boot(); + + // thread for reading events via interrupts + std::vector lsm_interrupt_sensors = {&lsm6ds3_accel, &lsm6ds3_gyro}; + std::thread lsm_interrupt_thread(&interrupt_loop, std::ref(lsm_interrupt_sensors), + std::ref(sensor_service)); + // polling loop for non interrupt handled sensors while (!do_exit) { std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now(); - const int num_events = sensors.size(); - MessageBuilder msg; - auto sensor_events = msg.initEvent().initSensorEvents(num_events); + for (Sensor *sensor : sensors) { + MessageBuilder msg; + if (!sensor->get_event(msg)) { + continue; + } - for (int i = 0; i < num_events; i++) { - auto event = sensor_events[i]; - sensors[i]->get_event(event); - } + if (!sensor->is_data_valid(init_ts, nanos_since_boot())) { + continue; + } - pm.send("sensorEvents", msg); + pm_non_int.send(sensor_service[sensor].c_str(), msg); + } std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now(); std::this_thread::sleep_for(std::chrono::milliseconds(10) - (end - begin)); } + + for (Sensor *sensor : sensors) { + sensor->shutdown(); + } + + lsm_interrupt_thread.join(); return 0; } int main(int argc, char *argv[]) { - setpriority(PRIO_PROCESS, 0, -18); - return sensor_loop(); + try { + auto i2c_bus_imu = std::make_unique(I2C_BUS_IMU); + return sensor_loop(i2c_bus_imu.get()); + } catch (std::exception &e) { + LOGE("I2CBus init failed"); + return -1; + } } diff --git a/selfdrive/sensord/tests/__init__.py b/selfdrive/sensord/tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/selfdrive/sensord/tests/test_pigeond.py b/selfdrive/sensord/tests/test_pigeond.py new file mode 100755 index 0000000000..d15b731d0c --- /dev/null +++ b/selfdrive/sensord/tests/test_pigeond.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +import time +import unittest + +import cereal.messaging as messaging +from cereal.services import service_list +from common.gpio import gpio_read +from selfdrive.test.helpers import with_processes +from selfdrive.manager.process_config import managed_processes +from system.hardware import TICI +from system.hardware.tici.pins import GPIO + + +# TODO: test TTFF when we have good A-GNSS +class TestPigeond(unittest.TestCase): + @classmethod + def setUpClass(cls): + if not TICI: + raise unittest.SkipTest + + def tearDown(self): + managed_processes['pigeond'].stop() + + @with_processes(['pigeond']) + def test_frequency(self): + sm = messaging.SubMaster(['ubloxRaw']) + + # setup time + time.sleep(2) + sm.update() + + for _ in range(int(10 * service_list['ubloxRaw'].frequency)): + sm.update() + assert sm.all_checks() + + def test_startup_time(self): + for _ in range(5): + sm = messaging.SubMaster(['ubloxRaw']) + managed_processes['pigeond'].start() + + start_time = time.monotonic() + for __ in range(10): + sm.update(1 * 1000) + if sm.updated['ubloxRaw']: + break + assert sm.rcv_frame['ubloxRaw'] > 0, "pigeond didn't start outputting messages in time" + + et = time.monotonic() - start_time + assert et < 5, f"pigeond took {et:.1f}s to start" + managed_processes['pigeond'].stop() + + def test_turns_off_ublox(self): + for s in (0.1, 0.5, 1, 5): + managed_processes['pigeond'].start() + time.sleep(s) + managed_processes['pigeond'].stop() + + assert gpio_read(GPIO.UBLOX_RST_N) == 0 + assert gpio_read(GPIO.UBLOX_PWR_EN) == 0 + + +if __name__ == "__main__": + unittest.main() diff --git a/selfdrive/sensord/tests/test_sensord.py b/selfdrive/sensord/tests/test_sensord.py new file mode 100755 index 0000000000..c6fe33129a --- /dev/null +++ b/selfdrive/sensord/tests/test_sensord.py @@ -0,0 +1,271 @@ +#!/usr/bin/env python3 +import os +import time +import unittest +import numpy as np +from collections import namedtuple, defaultdict + +import cereal.messaging as messaging +from cereal import log +from system.hardware import TICI, HARDWARE +from selfdrive.manager.process_config import managed_processes + +BMX = { + ('bmx055', 'acceleration'), + ('bmx055', 'gyroUncalibrated'), + ('bmx055', 'magneticUncalibrated'), + ('bmx055', 'temperature'), +} + +LSM = { + ('lsm6ds3', 'acceleration'), + ('lsm6ds3', 'gyroUncalibrated'), + ('lsm6ds3', 'temperature'), +} +LSM_C = {(x[0]+'trc', x[1]) for x in LSM} + +MMC = { + ('mmc5603nj', 'magneticUncalibrated'), +} + +RPR = { + ('rpr0521', 'light'), +} + +SENSOR_CONFIGURATIONS = ( + (BMX | LSM | RPR), + (MMC | LSM | RPR), + (BMX | LSM_C | RPR), + (MMC| LSM_C | RPR), +) + +Sensor = log.SensorEventData.SensorSource +SensorConfig = namedtuple('SensorConfig', ['type', 'sanity_min', 'sanity_max']) +ALL_SENSORS = { + Sensor.rpr0521: { + SensorConfig("light", 0, 1023), + }, + + Sensor.lsm6ds3: { + SensorConfig("acceleration", 5, 15), + SensorConfig("gyroUncalibrated", 0, .2), + SensorConfig("temperature", 0, 60), + }, + + Sensor.lsm6ds3trc: { + SensorConfig("acceleration", 5, 15), + SensorConfig("gyroUncalibrated", 0, .2), + SensorConfig("temperature", 0, 60), + }, + + Sensor.bmx055: { + SensorConfig("acceleration", 5, 15), + SensorConfig("gyroUncalibrated", 0, .2), + SensorConfig("magneticUncalibrated", 0, 300), + SensorConfig("temperature", 0, 60), + }, + + Sensor.mmc5603nj: { + SensorConfig("magneticUncalibrated", 0, 300), + } +} + +LSM_IRQ = 336 + +def get_irq_count(irq: int): + with open(f"/sys/kernel/irq/{irq}/per_cpu_count") as f: + per_cpu = map(int, f.read().split(",")) + return sum(per_cpu) + +def read_sensor_events(duration_sec): + sensor_types = ['accelerometer', 'gyroscope', 'magnetometer', 'accelerometer2', + 'gyroscope2', 'lightSensor', 'temperatureSensor'] + esocks = {} + events = defaultdict(list) + for stype in sensor_types: + esocks[stype] = messaging.sub_sock(stype, timeout=0.1) + + start_time_sec = time.monotonic() + while time.monotonic() - start_time_sec < duration_sec: + for esock in esocks: + events[esock] += messaging.drain_sock(esocks[esock]) + time.sleep(0.1) + + assert sum(map(len, events.values())) != 0, "No sensor events collected!" + + return events + +class TestSensord(unittest.TestCase): + @classmethod + def setUpClass(cls): + if not TICI: + raise unittest.SkipTest + + # make sure gpiochip0 is readable + HARDWARE.initialize_hardware() + + # enable LSM self test + os.environ["LSM_SELF_TEST"] = "1" + + # read initial sensor values every test case can use + os.system("pkill -f ./_sensord") + try: + managed_processes["sensord"].start() + time.sleep(3) + cls.sample_secs = 10 + cls.events = read_sensor_events(cls.sample_secs) + finally: + # teardown won't run if this doesn't succeed + managed_processes["sensord"].stop() + + @classmethod + def tearDownClass(cls): + managed_processes["sensord"].stop() + if "LSM_SELF_TEST" in os.environ: + del os.environ['LSM_SELF_TEST'] + + def tearDown(self): + managed_processes["sensord"].stop() + + def test_sensors_present(self): + # verify correct sensors configuration + + seen = set() + for etype in self.events: + for measurement in self.events[etype]: + m = getattr(measurement, measurement.which()) + seen.add((str(m.source), m.which())) + + self.assertIn(seen, SENSOR_CONFIGURATIONS) + + def test_lsm6ds3_timing(self): + # verify measurements are sampled and published at 104Hz + + sensor_t = { + 1: [], # accel + 5: [], # gyro + } + + for measurement in self.events['accelerometer']: + m = getattr(measurement, measurement.which()) + sensor_t[m.sensor].append(m.timestamp) + + for measurement in self.events['gyroscope']: + m = getattr(measurement, measurement.which()) + sensor_t[m.sensor].append(m.timestamp) + + for s, vals in sensor_t.items(): + with self.subTest(sensor=s): + assert len(vals) > 0 + tdiffs = np.diff(vals) / 1e6 # millis + + high_delay_diffs = list(filter(lambda d: d >= 20., tdiffs)) + assert len(high_delay_diffs) < 15, f"Too many large diffs: {high_delay_diffs}" + + avg_diff = sum(tdiffs)/len(tdiffs) + avg_freq = 1. / (avg_diff * 1e-3) + assert 92. < avg_freq < 114., f"avg freq {avg_freq}Hz wrong, expected 104Hz" + + stddev = np.std(tdiffs) + assert stddev < 2.0, f"Standard-dev to big {stddev}" + + def test_events_check(self): + # verify if all sensors produce events + + sensor_events = dict() + for etype in self.events: + for measurement in self.events[etype]: + m = getattr(measurement, measurement.which()) + + if m.type in sensor_events: + sensor_events[m.type] += 1 + else: + sensor_events[m.type] = 1 + + for s in sensor_events: + err_msg = f"Sensor {s}: 200 < {sensor_events[s]}" + assert sensor_events[s] > 200, err_msg + + def test_logmonottime_timestamp_diff(self): + # ensure diff between the message logMonotime and sample timestamp is small + + tdiffs = list() + for etype in self.events: + for measurement in self.events[etype]: + m = getattr(measurement, measurement.which()) + + # check if gyro and accel timestamps are before logMonoTime + if str(m.source).startswith("lsm6ds3") and m.which() != 'temperature': + err_msg = f"Timestamp after logMonoTime: {m.timestamp} > {measurement.logMonoTime}" + assert m.timestamp < measurement.logMonoTime, err_msg + + # negative values might occur, as non interrupt packages created + # before the sensor is read + tdiffs.append(abs(measurement.logMonoTime - m.timestamp) / 1e6) + + high_delay_diffs = set(filter(lambda d: d >= 15., tdiffs)) + assert len(high_delay_diffs) < 20, f"Too many measurements published : {high_delay_diffs}" + + avg_diff = round(sum(tdiffs)/len(tdiffs), 4) + assert avg_diff < 4, f"Avg packet diff: {avg_diff:.1f}ms" + + stddev = np.std(tdiffs) + assert stddev < 2, f"Timing diffs have too high stddev: {stddev}" + + def test_sensor_values_sanity_check(self): + sensor_values = dict() + for etype in self.events: + for measurement in self.events[etype]: + m = getattr(measurement, measurement.which()) + key = (m.source.raw, m.which()) + values = getattr(m, m.which()) + + if hasattr(values, 'v'): + values = values.v + values = np.atleast_1d(values) + + if key in sensor_values: + sensor_values[key].append(values) + else: + sensor_values[key] = [values] + + # Sanity check sensor values and counts + for sensor, stype in sensor_values: + for s in ALL_SENSORS[sensor]: + if s.type != stype: + continue + + key = (sensor, s.type) + val_cnt = len(sensor_values[key]) + min_samples = self.sample_secs * 100 # Hz + err_msg = f"Sensor {sensor} {s.type} got {val_cnt} measurements, expected {min_samples}" + assert min_samples*0.9 < val_cnt < min_samples*1.1, err_msg + + mean_norm = np.mean(np.linalg.norm(sensor_values[key], axis=1)) + err_msg = f"Sensor '{sensor} {s.type}' failed sanity checks {mean_norm} is not between {s.sanity_min} and {s.sanity_max}" + assert s.sanity_min <= mean_norm <= s.sanity_max, err_msg + + def test_sensor_verify_no_interrupts_after_stop(self): + managed_processes["sensord"].start() + time.sleep(3) + + # read /proc/interrupts to verify interrupts are received + state_one = get_irq_count(LSM_IRQ) + time.sleep(1) + state_two = get_irq_count(LSM_IRQ) + + error_msg = f"no interrupts received after sensord start!\n{state_one} {state_two}" + assert state_one != state_two, error_msg + + managed_processes["sensord"].stop() + time.sleep(1) + + # read /proc/interrupts to verify no more interrupts are received + state_one = get_irq_count(LSM_IRQ) + time.sleep(1) + state_two = get_irq_count(LSM_IRQ) + assert state_one == state_two, "Interrupts received after sensord stop!" + + +if __name__ == "__main__": + unittest.main() diff --git a/selfdrive/sensord/tests/ttff_test.py b/selfdrive/sensord/tests/ttff_test.py new file mode 100755 index 0000000000..e2cbc6d144 --- /dev/null +++ b/selfdrive/sensord/tests/ttff_test.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 + +import time +import atexit + +from cereal import messaging +from selfdrive.manager.process_config import managed_processes + +TIMEOUT = 10*60 + +def kill(): + for proc in ['ubloxd', 'pigeond']: + managed_processes[proc].stop(retry=True, block=True) + +if __name__ == "__main__": + # start ubloxd + managed_processes['ubloxd'].start() + atexit.register(kill) + + sm = messaging.SubMaster(['ubloxGnss']) + + times = [] + for i in range(20): + # start pigeond + st = time.monotonic() + managed_processes['pigeond'].start() + + # wait for a >4 satellite fix + while True: + sm.update(0) + msg = sm['ubloxGnss'] + if msg.which() == 'measurementReport' and sm.updated["ubloxGnss"]: + report = msg.measurementReport + if report.numMeas > 4: + times.append(time.monotonic() - st) + print(f"\033[94m{i}: Got a fix in {round(times[-1], 2)} seconds\033[0m") + break + + if time.monotonic() - st > TIMEOUT: + raise TimeoutError("\033[91mFailed to get a fix in {TIMEOUT} seconds!\033[0m") + + time.sleep(0.1) + + # stop pigeond + managed_processes['pigeond'].stop(retry=True, block=True) + time.sleep(20) + + print(f"\033[92mAverage TTFF: {round(sum(times) / len(times), 2)}s\033[0m") diff --git a/selfdrive/sentry.py b/selfdrive/sentry.py index 5f22bf18e0..aa409ea394 100644 --- a/selfdrive/sentry.py +++ b/selfdrive/sentry.py @@ -5,9 +5,9 @@ from sentry_sdk.integrations.threading import ThreadingIntegration from common.params import Params from selfdrive.athena.registration import is_registered_device -from selfdrive.hardware import HARDWARE, PC -from selfdrive.swaglog import cloudlog -from selfdrive.version import get_branch, get_commit, get_origin, get_version, \ +from system.hardware import HARDWARE, PC +from system.swaglog import cloudlog +from system.version import get_branch, get_commit, get_origin, get_version, \ is_comma_remote, is_dirty, is_tested_branch diff --git a/selfdrive/statsd.py b/selfdrive/statsd.py index 2e62e32536..7dc002727e 100755 --- a/selfdrive/statsd.py +++ b/selfdrive/statsd.py @@ -3,20 +3,22 @@ import os import zmq import time from pathlib import Path +from collections import defaultdict from datetime import datetime, timezone -from typing import NoReturn +from typing import NoReturn, Union, List, Dict from common.params import Params from cereal.messaging import SubMaster -from selfdrive.swaglog import cloudlog -from selfdrive.hardware import HARDWARE +from system.swaglog import cloudlog +from system.hardware import HARDWARE from common.file_helpers import atomic_write_in_dir -from selfdrive.version import get_normalized_origin, get_short_branch, get_short_version, is_dirty +from system.version import get_normalized_origin, get_short_branch, get_short_version, is_dirty from selfdrive.loggerd.config import STATS_DIR, STATS_DIR_FILE_LIMIT, STATS_SOCKET, STATS_FLUSH_TIME_S class METRIC_TYPE: GAUGE = 'g' + SAMPLE = 'sa' class StatLog: def __init__(self): @@ -42,14 +44,27 @@ class StatLog: def gauge(self, name: str, value: float) -> None: self._send(f"{name}:{value}|{METRIC_TYPE.GAUGE}") + # Samples will be recorded in a buffer and at aggregation time, + # statistical properties will be logged (mean, count, percentiles, ...) + def sample(self, name: str, value: float): + self._send(f"{name}:{value}|{METRIC_TYPE.SAMPLE}") + def main() -> NoReturn: dongle_id = Params().get("DongleId", encoding='utf-8') - def get_influxdb_line(measurement: str, value: float, timestamp: datetime, tags: dict) -> str: + def get_influxdb_line(measurement: str, value: Union[float, Dict[str, float]], timestamp: datetime, tags: dict) -> str: res = f"{measurement}" for k, v in tags.items(): res += f",{k}={str(v)}" - res += f" value={value},dongle_id=\"{dongle_id}\" {int(timestamp.timestamp() * 1e9)}\n" + res += " " + + if isinstance(value, float): + value = {'value': value} + + for k, v in value.items(): + res += f"{k}={v}," + + res += f"dongle_id=\"{dongle_id}\" {int(timestamp.timestamp() * 1e9)}\n" return res # open statistics socket @@ -73,8 +88,10 @@ def main() -> NoReturn: # subscribe to deviceState for started state sm = SubMaster(['deviceState']) + idx = 0 last_flush_time = time.monotonic() gauges = {} + samples: Dict[str, List[float]] = defaultdict(list) while True: started_prev = sm['deviceState'].started sm.update() @@ -86,10 +103,12 @@ def main() -> NoReturn: try: metric_type = metric.split('|')[1] metric_name = metric.split(':')[0] - metric_value = metric.split('|')[0].split(':')[1] + metric_value = float(metric.split('|')[0].split(':')[1]) if metric_type == METRIC_TYPE.GAUGE: gauges[metric_name] = metric_value + elif metric_type == METRIC_TYPE.SAMPLE: + samples[metric_name].append(metric_value) else: cloudlog.event("unknown metric type", metric_type=metric_type) except Exception: @@ -103,19 +122,38 @@ def main() -> NoReturn: current_time = datetime.utcnow().replace(tzinfo=timezone.utc) tags['started'] = sm['deviceState'].started - for gauge_key in gauges: - result += get_influxdb_line(f"gauge.{gauge_key}", gauges[gauge_key], current_time, tags) + for key, value in gauges.items(): + result += get_influxdb_line(f"gauge.{key}", value, current_time, tags) + + for key, values in samples.items(): + values.sort() + sample_count = len(values) + sample_sum = sum(values) + + stats = { + 'count': sample_count, + 'min': values[0], + 'max': values[-1], + 'mean': sample_sum / sample_count, + } + for percentile in [0.05, 0.5, 0.95]: + value = values[int(round(percentile * (sample_count - 1)))] + stats[f"p{int(percentile * 100)}"] = value + + result += get_influxdb_line(f"sample.{key}", stats, current_time, tags) # clear intermediate data - gauges = {} + gauges.clear() + samples.clear() last_flush_time = time.monotonic() # check that we aren't filling up the drive if len(os.listdir(STATS_DIR)) < STATS_DIR_FILE_LIMIT: if len(result) > 0: - stats_path = os.path.join(STATS_DIR, str(int(current_time.timestamp()))) + stats_path = os.path.join(STATS_DIR, f"{current_time.timestamp():.0f}_{idx}") with atomic_write_in_dir(stats_path) as f: f.write(result) + idx += 1 else: cloudlog.error("stats dir full") diff --git a/selfdrive/test/helpers.py b/selfdrive/test/helpers.py index 5abc0d964f..8cc996c28d 100644 --- a/selfdrive/test/helpers.py +++ b/selfdrive/test/helpers.py @@ -2,9 +2,9 @@ import os import time from functools import wraps -from selfdrive.hardware import PC +from system.hardware import PC from selfdrive.manager.process_config import managed_processes -from selfdrive.version import training_version, terms_version +from system.version import training_version, terms_version def set_params_enabled(): diff --git a/selfdrive/test/longitudinal_maneuvers/maneuver.py b/selfdrive/test/longitudinal_maneuvers/maneuver.py index 9b4d016430..65935f8979 100644 --- a/selfdrive/test/longitudinal_maneuvers/maneuver.py +++ b/selfdrive/test/longitudinal_maneuvers/maneuver.py @@ -2,7 +2,7 @@ import numpy as np from selfdrive.test.longitudinal_maneuvers.plant import Plant -class Maneuver(): +class Maneuver: def __init__(self, title, duration, **kwargs): # Was tempted to make a builder class self.distance_lead = kwargs.get("initial_distance_lead", 200.0) @@ -16,6 +16,9 @@ class Maneuver(): self.only_lead2 = kwargs.get("only_lead2", False) self.only_radar = kwargs.get("only_radar", False) + self.ensure_start = kwargs.get("ensure_start", False) + self.enabled = kwargs.get("enabled", True) + self.e2e = kwargs.get("e2e", False) self.duration = duration self.title = title @@ -25,23 +28,25 @@ class Maneuver(): lead_relevancy=self.lead_relevancy, speed=self.speed, distance_lead=self.distance_lead, + enabled=self.enabled, only_lead2=self.only_lead2, - only_radar=self.only_radar + only_radar=self.only_radar, + e2e=self.e2e, ) valid = True logs = [] - while plant.current_time() < self.duration: - speed_lead = np.interp(plant.current_time(), self.breakpoints, self.speed_lead_values) - prob = np.interp(plant.current_time(), self.breakpoints, self.prob_lead_values) - cruise = np.interp(plant.current_time(), self.breakpoints, self.cruise_values) + while plant.current_time < self.duration: + speed_lead = np.interp(plant.current_time, self.breakpoints, self.speed_lead_values) + prob = np.interp(plant.current_time, self.breakpoints, self.prob_lead_values) + cruise = np.interp(plant.current_time, self.breakpoints, self.cruise_values) log = plant.step(speed_lead, prob, cruise) d_rel = log['distance_lead'] - log['distance'] if self.lead_relevancy else 200. v_rel = speed_lead - log['speed'] if self.lead_relevancy else 0. log['d_rel'] = d_rel log['v_rel'] = v_rel - logs.append(np.array([plant.current_time(), + logs.append(np.array([plant.current_time, log['distance'], log['distance_lead'], log['speed'], @@ -52,5 +57,9 @@ class Maneuver(): print("Crashed!!!!") valid = False + if self.ensure_start and log['v_rel'] > 0 and log['speeds'][-1] <= 0.1: + print('LongitudinalPlanner not starting!') + valid = False + print("maneuver end", valid) return valid, np.array(logs) diff --git a/selfdrive/test/longitudinal_maneuvers/plant.py b/selfdrive/test/longitudinal_maneuvers/plant.py index 13025a9f03..8e150d800c 100755 --- a/selfdrive/test/longitudinal_maneuvers/plant.py +++ b/selfdrive/test/longitudinal_maneuvers/plant.py @@ -6,14 +6,16 @@ from cereal import log import cereal.messaging as messaging from common.realtime import Ratekeeper, DT_MDL from selfdrive.controls.lib.longcontrol import LongCtrlState -from selfdrive.controls.lib.longitudinal_planner import Planner +from selfdrive.modeld.constants import T_IDXS +from selfdrive.controls.lib.longitudinal_planner import LongitudinalPlanner +from selfdrive.controls.lib.radar_helpers import _LEAD_ACCEL_TAU -class Plant(): +class Plant: messaging_initialized = False def __init__(self, lead_relevancy=False, speed=0.0, distance_lead=2.0, - only_lead2=False, only_radar=False): + enabled=True, only_lead2=False, only_radar=False, e2e=False): self.rate = 1. / DT_MDL if not Plant.messaging_initialized: @@ -28,12 +30,15 @@ class Plant(): self.distance = 0. self.speed = speed self.acceleration = 0.0 + self.speeds = [] # lead car - self.distance_lead = distance_lead self.lead_relevancy = lead_relevancy - self.only_lead2=only_lead2 - self.only_radar=only_radar + self.distance_lead = distance_lead + self.enabled = enabled + self.only_lead2 = only_lead2 + self.only_radar = only_radar + self.e2e = e2e self.rk = Ratekeeper(self.rate, print_delay_threshold=100.0) self.ts = 1. / self.rate @@ -42,8 +47,10 @@ class Plant(): from selfdrive.car.honda.values import CAR from selfdrive.car.honda.interface import CarInterface - self.planner = Planner(CarInterface.get_params(CAR.CIVIC), init_v=self.speed) + self.planner = LongitudinalPlanner(CarInterface.get_params(CAR.CIVIC), init_v=self.speed) + + @property def current_time(self): return float(self.rk.frame) / self.rate @@ -53,6 +60,7 @@ class Plant(): radar = messaging.new_message('radarState') control = messaging.new_message('controlsState') car_state = messaging.new_message('carState') + model = messaging.new_message('modelV2') a_lead = (v_lead - self.v_lead_prev)/self.ts self.v_lead_prev = v_lead @@ -79,25 +87,42 @@ class Plant(): lead.vLead = float(v_lead) lead.vLeadK = float(v_lead) lead.aLeadK = float(a_lead) - lead.aLeadTau = float(1.5) + # TODO use real radard logic for this + lead.aLeadTau = float(_LEAD_ACCEL_TAU) lead.status = status lead.modelProb = float(prob) if not self.only_lead2: radar.radarState.leadOne = lead radar.radarState.leadTwo = lead - control.controlsState.longControlState = LongCtrlState.pid + # Simulate model predicting slightly faster speed + # this is to ensure lead policy is effective when model + # does not predict slowdown in e2e mode + position = log.ModelDataV2.XYZTData.new_message() + position.x = [float(x) for x in (self.speed + 0.5) * np.array(T_IDXS)] + model.modelV2.position = position + velocity = log.ModelDataV2.XYZTData.new_message() + velocity.x = [float(x) for x in (self.speed + 0.5) * np.ones_like(T_IDXS)] + model.modelV2.velocity = velocity + acceleration = log.ModelDataV2.XYZTData.new_message() + acceleration.x = [float(x) for x in np.zeros_like(T_IDXS)] + model.modelV2.acceleration = acceleration + + control.controlsState.longControlState = LongCtrlState.pid if self.enabled else LongCtrlState.off control.controlsState.vCruise = float(v_cruise * 3.6) + control.controlsState.experimentalMode = self.e2e car_state.carState.vEgo = float(self.speed) car_state.carState.standstill = self.speed < 0.01 # ******** get controlsState messages for plotting *** sm = {'radarState': radar.radarState, 'carState': car_state.carState, - 'controlsState': control.controlsState} + 'controlsState': control.controlsState, + 'modelV2': model.modelV2} self.planner.update(sm) self.speed = self.planner.v_desired_filter.x self.acceleration = self.planner.a_desired + self.speeds = self.planner.v_desired_trajectory.tolist() fcw = self.planner.fcw self.distance_lead = self.distance_lead + v_lead * self.ts @@ -119,7 +144,7 @@ class Plant(): # print at 5hz if (self.rk.frame % (self.rate // 5)) == 0: print("%2.2f sec %6.2f m %6.2f m/s %6.2f m/s2 lead_rel: %6.2f m %6.2f m/s" - % (self.current_time(), self.distance, self.speed, self.acceleration, d_rel, v_rel)) + % (self.current_time, self.distance, self.speed, self.acceleration, d_rel, v_rel)) # ******** update prevs ******** @@ -129,6 +154,7 @@ class Plant(): "distance": self.distance, "speed": self.speed, "acceleration": self.acceleration, + "speeds": self.speeds, "distance_lead": self.distance_lead, "fcw": fcw, } diff --git a/selfdrive/test/longitudinal_maneuvers/test_longitudinal.py b/selfdrive/test/longitudinal_maneuvers/test_longitudinal.py index 60aaeb724d..686b35e456 100755 --- a/selfdrive/test/longitudinal_maneuvers/test_longitudinal.py +++ b/selfdrive/test/longitudinal_maneuvers/test_longitudinal.py @@ -1,112 +1,145 @@ #!/usr/bin/env python3 import os +from parameterized import parameterized import unittest from common.params import Params +from selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc import STOP_DISTANCE from selfdrive.test.longitudinal_maneuvers.maneuver import Maneuver # TODO: make new FCW tests -maneuvers = [ - Maneuver( - 'approach stopped car at 20m/s', - duration=20., - initial_speed=25., - lead_relevancy=True, - initial_distance_lead=120., - speed_lead_values=[30., 0.], - breakpoints=[0., 1.], - ), - Maneuver( - 'approach stopped car at 20m/s', - duration=20., - initial_speed=20., - lead_relevancy=True, - initial_distance_lead=90., - speed_lead_values=[20., 0.], - breakpoints=[0., 1.], - ), - Maneuver( - 'steady state following a car at 20m/s, then lead decel to 0mph at 1m/s^2', - duration=50., - initial_speed=20., - lead_relevancy=True, - initial_distance_lead=35., - speed_lead_values=[20., 20., 0.], - breakpoints=[0., 15., 35.0], - ), - Maneuver( - 'steady state following a car at 20m/s, then lead decel to 0mph at 2m/s^2', - duration=50., - initial_speed=20., - lead_relevancy=True, - initial_distance_lead=35., - speed_lead_values=[20., 20., 0.], - breakpoints=[0., 15., 25.0], - ), - Maneuver( - 'steady state following a car at 20m/s, then lead decel to 0mph at 3m/s^2', - duration=50., - initial_speed=20., - lead_relevancy=True, - initial_distance_lead=35., - speed_lead_values=[20., 20., 0.], - breakpoints=[0., 15., 21.66], - ), - Maneuver( - 'steady state following a car at 20m/s, then lead decel to 0mph at 3+m/s^2', - duration=40., - initial_speed=20., - lead_relevancy=True, - initial_distance_lead=35., - speed_lead_values=[20., 20., 0.], - prob_lead_values=[0., 1., 1.], - cruise_values=[20., 20., 20.], - breakpoints=[2., 2.01, 8.8], - ), - Maneuver( - "approach stopped car at 20m/s", - duration=30., - initial_speed=20., - lead_relevancy=True, - initial_distance_lead=120., - speed_lead_values=[0.0, 0., 0.], - prob_lead_values=[0.0, 0., 1.], - cruise_values=[20., 20., 20.], - breakpoints=[0.0, 2., 2.01], - ), - Maneuver( - "approach slower cut-in car at 20m/s", - duration=20., - initial_speed=20., - lead_relevancy=True, - initial_distance_lead=50., - speed_lead_values=[15., 15.], - breakpoints=[1., 11.], - only_lead2=True, - ), - Maneuver( - "stay stopped behind radar override lead", - duration=20., - initial_speed=0., - lead_relevancy=True, - initial_distance_lead=10., - speed_lead_values=[0., 0.], - prob_lead_values=[0., 0.], - breakpoints=[1., 11.], - only_radar=True, - ), - Maneuver( - "NaN recovery", - duration=30., - initial_speed=15., - lead_relevancy=True, - initial_distance_lead=60., - speed_lead_values=[0., 0., 0.0], - breakpoints=[1., 1.01, 11.], - cruise_values=[float("nan"), 15., 15.], - ), -] +def create_maneuvers(e2e): + return [ + Maneuver( + 'approach stopped car at 25m/s, initial distance: 120m', + duration=20., + initial_speed=25., + lead_relevancy=True, + initial_distance_lead=120., + speed_lead_values=[30., 0.], + breakpoints=[0., 1.], + e2e=e2e, + ), + Maneuver( + 'approach stopped car at 20m/s, initial distance 90m', + duration=20., + initial_speed=20., + lead_relevancy=True, + initial_distance_lead=90., + speed_lead_values=[20., 0.], + breakpoints=[0., 1.], + e2e=e2e, + ), + Maneuver( + 'steady state following a car at 20m/s, then lead decel to 0mph at 1m/s^2', + duration=50., + initial_speed=20., + lead_relevancy=True, + initial_distance_lead=35., + speed_lead_values=[20., 20., 0.], + breakpoints=[0., 15., 35.0], + e2e=e2e, + ), + Maneuver( + 'steady state following a car at 20m/s, then lead decel to 0mph at 2m/s^2', + duration=50., + initial_speed=20., + lead_relevancy=True, + initial_distance_lead=35., + speed_lead_values=[20., 20., 0.], + breakpoints=[0., 15., 25.0], + e2e=e2e, + ), + Maneuver( + 'steady state following a car at 20m/s, then lead decel to 0mph at 3m/s^2', + duration=50., + initial_speed=20., + lead_relevancy=True, + initial_distance_lead=35., + speed_lead_values=[20., 20., 0.], + breakpoints=[0., 15., 21.66], + e2e=e2e, + ), + Maneuver( + 'steady state following a car at 20m/s, then lead decel to 0mph at 3+m/s^2', + duration=40., + initial_speed=20., + lead_relevancy=True, + initial_distance_lead=35., + speed_lead_values=[20., 20., 0.], + prob_lead_values=[0., 1., 1.], + cruise_values=[20., 20., 20.], + breakpoints=[2., 2.01, 8.8], + e2e=e2e, + ), + Maneuver( + "approach stopped car at 20m/s, with prob_lead_values", + duration=30., + initial_speed=20., + lead_relevancy=True, + initial_distance_lead=120., + speed_lead_values=[0.0, 0., 0.], + prob_lead_values=[0.0, 0., 1.], + cruise_values=[20., 20., 20.], + breakpoints=[0.0, 2., 2.01], + e2e=e2e, + ), + Maneuver( + "approach slower cut-in car at 20m/s", + duration=20., + initial_speed=20., + lead_relevancy=True, + initial_distance_lead=50., + speed_lead_values=[15., 15.], + breakpoints=[1., 11.], + only_lead2=True, + e2e=e2e, + ), + Maneuver( + "stay stopped behind radar override lead", + duration=20., + initial_speed=0., + lead_relevancy=True, + initial_distance_lead=10., + speed_lead_values=[0., 0.], + prob_lead_values=[0., 0.], + breakpoints=[1., 11.], + only_radar=True, + e2e=e2e, + ), + Maneuver( + "NaN recovery", + duration=30., + initial_speed=15., + lead_relevancy=True, + initial_distance_lead=60., + speed_lead_values=[0., 0., 0.0], + breakpoints=[1., 1.01, 11.], + cruise_values=[float("nan"), 15., 15.], + e2e=e2e, + ), + # controls relies on planner commanding to move for stock-ACC resume spamming + Maneuver( + "resume from a stop", + duration=20., + initial_speed=0., + lead_relevancy=True, + initial_distance_lead=STOP_DISTANCE, + speed_lead_values=[0., 0., 2.], + breakpoints=[1., 10., 15.], + ensure_start=True, + e2e=e2e, + ), + Maneuver( + 'cruising at 25 m/s while disabled', + duration=20., + initial_speed=25., + lead_relevancy=False, + enabled=False, + e2e=e2e, + ), + ] class LongitudinalControl(unittest.TestCase): @@ -121,23 +154,12 @@ class LongitudinalControl(unittest.TestCase): params.put_bool("Passive", bool(os.getenv("PASSIVE"))) params.put_bool("OpenpilotEnabledToggle", True) - # hack - def test_longitudinal_setup(self): - pass + @parameterized.expand([(man,) for e2e in [True, False] for man in create_maneuvers(e2e)]) + def test_maneuver(self, maneuver): + print(maneuver.title, f'in {"e2e" if maneuver.e2e else "acc"} mode') + valid, _ = maneuver.evaluate() + self.assertTrue(valid, msg=maneuver.title) -def run_maneuver_worker(k): - def run(self): - man = maneuvers[k] - print(man.title) - valid, _ = man.evaluate() - self.assertTrue(valid, msg=man.title) - return run - - -for k in range(len(maneuvers)): - setattr(LongitudinalControl, f"test_longitudinal_maneuvers_{k+1}", - run_maneuver_worker(k)) - if __name__ == "__main__": unittest.main(failfast=True) diff --git a/selfdrive/test/openpilotci.py b/selfdrive/test/openpilotci.py index 6483b6717f..1d1b6ec423 100755 --- a/selfdrive/test/openpilotci.py +++ b/selfdrive/test/openpilotci.py @@ -4,17 +4,18 @@ import sys import subprocess BASE_URL = "https://commadataci.blob.core.windows.net/openpilotci/" - TOKEN_PATH = "/data/azure_token" + def get_url(route_name, segment_num, log_type="rlog"): ext = "hevc" if log_type.endswith('camera') else "bz2" return BASE_URL + f"{route_name.replace('|', '/')}/{segment_num}/{log_type}.{ext}" + def upload_file(path, name): from azure.storage.blob import BlockBlobService # pylint: disable=import-error - sas_token = None + sas_token = os.environ.get("AZURE_TOKEN", None) if os.path.isfile(TOKEN_PATH): sas_token = open(TOKEN_PATH).read().strip() @@ -25,6 +26,7 @@ def upload_file(path, name): service.create_blob_from_path("openpilotci", name, path) return "https://commadataci.blob.core.windows.net/openpilotci/" + name + if __name__ == "__main__": for f in sys.argv[1:]: name = os.path.basename(f) diff --git a/selfdrive/test/process_replay/.gitignore b/selfdrive/test/process_replay/.gitignore index a35cd58d41..63c37e64e1 100644 --- a/selfdrive/test/process_replay/.gitignore +++ b/selfdrive/test/process_replay/.gitignore @@ -1 +1,2 @@ fakedata/ +debayer_diff.txt diff --git a/selfdrive/test/process_replay/README.md b/selfdrive/test/process_replay/README.md index 3add95f0a0..531ddb3a02 100644 --- a/selfdrive/test/process_replay/README.md +++ b/selfdrive/test/process_replay/README.md @@ -1,10 +1,11 @@ -# process replay +# Process replay Process replay is a regression test designed to identify any changes in the output of a process. This test replays a segment through individual processes and compares the output to a known good replay. Each make is represented in the test with a segment. If the test fails, make sure that you didn't unintentionally change anything. If there are intentional changes, the reference logs will be updated. Use `test_processes.py` to run the test locally. +Use `FILEREADER_CACHE='1' test_processes.py` to cache log files. Currently the following processes are tested: @@ -12,14 +13,35 @@ Currently the following processes are tested: * radard * plannerd * calibrationd +* dmonitoringd +* locationd +* laikad +* paramsd * ubloxd +### Usage +``` +Usage: test_processes.py [-h] [--whitelist-procs PROCS] [--whitelist-cars CARS] [--blacklist-procs PROCS] + [--blacklist-cars CARS] [--ignore-fields FIELDS] [--ignore-msgs MSGS] [--update-refs] [--upload-only] +Regression test to identify changes in a process's output +optional arguments: + -h, --help show this help message and exit + --whitelist-procs PROCS Whitelist given processes from the test (e.g. controlsd) + --whitelist-cars WHITELIST_CARS Whitelist given cars from the test (e.g. HONDA) + --blacklist-procs BLACKLIST_PROCS Blacklist given processes from the test (e.g. controlsd) + --blacklist-cars BLACKLIST_CARS Blacklist given cars from the test (e.g. HONDA) + --ignore-fields IGNORE_FIELDS Extra fields or msgs to ignore (e.g. carState.events) + --ignore-msgs IGNORE_MSGS Msgs to ignore (e.g. carEvents) + --update-refs Updates reference logs using current commit + --upload-only Skips testing processes and uploads logs from previous test run +``` + ## Forks -openpilot forks can use this test with their own reference logs +openpilot forks can use this test with their own reference logs, by default `test_proccess.py` saves logs locally. To generate new logs: -`./update_refs.py --no-upload` +`./test_processes.py` -Then, check in the new logs using git-lfs. Make sure to also include the updated `ref_commit` file. +Then, check in the new logs using git-lfs. Make sure to also update the `ref_commit` file to the current commit. diff --git a/selfdrive/test/process_replay/compare_logs.py b/selfdrive/test/process_replay/compare_logs.py index de734e52fb..c14956b1b2 100755 --- a/selfdrive/test/process_replay/compare_logs.py +++ b/selfdrive/test/process_replay/compare_logs.py @@ -1,31 +1,24 @@ #!/usr/bin/env python3 import bz2 -import os import sys import math import numbers import dictdiffer from collections import Counter -if "CI" in os.environ: - def tqdm(x): - return x -else: - from tqdm import tqdm # type: ignore - from tools.lib.logreader import LogReader EPSILON = sys.float_info.epsilon def save_log(dest, log_msgs, compress=True): - dat = b"".join(msg.as_builder().to_bytes() for msg in tqdm(log_msgs)) + dat = b"".join(msg.as_builder().to_bytes() for msg in log_msgs) if compress: dat = bz2.compress(dat) with open(dest, "wb") as f: - f.write(dat) + f.write(dat) def remove_ignored_fields(msg, ignore): @@ -48,16 +41,30 @@ def remove_ignored_fields(msg, ignore): elif isinstance(v, numbers.Number): val = 0 else: - raise NotImplementedError + raise NotImplementedError('Error ignoring field') setattr(attr, keys[-1], val) return msg.as_reader() -def compare_logs(log1, log2, ignore_fields=None, ignore_msgs=None, tolerance=None): +def get_field_tolerance(diff_field, field_tolerances): + diff_field_str = diff_field[0] + for s in diff_field[1:]: + # loop until number in field + if not isinstance(s, str): + break + diff_field_str += '.'+s + if diff_field_str in field_tolerances: + return field_tolerances[diff_field_str] + + +def compare_logs(log1, log2, ignore_fields=None, ignore_msgs=None, tolerance=None, field_tolerances=None): if ignore_fields is None: ignore_fields = [] if ignore_msgs is None: ignore_msgs = [] + if field_tolerances is None: + field_tolerances = {} + default_tolerance = EPSILON if tolerance is None else tolerance log1, log2 = (list(filter(lambda m: m.which() not in ignore_msgs, log)) for log in (log1, log2)) @@ -67,7 +74,7 @@ def compare_logs(log1, log2, ignore_fields=None, ignore_msgs=None, tolerance=Non raise Exception(f"logs are not same length: {len(log1)} VS {len(log2)}\n\t\t{cnt1}\n\t\t{cnt2}") diff = [] - for msg1, msg2 in tqdm(zip(log1, log2)): + for msg1, msg2 in zip(log1, log2): if msg1.which() != msg2.which(): print(msg1, msg2) raise Exception("msgs not aligned between logs") @@ -79,7 +86,6 @@ def compare_logs(log1, log2, ignore_fields=None, ignore_msgs=None, tolerance=Non msg1_dict = msg1.to_dict(verbose=True) msg2_dict = msg2.to_dict(verbose=True) - tolerance = EPSILON if tolerance is None else tolerance dd = dictdiffer.diff(msg1_dict, msg2_dict, ignore=ignore_fields) # Dictdiffer only supports relative tolerance, we also want to check for absolute @@ -87,10 +93,13 @@ def compare_logs(log1, log2, ignore_fields=None, ignore_msgs=None, tolerance=Non def outside_tolerance(diff): try: if diff[0] == "change": + field_tolerance = default_tolerance + if (tol := get_field_tolerance(diff[1], field_tolerances)) is not None: + field_tolerance = tol a, b = diff[2] finite = math.isfinite(a) and math.isfinite(b) if finite and isinstance(a, numbers.Number) and isinstance(b, numbers.Number): - return abs(a - b) > max(tolerance, tolerance * max(abs(a), abs(b))) + return abs(a - b) > max(field_tolerance, field_tolerance * max(abs(a), abs(b))) except TypeError: pass return True diff --git a/selfdrive/test/process_replay/debayer_replay_ref_commit b/selfdrive/test/process_replay/debayer_replay_ref_commit new file mode 100644 index 0000000000..551fc680ba --- /dev/null +++ b/selfdrive/test/process_replay/debayer_replay_ref_commit @@ -0,0 +1 @@ +8f9ba7540b4549b4a57312129b8ff678d045f70f \ No newline at end of file diff --git a/selfdrive/test/process_replay/helpers.py b/selfdrive/test/process_replay/helpers.py new file mode 100644 index 0000000000..8571f36c36 --- /dev/null +++ b/selfdrive/test/process_replay/helpers.py @@ -0,0 +1,26 @@ +import os +import shutil +import uuid + +from common.params import Params + +class OpenpilotPrefix(object): + def __init__(self, prefix: str = None) -> None: + self.prefix = prefix if prefix else str(uuid.uuid4()) + self.msgq_path = os.path.join('/dev/shm', self.prefix) + + def __enter__(self): + os.environ['OPENPILOT_PREFIX'] = self.prefix + try: + os.mkdir(self.msgq_path) + except FileExistsError: + pass + + def __exit__(self, exc_type, exc_obj, exc_tb): + symlink_path = Params().get_param_path() + if os.path.exists(symlink_path): + shutil.rmtree(os.path.realpath(symlink_path), ignore_errors=True) + os.remove(symlink_path) + shutil.rmtree(self.msgq_path, ignore_errors=True) + del os.environ['OPENPILOT_PREFIX'] + return False diff --git a/selfdrive/test/process_replay/model_replay.py b/selfdrive/test/process_replay/model_replay.py index 0028371e81..a63ec6489b 100755 --- a/selfdrive/test/process_replay/model_replay.py +++ b/selfdrive/test/process_replay/model_replay.py @@ -7,55 +7,52 @@ from typing import Any from itertools import zip_longest import cereal.messaging as messaging -from cereal.visionipc.visionipc_pyx import VisionIpcServer, VisionStreamType # pylint: disable=no-name-in-module, import-error +from cereal.visionipc import VisionIpcServer, VisionStreamType from common.spinner import Spinner from common.timeout import Timeout -from common.transformations.camera import get_view_frame_from_road_frame, eon_f_frame_size, tici_f_frame_size, \ - eon_d_frame_size, tici_d_frame_size -from selfdrive.hardware import PC, TICI +from common.transformations.camera import tici_f_frame_size, tici_d_frame_size +from system.hardware import PC from selfdrive.manager.process_config import managed_processes from selfdrive.test.openpilotci import BASE_URL, get_url from selfdrive.test.process_replay.compare_logs import compare_logs, save_log from selfdrive.test.process_replay.test_processes import format_diff -from selfdrive.version import get_commit +from system.version import get_commit from tools.lib.framereader import FrameReader from tools.lib.logreader import LogReader -TICI_TEST_ROUTE = "4cf7a6ad03080c90|2021-09-29--13-46-36" -EON_TEST_ROUTE = "303055c0002aefd1|2021-11-22--18-36-32" +TEST_ROUTE = "4cf7a6ad03080c90|2021-09-29--13-46-36" SEGMENT = 0 -if TICI: - TEST_ROUTE = TICI_TEST_ROUTE -else: - TEST_ROUTE = EON_TEST_ROUTE +MAX_FRAMES = 100 if PC else 600 SEND_EXTRA_INPUTS = bool(os.getenv("SEND_EXTRA_INPUTS", "0")) VIPC_STREAM = {"roadCameraState": VisionStreamType.VISION_STREAM_ROAD, "driverCameraState": VisionStreamType.VISION_STREAM_DRIVER, "wideRoadCameraState": VisionStreamType.VISION_STREAM_WIDE_ROAD} - -def get_log_fn(ref_commit, test_route, tici=True): - return f"{test_route}_{'model_tici' if tici else 'model'}_{ref_commit}.bz2" +def get_log_fn(ref_commit, test_route): + return f"{test_route}_model_tici_{ref_commit}.bz2" def replace_calib(msg, calib): msg = msg.as_builder() if calib is not None: - msg.liveCalibration.extrinsicMatrix = get_view_frame_from_road_frame(*calib, 1.22).flatten().tolist() + msg.liveCalibration.rpyCalib = calib.tolist() return msg def model_replay(lr, frs): - spinner = Spinner() - spinner.update("starting model replay") + if not PC: + spinner = Spinner() + spinner.update("starting model replay") + else: + spinner = None vipc_server = VisionIpcServer("camerad") - vipc_server.create_buffers(VisionStreamType.VISION_STREAM_ROAD, 40, False, *(tici_f_frame_size if TICI else eon_f_frame_size)) - vipc_server.create_buffers(VisionStreamType.VISION_STREAM_DRIVER, 40, False, *(tici_d_frame_size if TICI else eon_d_frame_size)) + vipc_server.create_buffers(VisionStreamType.VISION_STREAM_ROAD, 40, False, *(tici_f_frame_size)) + vipc_server.create_buffers(VisionStreamType.VISION_STREAM_DRIVER, 40, False, *(tici_d_frame_size)) vipc_server.create_buffers(VisionStreamType.VISION_STREAM_WIDE_ROAD, 40, False, *(tici_f_frame_size)) vipc_server.start_listener() - sm = messaging.SubMaster(['modelV2', 'driverState']) + sm = messaging.SubMaster(['modelV2', 'driverStateV2']) pm = messaging.PubMaster(['roadCameraState', 'wideRoadCameraState', 'driverCameraState', 'liveCalibration', 'lateralPlan']) try: @@ -66,8 +63,8 @@ def model_replay(lr, frs): log_msgs = [] last_desire = None - recv_cnt = defaultdict(lambda: 0) - frame_idxs = defaultdict(lambda: 0) + recv_cnt = defaultdict(int) + frame_idxs = defaultdict(int) # init modeld with valid calibration cal_msgs = [msg for msg in lr if msg.which() == "liveCalibration"] @@ -81,7 +78,7 @@ def model_replay(lr, frs): for cam_msgs in zip_longest(msgs['roadCameraState'], msgs['wideRoadCameraState'], msgs['driverCameraState']): # need a pair of road/wide msgs - if TICI and None in (cam_msgs[0], cam_msgs[1]): + if None in (cam_msgs[0], cam_msgs[1]): break for msg in cam_msgs: @@ -101,7 +98,7 @@ def model_replay(lr, frs): if msg.which() in VIPC_STREAM: msg = msg.as_builder() camera_state = getattr(msg, msg.which()) - img = frs[msg.which()].get(frame_idxs[msg.which()], pix_fmt="yuv420p")[0] + img = frs[msg.which()].get(frame_idxs[msg.which()], pix_fmt="nv12")[0] frame_idxs[msg.which()] += 1 # send camera state and frame @@ -112,10 +109,10 @@ def model_replay(lr, frs): recv = None if msg.which() in ('roadCameraState', 'wideRoadCameraState'): - if not TICI or min(frame_idxs['roadCameraState'], frame_idxs['wideRoadCameraState']) > recv_cnt['modelV2']: + if min(frame_idxs['roadCameraState'], frame_idxs['wideRoadCameraState']) > recv_cnt['modelV2']: recv = "modelV2" elif msg.which() == 'driverCameraState': - recv = "driverState" + recv = "driverStateV2" # wait for a response with Timeout(15, f"timed out waiting for {recv}"): @@ -123,14 +120,19 @@ def model_replay(lr, frs): recv_cnt[recv] += 1 log_msgs.append(messaging.recv_one(sm.sock[recv])) - spinner.update("replaying models: road %d/%d, driver %d/%d" % (frame_idxs['roadCameraState'], - frs['roadCameraState'].frame_count, frame_idxs['driverCameraState'], frs['driverCameraState'].frame_count)) + if spinner: + spinner.update("replaying models: road %d/%d, driver %d/%d" % (frame_idxs['roadCameraState'], + frs['roadCameraState'].frame_count, frame_idxs['driverCameraState'], frs['driverCameraState'].frame_count)) + - if any(frame_idxs[c] >= frs[c].frame_count for c in frame_idxs.keys()): + if any(frame_idxs[c] >= frs[c].frame_count for c in frame_idxs.keys()) or frame_idxs['roadCameraState'] == MAX_FRAMES: break + else: + print(f'Received {frame_idxs["roadCameraState"]} frames') finally: - spinner.close() + if spinner: + spinner.close() managed_processes['modeld'].stop() managed_processes['dmonitoringmodeld'].stop() @@ -147,11 +149,10 @@ if __name__ == "__main__": # load logs lr = list(LogReader(get_url(TEST_ROUTE, SEGMENT))) frs = { - 'roadCameraState': FrameReader(get_url(TEST_ROUTE, SEGMENT, log_type="fcamera")), - 'driverCameraState': FrameReader(get_url(TEST_ROUTE, SEGMENT, log_type="dcamera")), + 'roadCameraState': FrameReader(get_url(TEST_ROUTE, SEGMENT, log_type="fcamera"), readahead=True), + 'driverCameraState': FrameReader(get_url(TEST_ROUTE, SEGMENT, log_type="dcamera"), readahead=True), + 'wideRoadCameraState': FrameReader(get_url(TEST_ROUTE, SEGMENT, log_type="ecamera"), readahead=True) } - if TICI: - frs['wideRoadCameraState'] = FrameReader(get_url(TEST_ROUTE, SEGMENT, log_type="ecamera")) # run replay log_msgs = model_replay(lr, frs) @@ -161,21 +162,23 @@ if __name__ == "__main__": if not update: with open(ref_commit_fn) as f: ref_commit = f.read().strip() - log_fn = get_log_fn(ref_commit, TEST_ROUTE, tici=TICI) + log_fn = get_log_fn(ref_commit, TEST_ROUTE) try: - cmp_log = LogReader(BASE_URL + log_fn) + cmp_log = list(LogReader(BASE_URL + log_fn))[:2*MAX_FRAMES] ignore = [ 'logMonoTime', 'modelV2.frameDropPerc', 'modelV2.modelExecutionTime', - 'driverState.modelExecutionTime', - 'driverState.dspExecutionTime' + 'driverStateV2.modelExecutionTime', + 'driverStateV2.dspExecutionTime' ] - tolerance = None if not PC else 1e-3 + # TODO this tolerance is absurdly large + tolerance = 2.0 if PC else None results: Any = {TEST_ROUTE: {}} + log_paths: Any = {TEST_ROUTE: {"models": {'ref': BASE_URL + log_fn, 'new': log_fn}}} results[TEST_ROUTE]["models"] = compare_logs(cmp_log, log_msgs, tolerance=tolerance, ignore_fields=ignore) - diff1, diff2, failed = format_diff(results, ref_commit) + diff1, diff2, failed = format_diff(results, log_paths, ref_commit) print(diff2) print('-------------\n'*5) @@ -187,13 +190,13 @@ if __name__ == "__main__": failed = True # upload new refs - if update or failed: + if (update or failed) and not PC: from selfdrive.test.openpilotci import upload_file print("Uploading new refs") new_commit = get_commit() - log_fn = get_log_fn(new_commit, TEST_ROUTE, tici=TICI) + log_fn = get_log_fn(new_commit, TEST_ROUTE) save_log(log_fn, log_msgs) try: upload_file(log_fn, os.path.basename(log_fn)) diff --git a/selfdrive/test/process_replay/model_replay_ref_commit b/selfdrive/test/process_replay/model_replay_ref_commit index d210251c09..f541b6a6d5 100644 --- a/selfdrive/test/process_replay/model_replay_ref_commit +++ b/selfdrive/test/process_replay/model_replay_ref_commit @@ -1 +1 @@ -19720e79b1c5136a882efd689651d9044e2e2007 +30efb4238327d723e17a3bda7e7c19c18f8a3b18 diff --git a/selfdrive/test/process_replay/process_replay.py b/selfdrive/test/process_replay/process_replay.py index da9c717285..bc55e33cbf 100755 --- a/selfdrive/test/process_replay/process_replay.py +++ b/selfdrive/test/process_replay/process_replay.py @@ -8,15 +8,16 @@ import signal from collections import namedtuple import capnp -from tqdm import tqdm import cereal.messaging as messaging from cereal import car, log from cereal.services import service_list from common.params import Params from common.timeout import Timeout -from selfdrive.car.fingerprints import FW_VERSIONS +from common.realtime import DT_CTRL +from panda.python import ALTERNATIVE_EXPERIENCE from selfdrive.car.car_helpers import get_car, interfaces +from selfdrive.test.process_replay.helpers import OpenpilotPrefix from selfdrive.manager.process import PythonProcess from selfdrive.manager.process_config import managed_processes @@ -24,15 +25,17 @@ from selfdrive.manager.process_config import managed_processes NUMPY_TOLERANCE = 1e-7 CI = "CI" in os.environ TIMEOUT = 15 +PROC_REPLAY_DIR = os.path.dirname(os.path.abspath(__file__)) +FAKEDATA = os.path.join(PROC_REPLAY_DIR, "fakedata/") -ProcessConfig = namedtuple('ProcessConfig', ['proc_name', 'pub_sub', 'ignore', 'init_callback', 'should_recv_callback', 'tolerance', 'fake_pubsubmaster', 'submaster_config'], defaults=({},)) +ProcessConfig = namedtuple('ProcessConfig', ['proc_name', 'pub_sub', 'ignore', 'init_callback', 'should_recv_callback', 'tolerance', 'fake_pubsubmaster', 'submaster_config', 'environ', 'subtest_name', "field_tolerances"], defaults=({}, {}, "", {})) def wait_for_event(evt): if not evt.wait(TIMEOUT): if threading.currentThread().getName() == "MainThread": # tested process likely died. don't let test just hang - raise Exception("Timeout reached. Tested process likely crashed.") + raise Exception(f"Timeout reached. Tested process {os.environ['PROC_NAME']} likely crashed.") else: # done testing this process, let it die sys.exit(0) @@ -188,6 +191,7 @@ def get_car_params(msgs, fsm, can_sock, fingerprint): _, CP = get_car(can, sendcan) Params().put("CarParams", CP.to_bytes()) + def controlsd_rcv_callback(msg, CP, cfg, fsm): # no sendcan until controlsd is initialized socks = [s for s in cfg.pub_sub[msg.which()] if @@ -196,6 +200,7 @@ def controlsd_rcv_callback(msg, CP, cfg, fsm): socks.remove("sendcan") return socks, len(socks) > 0 + def radar_rcv_callback(msg, CP, cfg, fsm): if msg.which() != "can": return [], False @@ -224,6 +229,15 @@ def calibration_rcv_callback(msg, CP, cfg, fsm): return recv_socks, fsm.frame == 0 or msg.which() == 'cameraOdometry' +def torqued_rcv_callback(msg, CP, cfg, fsm): + # should_recv always true to increment frame + recv_socks = [] + frame = fsm.frame + 1 # incrementing hasn't happened yet in SubMaster + if msg.which() == 'liveLocationKalman' and (frame % 5) == 0: + recv_socks = ["liveTorqueParameters"] + return recv_socks, fsm.frame == 0 or msg.which() == 'liveLocationKalman' + + def ublox_rcv_callback(msg): msg_class, msg_id = msg.ubloxRaw[2:4] if (msg_class, msg_id) in {(1, 7 * 16)}: @@ -231,7 +245,14 @@ def ublox_rcv_callback(msg): elif (msg_class, msg_id) in {(2, 1 * 16 + 5), (10, 9)}: return ["ubloxGnss"] else: - return [] + return [] + + +def laika_rcv_callback(msg, CP, cfg, fsm): + if msg.which() == 'ubloxGnss' and msg.ubloxGnss.which() == "measurementReport": + return ["gnssMeasurements"], True + else: + return [], True CONFIGS = [ @@ -239,15 +260,20 @@ CONFIGS = [ proc_name="controlsd", pub_sub={ "can": ["controlsState", "carState", "carControl", "sendcan", "carEvents", "carParams"], - "deviceState": [], "pandaStates": [], "peripheralState": [], "liveCalibration": [], "driverMonitoringState": [], "longitudinalPlan": [], "lateralPlan": [], "liveLocationKalman": [], "liveParameters": [], "radarState": [], - "modelV2": [], "driverCameraState": [], "roadCameraState": [], "managerState": [], + "deviceState": [], "pandaStates": [], "peripheralState": [], "liveCalibration": [], "driverMonitoringState": [], + "longitudinalPlan": [], "lateralPlan": [], "liveLocationKalman": [], "liveParameters": [], "radarState": [], + "modelV2": [], "driverCameraState": [], "roadCameraState": [], "wideRoadCameraState": [], "managerState": [], + "testJoystick": [], "liveTorqueParameters": [], }, ignore=["logMonoTime", "valid", "controlsState.startMonoTime", "controlsState.cumLagMs"], init_callback=fingerprint, should_recv_callback=controlsd_rcv_callback, tolerance=NUMPY_TOLERANCE, fake_pubsubmaster=True, - submaster_config={'ignore_avg_freq': ['radarState', 'longitudinalPlan']} + submaster_config={ + 'ignore_avg_freq': ['radarState', 'longitudinalPlan', 'driverCameraState', 'driverMonitoringState'], # dcam is expected at 20 Hz + 'ignore_alive': ['wideRoadCameraState'], # TODO: Add to regen + } ), ProcessConfig( proc_name="radard", @@ -265,7 +291,7 @@ CONFIGS = [ proc_name="plannerd", pub_sub={ "modelV2": ["lateralPlan", "longitudinalPlan"], - "carState": [], "controlsState": [], "radarState": [], + "carControl": [], "carState": [], "controlsState": [], "radarState": [], }, ignore=["logMonoTime", "valid", "longitudinalPlan.processingDelay", "longitudinalPlan.solverExecutionTime", "lateralPlan.solverExecutionTime"], init_callback=get_car_params, @@ -277,7 +303,8 @@ CONFIGS = [ proc_name="calibrationd", pub_sub={ "carState": ["liveCalibration"], - "cameraOdometry": [] + "cameraOdometry": [], + "carParams": [], }, ignore=["logMonoTime", "valid"], init_callback=get_car_params, @@ -288,7 +315,7 @@ CONFIGS = [ ProcessConfig( proc_name="dmonitoringd", pub_sub={ - "driverState": ["driverMonitoringState"], + "driverStateV2": ["driverMonitoringState"], "liveCalibration": [], "carState": [], "modelV2": [], "controlsState": [], }, ignore=["logMonoTime", "valid"], @@ -301,7 +328,8 @@ CONFIGS = [ proc_name="locationd", pub_sub={ "cameraOdometry": ["liveLocationKalman"], - "sensorEvents": [], "gpsLocationExternal": [], "liveCalibration": [], "carState": [], + "accelerometer": [], "gyroscope": [], + "gpsLocationExternal": [], "liveCalibration": [], "carState": [], }, ignore=["logMonoTime", "valid"], init_callback=get_car_params, @@ -332,29 +360,106 @@ CONFIGS = [ tolerance=None, fake_pubsubmaster=False, ), + ProcessConfig( + proc_name="laikad", + subtest_name="Offline", + pub_sub={ + "ubloxGnss": ["gnssMeasurements"], + "clocks": [] + }, + ignore=["logMonoTime"], + init_callback=get_car_params, + should_recv_callback=laika_rcv_callback, + tolerance=NUMPY_TOLERANCE, + fake_pubsubmaster=True, + environ={"LAIKAD_NO_INTERNET": "1"}, + ), + ProcessConfig( + proc_name="laikad", + pub_sub={ + "ubloxGnss": ["gnssMeasurements"], + "clocks": [] + }, + ignore=["logMonoTime"], + init_callback=get_car_params, + should_recv_callback=laika_rcv_callback, + tolerance=NUMPY_TOLERANCE, + fake_pubsubmaster=True, + ), + ProcessConfig( + proc_name="torqued", + pub_sub={ + "liveLocationKalman": ["liveTorqueParameters"], + "carState": [], "controlsState": [], + }, + ignore=["logMonoTime"], + init_callback=get_car_params, + should_recv_callback=torqued_rcv_callback, + tolerance=NUMPY_TOLERANCE, + fake_pubsubmaster=True, + ), ] def replay_process(cfg, lr, fingerprint=None): - if cfg.fake_pubsubmaster: - return python_replay_process(cfg, lr, fingerprint) - else: - return cpp_replay_process(cfg, lr, fingerprint) + with OpenpilotPrefix(): + if cfg.fake_pubsubmaster: + return python_replay_process(cfg, lr, fingerprint) + else: + return cpp_replay_process(cfg, lr, fingerprint) -def setup_env(simulation=False): + +def setup_env(simulation=False, CP=None, cfg=None, controlsState=None): params = Params() params.clear_all() params.put_bool("OpenpilotEnabledToggle", True) params.put_bool("Passive", False) + params.put_bool("DisengageOnAccelerator", True) + params.put_bool("WideCameraOnly", False) + params.put_bool("DisableLogging", False) + params.put_bool("UbloxAvailable", True) os.environ["NO_RADAR_SLEEP"] = "1" os.environ["REPLAY"] = "1" + os.environ['SKIP_FW_QUERY'] = "" + os.environ['FINGERPRINT'] = "" + + if cfg is not None: + # Clear all custom processConfig environment variables + for config in CONFIGS: + for k, _ in config.environ.items(): + if k in os.environ: + del os.environ[k] + + os.environ.update(cfg.environ) + os.environ['PROC_NAME'] = cfg.proc_name if simulation: os.environ["SIMULATION"] = "1" elif "SIMULATION" in os.environ: del os.environ["SIMULATION"] + # Initialize controlsd with a controlsState packet + if controlsState is not None: + params.put("ReplayControlsState", controlsState.as_builder().to_bytes()) + else: + params.remove("ReplayControlsState") + + # Regen or python process + if CP is not None: + if CP.alternativeExperience == ALTERNATIVE_EXPERIENCE.DISABLE_DISENGAGE_ON_GAS: + params.put_bool("DisengageOnAccelerator", False) + + if CP.fingerprintSource == "fw": + params.put("CarParamsCache", CP.as_builder().to_bytes()) + else: + os.environ['SKIP_FW_QUERY'] = "1" + os.environ['FINGERPRINT'] = CP.carFingerprint + + if CP.openpilotLongitudinalControl: + params.put_bool("ExperimentalLongitudinalEnabled", True) + + def python_replay_process(cfg, lr, fingerprint=None): sub_sockets = [s for _, sub in cfg.pub_sub.items() for s in sub] pub_sockets = [s for s in cfg.pub_sub.keys() if s != 'can'] @@ -369,30 +474,25 @@ def python_replay_process(cfg, lr, fingerprint=None): all_msgs = sorted(lr, key=lambda msg: msg.logMonoTime) pub_msgs = [msg for msg in all_msgs if msg.which() in list(cfg.pub_sub.keys())] - setup_env() + controlsState = None + initialized = False + for msg in lr: + if msg.which() == 'controlsState': + controlsState = msg.controlsState + if initialized: + break + elif msg.which() == 'carEvents': + initialized = car.CarEvent.EventName.controlsInitializing not in [e.name for e in msg.carEvents] - # TODO: remove after getting new route for civic & accord - migration = { - "HONDA CIVIC 2016 TOURING": "HONDA CIVIC 2016", - "HONDA ACCORD 2018 SPORT 2T": "HONDA ACCORD 2018", - "HONDA ACCORD 2T 2018": "HONDA ACCORD 2018", - "Mazda CX-9 2021": "MAZDA CX-9 2021", - } + assert controlsState is not None and initialized, "controlsState never initialized" if fingerprint is not None: os.environ['SKIP_FW_QUERY'] = "1" os.environ['FINGERPRINT'] = fingerprint + setup_env(cfg=cfg, controlsState=controlsState) else: - os.environ['SKIP_FW_QUERY'] = "" - os.environ['FINGERPRINT'] = "" - for msg in lr: - if msg.which() == 'carParams': - car_fingerprint = migration.get(msg.carParams.carFingerprint, msg.carParams.carFingerprint) - if len(msg.carParams.carFw) and (car_fingerprint in FW_VERSIONS): - Params().put("CarParamsCache", msg.carParams.as_builder().to_bytes()) - else: - os.environ['SKIP_FW_QUERY'] = "1" - os.environ['FINGERPRINT'] = car_fingerprint + CP = [m for m in lr if m.which() == 'carParams'][0].carParams + setup_env(CP=CP, cfg=cfg, controlsState=controlsState) assert(type(managed_processes[cfg.proc_name]) is PythonProcess) managed_processes[cfg.proc_name].prepare() @@ -416,7 +516,7 @@ def python_replay_process(cfg, lr, fingerprint=None): fsm.wait_for_update() log_msgs, msg_queue = [], [] - for msg in tqdm(pub_msgs, disable=CI): + for msg in pub_msgs: if cfg.should_recv_callback is not None: recv_socks, should_recv = cfg.should_recv_callback(msg, CP, cfg, fsm) else: @@ -453,7 +553,7 @@ def cpp_replay_process(cfg, lr, fingerprint=None): log_msgs = [] # We need to fake SubMaster alive since we can't inject a fake clock - setup_env(simulation=True) + setup_env(simulation=True, cfg=cfg) managed_processes[cfg.proc_name].prepare() managed_processes[cfg.proc_name].start() @@ -468,7 +568,7 @@ def cpp_replay_process(cfg, lr, fingerprint=None): for s in sub_sockets: messaging.recv_one_or_none(sockets[s]) - for i, msg in enumerate(tqdm(pub_msgs, disable=False)): + for i, msg in enumerate(pub_msgs): pm.send(msg.which(), msg.as_builder()) resp_sockets = cfg.pub_sub[msg.which()] if cfg.should_recv_callback is None else cfg.should_recv_callback(msg) @@ -492,3 +592,20 @@ def cpp_replay_process(cfg, lr, fingerprint=None): managed_processes[cfg.proc_name].stop() return log_msgs + + +def check_enabled(msgs): + cur_enabled_count = 0 + max_enabled_count = 0 + for msg in msgs: + if msg.which() == "carParams": + if msg.carParams.notCar: + return True + elif msg.which() == "controlsState": + if msg.controlsState.active: + cur_enabled_count += 1 + else: + cur_enabled_count = 0 + max_enabled_count = max(max_enabled_count, cur_enabled_count) + + return max_enabled_count > int(10. / DT_CTRL) diff --git a/selfdrive/test/process_replay/ref_commit b/selfdrive/test/process_replay/ref_commit index d730a50ea7..4641299458 100644 --- a/selfdrive/test/process_replay/ref_commit +++ b/selfdrive/test/process_replay/ref_commit @@ -1 +1 @@ -60f58f58dae514eb8b956c03afa5f9b91c12a122 \ No newline at end of file +f17412941a0e8229eea308c33189a5bdb1a17ae8 diff --git a/selfdrive/test/process_replay/regen.py b/selfdrive/test/process_replay/regen.py index 16ee5e9a28..c9f9c6c362 100755 --- a/selfdrive/test/process_replay/regen.py +++ b/selfdrive/test/process_replay/regen.py @@ -1,40 +1,50 @@ #!/usr/bin/env python3 +import bz2 import os import time import multiprocessing -from tqdm import tqdm import argparse +from tqdm import tqdm # run DM procs os.environ["USE_WEBCAM"] = "1" import cereal.messaging as messaging +from cereal import car from cereal.services import service_list -from cereal.visionipc.visionipc_pyx import VisionIpcServer, VisionStreamType # pylint: disable=no-name-in-module, import-error +from cereal.visionipc import VisionIpcServer, VisionStreamType from common.params import Params from common.realtime import Ratekeeper, DT_MDL, DT_DMON, sec_since_boot from common.transformations.camera import eon_f_frame_size, eon_d_frame_size, tici_f_frame_size, tici_d_frame_size -from selfdrive.car.fingerprints import FW_VERSIONS +from panda.python import Panda +from selfdrive.car.toyota.values import EPS_SCALE from selfdrive.manager.process import ensure_running from selfdrive.manager.process_config import managed_processes +from selfdrive.test.process_replay.process_replay import FAKEDATA, setup_env, check_enabled from selfdrive.test.update_ci_routes import upload_route from tools.lib.route import Route from tools.lib.framereader import FrameReader from tools.lib.logreader import LogReader - -process_replay_dir = os.path.dirname(os.path.abspath(__file__)) -FAKEDATA = os.path.join(process_replay_dir, "fakedata/") - - def replay_panda_states(s, msgs): pm = messaging.PubMaster([s, 'peripheralState']) rk = Ratekeeper(service_list[s].frequency, print_delay_threshold=None) smsgs = [m for m in msgs if m.which() in ['pandaStates', 'pandaStateDEPRECATED']] + # TODO: safety param migration should be handled automatically + safety_param_migration = { + "TOYOTA PRIUS 2017": EPS_SCALE["TOYOTA PRIUS 2017"] | Panda.FLAG_TOYOTA_STOCK_LONGITUDINAL, + "TOYOTA RAV4 2017": EPS_SCALE["TOYOTA RAV4 2017"] | Panda.FLAG_TOYOTA_ALT_BRAKE, + "KIA EV6 2022": Panda.FLAG_HYUNDAI_EV_GAS | Panda.FLAG_HYUNDAI_CANFD_HDA2, + } + # Migrate safety param base on carState cp = [m for m in msgs if m.which() == 'carParams'][0].carParams - if len(cp.safetyConfigs): + if cp.carFingerprint in safety_param_migration: + safety_param = safety_param_migration[cp.carFingerprint] + elif len(cp.safetyConfigs): safety_param = cp.safetyConfigs[0].safetyParam + if cp.safetyConfigs[0].safetyParamDEPRECATED != 0: + safety_param = cp.safetyConfigs[0].safetyParamDEPRECATED else: safety_param = cp.safetyParamDEPRECATED @@ -47,6 +57,7 @@ def replay_panda_states(s, msgs): pm.send(s, new_m) else: new_m = m.as_builder() + new_m.pandaStates[-1].safetyParam = safety_param new_m.logMonoTime = int(sec_since_boot() * 1e9) pm.send(s, new_m) @@ -61,10 +72,10 @@ def replay_manager_state(s, msgs): rk = Ratekeeper(service_list[s].frequency, print_delay_threshold=None) while True: - new_m = messaging.new_message('managerState') - new_m.managerState.processes = [{'name': name, 'running': True} for name in managed_processes] - pm.send(s, new_m) - rk.keep_time() + new_m = messaging.new_message('managerState') + new_m.managerState.processes = [{'name': name, 'running': True} for name in managed_processes] + pm.send(s, new_m) + rk.keep_time() def replay_device_state(s, msgs): @@ -81,19 +92,16 @@ def replay_device_state(s, msgs): rk.keep_time() -def replay_sensor_events(s, msgs): +def replay_sensor_event(s, msgs): pm = messaging.PubMaster([s, ]) rk = Ratekeeper(service_list[s].frequency, print_delay_threshold=None) smsgs = [m for m in msgs if m.which() == s] while True: for m in smsgs: - new_m = m.as_builder() - new_m.logMonoTime = int(sec_since_boot() * 1e9) - - for evt in new_m.sensorEvents: - evt.timestamp = new_m.logMonoTime - - pm.send(s, new_m) + m = m.as_builder() + m.logMonoTime = int(sec_since_boot() * 1e9) + getattr(m, m.which()).timestamp = m.logMonoTime + pm.send(m.which(), m) rk.keep_time() @@ -109,33 +117,39 @@ def replay_service(s, msgs): rk.keep_time() -def replay_cameras(lr, frs): +def replay_cameras(lr, frs, disable_tqdm=False): eon_cameras = [ - ("roadCameraState", DT_MDL, eon_f_frame_size, VisionStreamType.VISION_STREAM_ROAD), - ("driverCameraState", DT_DMON, eon_d_frame_size, VisionStreamType.VISION_STREAM_DRIVER), + ("roadCameraState", DT_MDL, eon_f_frame_size, VisionStreamType.VISION_STREAM_ROAD, True), + ("driverCameraState", DT_DMON, eon_d_frame_size, VisionStreamType.VISION_STREAM_DRIVER, False), ] tici_cameras = [ - ("roadCameraState", DT_MDL, tici_f_frame_size, VisionStreamType.VISION_STREAM_ROAD), - ("driverCameraState", DT_MDL, tici_d_frame_size, VisionStreamType.VISION_STREAM_DRIVER), + ("roadCameraState", DT_MDL, tici_f_frame_size, VisionStreamType.VISION_STREAM_ROAD, True), + ("driverCameraState", DT_MDL, tici_d_frame_size, VisionStreamType.VISION_STREAM_DRIVER, False), ] - def replay_camera(s, stream, dt, vipc_server, frames, size): - pm = messaging.PubMaster([s, ]) + def replay_camera(s, stream, dt, vipc_server, frames, size, use_extra_client): + services = [(s, stream)] + if use_extra_client: + services.append(("wideRoadCameraState", VisionStreamType.VISION_STREAM_WIDE_ROAD)) + pm = messaging.PubMaster([s for s, _ in services]) rk = Ratekeeper(1 / dt, print_delay_threshold=None) - img = b"\x00" * int(size[0]*size[1]*3/2) + img = b"\x00" * int(size[0] * size[1] * 3 / 2) while True: if frames is not None: img = frames[rk.frame % len(frames)] rk.keep_time() - m = messaging.new_message(s) - msg = getattr(m, s) - msg.frameId = rk.frame - pm.send(s, m) + for s, stream in services: + m = messaging.new_message(s) + msg = getattr(m, s) + msg.frameId = rk.frame + msg.timestampSof = m.logMonoTime + msg.timestampEof = m.logMonoTime + pm.send(s, m) - vipc_server.send(stream, img, msg.frameId, msg.timestampSof, msg.timestampEof) + vipc_server.send(stream, img, msg.frameId, msg.timestampSof, msg.timestampEof) init_data = [m for m in lr if m.which() == 'initData'][0] cameras = tici_cameras if (init_data.initData.deviceType == 'tici') else eon_cameras @@ -143,65 +157,104 @@ def replay_cameras(lr, frs): # init vipc server and cameras p = [] vs = VisionIpcServer("camerad") - for (s, dt, size, stream) in cameras: + for (s, dt, size, stream, use_extra_client) in cameras: fr = frs.get(s, None) frames = None if fr is not None: - print(f"Decomressing frames {s}") + print(f"Decompressing frames {s}") frames = [] - for i in tqdm(range(fr.frame_count)): - img = fr.get(i, pix_fmt='yuv420p')[0] + for i in tqdm(range(fr.frame_count), disable=disable_tqdm): + img = fr.get(i, pix_fmt='nv12')[0] frames.append(img.flatten().tobytes()) vs.create_buffers(stream, 40, False, size[0], size[1]) + if use_extra_client: + vs.create_buffers(VisionStreamType.VISION_STREAM_WIDE_ROAD, 40, False, size[0], size[1]) p.append(multiprocessing.Process(target=replay_camera, - args=(s, stream, dt, vs, frames, size))) + args=(s, stream, dt, vs, frames, size, use_extra_client))) - # hack to make UI work - vs.create_buffers(VisionStreamType.VISION_STREAM_RGB_BACK, 4, True, eon_f_frame_size[0], eon_f_frame_size[1]) vs.start_listener() return vs, p -def regen_segment(lr, frs=None, outdir=FAKEDATA): - lr = list(lr) +def migrate_carparams(lr): + all_msgs = [] + for msg in lr: + if msg.which() == 'carParams': + CP = messaging.new_message('carParams') + CP.carParams = msg.carParams.as_builder() + for car_fw in CP.carParams.carFw: + car_fw.brand = CP.carParams.carName + msg = CP.as_reader() + all_msgs.append(msg) + + return all_msgs + + +def migrate_sensorEvents(lr, old_logtime=False): + all_msgs = [] + for msg in lr: + if msg.which() != 'sensorEventsDEPRECATED': + all_msgs.append(msg) + continue + + # migrate to split sensor events + for evt in msg.sensorEventsDEPRECATED: + # build new message for each sensor type + sensor_service = '' + if evt.which() == 'acceleration': + sensor_service = 'accelerometer' + elif evt.which() == 'gyro' or evt.which() == 'gyroUncalibrated': + sensor_service = 'gyroscope' + elif evt.which() == 'light' or evt.which() == 'proximity': + sensor_service = 'lightSensor' + elif evt.which() == 'magnetic' or evt.which() == 'magneticUncalibrated': + sensor_service = 'magnetometer' + elif evt.which() == 'temperature': + sensor_service = 'temperatureSensor' + + m = messaging.new_message(sensor_service) + m.valid = True + if old_logtime: + m.logMonoTime = msg.logMonoTime + + m_dat = getattr(m, sensor_service) + m_dat.version = evt.version + m_dat.sensor = evt.sensor + m_dat.type = evt.type + m_dat.source = evt.source + if old_logtime: + m_dat.timestamp = evt.timestamp + setattr(m_dat, evt.which(), getattr(evt, evt.which())) + + all_msgs.append(m.as_reader()) + + return all_msgs + +def regen_segment(lr, frs=None, outdir=FAKEDATA, disable_tqdm=False): + lr = migrate_carparams(list(lr)) + lr = migrate_sensorEvents(list(lr)) if frs is None: frs = dict() - # setup env params = Params() - params.clear_all() - params.put_bool("Passive", False) - params.put_bool("OpenpilotEnabledToggle", True) - os.environ["LOG_ROOT"] = outdir - os.environ["REPLAY"] = "1" - os.environ['SKIP_FW_QUERY'] = "" - os.environ['FINGERPRINT'] = "" + # Get and setup initial state + CP = [m for m in lr if m.which() == 'carParams'][0].carParams + controlsState = [m for m in lr if m.which() == 'controlsState'][0].controlsState + liveCalibration = [m for m in lr if m.which() == 'liveCalibration'][0] - # TODO: remove after getting new route for mazda - migration = { - "Mazda CX-9 2021": "MAZDA CX-9 2021", - } - - for msg in lr: - if msg.which() == 'carParams': - car_fingerprint = migration.get(msg.carParams.carFingerprint, msg.carParams.carFingerprint) - if len(msg.carParams.carFw) and (car_fingerprint in FW_VERSIONS): - params.put("CarParamsCache", msg.carParams.as_builder().to_bytes()) - else: - os.environ['SKIP_FW_QUERY'] = "1" - os.environ['FINGERPRINT'] = car_fingerprint - elif msg.which() == 'liveCalibration': - params.put("CalibrationParams", msg.as_builder().to_bytes()) - - vs, cam_procs = replay_cameras(lr, frs) + setup_env(CP=CP, controlsState=controlsState) + params.put("CalibrationParams", liveCalibration.as_builder().to_bytes()) + vs, cam_procs = replay_cameras(lr, frs, disable_tqdm=disable_tqdm) fake_daemons = { 'sensord': [ - multiprocessing.Process(target=replay_sensor_events, args=('sensorEvents', lr)), + multiprocessing.Process(target=replay_sensor_event, args=('accelerometer', lr)), + multiprocessing.Process(target=replay_sensor_event, args=('gyroscope', lr)), + multiprocessing.Process(target=replay_sensor_event, args=('magnetometer', lr)), ], 'pandad': [ multiprocessing.Process(target=replay_service, args=('can', lr)), @@ -209,7 +262,7 @@ def regen_segment(lr, frs=None, outdir=FAKEDATA): multiprocessing.Process(target=replay_panda_states, args=('pandaStates', lr)), ], 'managerState': [ - multiprocessing.Process(target=replay_manager_state, args=('managerState', lr)), + multiprocessing.Process(target=replay_manager_state, args=('managerState', lr)), ], 'thermald': [ multiprocessing.Process(target=replay_device_state, args=('deviceState', lr)), @@ -220,14 +273,19 @@ def regen_segment(lr, frs=None, outdir=FAKEDATA): } try: + # TODO: make first run of onnxruntime CUDA provider fast + managed_processes["modeld"].start() + managed_processes["dmonitoringmodeld"].start() + time.sleep(5) + # start procs up - ignore = list(fake_daemons.keys()) + ['ui', 'manage_athenad', 'uploader'] - ensure_running(managed_processes.values(), started=True, not_run=ignore) + ignore = list(fake_daemons.keys()) + ['ui', 'manage_athenad', 'uploader', 'soundd'] + ensure_running(managed_processes.values(), started=True, params=Params(), CP=car.CarParams(), not_run=ignore) for procs in fake_daemons.values(): for p in procs: p.start() - for _ in tqdm(range(60)): + for _ in tqdm(range(60), disable=disable_tqdm): # ensure all procs are running for d, procs in fake_daemons.items(): for p in procs: @@ -244,19 +302,31 @@ def regen_segment(lr, frs=None, outdir=FAKEDATA): del vs - r = params.get("CurrentRoute", encoding='utf-8') - return os.path.join(outdir, r + "--0") + segment = params.get("CurrentRoute", encoding='utf-8') + "--0" + seg_path = os.path.join(outdir, segment) + # check to make sure openpilot is engaged in the route + if not check_enabled(LogReader(os.path.join(seg_path, "rlog"))): + raise Exception(f"Route did not engage for long enough: {segment}") + + return seg_path -def regen_and_save(route, sidx, upload=False, use_route_meta=False): +def regen_and_save(route, sidx, upload=False, use_route_meta=True, outdir=FAKEDATA, disable_tqdm=False): if use_route_meta: - r = Route(args.route) - lr = LogReader(r.log_paths()[args.seg]) - fr = FrameReader(r.camera_paths()[args.seg]) + r = Route(route) + lr = LogReader(r.log_paths()[sidx]) + fr = FrameReader(r.camera_paths()[sidx]) else: lr = LogReader(f"cd:/{route.replace('|', '/')}/{sidx}/rlog.bz2") fr = FrameReader(f"cd:/{route.replace('|', '/')}/{sidx}/fcamera.hevc") - rpath = regen_segment(lr, {'roadCameraState': fr}) + rpath = regen_segment(lr, {'roadCameraState': fr}, outdir=outdir, disable_tqdm=disable_tqdm) + + # compress raw rlog before uploading + with open(os.path.join(rpath, "rlog"), "rb") as f: + data = bz2.compress(f.read()) + with open(os.path.join(rpath, "rlog.bz2"), "wb") as f: + f.write(data) + os.remove(os.path.join(rpath, "rlog")) lr = LogReader(os.path.join(rpath, 'rlog.bz2')) controls_state_active = [m.controlsState.active for m in lr if m.which() == 'controlsState'] @@ -267,7 +337,7 @@ def regen_and_save(route, sidx, upload=False, use_route_meta=False): print("\n\n", "*"*30, "\n\n") print("New route:", relr, "\n") if upload: - upload_route(relr) + upload_route(relr, exclude_patterns=['*.hevc', ]) return relr diff --git a/selfdrive/test/process_replay/regen_all.py b/selfdrive/test/process_replay/regen_all.py index 4f057bbf50..f69d07eb69 100755 --- a/selfdrive/test/process_replay/regen_all.py +++ b/selfdrive/test/process_replay/regen_all.py @@ -1,22 +1,44 @@ #!/usr/bin/env python3 +import argparse +import concurrent.futures +import os +import random +import traceback +from tqdm import tqdm + +from selfdrive.test.process_replay.helpers import OpenpilotPrefix from selfdrive.test.process_replay.regen import regen_and_save -from selfdrive.test.process_replay.test_processes import original_segments as segments +from selfdrive.test.process_replay.test_processes import FAKEDATA, source_segments as segments +from tools.lib.route import SegmentName + + +def regen_job(segment, upload, disable_tqdm): + with OpenpilotPrefix(): + sn = SegmentName(segment[1]) + fake_dongle_id = 'regen' + ''.join(random.choice('0123456789ABCDEF') for _ in range(11)) + try: + relr = regen_and_save(sn.route_name.canonical_name, sn.segment_num, upload=upload, use_route_meta=False, + outdir=os.path.join(FAKEDATA, fake_dongle_id), disable_tqdm=disable_tqdm) + relr = '|'.join(relr.split('/')[-2:]) + return f' ("{segment[0]}", "{relr}"), ' + except Exception as e: + err = f" {segment} failed: {str(e)}" + err += traceback.format_exc() + err += "\n\n" + return err + if __name__ == "__main__": - new_segments = [] - for segment in segments: - route = segment[1].rsplit('--', 1)[0] - sidx = int(segment[1].rsplit('--', 1)[1]) - print("Regen", route, sidx) - relr = regen_and_save(route, sidx, upload=True, use_route_meta=False) + parser = argparse.ArgumentParser(description="Generate new segments from old ones") + parser.add_argument("-j", "--jobs", type=int, default=1) + parser.add_argument("--no-upload", action="store_true") + args = parser.parse_args() - print("\n\n", "*"*30, "\n\n") - print("New route:", relr, "\n") - relr = relr.replace('/', '|') - new_segments.append(f' ("{segment[0]}", "{relr}"), ') - print() - print() - print() - print('COPY THIS INTO test_processes.py') - for seg in new_segments: - print(seg) + with concurrent.futures.ProcessPoolExecutor(max_workers=args.jobs) as pool: + p = pool.map(regen_job, segments, [not args.no_upload] * len(segments), [args.jobs > 1] * len(segments)) + msg = "Copy these new segments into test_processes.py:" + for seg in tqdm(p, desc="Generating segments", total=len(segments)): + msg += "\n" + str(seg) + print() + print() + print(msg) diff --git a/selfdrive/test/process_replay/test_debayer.py b/selfdrive/test/process_replay/test_debayer.py new file mode 100755 index 0000000000..1b3e0f112e --- /dev/null +++ b/selfdrive/test/process_replay/test_debayer.py @@ -0,0 +1,197 @@ +#!/usr/bin/env python3 +import os +import sys +import bz2 +import numpy as np + +import pyopencl as cl # install with `PYOPENCL_CL_PRETEND_VERSION=2.0 pip install pyopencl` + +from system.hardware import PC, TICI +from common.basedir import BASEDIR +from selfdrive.test.openpilotci import BASE_URL, get_url +from system.version import get_commit +from system.camerad.snapshot.snapshot import yuv_to_rgb +from tools.lib.logreader import LogReader +from tools.lib.filereader import FileReader + +TEST_ROUTE = "8345e3b82948d454|2022-05-04--13-45-33" +SEGMENT = 0 + +FRAME_WIDTH = 1928 +FRAME_HEIGHT = 1208 +FRAME_STRIDE = 2896 + +UV_WIDTH = FRAME_WIDTH // 2 +UV_HEIGHT = FRAME_HEIGHT // 2 +UV_SIZE = UV_WIDTH * UV_HEIGHT + + +def get_frame_fn(ref_commit, test_route, tici=True): + return f"{test_route}_debayer{'_tici' if tici else ''}_{ref_commit}.bz2" + + +def bzip_frames(frames): + data = bytes() + for y, u, v in frames: + data += y.tobytes() + data += u.tobytes() + data += v.tobytes() + return bz2.compress(data) + + +def unbzip_frames(url): + with FileReader(url) as f: + dat = f.read() + + data = bz2.decompress(dat) + + res = [] + for y_start in range(0, len(data), FRAME_WIDTH * FRAME_HEIGHT + UV_SIZE * 2): + u_start = y_start + FRAME_WIDTH * FRAME_HEIGHT + v_start = u_start + UV_SIZE + + y = np.frombuffer(data[y_start: u_start], dtype=np.uint8).reshape((FRAME_HEIGHT, FRAME_WIDTH)) + u = np.frombuffer(data[u_start: v_start], dtype=np.uint8).reshape((UV_HEIGHT, UV_WIDTH)) + v = np.frombuffer(data[v_start: v_start + UV_SIZE], dtype=np.uint8).reshape((UV_HEIGHT, UV_WIDTH)) + + res.append((y, u, v)) + + return res + + +def init_kernels(frame_offset=0): + ctx = cl.create_some_context(interactive=False) + + with open(os.path.join(BASEDIR, 'system/camerad/cameras/real_debayer.cl')) as f: + build_args = ' -cl-fast-relaxed-math -cl-denorms-are-zero -cl-single-precision-constant' + \ + f' -DFRAME_STRIDE={FRAME_STRIDE} -DRGB_WIDTH={FRAME_WIDTH} -DRGB_HEIGHT={FRAME_HEIGHT} -DFRAME_OFFSET={frame_offset} -DCAM_NUM=0' + if PC: + build_args += ' -DHALF_AS_FLOAT=1 -cl-std=CL2.0' + debayer_prg = cl.Program(ctx, f.read()).build(options=build_args) + + return ctx, debayer_prg + +def debayer_frame(ctx, debayer_prg, data, rgb=False): + q = cl.CommandQueue(ctx) + + yuv_buff = np.empty(FRAME_WIDTH * FRAME_HEIGHT + UV_SIZE * 2, dtype=np.uint8) + + cam_g = cl.Buffer(ctx, cl.mem_flags.READ_ONLY | cl.mem_flags.COPY_HOST_PTR, hostbuf=data) + yuv_g = cl.Buffer(ctx, cl.mem_flags.WRITE_ONLY, FRAME_WIDTH * FRAME_HEIGHT + UV_SIZE * 2) + + local_worksize = (20, 20) if TICI else (4, 4) + ev1 = debayer_prg.debayer10(q, (UV_WIDTH, UV_HEIGHT), local_worksize, cam_g, yuv_g) + cl.enqueue_copy(q, yuv_buff, yuv_g, wait_for=[ev1]).wait() + cl.enqueue_barrier(q) + + y = yuv_buff[:FRAME_WIDTH*FRAME_HEIGHT].reshape((FRAME_HEIGHT, FRAME_WIDTH)) + u = yuv_buff[FRAME_WIDTH*FRAME_HEIGHT:FRAME_WIDTH*FRAME_HEIGHT+UV_SIZE].reshape((UV_HEIGHT, UV_WIDTH)) + v = yuv_buff[FRAME_WIDTH*FRAME_HEIGHT+UV_SIZE:].reshape((UV_HEIGHT, UV_WIDTH)) + + if rgb: + return yuv_to_rgb(y, u, v) + else: + return y, u, v + + +def debayer_replay(lr): + ctx, debayer_prg = init_kernels() + + frames = [] + for m in lr: + if m.which() == 'roadCameraState': + cs = m.roadCameraState + if cs.image: + data = np.frombuffer(cs.image, dtype=np.uint8) + img = debayer_frame(ctx, debayer_prg, data) + + frames.append(img) + + return frames + + +if __name__ == "__main__": + update = "--update" in sys.argv + replay_dir = os.path.dirname(os.path.abspath(__file__)) + ref_commit_fn = os.path.join(replay_dir, "debayer_replay_ref_commit") + + # load logs + lr = list(LogReader(get_url(TEST_ROUTE, SEGMENT))) + + # run replay + frames = debayer_replay(lr) + + # get diff + failed = False + diff = '' + yuv_i = ['y', 'u', 'v'] + if not update: + with open(ref_commit_fn) as f: + ref_commit = f.read().strip() + frame_fn = get_frame_fn(ref_commit, TEST_ROUTE, tici=TICI) + + try: + cmp_frames = unbzip_frames(BASE_URL + frame_fn) + + if len(frames) != len(cmp_frames): + failed = True + diff += 'amount of frames not equal\n' + + for i, (frame, cmp_frame) in enumerate(zip(frames, cmp_frames)): + for j in range(3): + fr = frame[j] + cmp_f = cmp_frame[j] + if fr.shape != cmp_f.shape: + failed = True + diff += f'frame shapes not equal for ({i}, {yuv_i[j]})\n' + diff += f'{ref_commit}: {cmp_f.shape}\n' + diff += f'HEAD: {fr.shape}\n' + elif not np.array_equal(fr, cmp_f): + failed = True + if np.allclose(fr, cmp_f, atol=1): + diff += f'frames not equal for ({i}, {yuv_i[j]}), but are all close\n' + else: + diff += f'frames not equal for ({i}, {yuv_i[j]})\n' + + frame_diff = np.abs(np.subtract(fr, cmp_f)) + diff_len = len(np.nonzero(frame_diff)[0]) + if diff_len > 10000: + diff += f'different at a large amount of pixels ({diff_len})\n' + else: + diff += 'different at (frame, yuv, pixel, ref, HEAD):\n' + for k in zip(*np.nonzero(frame_diff)): + diff += f'{i}, {yuv_i[j]}, {k}, {cmp_f[k]}, {fr[k]}\n' + + if failed: + print(diff) + with open("debayer_diff.txt", "w") as f: + f.write(diff) + except Exception as e: + print(str(e)) + failed = True + + # upload new refs + if update or (failed and TICI): + from selfdrive.test.openpilotci import upload_file + + print("Uploading new refs") + + frames_bzip = bzip_frames(frames) + + new_commit = get_commit() + frame_fn = os.path.join(replay_dir, get_frame_fn(new_commit, TEST_ROUTE, tici=TICI)) + with open(frame_fn, "wb") as f2: + f2.write(frames_bzip) + + try: + upload_file(frame_fn, os.path.basename(frame_fn)) + except Exception as e: + print("failed to upload", e) + + if update: + with open(ref_commit_fn, 'w') as f: + f.write(str(new_commit)) + + print("\nNew ref commit: ", new_commit) + + sys.exit(int(failed)) diff --git a/selfdrive/test/process_replay/test_processes.py b/selfdrive/test/process_replay/test_processes.py index f7dae5c9fb..c58909bf7f 100755 --- a/selfdrive/test/process_replay/test_processes.py +++ b/selfdrive/test/process_replay/test_processes.py @@ -1,85 +1,114 @@ #!/usr/bin/env python3 import argparse +import concurrent.futures import os import sys -from typing import Any +from collections import defaultdict +from tqdm import tqdm +from typing import Any, DefaultDict, Dict from selfdrive.car.car_helpers import interface_names -from selfdrive.test.openpilotci import get_url -from selfdrive.test.process_replay.compare_logs import compare_logs -from selfdrive.test.process_replay.process_replay import CONFIGS, replay_process +from selfdrive.test.openpilotci import get_url, upload_file +from selfdrive.test.process_replay.compare_logs import compare_logs, save_log +from selfdrive.test.process_replay.process_replay import CONFIGS, PROC_REPLAY_DIR, FAKEDATA, check_enabled, replay_process +from system.version import get_commit +from tools.lib.filereader import FileReader from tools.lib.logreader import LogReader - -original_segments = [ +source_segments = [ + ("BODY", "937ccb7243511b65|2022-05-24--16-03-09--1"), # COMMA.BODY ("HYUNDAI", "02c45f73a2e5c6e9|2021-01-01--19-08-22--1"), # HYUNDAI.SONATA + ("HYUNDAI2", "d545129f3ca90f28|2022-11-07--20-43-08--3"), # HYUNDAI.KIA_EV6 ("TOYOTA", "0982d79ebb0de295|2021-01-04--17-13-21--13"), # TOYOTA.PRIUS (INDI) ("TOYOTA2", "0982d79ebb0de295|2021-01-03--20-03-36--6"), # TOYOTA.RAV4 (LQR) ("TOYOTA3", "f7d7e3538cda1a2a|2021-08-16--08-55-34--6"), # TOYOTA.COROLLA_TSS2 ("HONDA", "eb140f119469d9ab|2021-06-12--10-46-24--27"), # HONDA.CIVIC (NIDEC) ("HONDA2", "7d2244f34d1bbcda|2021-06-25--12-25-37--26"), # HONDA.ACCORD (BOSCH) - ("CHRYSLER", "4deb27de11bee626|2021-02-20--11-28-55--8"), # CHRYSLER.PACIFICA - ("SUBARU", "4d70bc5e608678be|2021-01-15--17-02-04--5"), # SUBARU.IMPREZA + ("CHRYSLER", "4deb27de11bee626|2021-02-20--11-28-55--8"), # CHRYSLER.PACIFICA_2018_HYBRID + ("RAM", "2f4452b03ccb98f0|2022-09-07--13-55-08--10"), # CHRYSLER.RAM_1500 + ("SUBARU", "341dccd5359e3c97|2022-09-12--10-35-33--3"), # SUBARU.OUTBACK ("GM", "0c58b6a25109da2b|2021-02-23--16-35-50--11"), # GM.VOLT + ("GM2", "376bf99325883932|2022-10-27--13-41-22--1"), # GM.BOLT_EUV ("NISSAN", "35336926920f3571|2021-02-12--18-38-48--46"), # NISSAN.XTRAIL ("VOLKSWAGEN", "de9592456ad7d144|2021-06-29--11-00-15--6"), # VOLKSWAGEN.GOLF - ("MAZDA", "bd6a637565e91581|2021-10-30--15-14-53--2"), # MAZDA.CX9_2021 + ("MAZDA", "bd6a637565e91581|2021-10-30--15-14-53--4"), # MAZDA.CX9_2021 - # Enable when port is tested and dascamOnly is no longer set + # Enable when port is tested and dashcamOnly is no longer set #("TESLA", "bb50caf5f0945ab1|2021-06-19--17-20-18--3"), # TESLA.AP2_MODELS + #("VOLKSWAGEN2", "3cfdec54aa035f3f|2022-07-19--23-45-10--2"), # VOLKSWAGEN.PASSAT_NMS ] segments = [ - ("HYUNDAI", "fakedata|2022-01-20--17-49-04--0"), - ("TOYOTA", "fakedata|2022-01-20--17-50-51--0"), - ("TOYOTA2", "fakedata|2022-01-20--17-52-36--0"), - ("TOYOTA3", "fakedata|2022-01-20--17-54-50--0"), - ("HONDA", "fakedata|2022-01-20--17-56-40--0"), - ("HONDA2", "fakedata|2022-01-20--17-58-25--0"), - ("CHRYSLER", "fakedata|2022-01-20--18-00-11--0"), - ("SUBARU", "fakedata|2022-01-20--18-01-57--0"), - ("GM", "fakedata|2022-01-20--18-03-41--0"), - ("NISSAN", "fakedata|2022-01-20--18-05-29--0"), - ("VOLKSWAGEN", "fakedata|2022-01-20--18-07-15--0"), - ("MAZDA", "fakedata|2022-01-20--18-09-32--0"), + ("BODY", "regenFA002A80700|2022-09-27--15-37-02--0"), + ("HYUNDAI", "regenBE53A59065B|2022-09-27--16-52-03--0"), + ("HYUNDAI2", "d545129f3ca90f28|2022-11-07--20-43-08--3"), + ("TOYOTA", "regen929C5790007|2022-09-27--16-27-47--0"), + ("TOYOTA2", "regenEA3950D7F22|2022-09-27--15-43-24--0"), + ("TOYOTA3", "regen89026F6BD8D|2022-09-27--15-45-37--0"), + ("HONDA", "regenC7D5645EB17|2022-09-27--15-47-29--0"), + ("HONDA2", "regenCC2ECCE5742|2022-09-27--16-18-01--0"), + ("CHRYSLER", "regenC253C4DAC90|2022-09-27--15-51-03--0"), + ("RAM", "regen20490083AE7|2022-09-27--15-53-15--0"), + ("SUBARU", "regen1E72BBDCED5|2022-09-27--15-55-31--0"), + ("GM", "regen45B05A80EF6|2022-09-27--15-57-22--0"), + ("GM2", "376bf99325883932|2022-10-27--13-41-22--1"), + ("NISSAN", "regenC19D899B46D|2022-09-27--15-59-13--0"), + ("VOLKSWAGEN", "regenD8F7AC4BD0D|2022-09-27--16-41-45--0"), + ("MAZDA", "regenFC3F9ECBB64|2022-09-27--16-03-09--0"), ] # dashcamOnly makes don't need to be tested until a full port is done excluded_interfaces = ["mock", "ford", "mazda", "tesla"] BASE_URL = "https://commadataci.blob.core.windows.net/openpilotci/" +REF_COMMIT_FN = os.path.join(PROC_REPLAY_DIR, "ref_commit") + + +def run_test_process(data): + segment, cfg, args, cur_log_fn, ref_log_path, lr_dat = data + res = None + if not args.upload_only: + lr = LogReader.from_bytes(lr_dat) + res, log_msgs = test_process(cfg, lr, ref_log_path, cur_log_fn, args.ignore_fields, args.ignore_msgs) + # save logs so we can upload when updating refs + save_log(cur_log_fn, log_msgs) + + if args.update_refs or args.upload_only: + print(f'Uploading: {os.path.basename(cur_log_fn)}') + assert os.path.exists(cur_log_fn), f"Cannot find log to upload: {cur_log_fn}" + upload_file(cur_log_fn, os.path.basename(cur_log_fn)) + os.remove(cur_log_fn) + return (segment, cfg.proc_name, cfg.subtest_name, res) + -# run the full test (including checks) when no args given -FULL_TEST = len(sys.argv) <= 1 +def get_log_data(segment): + r, n = segment.rsplit("--", 1) + with FileReader(get_url(r, n)) as f: + return (segment, f.read()) -def test_process(cfg, lr, cmp_log_fn, ignore_fields=None, ignore_msgs=None): +def test_process(cfg, lr, ref_log_path, new_log_path, ignore_fields=None, ignore_msgs=None): if ignore_fields is None: ignore_fields = [] if ignore_msgs is None: ignore_msgs = [] - cmp_log_path = cmp_log_fn if os.path.exists(cmp_log_fn) else BASE_URL + os.path.basename(cmp_log_fn) - cmp_log_msgs = list(LogReader(cmp_log_path)) + ref_log_msgs = list(LogReader(ref_log_path)) log_msgs = replay_process(cfg, lr) # check to make sure openpilot is engaged in the route if cfg.proc_name == "controlsd": - for msg in log_msgs: - if msg.which() == "controlsState": - if msg.controlsState.active: - break - else: - segment = cmp_log_fn.split("/")[-1].split("_")[0] - raise Exception(f"Route never enabled: {segment}") + if not check_enabled(log_msgs): + return f"Route did not enable at all or for long enough: {new_log_path}", log_msgs try: - return compare_logs(cmp_log_msgs, log_msgs, ignore_fields+cfg.ignore, ignore_msgs, cfg.tolerance) + return compare_logs(ref_log_msgs, log_msgs, ignore_fields + cfg.ignore, ignore_msgs, cfg.tolerance, cfg.field_tolerances), log_msgs except Exception as e: - return str(e) + return str(e), log_msgs + -def format_diff(results, ref_commit): +def format_diff(results, log_paths, ref_commit): diff1, diff2 = "", "" diff2 += f"***** tested against commit {ref_commit} *****\n" @@ -89,14 +118,23 @@ def format_diff(results, ref_commit): diff2 += f"***** differences for segment {segment} *****\n" for proc, diff in list(result.items()): - diff1 += f"\t{proc}\n" + # long diff diff2 += f"*** process: {proc} ***\n" + diff2 += f"\tref: {log_paths[segment][proc]['ref']}\n" + diff2 += f"\tnew: {log_paths[segment][proc]['new']}\n\n" + # short diff + diff1 += f" {proc}\n" if isinstance(diff, str): - diff1 += f"\t\t{diff}\n" + diff1 += f" ref: {log_paths[segment][proc]['ref']}\n" + diff1 += f" new: {log_paths[segment][proc]['new']}\n\n" + diff1 += f" {diff}\n" failed = True elif len(diff): - cnt = {} + diff1 += f" ref: {log_paths[segment][proc]['ref']}\n" + diff1 += f" new: {log_paths[segment][proc]['new']}\n\n" + + cnt: Dict[str, int] = {} for d in diff: diff2 += f"\t{str(d)}\n" @@ -104,78 +142,116 @@ def format_diff(results, ref_commit): cnt[k] = 1 if k not in cnt else cnt[k] + 1 for k, v in sorted(cnt.items()): - diff1 += f"\t\t{k}: {v}\n" + diff1 += f" {k}: {v}\n" failed = True return diff1, diff2, failed + if __name__ == "__main__": + all_cars = {car for car, _ in segments} + all_procs = {cfg.proc_name for cfg in CONFIGS} parser = argparse.ArgumentParser(description="Regression test to identify changes in a process's output") - - # whitelist has precedence over blacklist in case both are defined - parser.add_argument("--whitelist-procs", type=str, nargs="*", default=[], - help="Whitelist given processes from the test (e.g. controlsd)") - parser.add_argument("--whitelist-cars", type=str, nargs="*", default=[], - help="Whitelist given cars from the test (e.g. HONDA)") + parser.add_argument("--whitelist-procs", type=str, nargs="*", default=all_procs, + help="Whitelist given processes from the test (e.g. controlsd)") + parser.add_argument("--whitelist-cars", type=str, nargs="*", default=all_cars, + help="Whitelist given cars from the test (e.g. HONDA)") parser.add_argument("--blacklist-procs", type=str, nargs="*", default=[], - help="Blacklist given processes from the test (e.g. controlsd)") + help="Blacklist given processes from the test (e.g. controlsd)") parser.add_argument("--blacklist-cars", type=str, nargs="*", default=[], - help="Blacklist given cars from the test (e.g. HONDA)") + help="Blacklist given cars from the test (e.g. HONDA)") parser.add_argument("--ignore-fields", type=str, nargs="*", default=[], - help="Extra fields or msgs to ignore (e.g. carState.events)") + help="Extra fields or msgs to ignore (e.g. carState.events)") parser.add_argument("--ignore-msgs", type=str, nargs="*", default=[], - help="Msgs to ignore (e.g. carEvents)") + help="Msgs to ignore (e.g. carEvents)") + parser.add_argument("--update-refs", action="store_true", + help="Updates reference logs using current commit") + parser.add_argument("--upload-only", action="store_true", + help="Skips testing processes and uploads logs from previous test run") + parser.add_argument("-j", "--jobs", type=int, default=1) args = parser.parse_args() - cars_whitelisted = len(args.whitelist_cars) > 0 - procs_whitelisted = len(args.whitelist_procs) > 0 + tested_procs = set(args.whitelist_procs) - set(args.blacklist_procs) + tested_cars = set(args.whitelist_cars) - set(args.blacklist_cars) + tested_cars = {c.upper() for c in tested_cars} + + full_test = (tested_procs == all_procs) and (tested_cars == all_cars) and all(len(x) == 0 for x in (args.ignore_fields, args.ignore_msgs)) + upload = args.update_refs or args.upload_only + os.makedirs(os.path.dirname(FAKEDATA), exist_ok=True) + + if upload: + assert full_test, "Need to run full test when updating refs" - process_replay_dir = os.path.dirname(os.path.abspath(__file__)) try: - ref_commit = open(os.path.join(process_replay_dir, "ref_commit")).read().strip() + ref_commit = open(REF_COMMIT_FN).read().strip() except FileNotFoundError: - print("couldn't find reference commit") + print("Couldn't find reference commit") sys.exit(1) + cur_commit = get_commit() + if cur_commit is None: + raise Exception("Couldn't get current commit") + print(f"***** testing against commit {ref_commit} *****") # check to make sure all car brands are tested - if FULL_TEST: - tested_cars = {c.lower() for c, _ in segments} - untested = (set(interface_names) - set(excluded_interfaces)) - tested_cars + if full_test: + untested = (set(interface_names) - set(excluded_interfaces)) - {c.lower() for c in tested_cars} assert len(untested) == 0, f"Cars missing routes: {str(untested)}" - results: Any = {} - for car_brand, segment in segments: - if (cars_whitelisted and car_brand.upper() not in args.whitelist_cars) or \ - (not cars_whitelisted and car_brand.upper() in args.blacklist_cars): - continue - - print(f"***** testing route segment {segment} *****\n") - - results[segment] = {} - - r, n = segment.rsplit("--", 1) - lr = LogReader(get_url(r, n)) - - for cfg in CONFIGS: - if (procs_whitelisted and cfg.proc_name not in args.whitelist_procs) or \ - (not procs_whitelisted and cfg.proc_name in args.blacklist_procs): + log_paths: DefaultDict[str, Dict[str, Dict[str, str]]] = defaultdict(lambda: defaultdict(dict)) + with concurrent.futures.ProcessPoolExecutor(max_workers=args.jobs) as pool: + if not args.upload_only: + download_segments = [seg for car, seg in segments if car in tested_cars] + log_data: Dict[str, LogReader] = {} + p1 = pool.map(get_log_data, download_segments) + for segment, lr in tqdm(p1, desc="Getting Logs", total=len(download_segments)): + log_data[segment] = lr + + pool_args: Any = [] + for car_brand, segment in segments: + if car_brand not in tested_cars: continue - cmp_log_fn = os.path.join(process_replay_dir, f"{segment}_{cfg.proc_name}_{ref_commit}.bz2") - results[segment][cfg.proc_name] = test_process(cfg, lr, cmp_log_fn, args.ignore_fields, args.ignore_msgs) - - diff1, diff2, failed = format_diff(results, ref_commit) - with open(os.path.join(process_replay_dir, "diff.txt"), "w") as f: - f.write(diff2) - print(diff1) + for cfg in CONFIGS: + if cfg.proc_name not in tested_procs: + continue + + cur_log_fn = os.path.join(FAKEDATA, f"{segment}_{cfg.proc_name}{cfg.subtest_name}_{cur_commit}.bz2") + if args.update_refs: # reference logs will not exist if routes were just regenerated + ref_log_path = get_url(*segment.rsplit("--", 1)) + else: + ref_log_fn = os.path.join(FAKEDATA, f"{segment}_{cfg.proc_name}{cfg.subtest_name}_{ref_commit}.bz2") + ref_log_path = ref_log_fn if os.path.exists(ref_log_fn) else BASE_URL + os.path.basename(ref_log_fn) + + dat = None if args.upload_only else log_data[segment] + pool_args.append((segment, cfg, args, cur_log_fn, ref_log_path, dat)) + + log_paths[segment][cfg.proc_name + cfg.subtest_name]['ref'] = ref_log_path + log_paths[segment][cfg.proc_name + cfg.subtest_name]['new'] = cur_log_fn + + results: Any = defaultdict(dict) + p2 = pool.map(run_test_process, pool_args) + for (segment, proc, subtest_name, result) in tqdm(p2, desc="Running Tests", total=len(pool_args)): + if not args.upload_only: + results[segment][proc + subtest_name] = result + + diff1, diff2, failed = format_diff(results, log_paths, ref_commit) + if not upload: + with open(os.path.join(PROC_REPLAY_DIR, "diff.txt"), "w") as f: + f.write(diff2) + print(diff1) + + if failed: + print("TEST FAILED") + print("\n\nTo push the new reference logs for this commit run:") + print("./test_processes.py --upload-only") + else: + print("TEST SUCCEEDED") - if failed: - print("TEST FAILED") - print("\n\nTo update the reference logs for this test run:") - print("./update_refs.py") else: - print("TEST SUCCEEDED") + with open(REF_COMMIT_FN, "w") as f: + f.write(cur_commit) + print(f"\n\nUpdated reference logs for commit: {cur_commit}") sys.exit(int(failed)) diff --git a/selfdrive/test/process_replay/update_refs.py b/selfdrive/test/process_replay/update_refs.py deleted file mode 100755 index 0a3d95e714..0000000000 --- a/selfdrive/test/process_replay/update_refs.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env python3 -import os -import sys - -from selfdrive.test.openpilotci import upload_file, get_url -from selfdrive.test.process_replay.compare_logs import save_log -from selfdrive.test.process_replay.process_replay import replay_process, CONFIGS -from selfdrive.test.process_replay.test_processes import segments -from selfdrive.version import get_commit -from tools.lib.logreader import LogReader - -if __name__ == "__main__": - - no_upload = "--no-upload" in sys.argv - - process_replay_dir = os.path.dirname(os.path.abspath(__file__)) - ref_commit_fn = os.path.join(process_replay_dir, "ref_commit") - - ref_commit = get_commit() - if ref_commit is None: - raise Exception("couldn't get ref commit") - with open(ref_commit_fn, "w") as f: - f.write(ref_commit) - - for car_brand, segment in segments: - r, n = segment.rsplit("--", 1) - lr = LogReader(get_url(r, n)) - - for cfg in CONFIGS: - log_msgs = replay_process(cfg, lr) - log_fn = os.path.join(process_replay_dir, f"{segment}_{cfg.proc_name}_{ref_commit}.bz2") - save_log(log_fn, log_msgs) - - if not no_upload: - upload_file(log_fn, os.path.basename(log_fn)) - os.remove(log_fn) - - print("done") diff --git a/selfdrive/test/profiling/lib.py b/selfdrive/test/profiling/lib.py index fcc832d327..f28346f3f0 100644 --- a/selfdrive/test/profiling/lib.py +++ b/selfdrive/test/profiling/lib.py @@ -44,6 +44,7 @@ class SubMaster(messaging.SubMaster): self.rcv_time = {s: 0. for s in services} self.rcv_frame = {s: 0 for s in services} self.valid = {s: True for s in services} + self.freq_ok = {s: True for s in services} self.recv_dts = {s: deque([0.0] * messaging.AVG_FREQ_HISTORY, maxlen=messaging.AVG_FREQ_HISTORY) for s in services} self.logMonoTime = {} self.sock = {} diff --git a/selfdrive/test/profiling/profiler.py b/selfdrive/test/profiling/profiler.py index 5f73176fab..732a69eebd 100755 --- a/selfdrive/test/profiling/profiler.py +++ b/selfdrive/test/profiling/profiler.py @@ -53,6 +53,8 @@ def profile(proc, func, car='toyota'): msgs = list(LogReader(rlog_url)) * int(os.getenv("LOOP", "1")) os.environ['FINGERPRINT'] = fingerprint + os.environ['SKIP_FW_QUERY'] = "1" + os.environ['REPLAY'] = "1" def run(sm, pm, can_sock): try: @@ -81,12 +83,14 @@ if __name__ == '__main__': from selfdrive.controls.radard import radard_thread from selfdrive.locationd.paramsd import main as paramsd_thread from selfdrive.controls.plannerd import main as plannerd_thread + from selfdrive.locationd.laikad import main as laikad_thread procs = { 'radard': radard_thread, 'controlsd': controlsd_thread, 'paramsd': paramsd_thread, 'plannerd': plannerd_thread, + 'laikad': laikad_thread, } proc = sys.argv[1] diff --git a/selfdrive/test/setup_device_ci.sh b/selfdrive/test/setup_device_ci.sh index 260a1b4487..9e06b98662 100755 --- a/selfdrive/test/setup_device_ci.sh +++ b/selfdrive/test/setup_device_ci.sh @@ -19,29 +19,29 @@ fi umount /data/safe_staging/merged/ || true sudo umount /data/safe_staging/merged/ || true +rm -rf /data/safe_staging/* || true -if [ -f "/EON" ]; then - rm -rf /data/core - rm -rf /data/neoupdate - rm -rf /data/safe_staging -fi - -export KEYS_PATH="/usr/comma/setup_keys" -export CONTINUE_PATH="/data/continue.sh" -if [ -f "/EON" ]; then - export KEYS_PATH="/data/data/com.termux/files/home/setup_keys" - export CONTINUE_PATH="/data/data/com.termux/files/continue.sh" -fi +CONTINUE_PATH="/data/continue.sh" tee $CONTINUE_PATH << EOF #!/usr/bin/bash -PARAMS_ROOT="/data/params/d" +sudo abctl --set_success + +# patch sshd config +sudo mount -o rw,remount / +echo tici-$(cat /proc/cmdline | sed -e 's/^.*androidboot.serialno=//' -e 's/ .*$//') | sudo tee /etc/hostname +sudo sed -i "s,/data/params/d/GithubSshKeys,/usr/comma/setup_keys," /etc/ssh/sshd_config +sudo systemctl daemon-reload +sudo systemctl restart ssh +sudo systemctl disable ssh-param-watcher.path +sudo systemctl disable ssh-param-watcher.service +sudo mount -o ro,remount / while true; do - mkdir -p \$PARAMS_ROOT - cp $KEYS_PATH \$PARAMS_ROOT/GithubSshKeys - echo -n 1 > \$PARAMS_ROOT/SshEnabled - sleep 1m + if ! sudo systemctl is-active -q ssh; then + sudo systemctl start ssh + fi + sleep 5s done sleep infinity @@ -56,14 +56,17 @@ cd $SOURCE_DIR rm -f .git/index.lock git reset --hard -git fetch -find . -maxdepth 1 -not -path './.git' -not -name '.' -not -name '..' -exec rm -rf '{}' \; git fetch --verbose origin $GIT_COMMIT +find . -maxdepth 1 -not -path './.git' -not -name '.' -not -name '..' -exec rm -rf '{}' \; git reset --hard $GIT_COMMIT git checkout $GIT_COMMIT -git clean -xdf +git clean -xdff +git submodule sync git submodule update --init --recursive -git submodule foreach --recursive "git reset --hard && git clean -xdf" +git submodule foreach --recursive "git reset --hard && git clean -xdff" + +git lfs pull +(ulimit -n 65535 && git lfs prune) echo "git checkout done, t=$SECONDS" diff --git a/selfdrive/test/test_onroad.py b/selfdrive/test/test_onroad.py index a49f93e37d..4021e27de3 100755 --- a/selfdrive/test/test_onroad.py +++ b/selfdrive/test/test_onroad.py @@ -5,7 +5,7 @@ import subprocess import time import numpy as np import unittest -from collections import Counter +from collections import Counter, defaultdict from pathlib import Path from cereal import car @@ -15,57 +15,38 @@ from common.basedir import BASEDIR from common.timeout import Timeout from common.params import Params from selfdrive.controls.lib.events import EVENTS, ET -from selfdrive.hardware import EON, TICI from selfdrive.loggerd.config import ROOT from selfdrive.test.helpers import set_params_enabled, release_only from tools.lib.logreader import LogReader # Baseline CPU usage by process PROCS = { - "selfdrive.controls.controlsd": 55.0, - "./loggerd": 45.0, + "selfdrive.controls.controlsd": 39.0, + "./loggerd": 10.0, + "./encoderd": 17.0, + "./camerad": 14.5, "./locationd": 9.1, - "selfdrive.controls.plannerd": 22.6, - "./_ui": 20.0, - "selfdrive.locationd.paramsd": 14.0, - "./camerad": 9.16, - "./_sensord": 6.17, - "selfdrive.controls.radard": 7.0, + "selfdrive.controls.plannerd": 11.7, + "./_ui": 19.2, + "selfdrive.locationd.paramsd": 9.0, + "./_sensord": 12.0, + "selfdrive.controls.radard": 4.5, "./_modeld": 4.48, "./boardd": 3.63, - "./_dmonitoringmodeld": 2.67, - "selfdrive.thermald.thermald": 5.36, + "./_dmonitoringmodeld": 5.0, + "selfdrive.thermald.thermald": 3.87, "selfdrive.locationd.calibrationd": 2.0, + "selfdrive.locationd.torqued": 5.0, "./_soundd": 1.0, - "selfdrive.monitoring.dmonitoringd": 1.90, + "selfdrive.monitoring.dmonitoringd": 4.0, "./proclogd": 1.54, - "selfdrive.logmessaged": 0.2, + "system.logmessaged": 0.2, "./clocksd": 0.02, "./ubloxd": 0.02, "selfdrive.tombstoned": 0, "./logcatd": 0, } -if EON: - PROCS.update({ - "selfdrive.hardware.eon.androidd": 0.4, - "selfdrive.hardware.eon.shutdownd": 0.4, - }) - -if TICI: - PROCS.update({ - "./loggerd": 70.0, - "selfdrive.controls.controlsd": 31.0, - "./camerad": 36.8, - "./_ui": 33.0, - "selfdrive.controls.plannerd": 11.7, - "./_dmonitoringmodeld": 10.0, - "selfdrive.locationd.paramsd": 5.0, - "selfdrive.controls.radard": 4.5, - "selfdrive.thermald.thermald": 3.87, - }) - - TIMINGS = { # rtols: max/min, rsd "can": [2.5, 0.35], @@ -80,50 +61,53 @@ TIMINGS = { "roadCameraState": [2.5, 0.35], "driverCameraState": [2.5, 0.35], "modelV2": [2.5, 0.35], - "driverState": [2.5, 0.35], + "driverStateV2": [2.5, 0.40], "liveLocationKalman": [2.5, 0.35], + "wideRoadCameraState": [1.5, 0.35], } -if EON: - TIMINGS.update({ - "roadCameraState": [2.5, 0.45], - }) -if TICI: - TIMINGS.update({ - "wideRoadCameraState": [1.5, 0.35], - }) def cputime_total(ct): return ct.cpuUser + ct.cpuSystem + ct.cpuChildrenUser + ct.cpuChildrenSystem -def check_cpu_usage(first_proc, last_proc): +def check_cpu_usage(proclogs): result = "\n" result += "------------------------------------------------\n" result += "------------------ CPU Usage -------------------\n" result += "------------------------------------------------\n" + plogs_by_proc = defaultdict(list) + for pl in proclogs: + for x in pl.procLog.procs: + if len(x.cmdline) > 0: + n = list(x.cmdline)[0] + plogs_by_proc[n].append(x) + + print(plogs_by_proc.keys()) + r = True - dt = (last_proc.logMonoTime - first_proc.logMonoTime) / 1e9 - for proc_name, normal_cpu_usage in PROCS.items(): - first, last = None, None - try: - first = [p for p in first_proc.procLog.procs if proc_name in p.cmdline][0] - last = [p for p in last_proc.procLog.procs if proc_name in p.cmdline][0] - cpu_time = cputime_total(last) - cputime_total(first) + dt = (proclogs[-1].logMonoTime - proclogs[0].logMonoTime) / 1e9 + for proc_name, expected_cpu in PROCS.items(): + err = "" + cpu_usage = 0. + x = plogs_by_proc[proc_name] + if len(x) > 2: + cpu_time = cputime_total(x[-1]) - cputime_total(x[0]) cpu_usage = cpu_time / dt * 100. - if cpu_usage > max(normal_cpu_usage * 1.15, normal_cpu_usage + 5.0): + if cpu_usage > max(expected_cpu * 1.15, expected_cpu + 5.0): # cpu usage is high while playing sounds if not (proc_name == "./_soundd" and cpu_usage < 65.): - result += f"Warning {proc_name} using more CPU than normal\n" - r = False - elif cpu_usage < min(normal_cpu_usage * 0.65, max(normal_cpu_usage - 1.0, 0.0)): - result += f"Warning {proc_name} using less CPU than normal\n" - r = False - result += f"{proc_name.ljust(35)} {cpu_usage:.2f}%\n" - except IndexError: - result += f"{proc_name.ljust(35)} NO METRICS FOUND {first=} {last=}\n" + err = "using more CPU than normal" + elif cpu_usage < min(expected_cpu * 0.65, max(expected_cpu - 1.0, 0.0)): + err = "using less CPU than normal" + else: + err = "NO METRICS FOUND" + + result += f"{proc_name.ljust(35)} {cpu_usage:5.2f}% ({expected_cpu:5.2f}%) {err}\n" + if len(err) > 0: r = False + result += "------------------------------------------------\n" print(result) return r @@ -134,15 +118,17 @@ class TestOnroad(unittest.TestCase): @classmethod def setUpClass(cls): if "DEBUG" in os.environ: - segs = filter(lambda x: os.path.exists(os.path.join(x, "rlog.bz2")), Path(ROOT).iterdir()) + segs = filter(lambda x: os.path.exists(os.path.join(x, "rlog")), Path(ROOT).iterdir()) segs = sorted(segs, key=lambda x: x.stat().st_mtime) - cls.lr = list(LogReader(os.path.join(segs[-1], "rlog.bz2"))) + print(segs[-2]) + cls.lr = list(LogReader(os.path.join(segs[-2], "rlog"))) return # setup env os.environ['REPLAY'] = "1" os.environ['SKIP_FW_QUERY'] = "1" os.environ['FINGERPRINT'] = "TOYOTA COROLLA TSS2 2019" + os.environ['LOGPRINT'] = 'debug' params = Params() params.clear_all() @@ -152,6 +138,7 @@ class TestOnroad(unittest.TestCase): os.system("pkill -9 -f athena") # start manager and run openpilot for a minute + proc = None try: manager_path = os.path.join(BASEDIR, "selfdrive/manager/manager.py") proc = subprocess.Popen(["python", manager_path]) @@ -180,14 +167,15 @@ class TestOnroad(unittest.TestCase): cls.segments = cls.segments[:-1] finally: - proc.terminate() - if proc.wait(60) is None: - proc.kill() + if proc is not None: + proc.terminate() + if proc.wait(60) is None: + proc.kill() - cls.lrs = [list(LogReader(os.path.join(str(s), "rlog.bz2"))) for s in cls.segments] + cls.lrs = [list(LogReader(os.path.join(str(s), "rlog"))) for s in cls.segments] # use the second segment by default as it's the first full segment - cls.lr = list(LogReader(os.path.join(str(cls.segments[1]), "rlog.bz2"))) + cls.lr = list(LogReader(os.path.join(str(cls.segments[1]), "rlog"))) def test_cloudlog_size(self): msgs = [m for m in self.lr if m.which() == 'logMessage'] @@ -199,12 +187,45 @@ class TestOnroad(unittest.TestCase): big_logs = [f for f, n in cnt.most_common(3) if n / sum(cnt.values()) > 30.] self.assertEqual(len(big_logs), 0, f"Log spam: {big_logs}") + def test_ui_timings(self): + result = "\n" + result += "------------------------------------------------\n" + result += "-------------- UI Draw Timing ------------------\n" + result += "------------------------------------------------\n" + + ts = [m.uiDebug.drawTimeMillis for m in self.lr if m.which() == 'uiDebug'] + result += f"min {min(ts):.2f}ms\n" + result += f"max {max(ts):.2f}ms\n" + result += f"std {np.std(ts):.2f}ms\n" + result += f"mean {np.mean(ts):.2f}ms\n" + result += "------------------------------------------------\n" + print(result) + + self.assertGreater(len(ts), 20*50, "insufficient samples") + #self.assertLess(max(ts), 30.) + self.assertLess(np.mean(ts), 10.) + #self.assertLess(np.std(ts), 5.) + def test_cpu_usage(self): proclogs = [m for m in self.lr if m.which() == 'procLog'] self.assertGreater(len(proclogs), service_list['procLog'].frequency * 45, "insufficient samples") - cpu_ok = check_cpu_usage(proclogs[0], proclogs[-1]) + cpu_ok = check_cpu_usage(proclogs) self.assertTrue(cpu_ok) + def test_camera_processing_time(self): + result = "\n" + result += "------------------------------------------------\n" + result += "-------------- Debayer Timing ------------------\n" + result += "------------------------------------------------\n" + + ts = [getattr(getattr(m, m.which()), "processingTime") for m in self.lr if 'CameraState' in m.which()] + self.assertLess(min(ts), 0.025, f"high execution time: {min(ts)}") + result += f"execution time: min {min(ts):.5f}s\n" + result += f"execution time: max {max(ts):.5f}s\n" + result += f"execution time: mean {np.mean(ts):.5f}s\n" + result += "------------------------------------------------\n" + print(result) + def test_mpc_execution_timings(self): result = "\n" result += "------------------------------------------------\n" @@ -214,10 +235,11 @@ class TestOnroad(unittest.TestCase): cfgs = [("lateralPlan", 0.05, 0.05), ("longitudinalPlan", 0.05, 0.05)] for (s, instant_max, avg_max) in cfgs: ts = [getattr(getattr(m, s), "solverExecutionTime") for m in self.lr if m.which() == s] - self.assertLess(min(ts), instant_max, f"high '{s}' execution time: {min(ts)}") + self.assertLess(max(ts), instant_max, f"high '{s}' execution time: {max(ts)}") self.assertLess(np.mean(ts), avg_max, f"high avg '{s}' execution time: {np.mean(ts)}") - result += f"'{s}' execution time: {min(ts)}\n" - result += f"'{s}' avg execution time: {np.mean(ts)}\n" + result += f"'{s}' execution time: min {min(ts):.5f}s\n" + result += f"'{s}' execution time: max {max(ts):.5f}s\n" + result += f"'{s}' execution time: mean {np.mean(ts):.5f}s\n" result += "------------------------------------------------\n" print(result) @@ -227,18 +249,17 @@ class TestOnroad(unittest.TestCase): result += "----------------- Model Timing -----------------\n" result += "------------------------------------------------\n" # TODO: this went up when plannerd cpu usage increased, why? - cfgs = [("driverState", 0.028, 0.026)] - if EON: - cfgs += [("modelV2", 0.045, 0.04)] - else: - cfgs += [("modelV2", 0.038, 0.036), ("driverState", 0.028, 0.026)] - + cfgs = [ + ("modelV2", 0.050, 0.036), + ("driverStateV2", 0.050, 0.026), + ] for (s, instant_max, avg_max) in cfgs: ts = [getattr(getattr(m, s), "modelExecutionTime") for m in self.lr if m.which() == s] - self.assertLess(min(ts), instant_max, f"high '{s}' execution time: {min(ts)}") + self.assertLess(max(ts), instant_max, f"high '{s}' execution time: {max(ts)}") self.assertLess(np.mean(ts), avg_max, f"high avg '{s}' execution time: {np.mean(ts)}") - result += f"'{s}' execution time: {min(ts)}\n" - result += f"'{s}' avg execution time: {np.mean(ts)}\n" + result += f"'{s}' execution time: min {min(ts):.5f}s\n" + result += f"'{s}' execution time: max {max(ts):.5f}s\n" + result += f"'{s}' execution time: mean {np.mean(ts):.5f}s\n" result += "------------------------------------------------\n" print(result) diff --git a/selfdrive/test/test_routes.py b/selfdrive/test/test_routes.py deleted file mode 100644 index 02bcd36b19..0000000000 --- a/selfdrive/test/test_routes.py +++ /dev/null @@ -1,198 +0,0 @@ -#!/usr/bin/env python3 -from collections import namedtuple - -from selfdrive.car.chrysler.values import CAR as CHRYSLER -from selfdrive.car.gm.values import CAR as GM -from selfdrive.car.honda.values import CAR as HONDA -from selfdrive.car.hyundai.values import CAR as HYUNDAI -from selfdrive.car.nissan.values import CAR as NISSAN -from selfdrive.car.mazda.values import CAR as MAZDA -from selfdrive.car.subaru.values import CAR as SUBARU -from selfdrive.car.toyota.values import CAR as TOYOTA -from selfdrive.car.volkswagen.values import CAR as VOLKSWAGEN -from selfdrive.car.tesla.values import CAR as TESLA - -# TODO: add routes for these cars -non_tested_cars = [ - GM.CADILLAC_ATS, - GM.HOLDEN_ASTRA, - GM.MALIBU, - HYUNDAI.ELANTRA_GT_I30, - HYUNDAI.GENESIS_G90, - HYUNDAI.KIA_OPTIMA_H, -] - -TestRoute = namedtuple('TestRoute', ['route', 'car_fingerprint']) - -routes = [ - TestRoute("0c94aa1e1296d7c6|2021-05-05--19-48-37", CHRYSLER.JEEP_CHEROKEE), - TestRoute("91dfedae61d7bd75|2021-05-22--20-07-52", CHRYSLER.JEEP_CHEROKEE_2019), - TestRoute("420a8e183f1aed48|2020-03-05--07-15-29", CHRYSLER.PACIFICA_2017_HYBRID), - TestRoute("43a685a66291579b|2021-05-27--19-47-29", CHRYSLER.PACIFICA_2018), - TestRoute("378472f830ee7395|2021-05-28--07-38-43", CHRYSLER.PACIFICA_2018_HYBRID), - TestRoute("8190c7275a24557b|2020-01-29--08-33-58", CHRYSLER.PACIFICA_2019_HYBRID), - TestRoute("3d84727705fecd04|2021-05-25--08-38-56", CHRYSLER.PACIFICA_2020), - - #TestRoute("f1b4c567731f4a1b|2018-04-30--10-15-35", FORD.FUSION), - - TestRoute("7cc2a8365b4dd8a9|2018-12-02--12-10-44", GM.ACADIA), - TestRoute("aa20e335f61ba898|2019-02-05--16-59-04", GM.BUICK_REGAL), - TestRoute("46460f0da08e621e|2021-10-26--07-21-46", GM.ESCALADE_ESV), - TestRoute("c950e28c26b5b168|2018-05-30--22-03-41", GM.VOLT), - - TestRoute("0e7a2ba168465df5|2020-10-18--14-14-22", HONDA.ACURA_RDX_3G), - TestRoute("a74b011b32b51b56|2020-07-26--17-09-36", HONDA.CIVIC), - TestRoute("a859a044a447c2b0|2020-03-03--18-42-45", HONDA.CRV_EU), - TestRoute("68aac44ad69f838e|2021-05-18--20-40-52", HONDA.CRV), - TestRoute("14fed2e5fa0aa1a5|2021-05-25--14-59-42", HONDA.CRV_HYBRID), - TestRoute("52f3e9ae60c0d886|2021-05-23--15-59-43", HONDA.FIT), - TestRoute("2c4292a5cd10536c|2021-08-19--21-32-15", HONDA.FREED), - TestRoute("03be5f2fd5c508d1|2020-04-19--18-44-15", HONDA.HRV), - TestRoute("917b074700869333|2021-05-24--20-40-20", HONDA.ACURA_ILX), - TestRoute("81722949a62ea724|2019-04-06--15-19-25", HONDA.ODYSSEY_CHN), - TestRoute("08a3deb07573f157|2020-03-06--16-11-19", HONDA.ACCORD), # 1.5T - TestRoute("1da5847ac2488106|2021-05-24--19-31-50", HONDA.ACCORD), # 2.0T - TestRoute("085ac1d942c35910|2021-03-25--20-11-15", HONDA.ACCORD), # 2021 with new style HUD msgs - TestRoute("07585b0da3c88459|2021-05-26--18-52-04", HONDA.ACCORDH), - TestRoute("f29e2b57a55e7ad5|2021-03-24--20-52-38", HONDA.ACCORDH), # 2021 with new style HUD msgs - TestRoute("1ad763dd22ef1a0e|2020-02-29--18-37-03", HONDA.CRV_5G), - TestRoute("0a96f86fcfe35964|2020-02-05--07-25-51", HONDA.ODYSSEY), - TestRoute("d83f36766f8012a5|2020-02-05--18-42-21", HONDA.CIVIC_BOSCH_DIESEL), - TestRoute("f0890d16a07a236b|2021-05-25--17-27-22", HONDA.INSIGHT), - TestRoute("07d37d27996096b6|2020-03-04--21-57-27", HONDA.PILOT), - TestRoute("684e8f96bd491a0e|2021-11-03--11-08-42", HONDA.PASSPORT), - TestRoute("0a78dfbacc8504ef|2020-03-04--13-29-55", HONDA.CIVIC_BOSCH), - TestRoute("f34a60d68d83b1e5|2020-10-06--14-35-55", HONDA.ACURA_RDX), - TestRoute("54fd8451b3974762|2021-04-01--14-50-10", HONDA.RIDGELINE), - TestRoute("2d5808fae0b38ac6|2021-09-01--17-14-11", HONDA.HONDA_E), - - TestRoute("6fe86b4e410e4c37|2020-07-22--16-27-13", HYUNDAI.HYUNDAI_GENESIS), - TestRoute("70c5bec28ec8e345|2020-08-08--12-22-23", HYUNDAI.GENESIS_G70), - TestRoute("6b301bf83f10aa90|2020-11-22--16-45-07", HYUNDAI.GENESIS_G80), - TestRoute("38bfd238edecbcd7|2018-08-29--22-02-15", HYUNDAI.SANTA_FE), - TestRoute("bf43d9df2b660eb0|2021-09-23--14-16-37", HYUNDAI.SANTA_FE_2022), - TestRoute("37398f32561a23ad|2021-11-18--00-11-35", HYUNDAI.SANTA_FE_HEV_2022), - TestRoute("656ac0d830792fcc|2021-12-28--14-45-56", HYUNDAI.SANTA_FE_PHEV_2022), - TestRoute("e0e98335f3ebc58f|2021-03-07--16-38-29", HYUNDAI.KIA_CEED), - TestRoute("7653b2bce7bcfdaa|2020-03-04--15-34-32", HYUNDAI.KIA_OPTIMA), - TestRoute("c75a59efa0ecd502|2021-03-11--20-52-55", HYUNDAI.KIA_SELTOS), - TestRoute("5b7c365c50084530|2020-04-15--16-13-24", HYUNDAI.SONATA), - TestRoute("b2a38c712dcf90bd|2020-05-18--18-12-48", HYUNDAI.SONATA_LF), - TestRoute("5875672fc1d4bf57|2020-07-23--21-33-28", HYUNDAI.KIA_SORENTO), - TestRoute("9c917ba0d42ffe78|2020-04-17--12-43-19", HYUNDAI.PALISADE), - TestRoute("fa8db5869167f821|2021-06-10--22-50-10", HYUNDAI.IONIQ_PHEV), - TestRoute("2c5cf2dd6102e5da|2020-12-17--16-06-44", HYUNDAI.IONIQ_EV_2020), - TestRoute("610ebb9faaad6b43|2020-06-13--15-28-36", HYUNDAI.IONIQ_EV_LTD), - TestRoute("2c5cf2dd6102e5da|2020-06-26--16-00-08", HYUNDAI.IONIQ), - TestRoute("ab59fe909f626921|2021-10-18--18-34-28", HYUNDAI.IONIQ_HEV_2022), - TestRoute("22d955b2cd499c22|2020-08-10--19-58-21", HYUNDAI.KONA), - TestRoute("efc48acf44b1e64d|2021-05-28--21-05-04", HYUNDAI.KONA_EV), - TestRoute("49f3c13141b6bc87|2021-07-28--08-05-13", HYUNDAI.KONA_HEV), - TestRoute("5dddcbca6eb66c62|2020-07-26--13-24-19", HYUNDAI.KIA_STINGER), - TestRoute("d624b3d19adce635|2020-08-01--14-59-12", HYUNDAI.VELOSTER), - TestRoute("007d5e4ad9f86d13|2021-09-30--15-09-23", HYUNDAI.KIA_K5_2021), - TestRoute("50c6c9b85fd1ff03|2020-10-26--17-56-06", HYUNDAI.KIA_NIRO_EV), - TestRoute("173219cf50acdd7b|2021-07-05--10-27-41", HYUNDAI.KIA_NIRO_HEV), - TestRoute("34a875f29f69841a|2021-07-29--13-02-09", HYUNDAI.KIA_NIRO_HEV_2021), - TestRoute("50a2212c41f65c7b|2021-05-24--16-22-06", HYUNDAI.KIA_FORTE), - TestRoute("c5ac319aa9583f83|2021-06-01--18-18-31", HYUNDAI.ELANTRA), - TestRoute("82e9cdd3f43bf83e|2021-05-15--02-42-51", HYUNDAI.ELANTRA_2021), - TestRoute("715ac05b594e9c59|2021-06-20--16-21-07", HYUNDAI.ELANTRA_HEV_2021), - TestRoute("7120aa90bbc3add7|2021-08-02--07-12-31", HYUNDAI.SONATA_HYBRID), - TestRoute("715ac05b594e9c59|2021-10-27--23-24-56", HYUNDAI.GENESIS_G70_2020), - - TestRoute("00c829b1b7613dea|2021-06-24--09-10-10", TOYOTA.ALPHARD_TSS2), - TestRoute("000cf3730200c71c|2021-05-24--10-42-05", TOYOTA.AVALON), - TestRoute("0bb588106852abb7|2021-05-26--12-22-01", TOYOTA.AVALON_2019), - TestRoute("87bef2930af86592|2021-05-30--09-40-54", TOYOTA.AVALONH_2019), - TestRoute("e9966711cfb04ce3|2022-01-11--07-59-43", TOYOTA.AVALON_TSS2), - TestRoute("6cdecc4728d4af37|2020-02-23--15-44-18", TOYOTA.CAMRY), - TestRoute("3456ad0cd7281b24|2020-12-13--17-45-56", TOYOTA.CAMRY_TSS2), - TestRoute("ffccc77938ddbc44|2021-01-04--16-55-41", TOYOTA.CAMRYH_TSS2), - TestRoute("54034823d30962f5|2021-05-24--06-37-34", TOYOTA.CAMRYH), - TestRoute("4e45c89c38e8ec4d|2021-05-02--02-49-28", TOYOTA.COROLLA), - TestRoute("5f5afb36036506e4|2019-05-14--02-09-54", TOYOTA.COROLLA_TSS2), - TestRoute("5ceff72287a5c86c|2019-10-19--10-59-02", TOYOTA.COROLLAH_TSS2), - TestRoute("d2525c22173da58b|2021-04-25--16-47-04", TOYOTA.PRIUS), - TestRoute("b14c5b4742e6fc85|2020-07-28--19-50-11", TOYOTA.RAV4), - TestRoute("32a7df20486b0f70|2020-02-06--16-06-50", TOYOTA.RAV4H), - TestRoute("cdf2f7de565d40ae|2019-04-25--03-53-41", TOYOTA.RAV4_TSS2), - TestRoute("7e34a988419b5307|2019-12-18--19-13-30", TOYOTA.RAV4H_TSS2), - TestRoute("e6a24be49a6cd46e|2019-10-29--10-52-42", TOYOTA.LEXUS_ES_TSS2), - TestRoute("25057fa6a5a63dfb|2020-03-04--08-44-23", TOYOTA.LEXUS_CTH), - TestRoute("f49e8041283f2939|2019-05-30--11-51-51", TOYOTA.LEXUS_ESH_TSS2), - TestRoute("37041c500fd30100|2020-12-30--12-17-24", TOYOTA.LEXUS_ESH), - TestRoute("32696cea52831b02|2021-11-19--18-13-30", TOYOTA.LEXUS_RC), - TestRoute("886fcd8408d570e9|2020-01-29--05-11-22", TOYOTA.LEXUS_RX), - TestRoute("886fcd8408d570e9|2020-01-29--02-18-55", TOYOTA.LEXUS_RX), - TestRoute("d27ad752e9b08d4f|2021-05-26--19-39-51", TOYOTA.LEXUS_RXH), - TestRoute("01b22eb2ed121565|2020-02-02--11-25-51", TOYOTA.LEXUS_RX_TSS2), - TestRoute("b74758c690a49668|2020-05-20--15-58-57", TOYOTA.LEXUS_RXH_TSS2), - TestRoute("ec429c0f37564e3c|2020-02-01--17-28-12", TOYOTA.LEXUS_NXH), - TestRoute("964c09eb11ca8089|2020-11-03--22-04-00", TOYOTA.LEXUS_NX), - TestRoute("3fd5305f8b6ca765|2021-04-28--19-26-49", TOYOTA.LEXUS_NX_TSS2), - TestRoute("0a302ffddbb3e3d3|2020-02-08--16-19-08", TOYOTA.HIGHLANDER_TSS2), - TestRoute("437e4d2402abf524|2021-05-25--07-58-50", TOYOTA.HIGHLANDERH_TSS2), - TestRoute("3183cd9b021e89ce|2021-05-25--10-34-44", TOYOTA.HIGHLANDER), - TestRoute("80d16a262e33d57f|2021-05-23--20-01-43", TOYOTA.HIGHLANDERH), - TestRoute("eb6acd681135480d|2019-06-20--20-00-00", TOYOTA.SIENNA), - TestRoute("2e07163a1ba9a780|2019-08-25--13-15-13", TOYOTA.LEXUS_IS), - TestRoute("0a0de17a1e6a2d15|2020-09-21--21-24-41", TOYOTA.PRIUS_TSS2), - TestRoute("9b36accae406390e|2021-03-30--10-41-38", TOYOTA.MIRAI), - TestRoute("cd9cff4b0b26c435|2021-05-13--15-12-39", TOYOTA.CHR), - TestRoute("57858ede0369a261|2021-05-18--20-34-20", TOYOTA.CHRH), - TestRoute("14623aae37e549f3|2021-10-24--01-20-49", TOYOTA.PRIUS_V), - - TestRoute("202c40641158a6e5|2021-09-21--09-43-24", VOLKSWAGEN.ARTEON_MK1), - TestRoute("2c68dda277d887ac|2021-05-11--15-22-20", VOLKSWAGEN.ATLAS_MK1), - TestRoute("cae14e88932eb364|2021-03-26--14-43-28", VOLKSWAGEN.GOLF_MK7), - TestRoute("58a7d3b707987d65|2021-03-25--17-26-37", VOLKSWAGEN.JETTA_MK7), - TestRoute("4d134e099430fba2|2021-03-26--00-26-06", VOLKSWAGEN.PASSAT_MK8), - TestRoute("0cd0b7f7e31a3853|2021-11-03--19-30-22", VOLKSWAGEN.POLO_MK6), - TestRoute("7d82b2f3a9115f1f|2021-10-21--15-39-42", VOLKSWAGEN.TAOS_MK1), - TestRoute("2744c89a8dda9a51|2021-07-24--21-28-06", VOLKSWAGEN.TCROSS_MK1), - TestRoute("2cef8a0b898f331a|2021-03-25--20-13-57", VOLKSWAGEN.TIGUAN_MK2), - TestRoute("a589dcc642fdb10a|2021-06-14--20-54-26", VOLKSWAGEN.TOURAN_MK2), - TestRoute("a459f4556782eba1|2021-09-19--09-48-00", VOLKSWAGEN.TRANSPORTER_T61), - TestRoute("0cd0b7f7e31a3853|2021-11-18--00-38-32", VOLKSWAGEN.TROC_MK1), - TestRoute("07667b885add75fd|2021-01-23--19-48-42", VOLKSWAGEN.AUDI_A3_MK3), - TestRoute("6c6b466346192818|2021-06-06--14-17-47", VOLKSWAGEN.AUDI_Q2_MK1), - TestRoute("0cd0b7f7e31a3853|2021-12-03--03-12-05", VOLKSWAGEN.AUDI_Q3_MK2), - TestRoute("8f205bdd11bcbb65|2021-03-26--01-00-17", VOLKSWAGEN.SEAT_ATECA_MK1), - TestRoute("fc6b6c9a3471c846|2021-05-27--13-39-56", VOLKSWAGEN.SEAT_LEON_MK3), - TestRoute("12d6ae3057c04b0d|2021-09-15--00-04-07", VOLKSWAGEN.SKODA_KAMIQ_MK1), - TestRoute("12d6ae3057c04b0d|2021-09-04--21-21-21", VOLKSWAGEN.SKODA_KAROQ_MK1), - TestRoute("90434ff5d7c8d603|2021-03-15--12-07-31", VOLKSWAGEN.SKODA_KODIAQ_MK1), - TestRoute("66e5edc3a16459c5|2021-05-25--19-00-29", VOLKSWAGEN.SKODA_OCTAVIA_MK3), - TestRoute("026b6d18fba6417f|2021-03-26--09-17-04", VOLKSWAGEN.SKODA_SCALA_MK1), - TestRoute("b2e9858e29db492b|2021-03-26--16-58-42", VOLKSWAGEN.SKODA_SUPERB_MK3), - - TestRoute("3c8f0c502e119c1c|2020-06-30--12-58-02", SUBARU.ASCENT), - TestRoute("c321c6b697c5a5ff|2020-06-23--11-04-33", SUBARU.FORESTER), - TestRoute("791340bc01ed993d|2019-03-10--16-28-08", SUBARU.IMPREZA), - TestRoute("8bf7e79a3ce64055|2021-05-24--09-36-27", SUBARU.IMPREZA_2020), - # Dashcam - TestRoute("95441c38ae8c130e|2020-06-08--12-10-17", SUBARU.FORESTER_PREGLOBAL), - # Dashcam - TestRoute("df5ca7660000fba8|2020-06-16--17-37-19", SUBARU.LEGACY_PREGLOBAL), - # Dashcam - TestRoute("5ab784f361e19b78|2020-06-08--16-30-41", SUBARU.OUTBACK_PREGLOBAL), - # Dashcam - TestRoute("e19eb5d5353b1ac1|2020-08-09--14-37-56", SUBARU.OUTBACK_PREGLOBAL_2018), - - TestRoute("fbbfa6af821552b9|2020-03-03--08-09-43", NISSAN.XTRAIL), - TestRoute("5b7c365c50084530|2020-03-25--22-10-13", NISSAN.LEAF), - TestRoute("22c3dcce2dd627eb|2020-12-30--16-38-48", NISSAN.LEAF_IC), - TestRoute("059ab9162e23198e|2020-05-30--09-41-01", NISSAN.ROGUE), - TestRoute("b72d3ec617c0a90f|2020-12-11--15-38-17", NISSAN.ALTIMA), - - TestRoute("32a319f057902bb3|2020-04-27--15-18-58", MAZDA.CX5), - TestRoute("10b5a4b380434151|2020-08-26--17-11-45", MAZDA.CX9), - TestRoute("74f1038827005090|2020-08-26--20-05-50", MAZDA.MAZDA3), - TestRoute("fb53c640f499b73d|2021-06-01--04-17-56", MAZDA.MAZDA6), - TestRoute("f6d5b1a9d7a1c92e|2021-07-08--06-56-59", MAZDA.CX9_2021), - TestRoute("a4af1602d8e668ac|2022-02-03--12-17-07", MAZDA.CX5_2022), - - TestRoute("6c14ee12b74823ce|2021-06-30--11-49-02", TESLA.AP1_MODELS), - TestRoute("bb50caf5f0945ab1|2021-06-19--17-20-18", TESLA.AP2_MODELS), -] diff --git a/selfdrive/test/test_updated.py b/selfdrive/test/test_updated.py index 4c0ed2fddf..aab8b256ac 100755 --- a/selfdrive/test/test_updated.py +++ b/selfdrive/test/test_updated.py @@ -113,7 +113,7 @@ class TestUpdated(unittest.TestCase): def _wait_for_update(self, timeout=30, clear_param=False): if clear_param: - self.params.delete("LastUpdateTime") + self.params.remove("LastUpdateTime") self._update_now() t = self._read_param("LastUpdateTime", timeout=timeout) @@ -166,7 +166,7 @@ class TestUpdated(unittest.TestCase): last_update_time = datetime.datetime.fromisoformat(t) td = datetime.datetime.utcnow() - last_update_time self.assertLess(td.total_seconds(), 10) - self.params.delete("LastUpdateTime") + self.params.remove("LastUpdateTime") # wait a bit for the rest of the params to be written time.sleep(0.1) @@ -232,7 +232,7 @@ class TestUpdated(unittest.TestCase): # run for a cycle with no update self._wait_for_update(clear_param=True) - self.params.delete("LastUpdateTime") + self.params.remove("LastUpdateTime") first_mtime = os.path.getmtime(overlay_init_fn) # touch a file in the basedir diff --git a/selfdrive/test/update_ci_routes.py b/selfdrive/test/update_ci_routes.py index 3a392b4b36..a2b971999c 100755 --- a/selfdrive/test/update_ci_routes.py +++ b/selfdrive/test/update_ci_routes.py @@ -1,53 +1,63 @@ #!/usr/bin/env python3 +from functools import lru_cache import sys import subprocess +from tqdm import tqdm from azure.storage.blob import BlockBlobService # pylint: disable=import-error -from selfdrive.test.test_routes import routes as test_car_models_routes -from selfdrive.test.process_replay.test_processes import original_segments as replay_segments +from selfdrive.car.tests.routes import routes as test_car_models_routes +from selfdrive.test.process_replay.test_processes import source_segments as replay_segments from xx.chffr.lib import azureutil # pylint: disable=import-error from xx.chffr.lib.storage import _DATA_ACCOUNT_PRODUCTION, _DATA_ACCOUNT_CI, _DATA_BUCKET_PRODUCTION # pylint: disable=import-error SOURCES = [ (_DATA_ACCOUNT_PRODUCTION, _DATA_BUCKET_PRODUCTION), - (_DATA_ACCOUNT_PRODUCTION, "preserve"), (_DATA_ACCOUNT_CI, "commadataci"), ] -DEST_KEY = azureutil.get_user_token(_DATA_ACCOUNT_CI, "openpilotci") -SOURCE_KEYS = [azureutil.get_user_token(account, bucket) for account, bucket in SOURCES] -SERVICE = BlockBlobService(_DATA_ACCOUNT_CI, sas_token=DEST_KEY) -def upload_route(path): +@lru_cache +def get_azure_keys(): + dest_key = azureutil.get_user_token(_DATA_ACCOUNT_CI, "openpilotci") + source_keys = [azureutil.get_user_token(account, bucket) for account, bucket in SOURCES] + service = BlockBlobService(_DATA_ACCOUNT_CI, sas_token=dest_key) + return dest_key, source_keys, service + + +def upload_route(path, exclude_patterns=None): + dest_key, _, _ = get_azure_keys() + if exclude_patterns is None: + exclude_patterns = ['*/dcamera.hevc'] + r, n = path.rsplit("--", 1) + r = '/'.join(r.split('/')[-2:]) # strip out anything extra in the path destpath = f"{r}/{n}" cmd = [ "azcopy", "copy", f"{path}/*", - f"https://{_DATA_ACCOUNT_CI}.blob.core.windows.net/openpilotci/{destpath}?{DEST_KEY}", + f"https://{_DATA_ACCOUNT_CI}.blob.core.windows.net/openpilotci/{destpath}?{dest_key}", "--recursive=false", "--overwrite=false", - "--exclude-pattern=*/dcamera.hevc", - "--exclude-pattern=*.mkv", - ] + ] + [f"--exclude-pattern={p}" for p in exclude_patterns] subprocess.check_call(cmd) def sync_to_ci_public(route): + dest_key, source_keys, service = get_azure_keys() key_prefix = route.replace('|', '/') dongle_id = key_prefix.split('/')[0] - if next(azureutil.list_all_blobs(SERVICE, "openpilotci", prefix=key_prefix), None) is not None: + if next(azureutil.list_all_blobs(service, "openpilotci", prefix=key_prefix), None) is not None: return True print(f"Uploading {route}") - for (source_account, source_bucket), source_key in zip(SOURCES, SOURCE_KEYS): + for (source_account, source_bucket), source_key in zip(SOURCES, source_keys): print(f"Trying {source_account}/{source_bucket}") cmd = [ "azcopy", "copy", f"https://{source_account}.blob.core.windows.net/{source_bucket}/{key_prefix}?{source_key}", - f"https://{_DATA_ACCOUNT_CI}.blob.core.windows.net/openpilotci/{dongle_id}?{DEST_KEY}", + f"https://{_DATA_ACCOUNT_CI}.blob.core.windows.net/openpilotci/{dongle_id}?{dest_key}", "--recursive=true", "--overwrite=false", "--exclude-pattern=*/dcamera.hevc", @@ -70,11 +80,11 @@ if __name__ == "__main__": to_sync = sys.argv[1:] if not len(to_sync): - # sync routes from test_routes and process replay + # sync routes from the car tests routes and process replay to_sync.extend([rt.route for rt in test_car_models_routes]) to_sync.extend([s[1].rsplit('--', 1)[0] for s in replay_segments]) - for r in to_sync: + for r in tqdm(to_sync): if not sync_to_ci_public(r): failed_routes.append(r) diff --git a/selfdrive/thermald/fan_controller.py b/selfdrive/thermald/fan_controller.py new file mode 100644 index 0000000000..2094faeaa7 --- /dev/null +++ b/selfdrive/thermald/fan_controller.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 +from abc import ABC, abstractmethod + +from common.realtime import DT_TRML +from common.numpy_fast import interp +from system.swaglog import cloudlog +from selfdrive.controls.lib.pid import PIDController + +class BaseFanController(ABC): + @abstractmethod + def update(self, max_cpu_temp: float, ignition: bool) -> int: + pass + + +class TiciFanController(BaseFanController): + def __init__(self) -> None: + super().__init__() + cloudlog.info("Setting up TICI fan handler") + + self.last_ignition = False + self.controller = PIDController(k_p=0, k_i=4e-3, k_f=1, neg_limit=-80, pos_limit=0, rate=(1 / DT_TRML)) + + def update(self, max_cpu_temp: float, ignition: bool) -> int: + self.controller.neg_limit = -(80 if ignition else 30) + self.controller.pos_limit = -(30 if ignition else 0) + + if ignition != self.last_ignition: + self.controller.reset() + + error = 70 - max_cpu_temp + fan_pwr_out = -int(self.controller.update( + error=error, + feedforward=interp(max_cpu_temp, [60.0, 100.0], [0, -80]) + )) + + self.last_ignition = ignition + return fan_pwr_out + diff --git a/selfdrive/thermald/power_monitoring.py b/selfdrive/thermald/power_monitoring.py index 0dc4c5a1d3..85e9510eb7 100644 --- a/selfdrive/thermald/power_monitoring.py +++ b/selfdrive/thermald/power_monitoring.py @@ -1,27 +1,23 @@ -import random import threading -import time -from statistics import mean from typing import Optional -from cereal import log from common.params import Params, put_nonblocking from common.realtime import sec_since_boot -from selfdrive.hardware import HARDWARE -from selfdrive.swaglog import cloudlog +from system.hardware import HARDWARE +from system.swaglog import cloudlog from selfdrive.statsd import statlog -CAR_VOLTAGE_LOW_PASS_K = 0.091 # LPF gain for 5s tau (dt/tau / (dt/tau + 1)) +CAR_VOLTAGE_LOW_PASS_K = 0.011 # LPF gain for 45s tau (dt/tau / (dt/tau + 1)) -# A C2 uses about 1W while idling, and 30h seens like a good shutoff for most cars # While driving, a battery charges completely in about 30-60 minutes CAR_BATTERY_CAPACITY_uWh = 30e6 CAR_CHARGING_RATE_W = 45 -VBATT_PAUSE_CHARGING = 11.0 # Lower limit on the LPF car battery voltage +VBATT_PAUSE_CHARGING = 11.8 # Lower limit on the LPF car battery voltage VBATT_INSTANT_PAUSE_CHARGING = 7.0 # Lower limit on the instant car battery voltage measurements to avoid triggering on instant power loss MAX_TIME_OFFROAD_S = 30*3600 MIN_ON_TIME_S = 3600 +VOLTAGE_SHUTDOWN_MIN_OFFROAD_TIME_S = 60 class PowerMonitoring: def __init__(self): @@ -42,12 +38,12 @@ class PowerMonitoring: self.car_battery_capacity_uWh = max((CAR_BATTERY_CAPACITY_uWh / 10), int(car_battery_capacity_uWh)) # Calculation tick - def calculate(self, peripheralState, ignition): + def calculate(self, voltage: Optional[int], ignition: bool): try: now = sec_since_boot() # If peripheralState is None, we're probably not in a car, so we don't care - if peripheralState is None or peripheralState.pandaType == log.PandaState.PandaType.unknown: + if voltage is None: with self.integration_lock: self.last_measurement_time = None self.next_pulsed_measurement_time = None @@ -55,8 +51,8 @@ class PowerMonitoring: return # Low-pass battery voltage - self.car_voltage_instant_mV = peripheralState.voltage - self.car_voltage_mV = ((peripheralState.voltage * CAR_VOLTAGE_LOW_PASS_K) + (self.car_voltage_mV * (1 - CAR_VOLTAGE_LOW_PASS_K))) + self.car_voltage_instant_mV = voltage + self.car_voltage_mV = ((voltage * CAR_VOLTAGE_LOW_PASS_K) + (self.car_voltage_mV * (1 - CAR_VOLTAGE_LOW_PASS_K))) statlog.gauge("car_voltage", self.car_voltage_mV / 1e3) # Cap the car battery power and save it in a param every 10-ish seconds @@ -82,56 +78,8 @@ class PowerMonitoring: self.car_battery_capacity_uWh += (CAR_CHARGING_RATE_W * 1e6 * integration_time_h) self.last_measurement_time = now else: - # No ignition, we integrate the offroad power used by the device - is_uno = peripheralState.pandaType == log.PandaState.PandaType.uno # Get current power draw somehow - current_power = HARDWARE.get_current_power_draw() # pylint: disable=assignment-from-none - if current_power is not None: - pass - elif HARDWARE.get_battery_status() == 'Discharging': - # If the battery is discharging, we can use this measurement - # On C2: this is low by about 10-15%, probably mostly due to UNO draw not being factored in - current_power = ((HARDWARE.get_battery_voltage() / 1000000) * (HARDWARE.get_battery_current() / 1000000)) - elif (self.next_pulsed_measurement_time is not None) and (self.next_pulsed_measurement_time <= now): - # TODO: Figure out why this is off by a factor of 3/4??? - FUDGE_FACTOR = 1.33 - - # Turn off charging for about 10 sec in a thread that does not get killed on SIGINT, and perform measurement here to avoid blocking thermal - def perform_pulse_measurement(now): - try: - HARDWARE.set_battery_charging(False) - time.sleep(5) - - # Measure for a few sec to get a good average - voltages = [] - currents = [] - for _ in range(6): - voltages.append(HARDWARE.get_battery_voltage()) - currents.append(HARDWARE.get_battery_current()) - time.sleep(1) - current_power = ((mean(voltages) / 1000000) * (mean(currents) / 1000000)) - - self._perform_integration(now, current_power * FUDGE_FACTOR) - - # Enable charging again - HARDWARE.set_battery_charging(True) - except Exception: - cloudlog.exception("Pulsed power measurement failed") - - # Start pulsed measurement and return - threading.Thread(target=perform_pulse_measurement, args=(now,)).start() - self.next_pulsed_measurement_time = None - return - - elif self.next_pulsed_measurement_time is None and not is_uno: - # On a charging EON with black panda, or drawing more than 400mA out of a white/grey one - # Only way to get the power draw is to turn off charging for a few sec and check what the discharging rate is - # We shouldn't do this very often, so make sure it has been some long-ish random time interval - self.next_pulsed_measurement_time = now + random.randint(120, 180) - return - else: - # Do nothing - return + current_power = HARDWARE.get_current_power_draw() # Do the integration self._perform_integration(now, current_power) @@ -159,34 +107,23 @@ class PowerMonitoring: def get_car_battery_capacity(self) -> int: return int(self.car_battery_capacity_uWh) - # See if we need to disable charging - def should_disable_charging(self, ignition: bool, in_car: bool, offroad_timestamp: Optional[float]) -> bool: - if offroad_timestamp is None: - return False - - now = sec_since_boot() - disable_charging = False - disable_charging |= (now - offroad_timestamp) > MAX_TIME_OFFROAD_S - disable_charging |= (self.car_voltage_mV < (VBATT_PAUSE_CHARGING * 1e3)) and (self.car_voltage_instant_mV > (VBATT_INSTANT_PAUSE_CHARGING * 1e3)) - disable_charging |= (self.car_battery_capacity_uWh <= 0) - disable_charging &= not ignition - disable_charging &= (not self.params.get_bool("DisablePowerDown")) - disable_charging &= in_car - disable_charging |= self.params.get_bool("ForcePowerDown") - return disable_charging - # See if we need to shutdown - def should_shutdown(self, peripheralState, ignition, in_car, offroad_timestamp, started_seen): + def should_shutdown(self, ignition: bool, in_car: bool, offroad_timestamp: Optional[float], started_seen: bool): if offroad_timestamp is None: return False now = sec_since_boot() - panda_charging = (peripheralState.usbPowerMode != log.PeripheralState.UsbPowerMode.client) - BATT_PERC_OFF = 10 - should_shutdown = False - # Wait until we have shut down charging before powering down - should_shutdown |= (not panda_charging and self.should_disable_charging(ignition, in_car, offroad_timestamp)) - should_shutdown |= ((HARDWARE.get_battery_capacity() < BATT_PERC_OFF) and (not HARDWARE.get_battery_charging()) and ((now - offroad_timestamp) > 60)) + offroad_time = (now - offroad_timestamp) + low_voltage_shutdown = (self.car_voltage_mV < (VBATT_PAUSE_CHARGING * 1e3) and + self.car_voltage_instant_mV > (VBATT_INSTANT_PAUSE_CHARGING * 1e3) and + offroad_time > VOLTAGE_SHUTDOWN_MIN_OFFROAD_TIME_S) + should_shutdown |= offroad_time > MAX_TIME_OFFROAD_S + should_shutdown |= low_voltage_shutdown + should_shutdown |= (self.car_battery_capacity_uWh <= 0) + should_shutdown &= not ignition + should_shutdown &= (not self.params.get_bool("DisablePowerDown")) + should_shutdown &= in_car + should_shutdown |= self.params.get_bool("ForcePowerDown") should_shutdown &= started_seen or (now > MIN_ON_TIME_S) return should_shutdown diff --git a/selfdrive/thermald/tests/test_fan_controller.py b/selfdrive/thermald/tests/test_fan_controller.py new file mode 100755 index 0000000000..857866f64e --- /dev/null +++ b/selfdrive/thermald/tests/test_fan_controller.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 +import unittest +from unittest.mock import Mock, patch +from parameterized import parameterized + +from selfdrive.thermald.fan_controller import TiciFanController + +ALL_CONTROLLERS = [(TiciFanController,)] + +def patched_controller(controller_class): + with patch("os.system", new=Mock()): + return controller_class() + +class TestFanController(unittest.TestCase): + def wind_up(self, controller, ignition=True): + for _ in range(1000): + controller.update(max_cpu_temp=100, ignition=ignition) + + def wind_down(self, controller, ignition=False): + for _ in range(1000): + controller.update(max_cpu_temp=10, ignition=ignition) + + @parameterized.expand(ALL_CONTROLLERS) + def test_hot_onroad(self, controller_class): + controller = patched_controller(controller_class) + self.wind_up(controller) + self.assertGreaterEqual(controller.update(max_cpu_temp=100, ignition=True), 70) + + @parameterized.expand(ALL_CONTROLLERS) + def test_offroad_limits(self, controller_class): + controller = patched_controller(controller_class) + self.wind_up(controller) + self.assertLessEqual(controller.update(max_cpu_temp=100, ignition=False), 30) + + @parameterized.expand(ALL_CONTROLLERS) + def test_no_fan_wear(self, controller_class): + controller = patched_controller(controller_class) + self.wind_down(controller) + self.assertEqual(controller.update(max_cpu_temp=10, ignition=False), 0) + + @parameterized.expand(ALL_CONTROLLERS) + def test_limited(self, controller_class): + controller = patched_controller(controller_class) + self.wind_up(controller, ignition=True) + self.assertGreaterEqual(controller.update(max_cpu_temp=100, ignition=True), 80) + + @parameterized.expand(ALL_CONTROLLERS) + def test_windup_speed(self, controller_class): + controller = patched_controller(controller_class) + self.wind_down(controller, ignition=True) + for _ in range(10): + controller.update(max_cpu_temp=90, ignition=True) + self.assertGreaterEqual(controller.update(max_cpu_temp=90, ignition=True), 60) + +if __name__ == "__main__": + unittest.main() diff --git a/selfdrive/thermald/tests/test_power_monitoring.py b/selfdrive/thermald/tests/test_power_monitoring.py index 0086715fc6..d41e92454b 100755 --- a/selfdrive/thermald/tests/test_power_monitoring.py +++ b/selfdrive/thermald/tests/test_power_monitoring.py @@ -1,10 +1,7 @@ #!/usr/bin/env python3 import unittest from unittest.mock import patch -from parameterized import parameterized -from cereal import log -import cereal.messaging as messaging from common.params import Params params = Params() @@ -21,10 +18,8 @@ with patch("common.realtime.sec_since_boot", new=mock_sec_since_boot): CAR_CHARGING_RATE_W, VBATT_PAUSE_CHARGING TEST_DURATION_S = 50 -ALL_PANDA_TYPES = [(hw_type,) for hw_type in [log.PandaState.PandaType.whitePanda, - log.PandaState.PandaType.greyPanda, - log.PandaState.PandaType.blackPanda, - log.PandaState.PandaType.uno]] +GOOD_VOLTAGE = 12 * 1e3 +VOLTAGE_BELOW_PAUSE_CHARGING = (VBATT_PAUSE_CHARGING - 1) * 1e3 def pm_patch(name, value, constant=False): if constant: @@ -34,14 +29,8 @@ def pm_patch(name, value, constant=False): class TestPowerMonitoring(unittest.TestCase): def setUp(self): # Clear stored capacity before each test - params.delete("CarBatteryCapacity") - params.delete("DisablePowerDown") - - def mock_peripheralState(self, hw_type, car_voltage=12): - ps = messaging.new_message('peripheralState').peripheralState - ps.pandaType = hw_type - ps.voltage = car_voltage * 1e3 - return ps + params.remove("CarBatteryCapacity") + params.remove("DisablePowerDown") # Test to see that it doesn't do anything when pandaState is None def test_pandaState_present(self): @@ -52,172 +41,142 @@ class TestPowerMonitoring(unittest.TestCase): self.assertEqual(pm.get_car_battery_capacity(), (CAR_BATTERY_CAPACITY_uWh / 10)) # Test to see that it doesn't integrate offroad when ignition is True - @parameterized.expand(ALL_PANDA_TYPES) - def test_offroad_ignition(self, hw_type): + def test_offroad_ignition(self): pm = PowerMonitoring() for _ in range(10): - pm.calculate(self.mock_peripheralState(hw_type), True) + pm.calculate(GOOD_VOLTAGE, True) self.assertEqual(pm.get_power_used(), 0) # Test to see that it integrates with discharging battery - @parameterized.expand(ALL_PANDA_TYPES) - def test_offroad_integration_discharging(self, hw_type): - BATT_VOLTAGE = 4 - BATT_CURRENT = 1 - with pm_patch("HARDWARE.get_battery_voltage", BATT_VOLTAGE * 1e6), pm_patch("HARDWARE.get_battery_current", BATT_CURRENT * 1e6), \ - pm_patch("HARDWARE.get_battery_status", "Discharging"), pm_patch("HARDWARE.get_current_power_draw", None): + def test_offroad_integration_discharging(self): + POWER_DRAW = 4 + with pm_patch("HARDWARE.get_current_power_draw", POWER_DRAW): pm = PowerMonitoring() for _ in range(TEST_DURATION_S + 1): - pm.calculate(self.mock_peripheralState(hw_type), False) - expected_power_usage = ((TEST_DURATION_S/3600) * (BATT_VOLTAGE * BATT_CURRENT) * 1e6) + pm.calculate(GOOD_VOLTAGE, False) + expected_power_usage = ((TEST_DURATION_S/3600) * POWER_DRAW * 1e6) self.assertLess(abs(pm.get_power_used() - expected_power_usage), 10) # Test to check positive integration of car_battery_capacity - @parameterized.expand(ALL_PANDA_TYPES) - def test_car_battery_integration_onroad(self, hw_type): - BATT_VOLTAGE = 4 - BATT_CURRENT = 1 - with pm_patch("HARDWARE.get_battery_voltage", BATT_VOLTAGE * 1e6), pm_patch("HARDWARE.get_battery_current", BATT_CURRENT * 1e6), \ - pm_patch("HARDWARE.get_battery_status", "Discharging"), pm_patch("HARDWARE.get_current_power_draw", None): + def test_car_battery_integration_onroad(self): + POWER_DRAW = 4 + with pm_patch("HARDWARE.get_current_power_draw", POWER_DRAW): pm = PowerMonitoring() pm.car_battery_capacity_uWh = 0 for _ in range(TEST_DURATION_S + 1): - pm.calculate(self.mock_peripheralState(hw_type), True) + pm.calculate(GOOD_VOLTAGE, True) expected_capacity = ((TEST_DURATION_S/3600) * CAR_CHARGING_RATE_W * 1e6) self.assertLess(abs(pm.get_car_battery_capacity() - expected_capacity), 10) # Test to check positive integration upper limit - @parameterized.expand(ALL_PANDA_TYPES) - def test_car_battery_integration_upper_limit(self, hw_type): - BATT_VOLTAGE = 4 - BATT_CURRENT = 1 - with pm_patch("HARDWARE.get_battery_voltage", BATT_VOLTAGE * 1e6), pm_patch("HARDWARE.get_battery_current", BATT_CURRENT * 1e6), \ - pm_patch("HARDWARE.get_battery_status", "Discharging"), pm_patch("HARDWARE.get_current_power_draw", None): + def test_car_battery_integration_upper_limit(self): + POWER_DRAW = 4 + with pm_patch("HARDWARE.get_current_power_draw", POWER_DRAW): pm = PowerMonitoring() pm.car_battery_capacity_uWh = CAR_BATTERY_CAPACITY_uWh - 1000 for _ in range(TEST_DURATION_S + 1): - pm.calculate(self.mock_peripheralState(hw_type), True) + pm.calculate(GOOD_VOLTAGE, True) estimated_capacity = CAR_BATTERY_CAPACITY_uWh + (CAR_CHARGING_RATE_W / 3600 * 1e6) self.assertLess(abs(pm.get_car_battery_capacity() - estimated_capacity), 10) # Test to check negative integration of car_battery_capacity - @parameterized.expand(ALL_PANDA_TYPES) - def test_car_battery_integration_offroad(self, hw_type): - BATT_VOLTAGE = 4 - BATT_CURRENT = 1 - with pm_patch("HARDWARE.get_battery_voltage", BATT_VOLTAGE * 1e6), pm_patch("HARDWARE.get_battery_current", BATT_CURRENT * 1e6), \ - pm_patch("HARDWARE.get_battery_status", "Discharging"), pm_patch("HARDWARE.get_current_power_draw", None): + def test_car_battery_integration_offroad(self): + POWER_DRAW = 4 + with pm_patch("HARDWARE.get_current_power_draw", POWER_DRAW): pm = PowerMonitoring() pm.car_battery_capacity_uWh = CAR_BATTERY_CAPACITY_uWh for _ in range(TEST_DURATION_S + 1): - pm.calculate(self.mock_peripheralState(hw_type), False) - expected_capacity = CAR_BATTERY_CAPACITY_uWh - ((TEST_DURATION_S/3600) * (BATT_VOLTAGE * BATT_CURRENT) * 1e6) + pm.calculate(GOOD_VOLTAGE, False) + expected_capacity = CAR_BATTERY_CAPACITY_uWh - ((TEST_DURATION_S/3600) * POWER_DRAW * 1e6) self.assertLess(abs(pm.get_car_battery_capacity() - expected_capacity), 10) # Test to check negative integration lower limit - @parameterized.expand(ALL_PANDA_TYPES) - def test_car_battery_integration_lower_limit(self, hw_type): - BATT_VOLTAGE = 4 - BATT_CURRENT = 1 - with pm_patch("HARDWARE.get_battery_voltage", BATT_VOLTAGE * 1e6), pm_patch("HARDWARE.get_battery_current", BATT_CURRENT * 1e6), \ - pm_patch("HARDWARE.get_battery_status", "Discharging"), pm_patch("HARDWARE.get_current_power_draw", None): + def test_car_battery_integration_lower_limit(self): + POWER_DRAW = 4 + with pm_patch("HARDWARE.get_current_power_draw", POWER_DRAW): pm = PowerMonitoring() pm.car_battery_capacity_uWh = 1000 for _ in range(TEST_DURATION_S + 1): - pm.calculate(self.mock_peripheralState(hw_type), False) - estimated_capacity = 0 - ((1/3600) * (BATT_VOLTAGE * BATT_CURRENT) * 1e6) + pm.calculate(GOOD_VOLTAGE, False) + estimated_capacity = 0 - ((1/3600) * POWER_DRAW * 1e6) self.assertLess(abs(pm.get_car_battery_capacity() - estimated_capacity), 10) # Test to check policy of stopping charging after MAX_TIME_OFFROAD_S - @parameterized.expand(ALL_PANDA_TYPES) - def test_max_time_offroad(self, hw_type): - BATT_VOLTAGE = 4 - BATT_CURRENT = 0 # To stop shutting down for other reasons + def test_max_time_offroad(self): MOCKED_MAX_OFFROAD_TIME = 3600 - with pm_patch("HARDWARE.get_battery_voltage", BATT_VOLTAGE * 1e6), pm_patch("HARDWARE.get_battery_current", BATT_CURRENT * 1e6), \ - pm_patch("HARDWARE.get_battery_status", "Discharging"), pm_patch("MAX_TIME_OFFROAD_S", MOCKED_MAX_OFFROAD_TIME, constant=True), \ - pm_patch("HARDWARE.get_current_power_draw", None): + POWER_DRAW = 0 # To stop shutting down for other reasons + with pm_patch("MAX_TIME_OFFROAD_S", MOCKED_MAX_OFFROAD_TIME, constant=True), pm_patch("HARDWARE.get_current_power_draw", POWER_DRAW): pm = PowerMonitoring() pm.car_battery_capacity_uWh = CAR_BATTERY_CAPACITY_uWh start_time = ssb ignition = False - peripheralState = self.mock_peripheralState(hw_type) while ssb <= start_time + MOCKED_MAX_OFFROAD_TIME: - pm.calculate(peripheralState, ignition) + pm.calculate(GOOD_VOLTAGE, ignition) if (ssb - start_time) % 1000 == 0 and ssb < start_time + MOCKED_MAX_OFFROAD_TIME: - self.assertFalse(pm.should_disable_charging(ignition, True, start_time)) - self.assertTrue(pm.should_disable_charging(ignition, True, start_time)) + self.assertFalse(pm.should_shutdown(ignition, True, start_time, False)) + self.assertTrue(pm.should_shutdown(ignition, True, start_time, False)) # Test to check policy of stopping charging when the car voltage is too low - @parameterized.expand(ALL_PANDA_TYPES) - def test_car_voltage(self, hw_type): - BATT_VOLTAGE = 4 - BATT_CURRENT = 0 # To stop shutting down for other reasons + def test_car_voltage(self): + POWER_DRAW = 0 # To stop shutting down for other reasons TEST_TIME = 100 - with pm_patch("HARDWARE.get_battery_voltage", BATT_VOLTAGE * 1e6), pm_patch("HARDWARE.get_battery_current", BATT_CURRENT * 1e6), \ - pm_patch("HARDWARE.get_battery_status", "Discharging"), pm_patch("HARDWARE.get_current_power_draw", None): + VOLTAGE_SHUTDOWN_MIN_OFFROAD_TIME_S = 50 + with pm_patch("VOLTAGE_SHUTDOWN_MIN_OFFROAD_TIME_S", VOLTAGE_SHUTDOWN_MIN_OFFROAD_TIME_S, constant=True), pm_patch("HARDWARE.get_current_power_draw", POWER_DRAW): pm = PowerMonitoring() pm.car_battery_capacity_uWh = CAR_BATTERY_CAPACITY_uWh ignition = False - peripheralState = self.mock_peripheralState(hw_type, car_voltage=(VBATT_PAUSE_CHARGING - 1)) + start_time = ssb for i in range(TEST_TIME): - pm.calculate(peripheralState, ignition) + pm.calculate(VOLTAGE_BELOW_PAUSE_CHARGING, ignition) if i % 10 == 0: - self.assertEqual(pm.should_disable_charging(ignition, True, ssb), (pm.car_voltage_mV < VBATT_PAUSE_CHARGING*1e3)) - self.assertTrue(pm.should_disable_charging(ignition, True, ssb)) + self.assertEqual(pm.should_shutdown(ignition, True, start_time, True), + (pm.car_voltage_mV < VBATT_PAUSE_CHARGING*1e3 and + (ssb - start_time) > VOLTAGE_SHUTDOWN_MIN_OFFROAD_TIME_S)) + self.assertTrue(pm.should_shutdown(ignition, True, start_time, True)) # Test to check policy of not stopping charging when DisablePowerDown is set def test_disable_power_down(self): - BATT_VOLTAGE = 4 - BATT_CURRENT = 0 # To stop shutting down for other reasons + POWER_DRAW = 0 # To stop shutting down for other reasons TEST_TIME = 100 params.put_bool("DisablePowerDown", True) - with pm_patch("HARDWARE.get_battery_voltage", BATT_VOLTAGE * 1e6), pm_patch("HARDWARE.get_battery_current", BATT_CURRENT * 1e6), \ - pm_patch("HARDWARE.get_battery_status", "Discharging"), pm_patch("HARDWARE.get_current_power_draw", None): + with pm_patch("HARDWARE.get_current_power_draw", POWER_DRAW): pm = PowerMonitoring() pm.car_battery_capacity_uWh = CAR_BATTERY_CAPACITY_uWh ignition = False - peripheralState = self.mock_peripheralState(log.PandaState.PandaType.uno, car_voltage=(VBATT_PAUSE_CHARGING - 1)) for i in range(TEST_TIME): - pm.calculate(peripheralState, ignition) + pm.calculate(VOLTAGE_BELOW_PAUSE_CHARGING, ignition) if i % 10 == 0: - self.assertFalse(pm.should_disable_charging(ignition, True, ssb)) - self.assertFalse(pm.should_disable_charging(ignition, True, ssb)) + self.assertFalse(pm.should_shutdown(ignition, True, ssb, False)) + self.assertFalse(pm.should_shutdown(ignition, True, ssb, False)) # Test to check policy of not stopping charging when ignition def test_ignition(self): - BATT_VOLTAGE = 4 - BATT_CURRENT = 0 # To stop shutting down for other reasons + POWER_DRAW = 0 # To stop shutting down for other reasons TEST_TIME = 100 - with pm_patch("HARDWARE.get_battery_voltage", BATT_VOLTAGE * 1e6), pm_patch("HARDWARE.get_battery_current", BATT_CURRENT * 1e6), \ - pm_patch("HARDWARE.get_battery_status", "Discharging"), pm_patch("HARDWARE.get_current_power_draw", None): + with pm_patch("HARDWARE.get_current_power_draw", POWER_DRAW): pm = PowerMonitoring() pm.car_battery_capacity_uWh = CAR_BATTERY_CAPACITY_uWh ignition = True - peripheralState = self.mock_peripheralState(log.PandaState.PandaType.uno, car_voltage=(VBATT_PAUSE_CHARGING - 1)) for i in range(TEST_TIME): - pm.calculate(peripheralState, ignition) + pm.calculate(VOLTAGE_BELOW_PAUSE_CHARGING, ignition) if i % 10 == 0: - self.assertFalse(pm.should_disable_charging(ignition, True, ssb)) - self.assertFalse(pm.should_disable_charging(ignition, True, ssb)) + self.assertFalse(pm.should_shutdown(ignition, True, ssb, False)) + self.assertFalse(pm.should_shutdown(ignition, True, ssb, False)) # Test to check policy of not stopping charging when harness is not connected def test_harness_connection(self): - BATT_VOLTAGE = 4 - BATT_CURRENT = 0 # To stop shutting down for other reasons + POWER_DRAW = 0 # To stop shutting down for other reasons TEST_TIME = 100 - with pm_patch("HARDWARE.get_battery_voltage", BATT_VOLTAGE * 1e6), pm_patch("HARDWARE.get_battery_current", BATT_CURRENT * 1e6), \ - pm_patch("HARDWARE.get_battery_status", "Discharging"), pm_patch("HARDWARE.get_current_power_draw", None): + with pm_patch("HARDWARE.get_current_power_draw", POWER_DRAW): pm = PowerMonitoring() pm.car_battery_capacity_uWh = CAR_BATTERY_CAPACITY_uWh ignition = False - peripheralState = self.mock_peripheralState(log.PandaState.PandaType.uno, car_voltage=(VBATT_PAUSE_CHARGING - 1)) for i in range(TEST_TIME): - pm.calculate(peripheralState, ignition) + pm.calculate(VOLTAGE_BELOW_PAUSE_CHARGING, ignition) if i % 10 == 0: - self.assertFalse(pm.should_disable_charging(ignition, False,ssb)) - self.assertFalse(pm.should_disable_charging(ignition, False, ssb)) + self.assertFalse(pm.should_shutdown(ignition, False, ssb, False)) + self.assertFalse(pm.should_shutdown(ignition, False, ssb, False)) if __name__ == "__main__": unittest.main() diff --git a/selfdrive/thermald/thermald.py b/selfdrive/thermald/thermald.py index 113ffaa04c..eedeff31f1 100755 --- a/selfdrive/thermald/thermald.py +++ b/selfdrive/thermald/thermald.py @@ -9,23 +9,21 @@ from pathlib import Path from typing import Dict, Optional, Tuple import psutil -from smbus2 import SMBus import cereal.messaging as messaging from cereal import log from common.dict_helpers import strip_deprecated_keys from common.filter_simple import FirstOrderFilter -from common.numpy_fast import interp from common.params import Params from common.realtime import DT_TRML, sec_since_boot from selfdrive.controls.lib.alertmanager import set_offroad_alert -from selfdrive.controls.lib.pid import PIController -from selfdrive.hardware import EON, HARDWARE, PC, TICI +from system.hardware import HARDWARE, TICI, AGNOS from selfdrive.loggerd.config import get_available_percent from selfdrive.statsd import statlog -from selfdrive.swaglog import cloudlog +from system.swaglog import cloudlog from selfdrive.thermald.power_monitoring import PowerMonitoring -from selfdrive.version import terms_version, training_version +from selfdrive.thermald.fan_controller import TiciFanController +from system.version import terms_version, training_version ThermalStatus = log.DeviceState.ThermalStatus NetworkType = log.DeviceState.NetworkType @@ -33,10 +31,10 @@ NetworkStrength = log.DeviceState.NetworkStrength CURRENT_TAU = 15. # 15s time constant TEMP_TAU = 5. # 5s time constant DISCONNECT_TIMEOUT = 5. # wait 5 seconds before going offroad after disconnect so you get an alert -PANDA_STATES_TIMEOUT = int(1000 * 2.5 * DT_TRML) # 2.5x the expected pandaState frequency +PANDA_STATES_TIMEOUT = int(1000 * 1.5 * DT_TRML) # 1.5x the expected pandaState frequency ThermalBand = namedtuple("ThermalBand", ['min_temp', 'max_temp']) -HardwareState = namedtuple("HardwareState", ['network_type', 'network_strength', 'network_info', 'nvme_temps', 'modem_temps']) +HardwareState = namedtuple("HardwareState", ['network_type', 'network_info', 'network_strength', 'network_stats', 'network_metered', 'nvme_temps', 'modem_temps']) # List of thermal bands. We will stay within this region as long as we are within the bounds. # When exiting the bounds, we'll jump to the lower or higher band. Bands are ordered in the dict. @@ -48,14 +46,29 @@ THERMAL_BANDS = OrderedDict({ }) # Override to highest thermal band when offroad and above this temp -OFFROAD_DANGER_TEMP = 79.5 if TICI else 70.0 +OFFROAD_DANGER_TEMP = 79.5 prev_offroad_states: Dict[str, Tuple[bool, Optional[str]]] = {} +tz_by_type: Optional[Dict[str, int]] = None +def populate_tz_by_type(): + global tz_by_type + tz_by_type = {} + for n in os.listdir("/sys/devices/virtual/thermal"): + if not n.startswith("thermal_zone"): + continue + with open(os.path.join("/sys/devices/virtual/thermal", n, "type")) as f: + tz_by_type[f.read().strip()] = int(n.lstrip("thermal_zone")) + def read_tz(x): if x is None: return 0 + if isinstance(x, str): + if tz_by_type is None: + populate_tz_by_type() + x = tz_by_type[x] + try: with open(f"/sys/devices/virtual/thermal/thermal_zone{x}/temp") as f: return int(f.read()) @@ -73,83 +86,6 @@ def read_thermal(thermal_config): return dat -def setup_eon_fan(): - os.system("echo 2 > /sys/module/dwc3_msm/parameters/otg_switch") - - -last_eon_fan_val = None -def set_eon_fan(val): - global last_eon_fan_val - - if last_eon_fan_val is None or last_eon_fan_val != val: - bus = SMBus(7, force=True) - try: - i = [0x1, 0x3 | 0, 0x3 | 0x08, 0x3 | 0x10][val] - bus.write_i2c_block_data(0x3d, 0, [i]) - except OSError: - # tusb320 - if val == 0: - bus.write_i2c_block_data(0x67, 0xa, [0]) - else: - bus.write_i2c_block_data(0x67, 0xa, [0x20]) - bus.write_i2c_block_data(0x67, 0x8, [(val - 1) << 6]) - bus.close() - last_eon_fan_val = val - - -# temp thresholds to control fan speed - high hysteresis -_TEMP_THRS_H = [50., 65., 80., 10000] -# temp thresholds to control fan speed - low hysteresis -_TEMP_THRS_L = [42.5, 57.5, 72.5, 10000] -# fan speed options -_FAN_SPEEDS = [0, 16384, 32768, 65535] - - -def handle_fan_eon(controller, max_cpu_temp, fan_speed, ignition): - new_speed_h = next(speed for speed, temp_h in zip(_FAN_SPEEDS, _TEMP_THRS_H) if temp_h > max_cpu_temp) - new_speed_l = next(speed for speed, temp_l in zip(_FAN_SPEEDS, _TEMP_THRS_L) if temp_l > max_cpu_temp) - - if new_speed_h > fan_speed: - # update speed if using the high thresholds results in fan speed increment - fan_speed = new_speed_h - elif new_speed_l < fan_speed: - # update speed if using the low thresholds results in fan speed decrement - fan_speed = new_speed_l - - set_eon_fan(fan_speed // 16384) - - return fan_speed - - -def handle_fan_uno(controller, max_cpu_temp, fan_speed, ignition): - new_speed = int(interp(max_cpu_temp, [40.0, 80.0], [0, 80])) - - if not ignition: - new_speed = min(30, new_speed) - - return new_speed - - -last_ignition = False -def handle_fan_tici(controller, max_cpu_temp, fan_speed, ignition): - global last_ignition - - controller.neg_limit = -(80 if ignition else 30) - controller.pos_limit = -(30 if ignition else 0) - - if ignition != last_ignition: - controller.reset() - - fan_pwr_out = -int(controller.update( - setpoint=75, - measurement=max_cpu_temp, - feedforward=interp(max_cpu_temp, [60.0, 100.0], [0, -80]) - )) - - last_ignition = ignition - return fan_pwr_out - - def set_offroad_alert_if_changed(offroad_alert: str, show_alert: bool, extra_text: Optional[str]=None): if prev_offroad_states.get(offroad_alert, None) == (show_alert, extra_text): return @@ -160,20 +96,39 @@ def set_offroad_alert_if_changed(offroad_alert: str, show_alert: bool, extra_tex def hw_state_thread(end_event, hw_queue): """Handles non critical hardware state, and sends over queue""" count = 0 - registered_count = 0 + prev_hw_state = None + + modem_version = None + modem_nv = None + modem_configured = False while not end_event.is_set(): # these are expensive calls. update every 10s if (count % int(10. / DT_TRML)) == 0: try: network_type = HARDWARE.get_network_type() + modem_temps = HARDWARE.get_modem_temperatures() + if len(modem_temps) == 0 and prev_hw_state is not None: + modem_temps = prev_hw_state.modem_temps + + # Log modem version once + if AGNOS and ((modem_version is None) or (modem_nv is None)): + modem_version = HARDWARE.get_modem_version() # pylint: disable=assignment-from-none + modem_nv = HARDWARE.get_modem_nv() # pylint: disable=assignment-from-none + + if (modem_version is not None) and (modem_nv is not None): + cloudlog.event("modem version", version=modem_version, nv=modem_nv) + + tx, rx = HARDWARE.get_modem_data_usage() hw_state = HardwareState( network_type=network_type, - network_strength=HARDWARE.get_network_strength(network_type), network_info=HARDWARE.get_network_info(), + network_strength=HARDWARE.get_network_strength(network_type), + network_stats={'wwanTx': tx, 'wwanRx': rx}, + network_metered=HARDWARE.get_network_metered(network_type), nvme_temps=HARDWARE.get_nvme_temperatures(), - modem_temps=HARDWARE.get_modem_temperatures(), + modem_temps=modem_temps, ) try: @@ -181,18 +136,15 @@ def hw_state_thread(end_event, hw_queue): except queue.Full: pass - if TICI and (hw_state.network_info is not None) and (hw_state.network_info.get('state', None) == "REGISTERED"): - registered_count += 1 - else: - registered_count = 0 - - if registered_count > 10: - cloudlog.warning(f"Modem stuck in registered state {hw_state.network_info}. nmcli conn up lte") - os.system("nmcli conn up lte") - registered_count = 0 + # TODO: remove this once the config is in AGNOS + if not modem_configured and len(HARDWARE.get_sim_info().get('sim_id', '')) > 0: + cloudlog.warning("configuring modem") + HARDWARE.configure_modem() + modem_configured = True + prev_hw_state = hw_state except Exception: - cloudlog.exception("Error getting network status") + cloudlog.exception("Error getting hardware state") count += 1 time.sleep(DT_TRML) @@ -202,7 +154,6 @@ def thermald_thread(end_event, hw_queue): pm = messaging.PubMaster(['deviceState']) sm = messaging.SubMaster(["peripheralState", "gpsLocationExternal", "controlsState", "pandaStates"], poll=["pandaStates"]) - fan_speed = 0 count = 0 onroad_conditions: Dict[str, bool] = { @@ -215,22 +166,21 @@ def thermald_thread(end_event, hw_queue): started_ts = None started_seen = False thermal_status = ThermalStatus.green - usb_power = True last_hw_state = HardwareState( network_type=NetworkType.none, - network_strength=NetworkStrength.unknown, network_info=None, + network_metered=False, + network_strength=NetworkStrength.unknown, + network_stats={'wwanTx': -1, 'wwanRx': -1}, nvme_temps=[], modem_temps=[], ) - current_filter = FirstOrderFilter(0., CURRENT_TAU, DT_TRML) - temp_filter = FirstOrderFilter(0., TEMP_TAU, DT_TRML) + all_temp_filter = FirstOrderFilter(0., TEMP_TAU, DT_TRML) + offroad_temp_filter = FirstOrderFilter(0., TEMP_TAU, DT_TRML) should_start_prev = False in_car = False - handle_fan = None - is_uno = False engaged_prev = False params = Params() @@ -239,8 +189,7 @@ def thermald_thread(end_event, hw_queue): HARDWARE.initialize_hardware() thermal_config = HARDWARE.get_thermal_config() - # TODO: use PI controller for UNO - controller = PIController(k_p=0, k_i=2e-3, neg_limit=-80, pos_limit=0, rate=(1 / DT_TRML)) + fan_controller = None while not end_event.is_set(): sm.update(PANDA_STATES_TIMEOUT) @@ -258,22 +207,16 @@ def thermald_thread(end_event, hw_queue): pandaState = pandaStates[0] in_car = pandaState.harnessStatus != log.PandaState.HarnessStatus.notConnected - usb_power = peripheralState.usbPowerMode != log.PeripheralState.UsbPowerMode.client # Setup fan handler on first connect to panda - if handle_fan is None and peripheralState.pandaType != log.PandaState.PandaType.unknown: - is_uno = peripheralState.pandaType == log.PandaState.PandaType.uno - + if fan_controller is None and peripheralState.pandaType != log.PandaState.PandaType.unknown: if TICI: - cloudlog.info("Setting up TICI fan handler") - handle_fan = handle_fan_tici - elif is_uno or PC: - cloudlog.info("Setting up UNO fan handler") - handle_fan = handle_fan_uno - else: - cloudlog.info("Setting up EON fan handler") - setup_eon_fan() - handle_fan = handle_fan_eon + fan_controller = TiciFanController() + + elif (sec_since_boot() - sm.rcv_time['pandaStates']) > DISCONNECT_TIMEOUT: + if onroad_conditions["ignition"]: + onroad_conditions["ignition"] = False + cloudlog.error("panda timed out onroad") try: last_hw_state = hw_queue.get_nowait() @@ -286,7 +229,9 @@ def thermald_thread(end_event, hw_queue): msg.deviceState.gpuUsagePercent = int(round(HARDWARE.get_gpu_usage_percent())) msg.deviceState.networkType = last_hw_state.network_type + msg.deviceState.networkMetered = last_hw_state.network_metered msg.deviceState.networkStrength = last_hw_state.network_strength + msg.deviceState.networkStats = last_hw_state.network_stats if last_hw_state.network_info is not None: msg.deviceState.networkInfo = last_hw_state.network_info @@ -294,30 +239,33 @@ def thermald_thread(end_event, hw_queue): msg.deviceState.modemTempC = last_hw_state.modem_temps msg.deviceState.screenBrightnessPercent = HARDWARE.get_screen_brightness() - msg.deviceState.batteryPercent = HARDWARE.get_battery_capacity() - msg.deviceState.batteryCurrent = HARDWARE.get_battery_current() - msg.deviceState.usbOnline = HARDWARE.get_usb_present() - current_filter.update(msg.deviceState.batteryCurrent / 1e6) - max_comp_temp = temp_filter.update( - max(max(msg.deviceState.cpuTempC), msg.deviceState.memoryTempC, max(msg.deviceState.gpuTempC)) - ) + # this one is only used for offroad + temp_sources = [ + msg.deviceState.memoryTempC, + max(msg.deviceState.cpuTempC), + max(msg.deviceState.gpuTempC), + ] + offroad_comp_temp = offroad_temp_filter.update(max(temp_sources)) + + # this drives the thermal status while onroad + temp_sources.append(max(msg.deviceState.pmicTempC)) + all_comp_temp = all_temp_filter.update(max(temp_sources)) - if handle_fan is not None: - fan_speed = handle_fan(controller, max_comp_temp, fan_speed, onroad_conditions["ignition"]) - msg.deviceState.fanSpeedPercentDesired = fan_speed + if fan_controller is not None: + msg.deviceState.fanSpeedPercentDesired = fan_controller.update(all_comp_temp, onroad_conditions["ignition"]) is_offroad_for_5_min = (started_ts is None) and ((not started_seen) or (off_ts is None) or (sec_since_boot() - off_ts > 60 * 5)) - if is_offroad_for_5_min and max_comp_temp > OFFROAD_DANGER_TEMP: + if is_offroad_for_5_min and offroad_comp_temp > OFFROAD_DANGER_TEMP: # If device is offroad we want to cool down before going onroad # since going onroad increases load and can make temps go over 107 thermal_status = ThermalStatus.danger else: current_band = THERMAL_BANDS[thermal_status] band_idx = list(THERMAL_BANDS.keys()).index(thermal_status) - if current_band.min_temp is not None and max_comp_temp < current_band.min_temp: + if current_band.min_temp is not None and all_comp_temp < current_band.min_temp: thermal_status = list(THERMAL_BANDS.keys())[band_idx - 1] - elif current_band.max_temp is not None and max_comp_temp > current_band.max_temp: + elif current_band.max_temp is not None and all_comp_temp > current_band.max_temp: thermal_status = list(THERMAL_BANDS.keys())[band_idx + 1] # **** starting logic **** @@ -330,6 +278,7 @@ def thermald_thread(end_event, hw_queue): startup_conditions["up_to_date"] = params.get("Offroad_ConnectivityNeeded") is None or params.get_bool("DisableUpdates") or params.get_bool("SnoozeUpdate") startup_conditions["not_uninstalling"] = not params.get_bool("DoUninstall") startup_conditions["accepted_terms"] = params.get("HasAcceptedTerms") == terms_version + startup_conditions["offroad_min_time"] = (not started_seen) or ((off_ts is not None) and (sec_since_boot() - off_ts) > 5.) # with 2% left, we killall, otherwise the phone will take a long time to boot startup_conditions["free_space"] = msg.deviceState.freeSpacePercent > 2 @@ -342,9 +291,21 @@ def thermald_thread(end_event, hw_queue): onroad_conditions["device_temp_good"] = thermal_status < ThermalStatus.danger set_offroad_alert_if_changed("Offroad_TemperatureTooHigh", (not onroad_conditions["device_temp_good"])) + # TODO: this should move to TICI.initialize_hardware, but we currently can't import params there if TICI: - missing = (not Path("/data/media").is_mount()) and (not os.path.isfile("/persist/comma/living-in-the-moment")) - set_offroad_alert_if_changed("Offroad_StorageMissing", missing) + if not os.path.isfile("/persist/comma/living-in-the-moment"): + if not Path("/data/media").is_mount(): + set_offroad_alert_if_changed("Offroad_StorageMissing", True) + else: + # check for bad NVMe + try: + with open("/sys/block/nvme0n1/device/model") as f: + model = f.read().strip() + if not model.startswith("Samsung SSD 980") and params.get("Offroad_BadNvme") is None: + set_offroad_alert_if_changed("Offroad_BadNvme", True) + cloudlog.event("Unsupported NVMe", model=model, error=True) + except Exception: + pass # Handle offroad/onroad transition should_start = all(onroad_conditions.values()) @@ -378,28 +339,31 @@ def thermald_thread(end_event, hw_queue): started_seen = True else: if onroad_conditions["ignition"] and (startup_conditions != startup_conditions_prev): - cloudlog.event("Startup blocked", startup_conditions=startup_conditions, onroad_conditions=onroad_conditions) + cloudlog.event("Startup blocked", startup_conditions=startup_conditions, onroad_conditions=onroad_conditions, error=True) + startup_conditions_prev = startup_conditions.copy() started_ts = None if off_ts is None: off_ts = sec_since_boot() # Offroad power monitoring - power_monitor.calculate(peripheralState, onroad_conditions["ignition"]) + voltage = None if peripheralState.pandaType == log.PandaState.PandaType.unknown else peripheralState.voltage + power_monitor.calculate(voltage, onroad_conditions["ignition"]) msg.deviceState.offroadPowerUsageUwh = power_monitor.get_power_used() msg.deviceState.carBatteryCapacityUwh = max(0, power_monitor.get_car_battery_capacity()) - current_power_draw = HARDWARE.get_current_power_draw() # pylint: disable=assignment-from-none - msg.deviceState.powerDrawW = current_power_draw if current_power_draw is not None else 0 + current_power_draw = HARDWARE.get_current_power_draw() + statlog.sample("power_draw", current_power_draw) + msg.deviceState.powerDrawW = current_power_draw - # Check if we need to disable charging (handled by boardd) - msg.deviceState.chargingDisabled = power_monitor.should_disable_charging(onroad_conditions["ignition"], in_car, off_ts) + som_power_draw = HARDWARE.get_som_power_draw() + statlog.sample("som_power_draw", som_power_draw) + msg.deviceState.somPowerDrawW = som_power_draw # Check if we need to shut down - if power_monitor.should_shutdown(peripheralState, onroad_conditions["ignition"], in_car, off_ts, started_seen): + if power_monitor.should_shutdown(onroad_conditions["ignition"], in_car, off_ts, started_seen): cloudlog.warning(f"shutting device down, offroad since {off_ts}") params.put_bool("DoShutdown", True) - msg.deviceState.chargingError = current_filter.x > 0. and msg.deviceState.batteryPercent < 90 # if current is positive, then battery is being discharged msg.deviceState.started = started_ts is not None msg.deviceState.startedMonoTime = int(1e9*(started_ts or 0)) @@ -410,11 +374,7 @@ def thermald_thread(end_event, hw_queue): msg.deviceState.thermalStatus = thermal_status pm.send("deviceState", msg) - if EON and not is_uno: - set_offroad_alert_if_changed("Offroad_ChargeDisabled", (not usb_power)) - should_start_prev = should_start - startup_conditions_prev = startup_conditions.copy() # Log to statsd statlog.gauge("free_space_percent", msg.deviceState.freeSpacePercent) @@ -439,9 +399,6 @@ def thermald_thread(end_event, hw_queue): # report to server once every 10 minutes if (count % int(600. / DT_TRML)) == 0: - if EON and started_ts is None and msg.deviceState.memoryUsagePercent > 40: - cloudlog.event("High offroad memory usage", mem=msg.deviceState.memoryUsagePercent) - cloudlog.event("STATUS_PACKET", count=count, pandaStates=[strip_deprecated_keys(p.to_dict()) for p in pandaStates], diff --git a/selfdrive/tombstoned.py b/selfdrive/tombstoned.py index 459ab2f0f9..61a575f141 100755 --- a/selfdrive/tombstoned.py +++ b/selfdrive/tombstoned.py @@ -10,15 +10,12 @@ import glob from typing import NoReturn from common.file_helpers import mkdirs_exists_ok -from selfdrive.hardware import TICI from selfdrive.loggerd.config import ROOT import selfdrive.sentry as sentry -from selfdrive.swaglog import cloudlog -from selfdrive.version import get_commit +from system.swaglog import cloudlog +from system.version import get_commit -MAX_SIZE = 100000 * 10 # mal size is 40-100k, allow up to 1M -if TICI: - MAX_SIZE = MAX_SIZE * 100 # Allow larger size for tici since files contain coredump +MAX_SIZE = 1_000_000 * 100 # allow up to 100M MAX_TOMBSTONE_FN_LEN = 62 # 85 - 23 ("/crash/") TOMBSTONE_DIR = "/data/tombstones/" @@ -65,47 +62,6 @@ def get_tombstones(): return files -def report_tombstone_android(fn): - f_size = os.path.getsize(fn) - if f_size > MAX_SIZE: - cloudlog.error(f"Tombstone {fn} too big, {f_size}. Skipping...") - return - - with open(fn, encoding='ISO-8859-1') as f: - contents = f.read() - - message = " ".join(contents.split('\n')[5:7]) - - # Cut off pid/tid, since that varies per run - name_idx = message.find('name') - if name_idx >= 0: - message = message[name_idx:] - - executable = "" - start_exe_idx = message.find('>>> ') - end_exe_idx = message.find(' <<<') - if start_exe_idx >= 0 and end_exe_idx >= 0: - executable = message[start_exe_idx + 4:end_exe_idx] - - # Cut off fault addr - fault_idx = message.find(', fault addr') - if fault_idx >= 0: - message = message[:fault_idx] - - sentry.report_tombstone(fn, message, contents) - - # Copy crashlog to upload folder - clean_path = executable.replace('./', '').replace('/', '_') - date = datetime.datetime.now().strftime("%Y-%m-%d--%H-%M-%S") - - new_fn = f"{date}_{get_commit(default='nocommit')[:8]}_{safe_fn(clean_path)}"[:MAX_TOMBSTONE_FN_LEN] - - crashlog_dir = os.path.join(ROOT, "crash") - mkdirs_exists_ok(crashlog_dir) - - shutil.copy(fn, os.path.join(crashlog_dir, new_fn)) - - def report_tombstone_apport(fn): f_size = os.path.getsize(fn) if f_size > MAX_SIZE: @@ -153,9 +109,9 @@ def report_tombstone_apport(fn): # Try to find first entry in openpilot, fall back to first line for line in stacktrace_s: if "at selfdrive/" in line: - crash_function = line - found = True - break + crash_function = line + found = True + break if not found: crash_function = stacktrace_s[1] @@ -202,7 +158,7 @@ def main() -> NoReturn: if fn.endswith(".crash"): report_tombstone_apport(fn) else: - report_tombstone_android(fn) + cloudlog.error(f"unknown crash type: {fn}") except Exception: cloudlog.exception(f"Error reporting tombstone {fn}") diff --git a/selfdrive/ui/.gitignore b/selfdrive/ui/.gitignore index 5f8a96edf0..60eb4b43c7 100644 --- a/selfdrive/ui/.gitignore +++ b/selfdrive/ui/.gitignore @@ -1,11 +1,11 @@ moc_* *.moc +translations/main_test_en.* + _mui watch3 installer/installers/* -replay/replay -replay/tests/test_replay qt/text qt/spinner qt/setup/setup diff --git a/selfdrive/ui/SConscript b/selfdrive/ui/SConscript index 00d528e63d..669c214746 100644 --- a/selfdrive/ui/SConscript +++ b/selfdrive/ui/SConscript @@ -1,14 +1,14 @@ import os -Import('qt_env', 'arch', 'common', 'messaging', 'gpucommon', 'visionipc', +Import('qt_env', 'arch', 'common', 'messaging', 'visionipc', 'cereal', 'transformations') -base_libs = [gpucommon, common, messaging, cereal, visionipc, transformations, 'zmq', +base_libs = [common, messaging, cereal, visionipc, transformations, 'zmq', 'capnp', 'kj', 'm', 'OpenCL', 'ssl', 'crypto', 'pthread'] + qt_env["LIBS"] -maps = arch in ['larch64', 'x86_64'] +if arch == 'larch64': + base_libs.append('EGL') -if arch == 'aarch64': - base_libs += ['log', 'utils', 'gui', 'ui', 'CB', 'gsl', 'adreno_utils', 'cutils', 'uuid'] +maps = arch in ['larch64', 'x86_64'] if maps and arch == 'x86_64': rpath = [Dir(f"#third_party/mapbox-gl-native-qt/{arch}").srcnode().abspath] @@ -18,14 +18,12 @@ if arch == "Darwin": del base_libs[base_libs.index('OpenCL')] qt_env['FRAMEWORKS'] += ['OpenCL'] -widgets_src = ["qt/util.cc", "qt/widgets/input.cc", "qt/widgets/drive_stats.cc", +qt_util = qt_env.Library("qt_util", ["#selfdrive/ui/qt/api.cc", "#selfdrive/ui/qt/util.cc"], LIBS=base_libs) +widgets_src = ["ui.cc", "qt/widgets/input.cc", "qt/widgets/drive_stats.cc", "qt/widgets/ssh_keys.cc", "qt/widgets/toggle.cc", "qt/widgets/controls.cc", "qt/widgets/offroad_alerts.cc", "qt/widgets/prime.cc", "qt/widgets/keyboard.cc", - "qt/widgets/scrollview.cc", "qt/widgets/cameraview.cc", "#third_party/qrcode/QrCode.cc", "qt/api.cc", - "qt/request_repeater.cc", "qt/qt_window.cc"] - -if arch != 'aarch64': - widgets_src += ["qt/offroad/networking.cc", "qt/offroad/wifiManager.cc"] + "qt/widgets/scrollview.cc", "qt/widgets/cameraview.cc", "#third_party/qrcode/QrCode.cc", + "qt/request_repeater.cc", "qt/qt_window.cc", "qt/offroad/networking.cc", "qt/offroad/wifiManager.cc"] qt_env['CPPDEFINES'] = [] if maps: @@ -34,7 +32,8 @@ if maps: qt_env['CPPDEFINES'] += ["ENABLE_MAPS"] widgets = qt_env.Library("qt_widgets", widgets_src, LIBS=base_libs) -qt_libs = [widgets] + base_libs +Export('widgets') +qt_libs = [widgets, qt_util] + base_libs # build assets assets = "#selfdrive/assets/assets.cc" @@ -56,21 +55,32 @@ qt_env.Program("qt/text", ["qt/text.cc"], LIBS=qt_libs) qt_env.Program("qt/spinner", ["qt/spinner.cc"], LIBS=qt_libs) # build main UI -qt_src = ["main.cc", "ui.cc", "qt/sidebar.cc", "qt/onroad.cc", +qt_src = ["main.cc", "qt/sidebar.cc", "qt/onroad.cc", "qt/body.cc", "qt/window.cc", "qt/home.cc", "qt/offroad/settings.cc", - "qt/offroad/onboarding.cc", "qt/offroad/driverview.cc"] + "qt/offroad/software_settings.cc", "qt/offroad/onboarding.cc", + "qt/offroad/driverview.cc", "qt/offroad/experimental_mode.cc"] qt_env.Program("_ui", qt_src + [asset_obj], LIBS=qt_libs) +if GetOption('test'): + qt_src.remove("main.cc") # replaced by test_runner + qt_env.Program('tests/test_translations', [asset_obj, 'tests/test_runner.cc', 'tests/test_translations.cc'] + qt_src, LIBS=qt_libs) + + +# build translation files +translation_sources = Glob("#selfdrive/ui/translations/*.ts", strings=True) +translation_targets = [src.replace(".ts", ".qm") for src in translation_sources] +lrelease = 'third_party/qt5/larch64/bin/lrelease' if arch == 'larch64' else 'lrelease' +qt_env.Command(translation_targets, translation_sources, f"{lrelease} $SOURCES") # setup and factory resetter -if arch != 'aarch64' and GetOption('extras'): +if GetOption('extras'): qt_env.Program("qt/setup/reset", ["qt/setup/reset.cc"], LIBS=qt_libs) qt_env.Program("qt/setup/setup", ["qt/setup/setup.cc", asset_obj], LIBS=qt_libs + ['curl', 'common', 'json11']) if GetOption('extras'): - # buidl updater UI + # build updater UI qt_env.Program("qt/setup/updater", ["qt/setup/updater.cc", asset_obj], LIBS=qt_libs) # build mui @@ -80,8 +90,8 @@ if GetOption('extras'): senv = qt_env.Clone() senv['LINKFLAGS'].append('-Wl,-strip-debug') - release = "release3" if arch == 'larch64' else "release2" - dashcam = "dashcam3" if arch == 'larch64' else "dashcam" + release = "release3" + dashcam = "dashcam3" installers = [ ("openpilot", release), ("openpilot_test", f"{release}-staging"), @@ -110,25 +120,6 @@ if GetOption('extras'): # keep installers small assert f[0].get_size() < 300*1e3 - -# build headless replay +# build watch3 if arch in ['x86_64', 'Darwin'] or GetOption('extras'): - qt_env['CXXFLAGS'] += ["-Wno-deprecated-declarations"] - - replay_lib_src = ["replay/replay.cc", "replay/consoleui.cc", "replay/camera.cc", "replay/filereader.cc", "replay/logreader.cc", "replay/framereader.cc", "replay/route.cc", "replay/util.cc"] - - replay_lib = qt_env.Library("qt_replay", replay_lib_src, LIBS=base_libs) - replay_libs = [replay_lib, 'avutil', 'avcodec', 'avformat', 'bz2', 'curl', 'yuv', 'ncurses'] + qt_libs - qt_env.Program("replay/replay", ["replay/main.cc"], LIBS=replay_libs) qt_env.Program("watch3", ["watch3.cc"], LIBS=qt_libs + ['common', 'json11', 'zmq', 'visionipc', 'messaging']) - - if GetOption('test'): - qt_env.Program('replay/tests/test_replay', ['replay/tests/test_runner.cc', 'replay/tests/test_replay.cc'], LIBS=[replay_libs]) - -# navd -if maps: - navd_src = ["navd/main.cc", "navd/route_engine.cc", "navd/map_renderer.cc"] - qt_env.Program("navd/_navd", navd_src, LIBS=qt_libs + ['common', 'json11']) - - if GetOption('extras'): - qt_env.SharedLibrary("navd/map_renderer", ["navd/map_renderer.cc"], LIBS=qt_libs + ['common', 'messaging']) diff --git a/selfdrive/ui/installer/installer.cc b/selfdrive/ui/installer/installer.cc index 6ee6e99e09..7d8bbf74e0 100644 --- a/selfdrive/ui/installer/installer.cc +++ b/selfdrive/ui/installer/installer.cc @@ -25,12 +25,7 @@ const std::string GIT_URL = get_str("https://github.com/commaai/openpilot.git" " const std::string BRANCH_STR = get_str(BRANCH "? "); #define GIT_SSH_URL "git@github.com:commaai/openpilot.git" - -#ifdef QCOM - #define CONTINUE_PATH "/data/data/com.termux/files/continue.sh" -#else - #define CONTINUE_PATH "/data/continue.sh" -#endif +#define CONTINUE_PATH "/data/continue.sh" const QString CACHE_PATH = "/data/openpilot.cache"; @@ -58,7 +53,7 @@ Installer::Installer(QWidget *parent) : QWidget(parent) { layout->setContentsMargins(150, 290, 150, 150); layout->setSpacing(0); - QLabel *title = new QLabel("Installing..."); + QLabel *title = new QLabel(tr("Installing...")); title->setStyleSheet("font-size: 90px; font-weight: 600;"); layout->addWidget(title, 0, Qt::AlignTop); @@ -112,7 +107,7 @@ void Installer::doInstall() { qDebug() << "Waiting for valid time"; } - // cleanup previous install attemps + // cleanup previous install attempts run("rm -rf " TMP_INSTALL_PATH " " INSTALL_PATH); // do the install @@ -146,9 +141,9 @@ void Installer::cachedFetch(const QString &cache) { void Installer::readProgress() { const QVector> stages = { // prefix, weight in percentage - {"Receiving objects: ", 91}, - {"Resolving deltas: ", 2}, - {"Updating files: ", 7}, + {tr("Receiving objects: "), 91}, + {tr("Resolving deltas: "), 2}, + {tr("Updating files: "), 7}, }; auto line = QString(proc.readAllStandardError()); @@ -212,16 +207,12 @@ void Installer::cloneFinished(int exitCode, QProcess::ExitStatus exitStatus) { run("chmod +x /data/continue.sh.new"); run("mv /data/continue.sh.new " CONTINUE_PATH); -#ifdef QCOM - QTimer::singleShot(100, &QCoreApplication::quit); -#else // wait for the installed software's UI to take over QTimer::singleShot(60 * 1000, &QCoreApplication::quit); -#endif } int main(int argc, char *argv[]) { - initApp(); + initApp(argc, argv); QApplication a(argc, argv); Installer installer; setMainWindow(&installer); diff --git a/selfdrive/ui/main.cc b/selfdrive/ui/main.cc index 3d2411b9c6..ed54d5aa19 100644 --- a/selfdrive/ui/main.cc +++ b/selfdrive/ui/main.cc @@ -1,9 +1,9 @@ #include #include -#include +#include -#include "selfdrive/hardware/hw.h" +#include "system/hardware/hw.h" #include "selfdrive/ui/qt/qt_window.h" #include "selfdrive/ui/qt/util.h" #include "selfdrive/ui/qt/window.h" @@ -12,15 +12,17 @@ int main(int argc, char *argv[]) { setpriority(PRIO_PROCESS, 0, -20); qInstallMessageHandler(swagLogMessageHandler); - initApp(); + initApp(argc, argv); - if (Hardware::EON()) { - QSslConfiguration ssl = QSslConfiguration::defaultConfiguration(); - ssl.setCaCertificates(QSslCertificate::fromPath("/usr/etc/tls/cert.pem")); - QSslConfiguration::setDefaultConfiguration(ssl); + QTranslator translator; + QString translation_file = QString::fromStdString(Params().get("LanguageSetting")); + if (!translator.load(translation_file, "translations") && translation_file.length()) { + qCritical() << "Failed to load translation file:" << translation_file; } QApplication a(argc, argv); + a.installTranslator(&translator); + MainWindow w; setMainWindow(&w); a.installEventFilter(&w); diff --git a/selfdrive/ui/navd/.gitignore b/selfdrive/ui/navd/.gitignore deleted file mode 100644 index 0fa7b173e4..0000000000 --- a/selfdrive/ui/navd/.gitignore +++ /dev/null @@ -1 +0,0 @@ -_navd diff --git a/selfdrive/ui/navd/main.cc b/selfdrive/ui/navd/main.cc deleted file mode 100644 index 7ae0393a47..0000000000 --- a/selfdrive/ui/navd/main.cc +++ /dev/null @@ -1,45 +0,0 @@ -#include -#include -#include -#include -#include - -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/maps/map_helpers.h" -#include "selfdrive/ui/navd/route_engine.h" -#include "selfdrive/ui/navd/map_renderer.h" -#include "selfdrive/hardware/hw.h" -#include "selfdrive/common/params.h" - -void sigHandler(int s) { - qInfo() << "Shutting down"; - std::signal(s, SIG_DFL); - - qApp->quit(); -} - - -int main(int argc, char *argv[]) { - qInstallMessageHandler(swagLogMessageHandler); - - QApplication app(argc, argv); - std::signal(SIGINT, sigHandler); - std::signal(SIGTERM, sigHandler); - - QCommandLineParser parser; - parser.setApplicationDescription("Navigation server. Runs stand-alone, or using pre-computer route"); - parser.addHelpOption(); - parser.process(app); - const QStringList args = parser.positionalArguments(); - - - RouteEngine* route_engine = new RouteEngine(); - - if (Params().getBool("NavdRender")) { - MapRenderer * m = new MapRenderer(get_mapbox_settings()); - QObject::connect(route_engine, &RouteEngine::positionUpdated, m, &MapRenderer::updatePosition); - QObject::connect(route_engine, &RouteEngine::routeUpdated, m, &MapRenderer::updateRoute); - } - - return app.exec(); -} diff --git a/selfdrive/ui/navd/navd b/selfdrive/ui/navd/navd deleted file mode 100755 index ff3103bd97..0000000000 --- a/selfdrive/ui/navd/navd +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh -cd "$(dirname "$0")" -export QT_PLUGIN_PATH="../../../third_party/qt-plugins/$(uname -m)" -exec ./_navd diff --git a/selfdrive/ui/navd/route_engine.cc b/selfdrive/ui/navd/route_engine.cc deleted file mode 100644 index f3cb7df3d9..0000000000 --- a/selfdrive/ui/navd/route_engine.cc +++ /dev/null @@ -1,359 +0,0 @@ -#include "selfdrive/ui/navd/route_engine.h" - -#include - -#include "selfdrive/ui/qt/maps/map.h" -#include "selfdrive/ui/qt/maps/map_helpers.h" -#include "selfdrive/ui/qt/api.h" - -#include "selfdrive/common/params.h" - -const qreal REROUTE_DISTANCE = 25; -const float MANEUVER_TRANSITION_THRESHOLD = 10; - -static float get_time_typical(const QGeoRouteSegment &segment) { - auto maneuver = segment.maneuver(); - auto attrs = maneuver.extendedAttributes(); - return attrs.contains("mapbox.duration_typical") ? attrs["mapbox.duration_typical"].toDouble() : segment.travelTime(); -} - -static cereal::NavInstruction::Direction string_to_direction(QString d) { - if (d.contains("left")) { - return cereal::NavInstruction::Direction::LEFT; - } else if (d.contains("right")) { - return cereal::NavInstruction::Direction::RIGHT; - } else if (d.contains("straight")) { - return cereal::NavInstruction::Direction::STRAIGHT; - } - - return cereal::NavInstruction::Direction::NONE; -} - -static void parse_banner(cereal::NavInstruction::Builder &instruction, const QMap &banner, bool full) { - QString primary_str, secondary_str; - - auto p = banner["primary"].toMap(); - primary_str += p["text"].toString(); - - instruction.setShowFull(full); - - if (p.contains("type")) { - instruction.setManeuverType(p["type"].toString().toStdString()); - } - - if (p.contains("modifier")) { - instruction.setManeuverModifier(p["modifier"].toString().toStdString()); - } - - if (banner.contains("secondary")) { - auto s = banner["secondary"].toMap(); - secondary_str += s["text"].toString(); - } - - instruction.setManeuverPrimaryText(primary_str.toStdString()); - instruction.setManeuverSecondaryText(secondary_str.toStdString()); - - if (banner.contains("sub")) { - auto s = banner["sub"].toMap(); - auto components = s["components"].toList(); - - size_t num_lanes = 0; - for (auto &c : components) { - auto cc = c.toMap(); - if (cc["type"].toString() == "lane") { - num_lanes += 1; - } - } - - auto lanes = instruction.initLanes(num_lanes); - - size_t i = 0; - for (auto &c : components) { - auto cc = c.toMap(); - if (cc["type"].toString() == "lane") { - auto lane = lanes[i]; - lane.setActive(cc["active"].toBool()); - - if (cc.contains("active_direction")) { - lane.setActiveDirection(string_to_direction(cc["active_direction"].toString())); - } - - auto directions = lane.initDirections(cc["directions"].toList().size()); - - size_t j = 0; - for (auto &dir : cc["directions"].toList()) { - directions.set(j, string_to_direction(dir.toString())); - j++; - } - - - i++; - } - } - } -} - -RouteEngine::RouteEngine() { - sm = new SubMaster({"liveLocationKalman", "managerState"}); - pm = new PubMaster({"navInstruction", "navRoute"}); - - // Timers - route_timer = new QTimer(this); - QObject::connect(route_timer, SIGNAL(timeout()), this, SLOT(routeUpdate())); - route_timer->start(1000); - - msg_timer = new QTimer(this); - QObject::connect(msg_timer, SIGNAL(timeout()), this, SLOT(msgUpdate())); - msg_timer->start(50); - - // Build routing engine - QVariantMap parameters; - parameters["mapbox.access_token"] = get_mapbox_token(); - parameters["mapbox.directions_api_url"] = MAPS_HOST + "/directions/v5/mapbox/"; - - geoservice_provider = new QGeoServiceProvider("mapbox", parameters); - routing_manager = geoservice_provider->routingManager(); - if (routing_manager == nullptr) { - qWarning() << geoservice_provider->errorString(); - assert(routing_manager); - } - QObject::connect(routing_manager, &QGeoRoutingManager::finished, this, &RouteEngine::routeCalculated); - - // Get last gps position from params - auto last_gps_position = coordinate_from_param("LastGPSPosition"); - if (last_gps_position) { - last_position = *last_gps_position; - } -} - -void RouteEngine::msgUpdate() { - sm->update(1000); - if (!sm->updated("liveLocationKalman")) { - active = false; - return; - } - - - if (sm->updated("managerState")) { - for (auto const &p : (*sm)["managerState"].getManagerState().getProcesses()) { - if (p.getName() == "ui" && p.getRunning()) { - if (ui_pid && *ui_pid != p.getPid()){ - qWarning() << "UI restarting, sending route"; - QTimer::singleShot(5000, this, &RouteEngine::sendRoute); - } - ui_pid = p.getPid(); - } - } - } - - auto location = (*sm)["liveLocationKalman"].getLiveLocationKalman(); - auto pos = location.getPositionGeodetic(); - auto orientation = location.getCalibratedOrientationNED(); - - gps_ok = location.getGpsOK(); - - localizer_valid = (location.getStatus() == cereal::LiveLocationKalman::Status::VALID) && pos.getValid(); - - if (localizer_valid) { - last_bearing = RAD2DEG(orientation.getValue()[2]); - last_position = QMapbox::Coordinate(pos.getValue()[0], pos.getValue()[1]); - emit positionUpdated(*last_position, *last_bearing); - } - - active = true; -} - -void RouteEngine::routeUpdate() { - if (!active) { - return; - } - - recomputeRoute(); - - MessageBuilder msg; - cereal::Event::Builder evt = msg.initEvent(segment.isValid()); - cereal::NavInstruction::Builder instruction = evt.initNavInstruction(); - - // Show route instructions - if (segment.isValid()) { - auto cur_maneuver = segment.maneuver(); - auto attrs = cur_maneuver.extendedAttributes(); - if (cur_maneuver.isValid() && attrs.contains("mapbox.banner_instructions")) { - float along_geometry = distance_along_geometry(segment.path(), to_QGeoCoordinate(*last_position)); - float distance_to_maneuver_along_geometry = segment.distance() - along_geometry; - - auto banners = attrs["mapbox.banner_instructions"].toList(); - if (banners.size()) { - auto banner = banners[0].toMap(); - - for (auto &b : banners) { - auto bb = b.toMap(); - if (distance_to_maneuver_along_geometry < bb["distance_along_geometry"].toDouble()) { - banner = bb; - } - } - - instruction.setManeuverDistance(distance_to_maneuver_along_geometry); - parse_banner(instruction, banner, distance_to_maneuver_along_geometry < banner["distance_along_geometry"].toDouble()); - - // ETA - float progress = distance_along_geometry(segment.path(), to_QGeoCoordinate(*last_position)) / segment.distance(); - float total_distance = segment.distance() * (1.0 - progress); - float total_time = segment.travelTime() * (1.0 - progress); - float total_time_typical = get_time_typical(segment) * (1.0 - progress); - - auto s = segment.nextRouteSegment(); - while (s.isValid()) { - total_distance += s.distance(); - total_time += s.travelTime(); - total_time_typical += get_time_typical(s); - - s = s.nextRouteSegment(); - } - instruction.setTimeRemaining(total_time); - instruction.setTimeRemainingTypical(total_time_typical); - instruction.setDistanceRemaining(total_distance); - } - - // Transition to next route segment - if (distance_to_maneuver_along_geometry < -MANEUVER_TRANSITION_THRESHOLD) { - auto next_segment = segment.nextRouteSegment(); - if (next_segment.isValid()) { - segment = next_segment; - - recompute_backoff = std::max(0, recompute_backoff - 1); - recompute_countdown = 0; - } else { - qWarning() << "Destination reached"; - Params().remove("NavDestination"); - - // Clear route if driving away from destination - float d = segment.maneuver().position().distanceTo(to_QGeoCoordinate(*last_position)); - if (d > REROUTE_DISTANCE) { - clearRoute(); - } - } - } - } - } - - pm->send("navInstruction", msg); -} - -void RouteEngine::clearRoute() { - route = QGeoRoute(); - segment = QGeoRouteSegment(); - nav_destination = QMapbox::Coordinate(); -} - -bool RouteEngine::shouldRecompute() { - if (!segment.isValid()) { - return true; - } - - // Don't recompute in last segment, assume destination is reached - if (!segment.nextRouteSegment().isValid()) { - return false; - } - - // Compute closest distance to all line segments in the current path - float min_d = REROUTE_DISTANCE + 1; - auto path = segment.path(); - auto cur = to_QGeoCoordinate(*last_position); - for (size_t i = 0; i < path.size() - 1; i++) { - auto a = path[i]; - auto b = path[i+1]; - if (a.distanceTo(b) < 1.0) { - continue; - } - min_d = std::min(min_d, minimum_distance(a, b, cur)); - } - return min_d > REROUTE_DISTANCE; - - // TODO: Check for going wrong way in segment -} - -void RouteEngine::recomputeRoute() { - if (!last_position) { - return; - } - - auto new_destination = coordinate_from_param("NavDestination"); - if (!new_destination) { - clearRoute(); - return; - } - - bool should_recompute = shouldRecompute(); - if (*new_destination != nav_destination) { - qWarning() << "Got new destination from NavDestination param" << *new_destination; - should_recompute = true; - } - - if (!gps_ok && segment.isValid()) return; // Don't recompute when gps drifts in tunnels - - if (recompute_countdown == 0 && should_recompute) { - recompute_countdown = std::pow(2, recompute_backoff); - recompute_backoff = std::min(7, recompute_backoff + 1); - calculateRoute(*new_destination); - } else { - recompute_countdown = std::max(0, recompute_countdown - 1); - } -} - -void RouteEngine::calculateRoute(QMapbox::Coordinate destination) { - qWarning() << "Calculating route" << *last_position << "->" << destination; - - nav_destination = destination; - QGeoRouteRequest request(to_QGeoCoordinate(*last_position), to_QGeoCoordinate(destination)); - request.setFeatureWeight(QGeoRouteRequest::TrafficFeature, QGeoRouteRequest::AvoidFeatureWeight); - - if (last_bearing) { - QVariantMap params; - int bearing = ((int)(*last_bearing) + 360) % 360; - params["bearing"] = bearing; - request.setWaypointsMetadata({params}); - } - - routing_manager->calculateRoute(request); -} - -void RouteEngine::routeCalculated(QGeoRouteReply *reply) { - if (reply->error() == QGeoRouteReply::NoError) { - if (reply->routes().size() != 0) { - qWarning() << "Got route response"; - - route = reply->routes().at(0); - segment = route.firstRouteSegment(); - - auto path = route.path(); - emit routeUpdated(path); - } else { - qWarning() << "Got empty route response"; - } - } else { - qWarning() << "Got error in route reply" << reply->errorString(); - } - - sendRoute(); - - reply->deleteLater(); -} - -void RouteEngine::sendRoute() { - MessageBuilder msg; - cereal::Event::Builder evt = msg.initEvent(); - cereal::NavRoute::Builder nav_route = evt.initNavRoute(); - - auto path = route.path(); - auto coordinates = nav_route.initCoordinates(path.size()); - - size_t i = 0; - for (auto const &c : route.path()) { - coordinates[i].setLatitude(c.latitude()); - coordinates[i].setLongitude(c.longitude()); - i++; - } - - pm->send("navRoute", msg); -} diff --git a/selfdrive/ui/navd/route_engine.h b/selfdrive/ui/navd/route_engine.h deleted file mode 100644 index 33cbc79107..0000000000 --- a/selfdrive/ui/navd/route_engine.h +++ /dev/null @@ -1,62 +0,0 @@ -#pragma once - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "cereal/messaging/messaging.h" - -class RouteEngine : public QObject { - Q_OBJECT - -public: - RouteEngine(); - - SubMaster *sm; - PubMaster *pm; - - QTimer* msg_timer; - QTimer* route_timer; - - std::optional ui_pid; - - // Route - bool gps_ok = false; - QGeoServiceProvider *geoservice_provider; - QGeoRoutingManager *routing_manager; - QGeoRoute route; - QGeoRouteSegment segment; - QMapbox::Coordinate nav_destination; - - // Position - std::optional last_position; - std::optional last_bearing; - bool localizer_valid = false; - - // Route recompute - bool active = false; - int recompute_backoff = 0; - int recompute_countdown = 0; - void calculateRoute(QMapbox::Coordinate destination); - void clearRoute(); - bool shouldRecompute(); - -private slots: - void routeUpdate(); - void msgUpdate(); - void routeCalculated(QGeoRouteReply *reply); - void recomputeRoute(); - void sendRoute(); - -signals: - void positionUpdated(QMapbox::Coordinate position, float bearing); - void routeUpdated(QList coordinates); -}; diff --git a/selfdrive/ui/qt/api.cc b/selfdrive/ui/qt/api.cc index 8ac9b41313..84e1a4032e 100644 --- a/selfdrive/ui/qt/api.cc +++ b/selfdrive/ui/qt/api.cc @@ -12,9 +12,9 @@ #include #include -#include "selfdrive/common/params.h" -#include "selfdrive/common/util.h" -#include "selfdrive/hardware/hw.h" +#include "common/params.h" +#include "common/util.h" +#include "system/hardware/hw.h" #include "selfdrive/ui/qt/util.h" namespace CommaApi { @@ -117,7 +117,7 @@ void HttpRequest::requestFinished() { networkTimer->stop(); if (reply->error() == QNetworkReply::NoError) { - emit requestDone(reply->readAll(), true); + emit requestDone(reply->readAll(), true, reply->error()); } else { QString error; if (reply->error() == QNetworkReply::OperationCanceledError) { @@ -125,12 +125,9 @@ void HttpRequest::requestFinished() { nam()->clearConnectionCache(); error = "Request timed out"; } else { - if (reply->error() == QNetworkReply::ContentAccessDenied || reply->error() == QNetworkReply::AuthenticationRequiredError) { - qWarning() << ">> Unauthorized. Authenticate with tools/lib/auth.py <<"; - } error = reply->errorString(); } - emit requestDone(error, false); + emit requestDone(error, false, reply->error()); } reply->deleteLater(); diff --git a/selfdrive/ui/qt/api.h b/selfdrive/ui/qt/api.h index 8f74678109..ad64d7e722 100644 --- a/selfdrive/ui/qt/api.h +++ b/selfdrive/ui/qt/api.h @@ -5,7 +5,7 @@ #include #include -#include "selfdrive/common/util.h" +#include "common/util.h" namespace CommaApi { @@ -31,7 +31,7 @@ public: bool timeout() const; signals: - void requestDone(const QString &response, bool success); + void requestDone(const QString &response, bool success, QNetworkReply::NetworkError error); protected: QNetworkReply *reply = nullptr; diff --git a/selfdrive/ui/qt/body.cc b/selfdrive/ui/qt/body.cc new file mode 100644 index 0000000000..f2628d304f --- /dev/null +++ b/selfdrive/ui/qt/body.cc @@ -0,0 +1,161 @@ +#include "selfdrive/ui/qt/body.h" + +#include +#include + +#include +#include + +#include "common/params.h" +#include "common/timing.h" + +RecordButton::RecordButton(QWidget *parent) : QPushButton(parent) { + setCheckable(true); + setChecked(false); + setFixedSize(148, 148); + + QObject::connect(this, &QPushButton::toggled, [=]() { + setEnabled(false); + }); +} + +void RecordButton::paintEvent(QPaintEvent *event) { + QPainter p(this); + p.setRenderHint(QPainter::Antialiasing); + + QPoint center(width() / 2, height() / 2); + + QColor bg(isChecked() ? "#FFFFFF" : "#737373"); + QColor accent(isChecked() ? "#FF0000" : "#FFFFFF"); + if (!isEnabled()) { + bg = QColor("#404040"); + accent = QColor("#FFFFFF"); + } + + if (isDown()) { + accent.setAlphaF(0.7); + } + + p.setPen(Qt::NoPen); + p.setBrush(bg); + p.drawEllipse(center, 74, 74); + + p.setPen(QPen(accent, 6)); + p.setBrush(Qt::NoBrush); + p.drawEllipse(center, 42, 42); + + p.setPen(Qt::NoPen); + p.setBrush(accent); + p.drawEllipse(center, 22, 22); +} + + +BodyWindow::BodyWindow(QWidget *parent) : fuel_filter(1.0, 5., 1. / UI_FREQ), QWidget(parent) { + QStackedLayout *layout = new QStackedLayout(this); + layout->setStackingMode(QStackedLayout::StackAll); + + QWidget *w = new QWidget; + QVBoxLayout *vlayout = new QVBoxLayout(w); + vlayout->setMargin(45); + layout->addWidget(w); + + // face + face = new QLabel(); + face->setAlignment(Qt::AlignCenter); + layout->addWidget(face); + awake = new QMovie("../assets/body/awake.gif"); + awake->setCacheMode(QMovie::CacheAll); + sleep = new QMovie("../assets/body/sleep.gif"); + sleep->setCacheMode(QMovie::CacheAll); + + // record button + btn = new RecordButton(this); + vlayout->addWidget(btn, 0, Qt::AlignBottom | Qt::AlignRight); + QObject::connect(btn, &QPushButton::clicked, [=](bool checked) { + btn->setEnabled(false); + Params().putBool("DisableLogging", !checked); + last_button = nanos_since_boot(); + }); + w->raise(); + + QObject::connect(uiState(), &UIState::uiUpdate, this, &BodyWindow::updateState); +} + +void BodyWindow::paintEvent(QPaintEvent *event) { + QPainter p(this); + p.setRenderHint(QPainter::Antialiasing); + + p.fillRect(rect(), QColor(0, 0, 0)); + + // battery outline + detail + p.translate(width() - 136, 16); + const QColor gray = QColor("#737373"); + p.setBrush(Qt::NoBrush); + p.setPen(QPen(gray, 4, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); + p.drawRoundedRect(2, 2, 78, 36, 8, 8); + + p.setPen(Qt::NoPen); + p.setBrush(gray); + p.drawRoundedRect(84, 12, 6, 16, 4, 4); + p.drawRect(84, 12, 3, 16); + + // battery level + double fuel = std::clamp(fuel_filter.x(), 0.2f, 1.0f); + const int m = 5; // manual margin since we can't do an inner border + p.setPen(Qt::NoPen); + p.setBrush(fuel > 0.25 ? QColor("#32D74B") : QColor("#FF453A")); + p.drawRoundedRect(2 + m, 2 + m, (78 - 2*m)*fuel, 36 - 2*m, 4, 4); + + // charging status + if (charging) { + p.setPen(Qt::NoPen); + p.setBrush(Qt::white); + const QPolygonF charger({ + QPointF(12.31, 0), + QPointF(12.31, 16.92), + QPointF(18.46, 16.92), + QPointF(6.15, 40), + QPointF(6.15, 23.08), + QPointF(0, 23.08), + }); + p.drawPolygon(charger.translated(98, 0)); + } +} + +void BodyWindow::offroadTransition(bool offroad) { + btn->setChecked(true); + btn->setEnabled(true); + fuel_filter.reset(1.0); +} + +void BodyWindow::updateState(const UIState &s) { + if (!isVisible()) { + return; + } + + const SubMaster &sm = *(s.sm); + auto cs = sm["carState"].getCarState(); + + charging = cs.getCharging(); + fuel_filter.update(cs.getFuelGauge()); + + // TODO: use carState.standstill when that's fixed + const bool standstill = std::abs(cs.getVEgo()) < 0.01; + QMovie *m = standstill ? sleep : awake; + if (m != face->movie()) { + face->setMovie(m); + face->movie()->start(); + } + + // update record button state + if (sm.updated("managerState") && (sm.rcv_time("managerState") - last_button)*1e-9 > 0.5) { + for (auto proc : sm["managerState"].getManagerState().getProcesses()) { + if (proc.getName() == "loggerd") { + btn->setEnabled(true); + btn->setChecked(proc.getRunning()); + } + } + } + + update(); +} diff --git a/selfdrive/ui/qt/body.h b/selfdrive/ui/qt/body.h new file mode 100644 index 0000000000..567a54d49b --- /dev/null +++ b/selfdrive/ui/qt/body.h @@ -0,0 +1,38 @@ +#pragma once + +#include +#include +#include + +#include "common/util.h" +#include "selfdrive/ui/ui.h" + +class RecordButton : public QPushButton { + Q_OBJECT + +public: + RecordButton(QWidget* parent = 0); + +private: + void paintEvent(QPaintEvent*) override; +}; + +class BodyWindow : public QWidget { + Q_OBJECT + +public: + BodyWindow(QWidget* parent = 0); + +private: + bool charging = false; + uint64_t last_button = 0; + FirstOrderFilter fuel_filter; + QLabel *face; + QMovie *awake, *sleep; + RecordButton *btn; + void paintEvent(QPaintEvent*) override; + +private slots: + void updateState(const UIState &s); + void offroadTransition(bool onroad); +}; diff --git a/selfdrive/ui/qt/home.cc b/selfdrive/ui/qt/home.cc index df4f474943..3f3c9a5885 100644 --- a/selfdrive/ui/qt/home.cc +++ b/selfdrive/ui/qt/home.cc @@ -1,11 +1,10 @@ #include "selfdrive/ui/qt/home.h" -#include #include #include #include -#include "selfdrive/common/params.h" +#include "selfdrive/ui/qt/offroad/experimental_mode.h" #include "selfdrive/ui/qt/util.h" #include "selfdrive/ui/qt/widgets/drive_stats.h" #include "selfdrive/ui/qt/widgets/prime.h" @@ -24,26 +23,43 @@ HomeWindow::HomeWindow(QWidget* parent) : QWidget(parent) { slayout = new QStackedLayout(); main_layout->addLayout(slayout); - home = new OffroadHome(); + home = new OffroadHome(this); + QObject::connect(home, &OffroadHome::openSettings, this, &HomeWindow::openSettings); slayout->addWidget(home); onroad = new OnroadWindow(this); slayout->addWidget(onroad); + body = new BodyWindow(this); + slayout->addWidget(body); + driver_view = new DriverViewWindow(this); connect(driver_view, &DriverViewWindow::done, [=] { showDriverView(false); }); slayout->addWidget(driver_view); setAttribute(Qt::WA_NoSystemBackground); + QObject::connect(uiState(), &UIState::uiUpdate, this, &HomeWindow::updateState); QObject::connect(uiState(), &UIState::offroadTransition, this, &HomeWindow::offroadTransition); + QObject::connect(uiState(), &UIState::offroadTransition, sidebar, &Sidebar::offroadTransition); } void HomeWindow::showSidebar(bool show) { sidebar->setVisible(show); } +void HomeWindow::updateState(const UIState &s) { + const SubMaster &sm = *(s.sm); + + // switch to the generic robot UI + if (onroad->isVisible() && !body->isEnabled() && sm["carParams"].getCarParams().getNotCar()) { + body->setEnabled(true); + slayout->setCurrentWidget(body); + } +} + void HomeWindow::offroadTransition(bool offroad) { + body->setEnabled(false); sidebar->setVisible(offroad); if (offroad) { slayout->setCurrentWidget(home); @@ -64,11 +80,24 @@ void HomeWindow::showDriverView(bool show) { void HomeWindow::mousePressEvent(QMouseEvent* e) { // Handle sidebar collapsing - if (onroad->isVisible() && (!sidebar->isVisible() || e->x() > sidebar->width())) { + if ((onroad->isVisible() || body->isVisible()) && (!sidebar->isVisible() || e->x() > sidebar->width())) { sidebar->setVisible(!sidebar->isVisible() && !onroad->isMapVisible()); } } +void HomeWindow::mouseDoubleClickEvent(QMouseEvent* e) { + HomeWindow::mousePressEvent(e); + const SubMaster &sm = *(uiState()->sm); + if (sm["carParams"].getCarParams().getNotCar()) { + if (onroad->isVisible()) { + slayout->setCurrentWidget(body); + } else if (body->isVisible()) { + slayout->setCurrentWidget(onroad); + } + showSidebar(false); + } +} + // OffroadHome: the offroad home page OffroadHome::OffroadHome(QWidget* parent) : QFrame(parent) { @@ -80,22 +109,20 @@ OffroadHome::OffroadHome(QWidget* parent) : QFrame(parent) { header_layout->setContentsMargins(15, 15, 15, 0); header_layout->setSpacing(16); - date = new QLabel(); - header_layout->addWidget(date, 1, Qt::AlignHCenter | Qt::AlignLeft); - - update_notif = new QPushButton("UPDATE"); + update_notif = new QPushButton(tr("UPDATE")); update_notif->setVisible(false); update_notif->setStyleSheet("background-color: #364DEF;"); QObject::connect(update_notif, &QPushButton::clicked, [=]() { center_layout->setCurrentIndex(1); }); - header_layout->addWidget(update_notif, 0, Qt::AlignHCenter | Qt::AlignRight); + header_layout->addWidget(update_notif, 0, Qt::AlignHCenter | Qt::AlignLeft); alert_notif = new QPushButton(); alert_notif->setVisible(false); alert_notif->setStyleSheet("background-color: #E22C2C;"); QObject::connect(alert_notif, &QPushButton::clicked, [=] { center_layout->setCurrentIndex(2); }); - header_layout->addWidget(alert_notif, 0, Qt::AlignHCenter | Qt::AlignRight); + header_layout->addWidget(alert_notif, 0, Qt::AlignHCenter | Qt::AlignLeft); - header_layout->addWidget(new QLabel(getBrandVersion()), 0, Qt::AlignHCenter | Qt::AlignRight); + version = new ElidedLabel(); + header_layout->addWidget(version, 0, Qt::AlignHCenter | Qt::AlignRight); main_layout->addLayout(header_layout); @@ -103,11 +130,24 @@ OffroadHome::OffroadHome(QWidget* parent) : QFrame(parent) { main_layout->addSpacing(25); center_layout = new QStackedLayout(); + // Vertical experimental button and drive stats layout + QWidget* statsAndExperimentalModeButtonWidget = new QWidget(this); + QVBoxLayout* statsAndExperimentalModeButton = new QVBoxLayout(statsAndExperimentalModeButtonWidget); + statsAndExperimentalModeButton->setSpacing(30); + statsAndExperimentalModeButton->setMargin(0); + + ExperimentalModeButton *experimental_mode = new ExperimentalModeButton(this); + QObject::connect(experimental_mode, &ExperimentalModeButton::openSettings, this, &OffroadHome::openSettings); + + statsAndExperimentalModeButton->addWidget(experimental_mode, 1); + statsAndExperimentalModeButton->addWidget(new DriveStats, 1); + + // Horizontal experimental + drive stats and setup widget QWidget* statsAndSetupWidget = new QWidget(this); QHBoxLayout* statsAndSetup = new QHBoxLayout(statsAndSetupWidget); statsAndSetup->setMargin(0); statsAndSetup->setSpacing(30); - statsAndSetup->addWidget(new DriveStats, 1); + statsAndSetup->addWidget(statsAndExperimentalModeButtonWidget, 1); statsAndSetup->addWidget(new SetupWidget); center_layout->addWidget(statsAndSetupWidget); @@ -155,7 +195,7 @@ void OffroadHome::hideEvent(QHideEvent *event) { } void OffroadHome::refresh() { - date->setText(QDateTime::currentDateTime().toString("dddd, MMMM d")); + version->setText(getBrand() + " " + QString::fromStdString(params.get("UpdaterCurrentDescription"))); bool updateAvailable = update_widget->refresh(); int alerts = alerts_widget->refresh(); @@ -174,6 +214,6 @@ void OffroadHome::refresh() { update_notif->setVisible(updateAvailable); alert_notif->setVisible(alerts); if (alerts) { - alert_notif->setText(QString::number(alerts) + (alerts > 1 ? " ALERTS" : " ALERT")); + alert_notif->setText(QString::number(alerts) + (alerts > 1 ? tr(" ALERTS") : tr(" ALERT"))); } } diff --git a/selfdrive/ui/qt/home.h b/selfdrive/ui/qt/home.h index 732071c153..ed1c215467 100644 --- a/selfdrive/ui/qt/home.h +++ b/selfdrive/ui/qt/home.h @@ -7,9 +7,12 @@ #include #include +#include "common/params.h" #include "selfdrive/ui/qt/offroad/driverview.h" +#include "selfdrive/ui/qt/body.h" #include "selfdrive/ui/qt/onroad.h" #include "selfdrive/ui/qt/sidebar.h" +#include "selfdrive/ui/qt/widgets/controls.h" #include "selfdrive/ui/qt/widgets/offroad_alerts.h" #include "selfdrive/ui/ui.h" @@ -19,13 +22,18 @@ class OffroadHome : public QFrame { public: explicit OffroadHome(QWidget* parent = 0); +signals: + void openSettings(int index = 0, const QString ¶m = ""); + private: void showEvent(QShowEvent *event) override; void hideEvent(QHideEvent *event) override; void refresh(); + Params params; + QTimer* timer; - QLabel* date; + ElidedLabel* version; QStackedLayout* center_layout; UpdateAlert *update_widget; OffroadAlert* alerts_widget; @@ -40,7 +48,7 @@ public: explicit HomeWindow(QWidget* parent = 0); signals: - void openSettings(); + void openSettings(int index = 0, const QString ¶m = ""); void closeSettings(); public slots: @@ -50,11 +58,16 @@ public slots: protected: void mousePressEvent(QMouseEvent* e) override; + void mouseDoubleClickEvent(QMouseEvent* e) override; private: Sidebar *sidebar; OffroadHome *home; OnroadWindow *onroad; + BodyWindow *body; DriverViewWindow *driver_view; QStackedLayout *slayout; + +private slots: + void updateState(const UIState &s); }; diff --git a/selfdrive/ui/qt/maps/map.cc b/selfdrive/ui/qt/maps/map.cc index 5e5fdb40cf..b5519daccf 100644 --- a/selfdrive/ui/qt/maps/map.cc +++ b/selfdrive/ui/qt/maps/map.cc @@ -1,16 +1,18 @@ #include "selfdrive/ui/qt/maps/map.h" +#include #include #include -#include #include +#include -#include "selfdrive/common/swaglog.h" -#include "selfdrive/ui/ui.h" -#include "selfdrive/ui/qt/util.h" +#include "common/swaglog.h" +#include "common/transformations/coordinates.hpp" #include "selfdrive/ui/qt/maps/map_helpers.h" #include "selfdrive/ui/qt/request_repeater.h" +#include "selfdrive/ui/qt/util.h" +#include "selfdrive/ui/ui.h" const int PAN_TIMEOUT = 100; @@ -22,18 +24,12 @@ const float MAX_PITCH = 50; const float MIN_PITCH = 0; const float MAP_SCALE = 2; -const QString ICON_SUFFIX = ".png"; - -MapWindow::MapWindow(const QMapboxGLSettings &settings) : - m_settings(settings), velocity_filter(0, 10, 0.05) { - sm = new SubMaster({"liveLocationKalman", "navInstruction", "navRoute"}); +const float VALID_POS_STD = 50.0; // m - // Connect now, so any navRoutes sent while the map is initializing are not dropped - sm->update(0); +const QString ICON_SUFFIX = ".png"; - timer = new QTimer(this); - QObject::connect(timer, SIGNAL(timeout()), this, SLOT(timerUpdate())); - timer->start(50); +MapWindow::MapWindow(const QMapboxGLSettings &settings) : m_settings(settings), velocity_filter(0, 10, 0.05) { + QObject::connect(uiState(), &UIState::uiUpdate, this, &MapWindow::updateState); // Instructions map_instructions = new MapInstructions(this); @@ -105,33 +101,65 @@ void MapWindow::initLayers() { } } -void MapWindow::timerUpdate() { +void MapWindow::updateState(const UIState &s) { if (!uiState()->scene.started) { return; } - + const SubMaster &sm = *(s.sm); update(); - sm->update(0); - if (sm->updated("liveLocationKalman")) { - auto location = (*sm)["liveLocationKalman"].getLiveLocationKalman(); - auto pos = location.getPositionGeodetic(); - auto orientation = location.getCalibratedOrientationNED(); + if (sm.updated("liveLocationKalman")) { + auto locationd_location = sm["liveLocationKalman"].getLiveLocationKalman(); + auto locationd_pos = locationd_location.getPositionGeodetic(); + auto locationd_orientation = locationd_location.getCalibratedOrientationNED(); + auto locationd_velocity = locationd_location.getVelocityCalibrated(); - localizer_valid = (location.getStatus() == cereal::LiveLocationKalman::Status::VALID) && pos.getValid(); + locationd_valid = (locationd_location.getStatus() == cereal::LiveLocationKalman::Status::VALID) && + locationd_pos.getValid() && locationd_orientation.getValid() && locationd_velocity.getValid(); - if (localizer_valid) { - float velocity = location.getVelocityCalibrated().getValue()[0]; - float bearing = RAD2DEG(orientation.getValue()[2]); - auto coordinate = QMapbox::Coordinate(pos.getValue()[0], pos.getValue()[1]); + if (locationd_valid) { + last_position = QMapbox::Coordinate(locationd_pos.getValue()[0], locationd_pos.getValue()[1]); + last_bearing = RAD2DEG(locationd_orientation.getValue()[2]); + velocity_filter.update(locationd_velocity.getValue()[0]); + } + } - last_position = coordinate; - last_bearing = bearing; + if (sm.updated("gnssMeasurements")) { + auto laikad_location = sm["gnssMeasurements"].getGnssMeasurements(); + auto laikad_pos = laikad_location.getPositionECEF(); + auto laikad_pos_ecef = laikad_pos.getValue(); + auto laikad_pos_std = laikad_pos.getStd(); + auto laikad_velocity_ecef = laikad_location.getVelocityECEF().getValue(); + + laikad_valid = laikad_pos.getValid() && Eigen::Vector3d(laikad_pos_std[0], laikad_pos_std[1], laikad_pos_std[2]).norm() < VALID_POS_STD; + + if (laikad_valid && !locationd_valid) { + ECEF ecef = {.x = laikad_pos_ecef[0], .y = laikad_pos_ecef[1], .z = laikad_pos_ecef[2]}; + Geodetic laikad_pos_geodetic = ecef2geodetic(ecef); + last_position = QMapbox::Coordinate(laikad_pos_geodetic.lat, laikad_pos_geodetic.lon); + + // Compute NED velocity + LocalCoord converter(ecef); + ECEF next_ecef = {.x = ecef.x + laikad_velocity_ecef[0], .y = ecef.y + laikad_velocity_ecef[1], .z = ecef.z + laikad_velocity_ecef[2]}; + Eigen::VectorXd ned_vel = converter.ecef2ned(next_ecef).to_vector() - converter.ecef2ned(ecef).to_vector(); + + float velocity = ned_vel.norm(); velocity_filter.update(velocity); + + // Convert NED velocity to angle + if (velocity > 1.0) { + float new_bearing = fmod(RAD2DEG(atan2(ned_vel[1], ned_vel[0])) + 360.0, 360.0); + if (last_bearing) { + float delta = 0.1 * angle_difference(*last_bearing, new_bearing); // Smooth heading + last_bearing = fmod(*last_bearing + delta + 360.0, 360.0); + } else { + last_bearing = new_bearing; + } + } } } - if (sm->updated("navRoute")) { + if (sm.updated("navRoute") && sm["navRoute"].getNavRoute().getCoordinates().size()) { qWarning() << "Got new navRoute from navd. Opening map:" << allow_open; // Only open the map on setting destination the first time @@ -147,15 +175,13 @@ void MapWindow::timerUpdate() { loaded_once = loaded_once || m_map->isFullyLoaded(); if (!loaded_once) { - map_instructions->showError("Map Loading"); + map_instructions->showError(tr("Map Loading")); return; } initLayers(); - if (!localizer_valid) { - map_instructions->showError("Waiting for GPS"); - } else { + if (locationd_valid || laikad_valid) { map_instructions->noError(); // Update current location marker @@ -165,6 +191,8 @@ void MapWindow::timerUpdate() { carPosSource["type"] = "geojson"; carPosSource["data"] = QVariant::fromValue(feature1); m_map->updateSource("carPosSource", carPosSource); + } else { + map_instructions->showError(tr("Waiting for GPS")); } if (pan_counter == 0) { @@ -176,16 +204,17 @@ void MapWindow::timerUpdate() { if (zoom_counter == 0) { m_map->setZoom(util::map_val(velocity_filter.x(), 0, 30, MAX_ZOOM, MIN_ZOOM)); - } else { + zoom_counter = -1; + } else if (zoom_counter > 0) { zoom_counter--; } - if (sm->updated("navInstruction")) { - if (sm->valid("navInstruction")) { - auto i = (*sm)["navInstruction"].getNavInstruction(); + if (sm.updated("navInstruction")) { + if (sm.valid("navInstruction")) { + auto i = sm["navInstruction"].getNavInstruction(); emit ETAChanged(i.getTimeRemaining(), i.getTimeRemainingTypical(), i.getDistanceRemaining()); - if (localizer_valid) { + if (locationd_valid || laikad_valid) { m_map->setPitch(MAX_PITCH); // TODO: smooth pitching based on maneuver distance emit distanceChanged(i.getManeuverDistance()); // TODO: combine with instructionsChanged emit instructionsChanged(i); @@ -196,9 +225,9 @@ void MapWindow::timerUpdate() { } } - if (sm->rcv_frame("navRoute") != route_rcv_frame) { + if (sm.rcv_frame("navRoute") != route_rcv_frame) { qWarning() << "Updating navLayer with new route"; - auto route = (*sm)["navRoute"].getNavRoute(); + auto route = sm["navRoute"].getNavRoute(); auto route_points = capnp_coordinate_list_to_collection(route.getCoordinates()); QMapbox::Feature feature(QMapbox::Feature::LineStringType, route_points, {}, {}); QVariantMap navSource; @@ -207,7 +236,7 @@ void MapWindow::timerUpdate() { m_map->updateSource("navSource", navSource); m_map->setLayoutProperty("navLayer", "visibility", "visible"); - route_rcv_frame = sm->rcv_frame("navRoute"); + route_rcv_frame = sm.rcv_frame("navRoute"); } } @@ -333,7 +362,7 @@ void MapWindow::offroadTransition(bool offroad) { } MapInstructions::MapInstructions(QWidget * parent) : QWidget(parent) { - is_rhd = Params().getBool("IsRHD"); + is_rhd = Params().getBool("IsRhdDetected"); QHBoxLayout *main_layout = new QHBoxLayout(this); main_layout->setContentsMargins(11, 50, 11, 11); { @@ -390,10 +419,10 @@ void MapInstructions::updateDistance(float d) { if (uiState()->scene.is_metric) { if (d > 500) { distance_str.setNum(d / 1000, 'f', 1); - distance_str += " km"; + distance_str += tr(" km"); } else { distance_str.setNum(50 * int(d / 50)); - distance_str += " m"; + distance_str += tr(" m"); } } else { float miles = d * METER_TO_MILE; @@ -401,10 +430,10 @@ void MapInstructions::updateDistance(float d) { if (feet > 500) { distance_str.setNum(miles, 'f', 1); - distance_str += " mi"; + distance_str += tr(" mi"); } else { distance_str.setNum(50 * int(feet / 50)); - distance_str += " ft"; + distance_str += tr(" ft"); } } @@ -458,9 +487,9 @@ void MapInstructions::updateInstructions(cereal::NavInstruction::Reader instruct // for rhd, reflect direction and then flip if (is_rhd) { if (fn.contains("left")) { - fn.replace(QString("left"), QString("right")); + fn.replace("left", "right"); } else if (fn.contains("right")) { - fn.replace(QString("right"), QString("left")); + fn.replace("right", "left"); } } @@ -498,9 +527,12 @@ void MapInstructions::updateInstructions(cereal::NavInstruction::Reader instruct fn += "turn_straight"; } + if (!active) { + fn += "_inactive"; + } + auto icon = new QLabel; - int wh = active ? 125 : 75; - icon->setPixmap(loadPixmap(fn + ICON_SUFFIX, {wh, wh}, Qt::IgnoreAspectRatio)); + icon->setPixmap(loadPixmap(fn + ICON_SUFFIX, {125, 125}, Qt::IgnoreAspectRatio)); icon->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); lane_layout->addWidget(icon); } @@ -587,7 +619,7 @@ void MapETA::updateETA(float s, float s_typical, float d) { auto eta_time = QDateTime::currentDateTime().addSecs(s).time(); if (params.getBool("NavSettingTime24h")) { eta->setText(eta_time.toString("HH:mm")); - eta_unit->setText("eta"); + eta_unit->setText(tr("eta")); } else { auto t = eta_time.toString("h:mm a").split(' '); eta->setText(t[0]); @@ -597,11 +629,11 @@ void MapETA::updateETA(float s, float s_typical, float d) { // Remaining time if (s < 3600) { time->setText(QString::number(int(s / 60))); - time_unit->setText("min"); + time_unit->setText(tr("min")); } else { int hours = int(s) / 3600; time->setText(QString::number(hours) + ":" + QString::number(int((s - hours * 3600) / 60)).rightJustified(2, '0')); - time_unit->setText("hr"); + time_unit->setText(tr("hr")); } QString color; @@ -621,10 +653,10 @@ void MapETA::updateETA(float s, float s_typical, float d) { float num = 0; if (uiState()->scene.is_metric) { num = d / 1000.0; - distance_unit->setText("km"); + distance_unit->setText(tr("km")); } else { num = d * METER_TO_MILE; - distance_unit->setText("mi"); + distance_unit->setText(tr("mi")); } distance_str.setNum(num, 'f', num < 100 ? 1 : 0); diff --git a/selfdrive/ui/qt/maps/map.h b/selfdrive/ui/qt/maps/map.h index c62089cb25..c3d5e92530 100644 --- a/selfdrive/ui/qt/maps/map.h +++ b/selfdrive/ui/qt/maps/map.h @@ -5,22 +5,22 @@ #include #include #include -#include #include +#include #include #include #include +#include #include #include -#include -#include +#include #include -#include -#include +#include -#include "selfdrive/common/params.h" -#include "selfdrive/common/util.h" #include "cereal/messaging/messaging.h" +#include "common/params.h" +#include "common/util.h" +#include "selfdrive/ui/ui.h" class MapInstructions : public QWidget { Q_OBJECT @@ -91,8 +91,6 @@ private: void pinchTriggered(QPinchGesture *gesture); bool m_sourceAdded = false; - SubMaster *sm; - QTimer* timer; bool loaded_once = false; bool allow_open = true; @@ -100,13 +98,14 @@ private: // Panning QPointF m_lastPos; int pan_counter = 0; - int zoom_counter = 0; + int zoom_counter = -1; // Position std::optional last_position; std::optional last_bearing; FirstOrderFilter velocity_filter; - bool localizer_valid = false; + bool laikad_valid = false; + bool locationd_valid = false; MapInstructions* map_instructions; MapETA* map_eta; @@ -115,7 +114,7 @@ private: uint64_t route_rcv_frame = 0; private slots: - void timerUpdate(); + void updateState(const UIState &s); public slots: void offroadTransition(bool offroad); diff --git a/selfdrive/ui/qt/maps/map_helpers.cc b/selfdrive/ui/qt/maps/map_helpers.cc index f0545924c0..8d5d4e1715 100644 --- a/selfdrive/ui/qt/maps/map_helpers.cc +++ b/selfdrive/ui/qt/maps/map_helpers.cc @@ -3,8 +3,8 @@ #include #include -#include "selfdrive/common/params.h" -#include "selfdrive/hardware/hw.h" +#include "common/params.h" +#include "system/hardware/hw.h" #include "selfdrive/ui/qt/api.h" QString get_mapbox_token() { @@ -44,61 +44,31 @@ QMapbox::CoordinatesCollections model_to_collection( for (int i = 0; i < x.size(); i++) { Eigen::Vector3d point_ecef = ecef_from_local * Eigen::Vector3d(x[i], y[i], z[i]) + ecef; Geodetic point_geodetic = ecef2geodetic((ECEF){.x = point_ecef[0], .y = point_ecef[1], .z = point_ecef[2]}); - QMapbox::Coordinate coordinate(point_geodetic.lat, point_geodetic.lon); - coordinates.push_back(coordinate); + coordinates.push_back({point_geodetic.lat, point_geodetic.lon}); } - QMapbox::CoordinatesCollection collection; - collection.push_back(coordinates); - - QMapbox::CoordinatesCollections collections; - collections.push_back(collection); - return collections; + return {QMapbox::CoordinatesCollection{coordinates}}; } -QMapbox::CoordinatesCollections coordinate_to_collection(QMapbox::Coordinate c) { - QMapbox::Coordinates coordinates; - coordinates.push_back(c); - - QMapbox::CoordinatesCollection collection; - collection.push_back(coordinates); - - QMapbox::CoordinatesCollections collections; - collections.push_back(collection); - return collections; +QMapbox::CoordinatesCollections coordinate_to_collection(const QMapbox::Coordinate &c) { + QMapbox::Coordinates coordinates{c}; + return {QMapbox::CoordinatesCollection{coordinates}}; } QMapbox::CoordinatesCollections capnp_coordinate_list_to_collection(const capnp::List::Reader& coordinate_list) { QMapbox::Coordinates coordinates; - for (auto const &c: coordinate_list) { - QMapbox::Coordinate coordinate(c.getLatitude(), c.getLongitude()); - coordinates.push_back(coordinate); + coordinates.push_back({c.getLatitude(), c.getLongitude()}); } - - QMapbox::CoordinatesCollection collection; - collection.push_back(coordinates); - - QMapbox::CoordinatesCollections collections; - collections.push_back(collection); - return collections; - + return {QMapbox::CoordinatesCollection{coordinates}}; } -QMapbox::CoordinatesCollections coordinate_list_to_collection(QList coordinate_list) { +QMapbox::CoordinatesCollections coordinate_list_to_collection(const QList &coordinate_list) { QMapbox::Coordinates coordinates; - for (auto &c : coordinate_list) { - QMapbox::Coordinate coordinate(c.latitude(), c.longitude()); - coordinates.push_back(coordinate); + coordinates.push_back({c.latitude(), c.longitude()}); } - - QMapbox::CoordinatesCollection collection; - collection.push_back(coordinates); - - QMapbox::CoordinatesCollections collections; - collections.push_back(collection); - return collections; + return {QMapbox::CoordinatesCollection{coordinates}}; } QList polyline_to_coordinate_list(const QString &polylineString) { @@ -143,60 +113,7 @@ QList polyline_to_coordinate_list(const QString &polylineString) return path; } -static QGeoCoordinate sub(QGeoCoordinate v, QGeoCoordinate w) { - return QGeoCoordinate(v.latitude() - w.latitude(), v.longitude() - w.longitude()); -} - -static QGeoCoordinate add(QGeoCoordinate v, QGeoCoordinate w) { - return QGeoCoordinate(v.latitude() + w.latitude(), v.longitude() + w.longitude()); -} - -static QGeoCoordinate mul(QGeoCoordinate v, float c) { - return QGeoCoordinate(c * v.latitude(), c * v.longitude()); -} - -static float dot(QGeoCoordinate v, QGeoCoordinate w) { - return v.latitude() * w.latitude() + v.longitude() * w.longitude(); -} - -float minimum_distance(QGeoCoordinate a, QGeoCoordinate b, QGeoCoordinate p) { - // If a and b are the same coordinate the computation below doesn't work - if (a.distanceTo(b) < 0.01) { - return a.distanceTo(p); - } - - const QGeoCoordinate ap = sub(p, a); - const QGeoCoordinate ab = sub(b, a); - const float t = std::clamp(dot(ap, ab) / dot(ab, ab), 0.0f, 1.0f); - const QGeoCoordinate projection = add(a, mul(ab, t)); - return projection.distanceTo(p); -} - -float distance_along_geometry(QList geometry, QGeoCoordinate pos) { - if (geometry.size() <= 2) { - return geometry[0].distanceTo(pos); - } - - // 1. Find segment that is closest to current position - // 2. Total distance is sum of distance to start of closest segment - // + all previous segments - double total_distance = 0; - double total_distance_closest = 0; - double closest_distance = std::numeric_limits::max(); - - for (int i = 0; i < geometry.size() - 1; i++) { - double d = minimum_distance(geometry[i], geometry[i+1], pos); - if (d < closest_distance) { - closest_distance = d; - total_distance_closest = total_distance + geometry[i].distanceTo(pos); - } - total_distance += geometry[i].distanceTo(geometry[i+1]); - } - - return total_distance_closest; -} - -std::optional coordinate_from_param(std::string param) { +std::optional coordinate_from_param(const std::string ¶m) { QString json_str = QString::fromStdString(Params().get(param)); if (json_str.isEmpty()) return {}; @@ -211,3 +128,8 @@ std::optional coordinate_from_param(std::string param) { return {}; } } + +double angle_difference(double angle1, double angle2) { + double diff = fmod(angle2 - angle1 + 180.0, 360.0) - 180.0; + return diff < -180.0 ? diff + 360.0 : diff; +} diff --git a/selfdrive/ui/qt/maps/map_helpers.h b/selfdrive/ui/qt/maps/map_helpers.h index 1c8cacbebc..6bd5b0f067 100644 --- a/selfdrive/ui/qt/maps/map_helpers.h +++ b/selfdrive/ui/qt/maps/map_helpers.h @@ -5,7 +5,7 @@ #include #include -#include "selfdrive/common/util.h" +#include "common/util.h" #include "common/transformations/coordinates.hpp" #include "common/transformations/orientation.hpp" #include "cereal/messaging/messaging.h" @@ -21,11 +21,10 @@ QMapbox::CoordinatesCollections model_to_collection( const cereal::LiveLocationKalman::Measurement::Reader &calibratedOrientationECEF, const cereal::LiveLocationKalman::Measurement::Reader &positionECEF, const cereal::ModelDataV2::XYZTData::Reader &line); -QMapbox::CoordinatesCollections coordinate_to_collection(QMapbox::Coordinate c); +QMapbox::CoordinatesCollections coordinate_to_collection(const QMapbox::Coordinate &c); QMapbox::CoordinatesCollections capnp_coordinate_list_to_collection(const capnp::List::Reader &coordinate_list); -QMapbox::CoordinatesCollections coordinate_list_to_collection(QList coordinate_list); +QMapbox::CoordinatesCollections coordinate_list_to_collection(const QList &coordinate_list); QList polyline_to_coordinate_list(const QString &polylineString); -float minimum_distance(QGeoCoordinate a, QGeoCoordinate b, QGeoCoordinate p); -std::optional coordinate_from_param(std::string param); -float distance_along_geometry(QList geometry, QGeoCoordinate pos); +std::optional coordinate_from_param(const std::string ¶m); +double angle_difference(double angle1, double angle2); diff --git a/selfdrive/ui/qt/maps/map_settings.cc b/selfdrive/ui/qt/maps/map_settings.cc index 1e3a99e31a..3205ca517d 100644 --- a/selfdrive/ui/qt/maps/map_settings.cc +++ b/selfdrive/ui/qt/maps/map_settings.cc @@ -2,7 +2,7 @@ #include -#include "selfdrive/common/util.h" +#include "common/util.h" #include "selfdrive/ui/qt/util.h" #include "selfdrive/ui/qt/request_repeater.h" #include "selfdrive/ui/qt/widgets/controls.h" @@ -59,11 +59,11 @@ MapPanel::MapPanel(QWidget* parent) : QWidget(parent) { current_widget = new QWidget(this); QVBoxLayout *current_layout = new QVBoxLayout(current_widget); - QLabel *title = new QLabel("Current Destination"); + QLabel *title = new QLabel(tr("Current Destination")); title->setStyleSheet("font-size: 55px"); current_layout->addWidget(title); - current_route = new ButtonControl("", "CLEAR"); + current_route = new ButtonControl("", tr("CLEAR")); current_route->setStyleSheet("padding-left: 40px;"); current_layout->addWidget(current_route); QObject::connect(current_route, &ButtonControl::clicked, [=]() { @@ -78,7 +78,7 @@ MapPanel::MapPanel(QWidget* parent) : QWidget(parent) { main_layout->addWidget(current_widget); // Recents - QLabel *recents_title = new QLabel("Recent Destinations"); + QLabel *recents_title = new QLabel(tr("Recent Destinations")); recents_title->setStyleSheet("font-size: 55px"); main_layout->addWidget(recents_title); main_layout->addSpacing(20); @@ -92,7 +92,7 @@ MapPanel::MapPanel(QWidget* parent) : QWidget(parent) { QWidget * no_prime_widget = new QWidget; { QVBoxLayout *no_prime_layout = new QVBoxLayout(no_prime_widget); - QLabel *signup_header = new QLabel("Try the Navigation Beta"); + QLabel *signup_header = new QLabel(tr("Try the Navigation Beta")); signup_header->setStyleSheet(R"(font-size: 75px; color: white; font-weight:600;)"); signup_header->setAlignment(Qt::AlignCenter); @@ -104,7 +104,7 @@ MapPanel::MapPanel(QWidget* parent) : QWidget(parent) { screenshot->setPixmap(pm.scaledToWidth(1080, Qt::SmoothTransformation)); no_prime_layout->addWidget(screenshot, 0, Qt::AlignHCenter); - QLabel *signup = new QLabel("Get turn-by-turn directions displayed and more with a comma \nprime subscription. Sign up now: https://connect.comma.ai"); + QLabel *signup = new QLabel(tr("Get turn-by-turn directions displayed and more with a comma\nprime subscription. Sign up now: https://connect.comma.ai")); signup->setStyleSheet(R"(font-size: 45px; color: white; font-weight:300;)"); signup->setAlignment(Qt::AlignCenter); @@ -115,7 +115,9 @@ MapPanel::MapPanel(QWidget* parent) : QWidget(parent) { stack->addWidget(main_widget); stack->addWidget(no_prime_widget); - stack->setCurrentIndex(uiState()->prime_type ? 0 : 1); + connect(uiState(), &UIState::primeTypeChanged, [=](int prime_type) { + stack->setCurrentIndex(prime_type ? 0 : 1); + }); QVBoxLayout *wrapper = new QVBoxLayout(this); wrapper->addWidget(stack); @@ -156,17 +158,18 @@ MapPanel::MapPanel(QWidget* parent) : QWidget(parent) { void MapPanel::showEvent(QShowEvent *event) { updateCurrentRoute(); + refresh(); } void MapPanel::clear() { home_button->setIcon(QPixmap("../assets/navigation/home_inactive.png")); home_address->setStyleSheet(R"(font-size: 50px; color: grey;)"); - home_address->setText("No home\nlocation set"); + home_address->setText(tr("No home\nlocation set")); home_button->disconnect(); work_button->setIcon(QPixmap("../assets/navigation/work_inactive.png")); work_address->setStyleSheet(R"(font-size: 50px; color: grey;)"); - work_address->setText("No work\nlocation set"); + work_address->setText(tr("No work\nlocation set")); work_button->disconnect(); clearLayout(recent_layout); @@ -184,18 +187,24 @@ void MapPanel::updateCurrentRoute() { } void MapPanel::parseResponse(const QString &response, bool success) { - stack->setCurrentIndex((uiState()->prime_type || success) ? 0 : 1); + if (!success) return; - if (!success) { - return; + cur_destinations = response; + if (isVisible()) { + refresh(); } +} + +void MapPanel::refresh() { + if (cur_destinations == prev_destinations) return; - QJsonDocument doc = QJsonDocument::fromJson(response.trimmed().toUtf8()); + QJsonDocument doc = QJsonDocument::fromJson(cur_destinations.trimmed().toUtf8()); if (doc.isNull()) { qDebug() << "JSON Parse failed on navigation locations"; return; } + prev_destinations = cur_destinations; clear(); bool has_recents = false; @@ -279,7 +288,7 @@ void MapPanel::parseResponse(const QString &response, bool success) { } if (!has_recents) { - QLabel *no_recents = new QLabel("no recent destinations"); + QLabel *no_recents = new QLabel(tr("no recent destinations")); no_recents->setStyleSheet(R"(font-size: 50px; color: #9c9c9c)"); recent_layout->addWidget(no_recents); } diff --git a/selfdrive/ui/qt/maps/map_settings.h b/selfdrive/ui/qt/maps/map_settings.h index 03720edee7..165673b7c1 100644 --- a/selfdrive/ui/qt/maps/map_settings.h +++ b/selfdrive/ui/qt/maps/map_settings.h @@ -8,7 +8,7 @@ #include #include -#include "selfdrive/common/params.h" +#include "common/params.h" #include "selfdrive/ui/qt/widgets/controls.h" class MapPanel : public QWidget { @@ -23,8 +23,10 @@ public: private: void showEvent(QShowEvent *event) override; + void refresh(); Params params; + QString prev_destinations, cur_destinations; QStackedWidget *stack; QPushButton *home_button, *work_button; QLabel *home_address, *work_address; diff --git a/selfdrive/ui/qt/offroad/driverview.cc b/selfdrive/ui/qt/offroad/driverview.cc index 3ab5b999b2..1377bb3b23 100644 --- a/selfdrive/ui/qt/offroad/driverview.cc +++ b/selfdrive/ui/qt/offroad/driverview.cc @@ -12,11 +12,11 @@ DriverViewWindow::DriverViewWindow(QWidget* parent) : QWidget(parent) { layout = new QStackedLayout(this); layout->setStackingMode(QStackedLayout::StackAll); - cameraView = new CameraViewWidget("camerad", VISION_STREAM_RGB_FRONT, true, this); + cameraView = new CameraWidget("camerad", VISION_STREAM_DRIVER, true, this); layout->addWidget(cameraView); scene = new DriverViewScene(this); - connect(cameraView, &CameraViewWidget::vipcThreadFrameReceived, scene, &DriverViewScene::frameUpdated); + connect(cameraView, &CameraWidget::vipcThreadFrameReceived, scene, &DriverViewScene::frameUpdated); layout->addWidget(scene); layout->setCurrentWidget(scene); } @@ -25,17 +25,17 @@ void DriverViewWindow::mouseReleaseEvent(QMouseEvent* e) { emit done(); } -DriverViewScene::DriverViewScene(QWidget* parent) : sm({"driverState"}), QWidget(parent) { +DriverViewScene::DriverViewScene(QWidget* parent) : sm({"driverStateV2"}), QWidget(parent) { face_img = loadPixmap("../assets/img_driver_face.png", {FACE_IMG_SIZE, FACE_IMG_SIZE}); } void DriverViewScene::showEvent(QShowEvent* event) { frame_updated = false; - is_rhd = params.getBool("IsRHD"); params.putBool("IsDriverViewEnabled", true); } void DriverViewScene::hideEvent(QHideEvent* event) { + // TODO: stop vipc thread ? params.putBool("IsDriverViewEnabled", false); } @@ -53,49 +53,40 @@ void DriverViewScene::paintEvent(QPaintEvent* event) { p.setPen(Qt::white); p.setRenderHint(QPainter::TextAntialiasing); configFont(p, "Inter", 100, "Bold"); - p.drawText(geometry(), Qt::AlignCenter, "camera starting"); + p.drawText(geometry(), Qt::AlignCenter, tr("camera starting")); return; } - const int width = 4 * height() / 3; - const QRect rect2 = {rect().center().x() - width / 2, rect().top(), width, rect().height()}; - const QRect valid_rect = {is_rhd ? rect2.right() - rect2.height() / 2 : rect2.left(), rect2.top(), rect2.height() / 2, rect2.height()}; - - // blackout - const QColor bg(0, 0, 0, 140); - const QRect& blackout_rect = Hardware::TICI() ? rect() : rect2; - p.fillRect(blackout_rect.adjusted(0, 0, valid_rect.left() - blackout_rect.right(), 0), bg); - p.fillRect(blackout_rect.adjusted(valid_rect.right() - blackout_rect.left(), 0, 0, 0), bg); - if (Hardware::TICI()) { - p.fillRect(blackout_rect.adjusted(valid_rect.left()-blackout_rect.left()+1, 0, valid_rect.right()-blackout_rect.right()-1, -valid_rect.height()*7/10), bg); // top dz - } + cereal::DriverStateV2::Reader driver_state = sm["driverStateV2"].getDriverStateV2(); + cereal::DriverStateV2::DriverData::Reader driver_data; + + is_rhd = driver_state.getWheelOnRightProb() > 0.5; + driver_data = is_rhd ? driver_state.getRightDriverData() : driver_state.getLeftDriverData(); - // face bounding box - cereal::DriverState::Reader driver_state = sm["driverState"].getDriverState(); - bool face_detected = driver_state.getFaceProb() > 0.5; + bool face_detected = driver_data.getFaceProb() > 0.7; if (face_detected) { - auto fxy_list = driver_state.getFacePosition(); - auto std_list = driver_state.getFaceOrientationStd(); + auto fxy_list = driver_data.getFacePosition(); + auto std_list = driver_data.getFaceOrientationStd(); float face_x = fxy_list[0]; float face_y = fxy_list[1]; float face_std = std::max(std_list[0], std_list[1]); float alpha = 0.7; - if (face_std > 0.08) { - alpha = std::max(0.7 - (face_std-0.08)*7, 0.0); + if (face_std > 0.15) { + alpha = std::max(0.7 - (face_std-0.15)*3.5, 0.0); } - const int box_size = 0.6 * rect2.height() / 2; - const float rhd_offset = 0.05; // lhd is shifted, so rhd is not mirrored - int fbox_x = valid_rect.center().x() + (is_rhd ? (face_x + rhd_offset) : -face_x) * valid_rect.width(); - int fbox_y = valid_rect.center().y() + face_y * valid_rect.height(); + const int box_size = 220; + // use approx instead of distort_points + int fbox_x = 1080.0 - 1714.0 * face_x; + int fbox_y = -135.0 + (504.0 + std::abs(face_x)*112.0) + (1205.0 - std::abs(face_x)*724.0) * face_y; p.setPen(QPen(QColor(255, 255, 255, alpha * 255), 10)); p.drawRoundedRect(fbox_x - box_size / 2, fbox_y - box_size / 2, box_size, box_size, 35.0, 35.0); } // icon - const int img_offset = 30; - const int img_x = is_rhd ? rect2.right() - FACE_IMG_SIZE - img_offset : rect2.left() + img_offset; - const int img_y = rect2.bottom() - FACE_IMG_SIZE - img_offset; - p.setOpacity(face_detected ? 1.0 : 0.3); + const int img_offset = 60; + const int img_x = is_rhd ? rect().right() - FACE_IMG_SIZE - img_offset : rect().left() + img_offset; + const int img_y = rect().bottom() - FACE_IMG_SIZE - img_offset; + p.setOpacity(face_detected ? 1.0 : 0.2); p.drawPixmap(img_x, img_y, face_img); } diff --git a/selfdrive/ui/qt/offroad/driverview.h b/selfdrive/ui/qt/offroad/driverview.h index 4d4a4358ef..255857970d 100644 --- a/selfdrive/ui/qt/offroad/driverview.h +++ b/selfdrive/ui/qt/offroad/driverview.h @@ -4,7 +4,7 @@ #include -#include "selfdrive/common/util.h" +#include "common/util.h" #include "selfdrive/ui/qt/widgets/cameraview.h" class DriverViewScene : public QWidget { @@ -42,7 +42,7 @@ protected: void mouseReleaseEvent(QMouseEvent* e) override; private: - CameraViewWidget *cameraView; + CameraWidget *cameraView; DriverViewScene *scene; QStackedLayout *layout; }; diff --git a/selfdrive/ui/qt/offroad/experimental_mode.cc b/selfdrive/ui/qt/offroad/experimental_mode.cc new file mode 100644 index 0000000000..b99220c1d1 --- /dev/null +++ b/selfdrive/ui/qt/offroad/experimental_mode.cc @@ -0,0 +1,76 @@ +#include "selfdrive/ui/qt/offroad/experimental_mode.h" + +#include +#include +#include +#include +#include + +#include "selfdrive/ui/ui.h" + +ExperimentalModeButton::ExperimentalModeButton(QWidget *parent) : QPushButton(parent) { + chill_pixmap = QPixmap("../assets/img_couch.svg").scaledToWidth(img_width, Qt::SmoothTransformation); + experimental_pixmap = QPixmap("../assets/img_experimental_grey.svg").scaledToWidth(img_width, Qt::SmoothTransformation); + + // go to toggles and expand experimental mode description + connect(this, &QPushButton::clicked, [=]() { emit openSettings(2, "ExperimentalMode"); }); + + setFixedHeight(125); + QHBoxLayout *main_layout = new QHBoxLayout; + main_layout->setContentsMargins(horizontal_padding, 0, horizontal_padding, 0); + + mode_label = new QLabel; + mode_icon = new QLabel; + mode_icon->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); + + main_layout->addWidget(mode_label, 1, Qt::AlignLeft); + main_layout->addWidget(mode_icon, 0, Qt::AlignRight); + + setLayout(main_layout); + + setStyleSheet(R"( + QPushButton { + border: none; + } + + QLabel { + font-size: 45px; + font-weight: 300; + text-align: left; + font-family: JetBrainsMono; + color: #000000; + } + )"); +} + +void ExperimentalModeButton::paintEvent(QPaintEvent *event) { + QPainter p(this); + p.setPen(Qt::NoPen); + p.setRenderHint(QPainter::Antialiasing); + + QPainterPath path; + path.addRoundedRect(rect(), 10, 10); + + // gradient + bool pressed = isDown(); + QLinearGradient gradient(rect().left(), 0, rect().right(), 0); + if (experimental_mode) { + gradient.setColorAt(0, QColor(255, 155, 63, pressed ? 0xcc : 0xff)); + gradient.setColorAt(1, QColor(219, 56, 34, pressed ? 0xcc : 0xff)); + } else { + gradient.setColorAt(0, QColor(20, 255, 171, pressed ? 0xcc : 0xff)); + gradient.setColorAt(1, QColor(35, 149, 255, pressed ? 0xcc : 0xff)); + } + p.fillPath(path, gradient); + + // vertical line + p.setPen(QPen(QColor(0, 0, 0, 0x4d), 3, Qt::SolidLine)); + int line_x = rect().right() - img_width - (2 * horizontal_padding); + p.drawLine(line_x, rect().bottom(), line_x, rect().top()); +} + +void ExperimentalModeButton::showEvent(QShowEvent *event) { + experimental_mode = params.getBool("ExperimentalMode"); + mode_icon->setPixmap(experimental_mode ? experimental_pixmap : chill_pixmap); + mode_label->setText(experimental_mode ? tr("EXPERIMENTAL MODE ON") : tr("CHILL MODE ON")); +} diff --git a/selfdrive/ui/qt/offroad/experimental_mode.h b/selfdrive/ui/qt/offroad/experimental_mode.h new file mode 100644 index 0000000000..bfb7638bbe --- /dev/null +++ b/selfdrive/ui/qt/offroad/experimental_mode.h @@ -0,0 +1,31 @@ +#pragma once + +#include +#include + +#include "common/params.h" + +class ExperimentalModeButton : public QPushButton { + Q_OBJECT + +public: + explicit ExperimentalModeButton(QWidget* parent = 0); + +signals: + void openSettings(int index = 0, const QString &toggle = ""); + +private: + void showEvent(QShowEvent *event) override; + + Params params; + bool experimental_mode; + int img_width = 100; + int horizontal_padding = 30; + QPixmap experimental_pixmap; + QPixmap chill_pixmap; + QLabel *mode_label; + QLabel *mode_icon; + +protected: + void paintEvent(QPaintEvent *event) override; +}; diff --git a/selfdrive/ui/qt/offroad/networking.cc b/selfdrive/ui/qt/offroad/networking.cc index 9c2088b1d7..d69d67edeb 100644 --- a/selfdrive/ui/qt/offroad/networking.cc +++ b/selfdrive/ui/qt/offroad/networking.cc @@ -8,9 +8,11 @@ #include #include +#include "selfdrive/ui/ui.h" #include "selfdrive/ui/qt/util.h" #include "selfdrive/ui/qt/qt_window.h" #include "selfdrive/ui/qt/widgets/controls.h" +#include "selfdrive/ui/qt/widgets/prime.h" #include "selfdrive/ui/qt/widgets/scrollview.h" @@ -27,10 +29,10 @@ Networking::Networking(QWidget* parent, bool show_advanced) : QFrame(parent) { QVBoxLayout* vlayout = new QVBoxLayout(wifiScreen); vlayout->setContentsMargins(20, 20, 20, 20); if (show_advanced) { - QPushButton* advancedSettings = new QPushButton("Advanced"); - advancedSettings->setObjectName("advancedBtn"); + QPushButton* advancedSettings = new QPushButton(tr("Advanced")); + advancedSettings->setObjectName("advanced_btn"); advancedSettings->setStyleSheet("margin-right: 30px;"); - advancedSettings->setFixedSize(350, 100); + advancedSettings->setFixedSize(400, 100); connect(advancedSettings, &QPushButton::clicked, [=]() { main_layout->setCurrentWidget(an); }); vlayout->addSpacing(10); vlayout->addWidget(advancedSettings, 0, Qt::AlignRight); @@ -55,16 +57,18 @@ Networking::Networking(QWidget* parent, bool show_advanced) : QFrame(parent) { setAutoFillBackground(true); setPalette(pal); - // TODO: revisit pressed colors setStyleSheet(R"( - #wifiWidget > QPushButton, #back_btn, #advancedBtn { + #wifiWidget > QPushButton, #back_btn, #advanced_btn { font-size: 50px; margin: 0px; padding: 15px; border-width: 0; border-radius: 30px; color: #dddddd; - background-color: #444444; + background-color: #393939; + } + #back_btn:pressed, #advanced_btn:pressed { + background-color: #4a4a4a; } )"); main_layout->setCurrentWidget(wifiScreen); @@ -82,7 +86,7 @@ void Networking::connectToNetwork(const Network &n) { } else if (n.security_type == SecurityType::OPEN) { wifi->connect(n); } else if (n.security_type == SecurityType::WPA) { - QString pass = InputDialog::getText("Enter password", this, "for \"" + n.ssid + "\"", true, 8); + QString pass = InputDialog::getText(tr("Enter password"), this, tr("for \"%1\"").arg(QString::fromUtf8(n.ssid)), true, 8); if (!pass.isEmpty()) { wifi->connect(n, pass); } @@ -92,7 +96,7 @@ void Networking::connectToNetwork(const Network &n) { void Networking::wrongPassword(const QString &ssid) { if (wifi->seenNetworks.contains(ssid)) { const Network &n = wifi->seenNetworks.value(ssid); - QString pass = InputDialog::getText("Wrong password", this, "for \"" + n.ssid +"\"", true, 8); + QString pass = InputDialog::getText(tr("Wrong password"), this, tr("for \"%1\"").arg(QString::fromUtf8(n.ssid)), true, 8); if (!pass.isEmpty()) { wifi->connect(n, pass); } @@ -116,22 +120,22 @@ AdvancedNetworking::AdvancedNetworking(QWidget* parent, WifiManager* wifi): QWid main_layout->setSpacing(20); // Back button - QPushButton* back = new QPushButton("Back"); + QPushButton* back = new QPushButton(tr("Back")); back->setObjectName("back_btn"); - back->setFixedSize(500, 100); + back->setFixedSize(400, 100); connect(back, &QPushButton::clicked, [=]() { emit backPress(); }); main_layout->addWidget(back, 0, Qt::AlignLeft); ListWidget *list = new ListWidget(this); // Enable tethering layout - tetheringToggle = new ToggleControl("Enable Tethering", "", "", wifi->isTetheringEnabled()); + tetheringToggle = new ToggleControl(tr("Enable Tethering"), "", "", wifi->isTetheringEnabled()); list->addItem(tetheringToggle); QObject::connect(tetheringToggle, &ToggleControl::toggleFlipped, this, &AdvancedNetworking::toggleTethering); // Change tethering password - ButtonControl *editPasswordButton = new ButtonControl("Tethering Password", "EDIT"); + ButtonControl *editPasswordButton = new ButtonControl(tr("Tethering Password"), tr("EDIT")); connect(editPasswordButton, &ButtonControl::clicked, [=]() { - QString pass = InputDialog::getText("Enter new tethering password", this, "", true, 8, wifi->getTetheringPassword()); + QString pass = InputDialog::getText(tr("Enter new tethering password"), this, "", true, 8, wifi->getTetheringPassword()); if (!pass.isEmpty()) { wifi->changeTetheringPassword(pass); } @@ -139,7 +143,7 @@ AdvancedNetworking::AdvancedNetworking(QWidget* parent, WifiManager* wifi): QWid list->addItem(editPasswordButton); // IP address - ipLabel = new LabelControl("IP Address", wifi->ipv4_address); + ipLabel = new LabelControl(tr("IP Address"), wifi->ipv4_address); list->addItem(ipLabel); // SSH keys @@ -148,31 +152,46 @@ AdvancedNetworking::AdvancedNetworking(QWidget* parent, WifiManager* wifi): QWid // Roaming toggle const bool roamingEnabled = params.getBool("GsmRoaming"); - ToggleControl *roamingToggle = new ToggleControl("Enable Roaming", "", "", roamingEnabled); - QObject::connect(roamingToggle, &SshToggle::toggleFlipped, [=](bool state) { + roamingToggle = new ToggleControl(tr("Enable Roaming"), "", "", roamingEnabled); + QObject::connect(roamingToggle, &ToggleControl::toggleFlipped, [=](bool state) { params.putBool("GsmRoaming", state); - wifi->updateGsmSettings(state, QString::fromStdString(params.get("GsmApn"))); + wifi->updateGsmSettings(state, QString::fromStdString(params.get("GsmApn")), params.getBool("GsmMetered")); }); list->addItem(roamingToggle); // APN settings - ButtonControl *editApnButton = new ButtonControl("APN Setting", "EDIT"); + editApnButton = new ButtonControl(tr("APN Setting"), tr("EDIT")); connect(editApnButton, &ButtonControl::clicked, [=]() { - const bool roamingEnabled = params.getBool("GsmRoaming"); const QString cur_apn = QString::fromStdString(params.get("GsmApn")); - QString apn = InputDialog::getText("Enter APN", this, "leave blank for automatic configuration", false, -1, cur_apn).trimmed(); + QString apn = InputDialog::getText(tr("Enter APN"), this, tr("leave blank for automatic configuration"), false, -1, cur_apn).trimmed(); if (apn.isEmpty()) { params.remove("GsmApn"); } else { params.put("GsmApn", apn.toStdString()); } - wifi->updateGsmSettings(roamingEnabled, apn); + wifi->updateGsmSettings(params.getBool("GsmRoaming"), apn, params.getBool("GsmMetered")); }); list->addItem(editApnButton); + // Metered toggle + const bool metered = params.getBool("GsmMetered"); + meteredToggle = new ToggleControl(tr("Cellular Metered"), tr("Prevent large data uploads when on a metered connection"), "", metered); + QObject::connect(meteredToggle, &SshToggle::toggleFlipped, [=](bool state) { + params.putBool("GsmMetered", state); + wifi->updateGsmSettings(params.getBool("GsmRoaming"), QString::fromStdString(params.get("GsmApn")), state); + }); + list->addItem(meteredToggle); + // Set initial config - wifi->updateGsmSettings(roamingEnabled, QString::fromStdString(params.get("GsmApn"))); + wifi->updateGsmSettings(roamingEnabled, QString::fromStdString(params.get("GsmApn")), metered); + + connect(uiState(), &UIState::primeTypeChanged, this, [=](int prime_type) { + bool gsmVisible = prime_type == PrimeType::NONE || prime_type == PrimeType::LITE; + roamingToggle->setVisible(gsmVisible); + editApnButton->setVisible(gsmVisible); + meteredToggle->setVisible(gsmVisible); + }); main_layout->addWidget(new ScrollView(list, this)); main_layout->addStretch(1); @@ -205,9 +224,12 @@ WifiUI::WifiUI(QWidget *parent, WifiManager* wifi) : QWidget(parent), wifi(wifi) checkmark = QPixmap(ASSET_PATH + "offroad/icon_checkmark.svg").scaledToWidth(49, Qt::SmoothTransformation); circled_slash = QPixmap(ASSET_PATH + "img_circled_slash.svg").scaledToWidth(49, Qt::SmoothTransformation); - QLabel *scanning = new QLabel("Scanning for networks..."); - scanning->setStyleSheet("font-size: 65px;"); - main_layout->addWidget(scanning, 0, Qt::AlignCenter); + scanningLabel = new QLabel(tr("Scanning for networks...")); + scanningLabel->setStyleSheet("font-size: 65px;"); + main_layout->addWidget(scanningLabel, 0, Qt::AlignCenter); + + list_layout = new QVBoxLayout; + main_layout->addLayout(list_layout); setStyleSheet(R"( QScrollBar::handle:vertical { @@ -255,14 +277,12 @@ WifiUI::WifiUI(QWidget *parent, WifiManager* wifi) : QWidget(parent), wifi(wifi) void WifiUI::refresh() { // TODO: don't rebuild this every time - clearLayout(main_layout); + clearLayout(list_layout); + + bool is_empty = wifi->seenNetworks.isEmpty(); + scanningLabel->setVisible(is_empty); + if (is_empty) return; - if (wifi->seenNetworks.size() == 0) { - QLabel *scanning = new QLabel("Scanning for networks..."); - scanning->setStyleSheet("font-size: 65px;"); - main_layout->addWidget(scanning, 0, Qt::AlignCenter); - return; - } QList sortedNetworks = wifi->seenNetworks.values(); std::sort(sortedNetworks.begin(), sortedNetworks.end(), compare_by_strength); @@ -284,17 +304,17 @@ void WifiUI::refresh() { hlayout->addWidget(ssidLabel, network.connected == ConnectedType::CONNECTING ? 0 : 1); if (network.connected == ConnectedType::CONNECTING) { - QPushButton *connecting = new QPushButton("CONNECTING..."); + QPushButton *connecting = new QPushButton(tr("CONNECTING...")); connecting->setObjectName("connecting"); hlayout->addWidget(connecting, 2, Qt::AlignLeft); } // Forget button if (wifi->isKnownConnection(network.ssid) && !wifi->isTetheringEnabled()) { - QPushButton *forgetBtn = new QPushButton("FORGET"); + QPushButton *forgetBtn = new QPushButton(tr("FORGET")); forgetBtn->setObjectName("forgetBtn"); QObject::connect(forgetBtn, &QPushButton::clicked, [=]() { - if (ConfirmationDialog::confirm("Forget Wi-Fi Network \"" + QString::fromUtf8(network.ssid) + "\"?", this)) { + if (ConfirmationDialog::confirm(tr("Forget Wi-Fi Network \"%1\"?").arg(QString::fromUtf8(network.ssid)), tr("Forget"), this)) { wifi->forgetConnection(network.ssid); } }); @@ -325,6 +345,6 @@ void WifiUI::refresh() { list->addItem(hlayout); } - main_layout->addWidget(list); - main_layout->addStretch(1); + list_layout->addWidget(list); + list_layout->addStretch(1); } diff --git a/selfdrive/ui/qt/offroad/networking.h b/selfdrive/ui/qt/offroad/networking.h index e78d65ef0f..79cbcc3493 100644 --- a/selfdrive/ui/qt/offroad/networking.h +++ b/selfdrive/ui/qt/offroad/networking.h @@ -17,6 +17,8 @@ public: private: WifiManager *wifi = nullptr; + QVBoxLayout *list_layout = nullptr; + QLabel *scanningLabel = nullptr; QVBoxLayout* main_layout; QPixmap lock; QPixmap checkmark; @@ -38,6 +40,9 @@ public: private: LabelControl* ipLabel; ToggleControl* tetheringToggle; + ToggleControl* roamingToggle; + ButtonControl* editApnButton; + ToggleControl* meteredToggle; WifiManager* wifi = nullptr; Params params; diff --git a/selfdrive/ui/qt/offroad/networkmanager.h b/selfdrive/ui/qt/offroad/networkmanager.h index 52d85c16af..31b33fc9f5 100644 --- a/selfdrive/ui/qt/offroad/networkmanager.h +++ b/selfdrive/ui/qt/offroad/networkmanager.h @@ -36,3 +36,10 @@ const int NM_DEVICE_TYPE_WIFI = 2; const int NM_DEVICE_TYPE_MODEM = 8; const int NM_DEVICE_STATE_REASON_SUPPLICANT_DISCONNECT = 8; const int DBUS_TIMEOUT = 100; + +// https://developer-old.gnome.org/NetworkManager/1.26/nm-dbus-types.html#NMMetered +const int NM_METERED_UNKNOWN = 0; +const int NM_METERED_YES = 1; +const int NM_METERED_NO = 2; +const int NM_METERED_GUESS_YES = 3; +const int NM_METERED_GUESS_NO = 4; diff --git a/selfdrive/ui/qt/offroad/onboarding.cc b/selfdrive/ui/qt/offroad/onboarding.cc index 458464239e..f3e50b572b 100644 --- a/selfdrive/ui/qt/offroad/onboarding.cc +++ b/selfdrive/ui/qt/offroad/onboarding.cc @@ -6,8 +6,8 @@ #include #include -#include "selfdrive/common/util.h" -#include "selfdrive/common/params.h" +#include "common/util.h" +#include "common/params.h" #include "selfdrive/ui/qt/util.h" #include "selfdrive/ui/qt/widgets/input.h" @@ -23,7 +23,7 @@ void TrainingGuide::mouseReleaseEvent(QMouseEvent *e) { if (boundingRect[currentIndex].contains(e->x(), e->y())) { if (currentIndex == 9) { - const QRect yes = QRect(692, 842, 492, 148); + const QRect yes = QRect(707, 804, 531, 164); Params().putBool("RecordFront", yes.contains(e->x(), e->y())); } currentIndex += 1; @@ -76,7 +76,7 @@ void TermsPage::showEvent(QShowEvent *event) { main_layout->setContentsMargins(45, 35, 45, 45); main_layout->setSpacing(0); - QLabel *title = new QLabel("Terms & Conditions"); + QLabel *title = new QLabel(tr("Terms & Conditions")); title->setStyleSheet("font-size: 90px; font-weight: 600;"); main_layout->addWidget(title); @@ -104,11 +104,11 @@ void TermsPage::showEvent(QShowEvent *event) { buttons->setSpacing(45); main_layout->addLayout(buttons); - QPushButton *decline_btn = new QPushButton("Decline"); + QPushButton *decline_btn = new QPushButton(tr("Decline")); buttons->addWidget(decline_btn); QObject::connect(decline_btn, &QPushButton::clicked, this, &TermsPage::declinedTerms); - accept_btn = new QPushButton("Scroll to accept"); + accept_btn = new QPushButton(tr("Scroll to accept")); accept_btn->setEnabled(false); accept_btn->setStyleSheet(R"( QPushButton { @@ -123,7 +123,7 @@ void TermsPage::showEvent(QShowEvent *event) { } void TermsPage::enableAccept() { - accept_btn->setText("Agree"); + accept_btn->setText(tr("Agree")); accept_btn->setEnabled(true); } @@ -137,7 +137,7 @@ void DeclinePage::showEvent(QShowEvent *event) { main_layout->setSpacing(40); QLabel *text = new QLabel(this); - text->setText("You must accept the Terms and Conditions in order to use openpilot."); + text->setText(tr("You must accept the Terms and Conditions in order to use openpilot.")); text->setStyleSheet(R"(font-size: 80px; font-weight: 300; margin: 200px;)"); text->setWordWrap(true); main_layout->addWidget(text, 0, Qt::AlignCenter); @@ -146,12 +146,12 @@ void DeclinePage::showEvent(QShowEvent *event) { buttons->setSpacing(45); main_layout->addLayout(buttons); - QPushButton *back_btn = new QPushButton("Back"); + QPushButton *back_btn = new QPushButton(tr("Back")); buttons->addWidget(back_btn); QObject::connect(back_btn, &QPushButton::clicked, this, &DeclinePage::getBack); - QPushButton *uninstall_btn = new QPushButton(QString("Decline, uninstall %1").arg(getBrand())); + QPushButton *uninstall_btn = new QPushButton(tr("Decline, uninstall %1").arg(getBrand())); uninstall_btn->setStyleSheet("background-color: #B73D3D"); buttons->addWidget(uninstall_btn); QObject::connect(uninstall_btn, &QPushButton::clicked, [=]() { diff --git a/selfdrive/ui/qt/offroad/onboarding.h b/selfdrive/ui/qt/offroad/onboarding.h index 9424c07d19..48f4094899 100644 --- a/selfdrive/ui/qt/offroad/onboarding.h +++ b/selfdrive/ui/qt/offroad/onboarding.h @@ -7,7 +7,7 @@ #include #include -#include "selfdrive/common/params.h" +#include "common/params.h" #include "selfdrive/ui/qt/qt_window.h" class TrainingGuide : public QFrame { @@ -25,52 +25,52 @@ private: int currentIndex = 0; // Bounding boxes for each training guide step - const QRect continueBtnStandard = {1610, 0, 310, 1080}; + const QRect continueBtnStandard = {1620, 0, 300, 1080}; QVector boundingRectStandard { - QRect(650, 710, 720, 190), + QRect(112, 804, 619, 166), continueBtnStandard, continueBtnStandard, - QRect(1442, 565, 230, 310), - QRect(1515, 562, 133, 60), + QRect(1476, 565, 253, 308), + QRect(1501, 529, 184, 108), continueBtnStandard, - QRect(1580, 630, 215, 130), - QRect(1210, 0, 485, 590), - QRect(1460, 400, 375, 210), - QRect(166, 842, 1019, 148), - QRect(1460, 210, 300, 310), + QRect(1613, 665, 178, 153), + QRect(1220, 0, 420, 730), + QRect(1335, 499, 440, 147), + QRect(112, 820, 996, 148), + QRect(1412, 199, 316, 333), continueBtnStandard, - QRect(1375, 80, 545, 1000), + QRect(1237, 63, 683, 1017), continueBtnStandard, - QRect(1610, 130, 280, 800), - QRect(1385, 485, 400, 270), + QRect(1455, 110, 313, 860), + QRect(1253, 519, 383, 228), continueBtnStandard, continueBtnStandard, - QRect(1036, 769, 718, 189), - QRect(201, 769, 718, 189), + QRect(630, 804, 626, 164), + QRect(108, 804, 426, 164), }; - const QRect continueBtnWide = {1850, 0, 310, 1080}; + const QRect continueBtnWide = {1840, 0, 320, 1080}; QVector boundingRectWide { - QRect(654, 721, 718, 189), + QRect(112, 804, 618, 164), continueBtnWide, continueBtnWide, - QRect(1690, 570, 165, 300), - QRect(1690, 560, 133, 60), + QRect(1641, 558, 210, 313), + QRect(1662, 528, 184, 108), continueBtnWide, - QRect(1820, 630, 180, 155), - QRect(1360, 0, 460, 620), - QRect(1570, 400, 375, 215), - QRect(167, 842, 1018, 148), - QRect(1610, 210, 295, 310), + QRect(1814, 621, 211, 170), + QRect(1350, 0, 497, 755), + QRect(1553, 516, 406, 112), + QRect(112, 804, 1126, 164), + QRect(1598, 199, 316, 333), continueBtnWide, - QRect(1555, 90, 610, 990), + QRect(1364, 90, 796, 990), continueBtnWide, - QRect(1600, 140, 280, 790), - QRect(1385, 490, 750, 270), + QRect(1593, 114, 318, 853), + QRect(1379, 511, 391, 243), continueBtnWide, continueBtnWide, - QRect(1138, 755, 718, 189), - QRect(303, 755, 718, 189), + QRect(630, 804, 626, 164), + QRect(108, 804, 426, 164), }; QString img_path; diff --git a/selfdrive/ui/qt/offroad/settings.cc b/selfdrive/ui/qt/offroad/settings.cc index f3584460d6..bde8628dc4 100644 --- a/selfdrive/ui/qt/offroad/settings.cc +++ b/selfdrive/ui/qt/offroad/settings.cc @@ -6,17 +6,16 @@ #include -#ifndef QCOM #include "selfdrive/ui/qt/offroad/networking.h" -#endif #ifdef ENABLE_MAPS #include "selfdrive/ui/qt/maps/map_settings.h" #endif -#include "selfdrive/common/params.h" -#include "selfdrive/common/util.h" -#include "selfdrive/hardware/hw.h" +#include "common/params.h" +#include "common/watchdog.h" +#include "common/util.h" +#include "system/hardware/hw.h" #include "selfdrive/ui/qt/widgets/controls.h" #include "selfdrive/ui/qt/widgets/input.h" #include "selfdrive/ui/qt/widgets/scrollview.h" @@ -25,104 +24,173 @@ #include "selfdrive/ui/ui.h" #include "selfdrive/ui/qt/util.h" #include "selfdrive/ui/qt/qt_window.h" +#include "selfdrive/ui/qt/widgets/input.h" TogglesPanel::TogglesPanel(SettingsWindow *parent) : ListWidget(parent) { - // param, title, desc, icon - std::vector> toggles{ + // param, title, desc, icon, confirm + std::vector> toggle_defs{ { "OpenpilotEnabledToggle", - "Enable openpilot", - "Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off.", + tr("Enable openpilot"), + tr("Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off."), "../assets/offroad/icon_openpilot.png", }, { - "IsLdwEnabled", - "Enable Lane Departure Warnings", - "Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h).", - "../assets/offroad/icon_warning.png", + "ExperimentalMode", + tr("Experimental Mode"), + "", + "../assets/img_experimental_white.svg", + }, + { + "ExperimentalLongitudinalEnabled", + tr("Experimental openpilot Longitudinal Control"), + QString("%1
%2") + .arg(tr("WARNING: openpilot longitudinal control is experimental for this car and will disable Automatic Emergency Braking (AEB).")) + .arg(tr("On this car, openpilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when using experimental openpilot longitudinal control.")), + "../assets/offroad/icon_speed_limit.png", }, { - "IsRHD", - "Enable Right-Hand Drive", - "Allow openpilot to obey left-hand traffic conventions and perform driver monitoring on right driver seat.", - "../assets/offroad/icon_openpilot_mirrored.png", + "IsLdwEnabled", + tr("Enable Lane Departure Warnings"), + tr("Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h)."), + "../assets/offroad/icon_warning.png", }, { "IsMetric", - "Use Metric System", - "Display speed in km/h instead of mph.", + tr("Use Metric System"), + tr("Display speed in km/h instead of mph."), "../assets/offroad/icon_metric.png", }, { "RecordFront", - "Record and Upload Driver Camera", - "Upload data from the driver facing camera and help improve the driver monitoring algorithm.", + tr("Record and Upload Driver Camera"), + tr("Upload data from the driver facing camera and help improve the driver monitoring algorithm."), "../assets/offroad/icon_monitoring.png", }, { - "EndToEndToggle", - "\U0001f96c Disable use of lanelines (Alpha) \U0001f96c", - "In this mode openpilot will ignore lanelines and just drive how it thinks a human would.", - "../assets/offroad/icon_road.png", + "DisengageOnAccelerator", + tr("Disengage on Accelerator Pedal"), + tr("When enabled, pressing the accelerator pedal will disengage openpilot."), + "../assets/offroad/icon_disengage_on_accelerator.svg", }, #ifdef ENABLE_MAPS { "NavSettingTime24h", - "Show ETA in 24h format", - "Use 24h format instead of am/pm", + tr("Show ETA in 24h Format"), + tr("Use 24h format instead of am/pm"), "../assets/offroad/icon_metric.png", }, + { + "NavSettingLeftSide", + tr("Show Map on Left Side of UI"), + tr("Show map on left side when in split screen view."), + "../assets/offroad/icon_road.png", + }, #endif - }; - Params params; - - if (params.getBool("DisableRadar_Allow")) { - toggles.push_back({ - "DisableRadar", - "openpilot Longitudinal Control", - "openpilot will disable the car's radar and will take over control of gas and brakes. Warning: this disables AEB!", - "../assets/offroad/icon_speed_limit.png", - }); - } - - for (auto &[param, title, desc, icon] : toggles) { + for (auto &[param, title, desc, icon] : toggle_defs) { auto toggle = new ParamControl(param, title, desc, icon, this); + bool locked = params.getBool((param + "Lock").toStdString()); toggle->setEnabled(!locked); - if (!locked) { - connect(uiState(), &UIState::offroadTransition, toggle, &ParamControl::setEnabled); - } + addItem(toggle); + toggles[param.toStdString()] = toggle; + } + + // Toggles with confirmation dialogs + toggles["ExperimentalMode"]->setActiveIcon("../assets/img_experimental.svg"); + toggles["ExperimentalMode"]->setConfirmation(true, true); + toggles["ExperimentalLongitudinalEnabled"]->setConfirmation(true, false); + + connect(toggles["ExperimentalLongitudinalEnabled"], &ToggleControl::toggleFlipped, [=]() { + updateToggles(); + }); +} + +void TogglesPanel::expandToggleDescription(const QString ¶m) { + toggles[param.toStdString()]->showDescription(); +} + +void TogglesPanel::showEvent(QShowEvent *event) { + updateToggles(); +} + +void TogglesPanel::updateToggles() { + auto e2e_toggle = toggles["ExperimentalMode"]; + auto op_long_toggle = toggles["ExperimentalLongitudinalEnabled"]; + const QString e2e_description = QString("%1
" + "

%2


" + "%3
" + "

%4


" + "%5") + .arg(tr("openpilot defaults to driving in chill mode. Experimental mode enables alpha-level features that aren't ready for chill mode. Experimental features are listed below:")) + .arg(tr("🌮 End-to-End Longitudinal Control 🌮")) + .arg(tr("Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would, including stopping for red lights and stop signs. " + "Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected.")) + .arg(tr("New Driving Visualization")) + .arg(tr("The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner.")); + + auto cp_bytes = params.get("CarParamsPersistent"); + if (!cp_bytes.empty()) { + AlignedBuffer aligned_buf; + capnp::FlatArrayMessageReader cmsg(aligned_buf.align(cp_bytes.data(), cp_bytes.size())); + cereal::CarParams::Reader CP = cmsg.getRoot(); + + if (!CP.getExperimentalLongitudinalAvailable()) { + params.remove("ExperimentalLongitudinalEnabled"); + } + op_long_toggle->setVisible(CP.getExperimentalLongitudinalAvailable()); + + const bool op_long = CP.getOpenpilotLongitudinalControl() && !CP.getExperimentalLongitudinalAvailable(); + const bool exp_long_enabled = CP.getExperimentalLongitudinalAvailable() && params.getBool("ExperimentalLongitudinalEnabled"); + if (op_long || exp_long_enabled) { + // normal description and toggle + e2e_toggle->setEnabled(true); + e2e_toggle->setDescription(e2e_description); + } else { + // no long for now + e2e_toggle->setEnabled(false); + params.remove("ExperimentalMode"); + + const QString no_long = tr("Experimental mode is currently unavailable on this car, since the car's stock ACC is used for longitudinal control."); + const QString exp_long = tr("Enable experimental longitudinal control to allow experimental mode."); + e2e_toggle->setDescription("" + (CP.getExperimentalLongitudinalAvailable() ? exp_long : no_long) + "

" + e2e_description); + } + + e2e_toggle->refresh(); + } else { + e2e_toggle->setDescription(e2e_description); + op_long_toggle->setVisible(false); } } DevicePanel::DevicePanel(SettingsWindow *parent) : ListWidget(parent) { setSpacing(50); - addItem(new LabelControl("Dongle ID", getDongleId().value_or("N/A"))); - addItem(new LabelControl("Serial", params.get("HardwareSerial").c_str())); + addItem(new LabelControl(tr("Dongle ID"), getDongleId().value_or(tr("N/A")))); + addItem(new LabelControl(tr("Serial"), params.get("HardwareSerial").c_str())); // offroad-only buttons - auto dcamBtn = new ButtonControl("Driver Camera", "PREVIEW", - "Preview the driver facing camera to help optimize device mounting position for best driver monitoring experience. (vehicle must be off)"); + auto dcamBtn = new ButtonControl(tr("Driver Camera"), tr("PREVIEW"), + tr("Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)")); connect(dcamBtn, &ButtonControl::clicked, [=]() { emit showDriverView(); }); addItem(dcamBtn); - auto resetCalibBtn = new ButtonControl("Reset Calibration", "RESET", " "); - connect(resetCalibBtn, &ButtonControl::showDescription, this, &DevicePanel::updateCalibDescription); + auto resetCalibBtn = new ButtonControl(tr("Reset Calibration"), tr("RESET"), ""); + connect(resetCalibBtn, &ButtonControl::showDescriptionEvent, this, &DevicePanel::updateCalibDescription); connect(resetCalibBtn, &ButtonControl::clicked, [&]() { - if (ConfirmationDialog::confirm("Are you sure you want to reset calibration?", this)) { + if (ConfirmationDialog::confirm(tr("Are you sure you want to reset calibration?"), tr("Reset"), this)) { params.remove("CalibrationParams"); } }); addItem(resetCalibBtn); if (!params.getBool("Passive")) { - auto retrainingBtn = new ButtonControl("Review Training Guide", "REVIEW", "Review the rules, features, and limitations of openpilot"); + auto retrainingBtn = new ButtonControl(tr("Review Training Guide"), tr("REVIEW"), tr("Review the rules, features, and limitations of openpilot")); connect(retrainingBtn, &ButtonControl::clicked, [=]() { - if (ConfirmationDialog::confirm("Are you sure you want to review the training guide?", this)) { + if (ConfirmationDialog::confirm(tr("Are you sure you want to review the training guide?"), tr("Review"), this)) { emit reviewTrainingGuide(); } }); @@ -130,14 +198,27 @@ DevicePanel::DevicePanel(SettingsWindow *parent) : ListWidget(parent) { } if (Hardware::TICI()) { - auto regulatoryBtn = new ButtonControl("Regulatory", "VIEW", ""); + auto regulatoryBtn = new ButtonControl(tr("Regulatory"), tr("VIEW"), ""); connect(regulatoryBtn, &ButtonControl::clicked, [=]() { const std::string txt = util::read_file("../assets/offroad/fcc.html"); - RichTextDialog::alert(QString::fromStdString(txt), this); + ConfirmationDialog::rich(QString::fromStdString(txt), this); }); addItem(regulatoryBtn); } + auto translateBtn = new ButtonControl(tr("Change Language"), tr("CHANGE"), ""); + connect(translateBtn, &ButtonControl::clicked, [=]() { + QMap langs = getSupportedLanguages(); + QString selection = MultiOptionDialog::getSelection(tr("Select a language"), langs.keys(), langs.key(uiState()->language), this); + if (!selection.isEmpty()) { + // put language setting, exit Qt UI, and trigger fast restart + Params().put("LanguageSetting", langs[selection].toStdString()); + qApp->exit(18); + watchdog_kick(0); + } + }); + addItem(translateBtn); + QObject::connect(uiState(), &UIState::offroadTransition, [=](bool offroad) { for (auto btn : findChildren()) { btn->setEnabled(offroad); @@ -148,17 +229,17 @@ DevicePanel::DevicePanel(SettingsWindow *parent) : ListWidget(parent) { QHBoxLayout *power_layout = new QHBoxLayout(); power_layout->setSpacing(30); - QPushButton *reboot_btn = new QPushButton("Reboot"); + QPushButton *reboot_btn = new QPushButton(tr("Reboot")); reboot_btn->setObjectName("reboot_btn"); power_layout->addWidget(reboot_btn); QObject::connect(reboot_btn, &QPushButton::clicked, this, &DevicePanel::reboot); - QPushButton *poweroff_btn = new QPushButton("Power Off"); + QPushButton *poweroff_btn = new QPushButton(tr("Power Off")); poweroff_btn->setObjectName("poweroff_btn"); power_layout->addWidget(poweroff_btn); QObject::connect(poweroff_btn, &QPushButton::clicked, this, &DevicePanel::poweroff); - if (Hardware::TICI()) { + if (!Hardware::PC()) { connect(uiState(), &UIState::offroadTransition, poweroff_btn, &QPushButton::setVisible); } @@ -173,8 +254,8 @@ DevicePanel::DevicePanel(SettingsWindow *parent) : ListWidget(parent) { void DevicePanel::updateCalibDescription() { QString desc = - "openpilot requires the device to be mounted within 4° left or right and " - "within 5° up or 8° down. openpilot is continuously calibrating, resetting is rarely required."; + tr("openpilot requires the device to be mounted within 4° left or right and " + "within 5° up or 8° down. openpilot is continuously calibrating, resetting is rarely required."); std::string calib_bytes = Params().get("CalibrationParams"); if (!calib_bytes.empty()) { try { @@ -184,9 +265,9 @@ void DevicePanel::updateCalibDescription() { if (calib.getCalStatus() != 0) { double pitch = calib.getRpyCalib()[1] * (180 / M_PI); double yaw = calib.getRpyCalib()[2] * (180 / M_PI); - desc += QString(" Your device is pointed %1° %2 and %3° %4.") - .arg(QString::number(std::abs(pitch), 'g', 1), pitch > 0 ? "down" : "up", - QString::number(std::abs(yaw), 'g', 1), yaw > 0 ? "left" : "right"); + desc += tr(" Your device is pointed %1° %2 and %3° %4.") + .arg(QString::number(std::abs(pitch), 'g', 1), pitch > 0 ? tr("down") : tr("up"), + QString::number(std::abs(yaw), 'g', 1), yaw > 0 ? tr("left") : tr("right")); } } catch (kj::Exception) { qInfo() << "invalid CalibrationParams"; @@ -197,149 +278,40 @@ void DevicePanel::updateCalibDescription() { void DevicePanel::reboot() { if (!uiState()->engaged()) { - if (ConfirmationDialog::confirm("Are you sure you want to reboot?", this)) { + if (ConfirmationDialog::confirm(tr("Are you sure you want to reboot?"), tr("Reboot"), this)) { // Check engaged again in case it changed while the dialog was open if (!uiState()->engaged()) { Params().putBool("DoReboot", true); } } } else { - ConfirmationDialog::alert("Disengage to Reboot", this); + ConfirmationDialog::alert(tr("Disengage to Reboot"), this); } } void DevicePanel::poweroff() { if (!uiState()->engaged()) { - if (ConfirmationDialog::confirm("Are you sure you want to power off?", this)) { + if (ConfirmationDialog::confirm(tr("Are you sure you want to power off?"), tr("Power Off"), this)) { // Check engaged again in case it changed while the dialog was open if (!uiState()->engaged()) { Params().putBool("DoShutdown", true); } } } else { - ConfirmationDialog::alert("Disengage to Power Off", this); + ConfirmationDialog::alert(tr("Disengage to Power Off"), this); } } -SoftwarePanel::SoftwarePanel(QWidget* parent) : ListWidget(parent) { - gitBranchLbl = new LabelControl("Git Branch"); - gitCommitLbl = new LabelControl("Git Commit"); - osVersionLbl = new LabelControl("OS Version"); - versionLbl = new LabelControl("Version", "", QString::fromStdString(params.get("ReleaseNotes")).trimmed()); - lastUpdateLbl = new LabelControl("Last Update Check", "", "The last time openpilot successfully checked for an update. The updater only runs while the car is off."); - updateBtn = new ButtonControl("Check for Update", ""); - connect(updateBtn, &ButtonControl::clicked, [=]() { - if (params.getBool("IsOffroad")) { - fs_watch->addPath(QString::fromStdString(params.getParamPath("LastUpdateTime"))); - fs_watch->addPath(QString::fromStdString(params.getParamPath("UpdateFailedCount"))); - updateBtn->setText("CHECKING"); - updateBtn->setEnabled(false); - } - std::system("pkill -1 -f selfdrive.updated"); - }); - - - auto uninstallBtn = new ButtonControl("Uninstall " + getBrand(), "UNINSTALL"); - connect(uninstallBtn, &ButtonControl::clicked, [&]() { - if (ConfirmationDialog::confirm("Are you sure you want to uninstall?", this)) { - params.putBool("DoUninstall", true); - } - }); - connect(uiState(), &UIState::offroadTransition, uninstallBtn, &QPushButton::setEnabled); - - QWidget *widgets[] = {versionLbl, lastUpdateLbl, updateBtn, gitBranchLbl, gitCommitLbl, osVersionLbl, uninstallBtn}; - for (QWidget* w : widgets) { - addItem(w); - } - - fs_watch = new QFileSystemWatcher(this); - QObject::connect(fs_watch, &QFileSystemWatcher::fileChanged, [=](const QString path) { - if (path.contains("UpdateFailedCount") && std::atoi(params.get("UpdateFailedCount").c_str()) > 0) { - lastUpdateLbl->setText("failed to fetch update"); - updateBtn->setText("CHECK"); - updateBtn->setEnabled(true); - } else if (path.contains("LastUpdateTime")) { - updateLabels(); - } - }); -} - -void SoftwarePanel::showEvent(QShowEvent *event) { - updateLabels(); +void SettingsWindow::showEvent(QShowEvent *event) { + setCurrentPanel(0); } -void SoftwarePanel::updateLabels() { - QString lastUpdate = ""; - auto tm = params.get("LastUpdateTime"); - if (!tm.empty()) { - lastUpdate = timeAgo(QDateTime::fromString(QString::fromStdString(tm + "Z"), Qt::ISODate)); +void SettingsWindow::setCurrentPanel(int index, const QString ¶m) { + panel_widget->setCurrentIndex(index); + nav_btns->buttons()[index]->setChecked(true); + if (!param.isEmpty()) { + emit expandToggleDescription(param); } - - versionLbl->setText(getBrandVersion()); - lastUpdateLbl->setText(lastUpdate); - updateBtn->setText("CHECK"); - updateBtn->setEnabled(true); - gitBranchLbl->setText(QString::fromStdString(params.get("GitBranch"))); - gitCommitLbl->setText(QString::fromStdString(params.get("GitCommit")).left(10)); - osVersionLbl->setText(QString::fromStdString(Hardware::get_os_version()).trimmed()); -} - -C2NetworkPanel::C2NetworkPanel(QWidget *parent) : QWidget(parent) { - QVBoxLayout *layout = new QVBoxLayout(this); - layout->setContentsMargins(50, 0, 50, 0); - - ListWidget *list = new ListWidget(); - list->setSpacing(30); - // wifi + tethering buttons -#ifdef QCOM - auto wifiBtn = new ButtonControl("Wi-Fi Settings", "OPEN"); - QObject::connect(wifiBtn, &ButtonControl::clicked, [=]() { HardwareEon::launch_wifi(); }); - list->addItem(wifiBtn); - - auto tetheringBtn = new ButtonControl("Tethering Settings", "OPEN"); - QObject::connect(tetheringBtn, &ButtonControl::clicked, [=]() { HardwareEon::launch_tethering(); }); - list->addItem(tetheringBtn); -#endif - ipaddress = new LabelControl("IP Address", ""); - list->addItem(ipaddress); - - // SSH key management - list->addItem(new SshToggle()); - list->addItem(new SshControl()); - layout->addWidget(list); - layout->addStretch(1); -} - -void C2NetworkPanel::showEvent(QShowEvent *event) { - ipaddress->setText(getIPAddress()); -} - -QString C2NetworkPanel::getIPAddress() { - std::string result = util::check_output("ifconfig wlan0"); - if (result.empty()) return ""; - - const std::string inetaddrr = "inet addr:"; - std::string::size_type begin = result.find(inetaddrr); - if (begin == std::string::npos) return ""; - - begin += inetaddrr.length(); - std::string::size_type end = result.find(' ', begin); - if (end == std::string::npos) return ""; - - return result.substr(begin, end - begin).c_str(); -} - -QWidget *network_panel(QWidget *parent) { -#ifdef QCOM - return new C2NetworkPanel(parent); -#else - return new Networking(parent); -#endif -} - -void SettingsWindow::showEvent(QShowEvent *event) { - panel_widget->setCurrentIndex(0); - nav_btns->buttons()[0]->setChecked(true); } SettingsWindow::SettingsWindow(QWidget *parent) : QFrame(parent) { @@ -355,7 +327,7 @@ SettingsWindow::SettingsWindow(QWidget *parent) : QFrame(parent) { )"); // close button - QPushButton *close_btn = new QPushButton("×"); + QPushButton *close_btn = new QPushButton(tr("×")); close_btn->setStyleSheet(R"( QPushButton { font-size: 140px; @@ -380,16 +352,19 @@ SettingsWindow::SettingsWindow(QWidget *parent) : QFrame(parent) { QObject::connect(device, &DevicePanel::reviewTrainingGuide, this, &SettingsWindow::reviewTrainingGuide); QObject::connect(device, &DevicePanel::showDriverView, this, &SettingsWindow::showDriverView); + TogglesPanel *toggles = new TogglesPanel(this); + QObject::connect(this, &SettingsWindow::expandToggleDescription, toggles, &TogglesPanel::expandToggleDescription); + QList> panels = { - {"Device", device}, - {"Network", network_panel(this)}, - {"Toggles", new TogglesPanel(this)}, - {"Software", new SoftwarePanel(this)}, + {tr("Device"), device}, + {tr("Network"), new Networking(this)}, + {tr("Toggles"), toggles}, + {tr("Software"), new SoftwarePanel(this)}, }; #ifdef ENABLE_MAPS auto map_panel = new MapPanel(this); - panels.push_back({"Navigation", map_panel}); + panels.push_back({tr("Navigation"), map_panel}); QObject::connect(map_panel, &MapPanel::closeSettings, this, &SettingsWindow::closeSettings); #endif @@ -421,7 +396,7 @@ SettingsWindow::SettingsWindow(QWidget *parent) : QFrame(parent) { nav_btns->addButton(btn); sidebar_layout->addWidget(btn, 0, Qt::AlignRight); - const int lr_margin = name != "Network" ? 50 : 0; // Network panel handles its own margins + const int lr_margin = name != tr("Network") ? 50 : 0; // Network panel handles its own margins panel->setContentsMargins(lr_margin, 25, lr_margin, 25); ScrollView *panel_frame = new ScrollView(panel, this); @@ -451,9 +426,3 @@ SettingsWindow::SettingsWindow(QWidget *parent) : QFrame(parent) { } )"); } - -void SettingsWindow::hideEvent(QHideEvent *event) { -#ifdef QCOM - HardwareEon::close_activities(); -#endif -} diff --git a/selfdrive/ui/qt/offroad/settings.h b/selfdrive/ui/qt/offroad/settings.h index c3acf3d94a..c63be4e138 100644 --- a/selfdrive/ui/qt/offroad/settings.h +++ b/selfdrive/ui/qt/offroad/settings.h @@ -17,15 +17,16 @@ class SettingsWindow : public QFrame { public: explicit SettingsWindow(QWidget *parent = 0); + void setCurrentPanel(int index, const QString ¶m = ""); protected: - void hideEvent(QHideEvent *event) override; void showEvent(QShowEvent *event) override; signals: void closeSettings(); void reviewTrainingGuide(); void showDriverView(); + void expandToggleDescription(const QString ¶m); private: QPushButton *sidebar_alert_widget; @@ -55,6 +56,16 @@ class TogglesPanel : public ListWidget { Q_OBJECT public: explicit TogglesPanel(SettingsWindow *parent); + void showEvent(QShowEvent *event) override; + +public slots: + void expandToggleDescription(const QString ¶m); + +private: + Params params; + std::map toggles; + + void updateToggles(); }; class SoftwarePanel : public ListWidget { @@ -65,25 +76,16 @@ public: private: void showEvent(QShowEvent *event) override; void updateLabels(); + void checkForUpdates(); + + bool is_onroad = false; - LabelControl *gitBranchLbl; - LabelControl *gitCommitLbl; - LabelControl *osVersionLbl; + QLabel *onroadLbl; LabelControl *versionLbl; - LabelControl *lastUpdateLbl; - ButtonControl *updateBtn; + ButtonControl *installBtn; + ButtonControl *downloadBtn; + ButtonControl *targetBranchBtn; Params params; QFileSystemWatcher *fs_watch; }; - -class C2NetworkPanel: public QWidget { - Q_OBJECT -public: - explicit C2NetworkPanel(QWidget* parent = nullptr); - -private: - void showEvent(QShowEvent *event) override; - QString getIPAddress(); - LabelControl *ipaddress; -}; diff --git a/selfdrive/ui/qt/offroad/software_settings.cc b/selfdrive/ui/qt/offroad/software_settings.cc new file mode 100644 index 0000000000..12d62e63fb --- /dev/null +++ b/selfdrive/ui/qt/offroad/software_settings.cc @@ -0,0 +1,156 @@ +#include "selfdrive/ui/qt/offroad/settings.h" + +#include +#include +#include + +#include +#include + +#include "common/params.h" +#include "common/util.h" +#include "selfdrive/ui/ui.h" +#include "selfdrive/ui/qt/util.h" +#include "selfdrive/ui/qt/widgets/controls.h" +#include "selfdrive/ui/qt/widgets/input.h" +#include "system/hardware/hw.h" + + +void SoftwarePanel::checkForUpdates() { + std::system("pkill -SIGUSR1 -f selfdrive.updated"); +} + +SoftwarePanel::SoftwarePanel(QWidget* parent) : ListWidget(parent) { + onroadLbl = new QLabel(tr("Updates are only downloaded while the car is off.")); + onroadLbl->setStyleSheet("font-size: 50px; font-weight: 400; text-align: left; padding-top: 30px; padding-bottom: 30px;"); + addItem(onroadLbl); + + // current version + versionLbl = new LabelControl(tr("Current Version"), ""); + addItem(versionLbl); + + // download update btn + downloadBtn = new ButtonControl(tr("Download"), tr("CHECK")); + connect(downloadBtn, &ButtonControl::clicked, [=]() { + downloadBtn->setEnabled(false); + if (downloadBtn->text() == tr("CHECK")) { + checkForUpdates(); + } else { + std::system("pkill -SIGHUP -f selfdrive.updated"); + } + }); + addItem(downloadBtn); + + // install update btn + installBtn = new ButtonControl(tr("Install Update"), tr("INSTALL")); + connect(installBtn, &ButtonControl::clicked, [=]() { + installBtn->setEnabled(false); + params.putBool("DoReboot", true); + }); + addItem(installBtn); + + // branch selecting + targetBranchBtn = new ButtonControl(tr("Target Branch"), tr("SELECT")); + connect(targetBranchBtn, &ButtonControl::clicked, [=]() { + auto current = params.get("GitBranch"); + QStringList branches = QString::fromStdString(params.get("UpdaterAvailableBranches")).split(","); + for (QString b : {current.c_str(), "devel-staging", "devel", "master-ci", "master"}) { + auto i = branches.indexOf(b); + if (i >= 0) { + branches.removeAt(i); + branches.insert(0, b); + } + } + + QString cur = QString::fromStdString(params.get("UpdaterTargetBranch")); + QString selection = MultiOptionDialog::getSelection(tr("Select a branch"), branches, cur, this); + if (!selection.isEmpty()) { + params.put("UpdaterTargetBranch", selection.toStdString()); + targetBranchBtn->setValue(QString::fromStdString(params.get("UpdaterTargetBranch"))); + checkForUpdates(); + } + }); + if (!params.getBool("IsTestedBranch")) { + addItem(targetBranchBtn); + } + + // uninstall button + auto uninstallBtn = new ButtonControl(tr("Uninstall %1").arg(getBrand()), tr("UNINSTALL")); + connect(uninstallBtn, &ButtonControl::clicked, [&]() { + if (ConfirmationDialog::confirm(tr("Are you sure you want to uninstall?"), tr("Uninstall"), this)) { + params.putBool("DoUninstall", true); + } + }); + addItem(uninstallBtn); + + fs_watch = new QFileSystemWatcher(this); + QObject::connect(fs_watch, &QFileSystemWatcher::fileChanged, [=](const QString path) { + updateLabels(); + }); + + connect(uiState(), &UIState::offroadTransition, [=](bool offroad) { + is_onroad = !offroad; + updateLabels(); + }); + + updateLabels(); +} + +void SoftwarePanel::showEvent(QShowEvent *event) { + // nice for testing on PC + installBtn->setEnabled(true); + + updateLabels(); +} + +void SoftwarePanel::updateLabels() { + // add these back in case the files got removed + fs_watch->addPath(QString::fromStdString(params.getParamPath("LastUpdateTime"))); + fs_watch->addPath(QString::fromStdString(params.getParamPath("UpdateFailedCount"))); + fs_watch->addPath(QString::fromStdString(params.getParamPath("UpdaterState"))); + fs_watch->addPath(QString::fromStdString(params.getParamPath("UpdateAvailable"))); + + if (!isVisible()) { + return; + } + + // updater only runs offroad + onroadLbl->setVisible(is_onroad); + downloadBtn->setVisible(!is_onroad); + + // download update + QString updater_state = QString::fromStdString(params.get("UpdaterState")); + bool failed = std::atoi(params.get("UpdateFailedCount").c_str()) > 0; + if (updater_state != "idle") { + downloadBtn->setEnabled(false); + downloadBtn->setValue(updater_state); + } else { + if (failed) { + downloadBtn->setText("CHECK"); + downloadBtn->setValue("failed to check for update"); + } else if (params.getBool("UpdaterFetchAvailable")) { + downloadBtn->setText("DOWNLOAD"); + downloadBtn->setValue("update available"); + } else { + QString lastUpdate = "never"; + auto tm = params.get("LastUpdateTime"); + if (!tm.empty()) { + lastUpdate = timeAgo(QDateTime::fromString(QString::fromStdString(tm + "Z"), Qt::ISODate)); + } + downloadBtn->setText("CHECK"); + downloadBtn->setValue("up to date, last checked " + lastUpdate); + } + downloadBtn->setEnabled(true); + } + targetBranchBtn->setValue(QString::fromStdString(params.get("UpdaterTargetBranch"))); + + // current + new versions + versionLbl->setText(QString::fromStdString(params.get("UpdaterCurrentDescription"))); + versionLbl->setDescription(QString::fromStdString(params.get("UpdaterCurrentReleaseNotes"))); + + installBtn->setVisible(!is_onroad && params.getBool("UpdateAvailable")); + installBtn->setValue(QString::fromStdString(params.get("UpdaterNewDescription"))); + installBtn->setDescription(QString::fromStdString(params.get("UpdaterNewReleaseNotes"))); + + update(); +} diff --git a/selfdrive/ui/qt/offroad/wifiManager.cc b/selfdrive/ui/qt/offroad/wifiManager.cc index 1628f35d99..fde8645586 100644 --- a/selfdrive/ui/qt/offroad/wifiManager.cc +++ b/selfdrive/ui/qt/offroad/wifiManager.cc @@ -3,8 +3,8 @@ #include "selfdrive/ui/ui.h" #include "selfdrive/ui/qt/widgets/prime.h" -#include "selfdrive/common/params.h" -#include "selfdrive/common/swaglog.h" +#include "common/params.h" +#include "common/swaglog.h" #include "selfdrive/ui/qt/util.h" bool compare_by_strength(const Network &a, const Network &b) { @@ -303,7 +303,7 @@ void WifiManager::initConnections() { const Connection settings = getConnectionSettings(path); if (settings.value("connection").value("type") == "802-11-wireless") { knownConnections[path] = settings.value("802-11-wireless").value("ssid").toString(); - } else if (path.path() != "/") { + } else if (settings.value("connection").value("id") == "lte") { lteConnectionPath = path; } } @@ -345,7 +345,7 @@ NetworkType WifiManager::currentNetworkType() { return NetworkType::NONE; } -void WifiManager::updateGsmSettings(bool roaming, QString apn) { +void WifiManager::updateGsmSettings(bool roaming, QString apn, bool metered) { if (!lteConnectionPath.path().isEmpty()) { bool changes = false; bool auto_config = apn.isEmpty(); @@ -368,6 +368,13 @@ void WifiManager::updateGsmSettings(bool roaming, QString apn) { changes = true; } + int meteredInt = metered ? NM_METERED_UNKNOWN : NM_METERED_NO; + if (settings.value("connection").value("metered").toInt() != meteredInt) { + qWarning() << "Changing connection.metered to" << meteredInt; + settings["connection"]["metered"] = meteredInt; + changes = true; + } + if (changes) { call(lteConnectionPath.path(), NM_DBUS_INTERFACE_SETTINGS_CONNECTION, "UpdateUnsaved", QVariant::fromValue(settings)); // update is temporary deactivateConnection(lteConnectionPath); @@ -408,16 +415,16 @@ void WifiManager::addTetheringConnection() { } void WifiManager::tetheringActivated(QDBusPendingCallWatcher *call) { - int prime_type = uiState()->prime_type; - int ipv4_forward = (prime_type == PrimeType::NONE || prime_type == PrimeType::LITE); - - if (!ipv4_forward) { - QTimer::singleShot(5000, this, [=] { - qWarning() << "net.ipv4.ip_forward = 0"; - std::system("sudo sysctl net.ipv4.ip_forward=0"); - }); - } - call->deleteLater(); + int prime_type = uiState()->prime_type; + int ipv4_forward = (prime_type == PrimeType::NONE || prime_type == PrimeType::LITE); + + if (!ipv4_forward) { + QTimer::singleShot(5000, this, [=] { + qWarning() << "net.ipv4.ip_forward = 0"; + std::system("sudo sysctl net.ipv4.ip_forward=0"); + }); + } + call->deleteLater(); } void WifiManager::setTetheringEnabled(bool enabled) { diff --git a/selfdrive/ui/qt/offroad/wifiManager.h b/selfdrive/ui/qt/offroad/wifiManager.h index 07b982c2c2..01f9cd6b65 100644 --- a/selfdrive/ui/qt/offroad/wifiManager.h +++ b/selfdrive/ui/qt/offroad/wifiManager.h @@ -50,7 +50,7 @@ public: bool isKnownConnection(const QString &ssid); std::optional activateWifiConnection(const QString &ssid); NetworkType currentNetworkType(); - void updateGsmSettings(bool roaming, QString apn); + void updateGsmSettings(bool roaming, QString apn, bool metered); void connect(const Network &ssid, const QString &password = {}, const QString &username = {}); // Tethering functions diff --git a/selfdrive/ui/qt/onroad.cc b/selfdrive/ui/qt/onroad.cc index 44dde85817..fed59ef123 100644 --- a/selfdrive/ui/qt/onroad.cc +++ b/selfdrive/ui/qt/onroad.cc @@ -4,7 +4,7 @@ #include -#include "selfdrive/common/timing.h" +#include "common/timing.h" #include "selfdrive/ui/qt/util.h" #ifdef ENABLE_MAPS #include "selfdrive/ui/qt/maps/map.h" @@ -18,18 +18,18 @@ OnroadWindow::OnroadWindow(QWidget *parent) : QWidget(parent) { stacked_layout->setStackingMode(QStackedLayout::StackAll); main_layout->addLayout(stacked_layout); - QStackedLayout *road_view_layout = new QStackedLayout; - road_view_layout->setStackingMode(QStackedLayout::StackAll); - nvg = new NvgWindow(VISION_STREAM_RGB_BACK, this); - road_view_layout->addWidget(nvg); - hud = new OnroadHud(this); - road_view_layout->addWidget(hud); + nvg = new AnnotatedCameraWidget(VISION_STREAM_ROAD, this); QWidget * split_wrapper = new QWidget; split = new QHBoxLayout(split_wrapper); split->setContentsMargins(0, 0, 0, 0); split->setSpacing(0); - split->addLayout(road_view_layout); + split->addWidget(nvg); + + if (getenv("DUAL_CAMERA_VIEW")) { + CameraWidget *arCam = new CameraWidget("camerad", VISION_STREAM_ROAD, true, this); + split->insertWidget(0, arCam); + } stacked_layout->addWidget(split_wrapper); @@ -57,7 +57,13 @@ void OnroadWindow::updateState(const UIState &s) { alerts->updateAlert(alert, bgColor); } - hud->updateState(s); + if (s.scene.map_on_left) { + split->setDirection(QBoxLayout::LeftToRight); + } else { + split->setDirection(QBoxLayout::RightToLeft); + } + + nvg->updateState(s); if (bg != bgColor) { // repaint border @@ -85,7 +91,7 @@ void OnroadWindow::offroadTransition(bool offroad) { QObject::connect(uiState(), &UIState::offroadTransition, m, &MapWindow::offroadTransition); m->setFixedWidth(topWidget(this)->width() / 2); - split->addWidget(m, 0, Qt::AlignRight); + split->insertWidget(0, m); // Make map visible after adding to split m->offroadTransition(offroad); @@ -94,10 +100,6 @@ void OnroadWindow::offroadTransition(bool offroad) { #endif alerts->updateAlert({}, bg); - - // update stream type - bool wide_cam = Hardware::TICI() && Params().getBool("EnableWideCamera"); - nvg->setStreamType(wide_cam ? VISION_STREAM_RGB_WIDE : VISION_STREAM_RGB_BACK); } void OnroadWindow::paintEvent(QPaintEvent *event) { @@ -151,47 +153,72 @@ void OnroadAlerts::paintEvent(QPaintEvent *event) { p.setPen(QColor(0xff, 0xff, 0xff)); p.setRenderHint(QPainter::TextAntialiasing); if (alert.size == cereal::ControlsState::AlertSize::SMALL) { - configFont(p, "Open Sans", 74, "SemiBold"); + configFont(p, "Inter", 74, "SemiBold"); p.drawText(r, Qt::AlignCenter, alert.text1); } else if (alert.size == cereal::ControlsState::AlertSize::MID) { - configFont(p, "Open Sans", 88, "Bold"); + configFont(p, "Inter", 88, "Bold"); p.drawText(QRect(0, c.y() - 125, width(), 150), Qt::AlignHCenter | Qt::AlignTop, alert.text1); - configFont(p, "Open Sans", 66, "Regular"); + configFont(p, "Inter", 66, "Regular"); p.drawText(QRect(0, c.y() + 21, width(), 90), Qt::AlignHCenter, alert.text2); } else if (alert.size == cereal::ControlsState::AlertSize::FULL) { bool l = alert.text1.length() > 15; - configFont(p, "Open Sans", l ? 132 : 177, "Bold"); + configFont(p, "Inter", l ? 132 : 177, "Bold"); p.drawText(QRect(0, r.y() + (l ? 240 : 270), width(), 600), Qt::AlignHCenter | Qt::TextWordWrap, alert.text1); - configFont(p, "Open Sans", 88, "Regular"); + configFont(p, "Inter", 88, "Regular"); p.drawText(QRect(0, r.height() - (l ? 361 : 420), width(), 300), Qt::AlignHCenter | Qt::TextWordWrap, alert.text2); } } -// OnroadHud -OnroadHud::OnroadHud(QWidget *parent) : QWidget(parent) { + +AnnotatedCameraWidget::AnnotatedCameraWidget(VisionStreamType type, QWidget* parent) : fps_filter(UI_FREQ, 3, 1. / UI_FREQ), CameraWidget("camerad", type, true, parent) { + pm = std::make_unique>({"uiDebug"}); + engage_img = loadPixmap("../assets/img_chffr_wheel.png", {img_size, img_size}); + experimental_img = loadPixmap("../assets/img_experimental.svg", {img_size - 5, img_size - 5}); dm_img = loadPixmap("../assets/img_driver_face.png", {img_size, img_size}); - - connect(this, &OnroadHud::valueChanged, [=] { update(); }); } -void OnroadHud::updateState(const UIState &s) { +void AnnotatedCameraWidget::updateState(const UIState &s) { const int SET_SPEED_NA = 255; const SubMaster &sm = *(s.sm); + + const bool cs_alive = sm.alive("controlsState"); + const bool nav_alive = sm.alive("navInstruction") && sm["navInstruction"].getValid(); + const auto cs = sm["controlsState"].getControlsState(); - float maxspeed = cs.getVCruise(); - bool cruise_set = maxspeed > 0 && (int)maxspeed != SET_SPEED_NA; + // Handle older routes where vCruiseCluster is not set + float v_cruise = cs.getVCruiseCluster() == 0.0 ? cs.getVCruise() : cs.getVCruiseCluster(); + float set_speed = cs_alive ? v_cruise : SET_SPEED_NA; + bool cruise_set = set_speed > 0 && (int)set_speed != SET_SPEED_NA; if (cruise_set && !s.scene.is_metric) { - maxspeed *= KM_TO_MILE; + set_speed *= KM_TO_MILE; + } + + // Handle older routes where vEgoCluster is not set + float v_ego; + if (sm["carState"].getCarState().getVEgoCluster() == 0.0 && !v_ego_cluster_seen) { + v_ego = sm["carState"].getCarState().getVEgo(); + } else { + v_ego = sm["carState"].getCarState().getVEgoCluster(); + v_ego_cluster_seen = true; } - QString maxspeed_str = cruise_set ? QString::number(std::nearbyint(maxspeed)) : "N/A"; - float cur_speed = std::max(0.0, sm["carState"].getCarState().getVEgo() * (s.scene.is_metric ? MS_TO_KPH : MS_TO_MPH)); + float cur_speed = cs_alive ? std::max(0.0, v_ego) : 0.0; + cur_speed *= s.scene.is_metric ? MS_TO_KPH : MS_TO_MPH; + + auto speed_limit_sign = sm["navInstruction"].getNavInstruction().getSpeedLimitSign(); + float speed_limit = nav_alive ? sm["navInstruction"].getNavInstruction().getSpeedLimit() : 0.0; + speed_limit *= (s.scene.is_metric ? MS_TO_KPH : MS_TO_MPH); + + setProperty("speedLimit", speed_limit); + setProperty("has_us_speed_limit", nav_alive && speed_limit_sign == cereal::NavInstruction::SpeedLimitSign::MUTCD); + setProperty("has_eu_speed_limit", nav_alive && speed_limit_sign == cereal::NavInstruction::SpeedLimitSign::VIENNA); setProperty("is_cruise_set", cruise_set); - setProperty("speed", QString::number(std::nearbyint(cur_speed))); - setProperty("maxSpeed", maxspeed_str); - setProperty("speedUnit", s.scene.is_metric ? "km/h" : "mph"); + setProperty("is_metric", s.scene.is_metric); + setProperty("speed", cur_speed); + setProperty("setSpeed", set_speed); + setProperty("speedUnit", s.scene.is_metric ? tr("km/h") : tr("mph")); setProperty("hideDM", cs.getAlertSize() != cereal::ControlsState::AlertSize::NONE); setProperty("status", s.status); @@ -199,12 +226,12 @@ void OnroadHud::updateState(const UIState &s) { if (sm.frame % (UI_FREQ / 2) == 0) { setProperty("engageable", cs.getEngageable() || cs.getEnabled()); setProperty("dmActive", sm["driverMonitoringState"].getDriverMonitoringState().getIsActiveMode()); + setProperty("rightHandDM", sm["driverMonitoringState"].getDriverMonitoringState().getIsRHD()); } } -void OnroadHud::paintEvent(QPaintEvent *event) { - QPainter p(this); - p.setRenderHint(QPainter::Antialiasing); +void AnnotatedCameraWidget::drawHud(QPainter &p) { + p.save(); // Header gradient QLinearGradient bg(0, header_h - (header_h / 2.5), 0, header_h); @@ -212,63 +239,184 @@ void OnroadHud::paintEvent(QPaintEvent *event) { bg.setColorAt(1, QColor::fromRgbF(0, 0, 0, 0)); p.fillRect(0, 0, width(), header_h, bg); - // max speed - QRect rc(bdr_s * 2, bdr_s * 1.5, 184, 202); - p.setPen(QPen(QColor(0xff, 0xff, 0xff, 100), 10)); - p.setBrush(QColor(0, 0, 0, 100)); - p.drawRoundedRect(rc, 20, 20); - p.setPen(Qt::NoPen); + QString speedLimitStr = (speedLimit > 1) ? QString::number(std::nearbyint(speedLimit)) : "–"; + QString speedStr = QString::number(std::nearbyint(speed)); + QString setSpeedStr = is_cruise_set ? QString::number(std::nearbyint(setSpeed)) : "–"; + + // Draw outer box + border to contain set speed and speed limit + int default_rect_width = 172; + int rect_width = default_rect_width; + if (is_metric || has_eu_speed_limit) rect_width = 200; + if (has_us_speed_limit && speedLimitStr.size() >= 3) rect_width = 223; + + int rect_height = 204; + if (has_us_speed_limit) rect_height = 402; + else if (has_eu_speed_limit) rect_height = 392; + + int top_radius = 32; + int bottom_radius = has_eu_speed_limit ? 100 : 32; + + QRect set_speed_rect(60 + default_rect_width / 2 - rect_width / 2, 45, rect_width, rect_height); + p.setPen(QPen(whiteColor(75), 6)); + p.setBrush(blackColor(166)); + drawRoundedRect(p, set_speed_rect, top_radius, top_radius, bottom_radius, bottom_radius); - configFont(p, "Open Sans", 48, "Regular"); - drawText(p, rc.center().x(), 118, "MAX", is_cruise_set ? 200 : 100); + // Draw MAX if (is_cruise_set) { - configFont(p, "Open Sans", 88, is_cruise_set ? "Bold" : "SemiBold"); - drawText(p, rc.center().x(), 212, maxSpeed, 255); + if (status == STATUS_DISENGAGED) { + p.setPen(whiteColor()); + } else if (status == STATUS_OVERRIDE) { + p.setPen(QColor(0x91, 0x9b, 0x95, 0xff)); + } else if (speedLimit > 0) { + p.setPen(interpColor( + setSpeed, + {speedLimit + 5, speedLimit + 15, speedLimit + 25}, + {QColor(0x80, 0xd8, 0xa6, 0xff), QColor(0xff, 0xe4, 0xbf, 0xff), QColor(0xff, 0xbf, 0xbf, 0xff)} + )); + } else { + p.setPen(QColor(0x80, 0xd8, 0xa6, 0xff)); + } } else { - configFont(p, "Open Sans", 80, "SemiBold"); - drawText(p, rc.center().x(), 212, maxSpeed, 100); + p.setPen(QColor(0xa6, 0xa6, 0xa6, 0xff)); + } + configFont(p, "Inter", 40, "SemiBold"); + QRect max_rect = getTextRect(p, Qt::AlignCenter, tr("MAX")); + max_rect.moveCenter({set_speed_rect.center().x(), 0}); + max_rect.moveTop(set_speed_rect.top() + 27); + p.drawText(max_rect, Qt::AlignCenter, tr("MAX")); + + // Draw set speed + if (is_cruise_set) { + if (speedLimit > 0 && status != STATUS_DISENGAGED && status != STATUS_OVERRIDE) { + p.setPen(interpColor( + setSpeed, + {speedLimit + 5, speedLimit + 15, speedLimit + 25}, + {whiteColor(), QColor(0xff, 0x95, 0x00, 0xff), QColor(0xff, 0x00, 0x00, 0xff)} + )); + } else { + p.setPen(whiteColor()); + } + } else { + p.setPen(QColor(0x72, 0x72, 0x72, 0xff)); + } + configFont(p, "Inter", 90, "Bold"); + QRect speed_rect = getTextRect(p, Qt::AlignCenter, setSpeedStr); + speed_rect.moveCenter({set_speed_rect.center().x(), 0}); + speed_rect.moveTop(set_speed_rect.top() + 77); + p.drawText(speed_rect, Qt::AlignCenter, setSpeedStr); + + + + // US/Canada (MUTCD style) sign + if (has_us_speed_limit) { + const int border_width = 6; + const int sign_width = rect_width - 24; + const int sign_height = 186; + + // White outer square + QRect sign_rect_outer(set_speed_rect.left() + 12, set_speed_rect.bottom() - 11 - sign_height, sign_width, sign_height); + p.setPen(Qt::NoPen); + p.setBrush(whiteColor()); + p.drawRoundedRect(sign_rect_outer, 24, 24); + + // Smaller white square with black border + QRect sign_rect(sign_rect_outer.left() + 1.5 * border_width, sign_rect_outer.top() + 1.5 * border_width, sign_width - 3 * border_width, sign_height - 3 * border_width); + p.setPen(QPen(blackColor(), border_width)); + p.setBrush(whiteColor()); + p.drawRoundedRect(sign_rect, 16, 16); + + // "SPEED" + configFont(p, "Inter", 28, "SemiBold"); + QRect text_speed_rect = getTextRect(p, Qt::AlignCenter, tr("SPEED")); + text_speed_rect.moveCenter({sign_rect.center().x(), 0}); + text_speed_rect.moveTop(sign_rect_outer.top() + 22); + p.drawText(text_speed_rect, Qt::AlignCenter, tr("SPEED")); + + // "LIMIT" + QRect text_limit_rect = getTextRect(p, Qt::AlignCenter, tr("LIMIT")); + text_limit_rect.moveCenter({sign_rect.center().x(), 0}); + text_limit_rect.moveTop(sign_rect_outer.top() + 51); + p.drawText(text_limit_rect, Qt::AlignCenter, tr("LIMIT")); + + // Speed limit value + configFont(p, "Inter", 70, "Bold"); + QRect speed_limit_rect = getTextRect(p, Qt::AlignCenter, speedLimitStr); + speed_limit_rect.moveCenter({sign_rect.center().x(), 0}); + speed_limit_rect.moveTop(sign_rect_outer.top() + 85); + p.drawText(speed_limit_rect, Qt::AlignCenter, speedLimitStr); + } + + // EU (Vienna style) sign + if (has_eu_speed_limit) { + int outer_radius = 176 / 2; + int inner_radius_1 = outer_radius - 6; // White outer border + int inner_radius_2 = inner_radius_1 - 20; // Red circle + + // Draw white circle with red border + QPoint center(set_speed_rect.center().x() + 1, set_speed_rect.top() + 204 + outer_radius); + p.setPen(Qt::NoPen); + p.setBrush(whiteColor()); + p.drawEllipse(center, outer_radius, outer_radius); + p.setBrush(QColor(255, 0, 0, 255)); + p.drawEllipse(center, inner_radius_1, inner_radius_1); + p.setBrush(whiteColor()); + p.drawEllipse(center, inner_radius_2, inner_radius_2); + + // Speed limit value + int font_size = (speedLimitStr.size() >= 3) ? 60 : 70; + configFont(p, "Inter", font_size, "Bold"); + QRect speed_limit_rect = getTextRect(p, Qt::AlignCenter, speedLimitStr); + speed_limit_rect.moveCenter(center); + p.setPen(blackColor()); + p.drawText(speed_limit_rect, Qt::AlignCenter, speedLimitStr); } // current speed - configFont(p, "Open Sans", 176, "Bold"); - drawText(p, rect().center().x(), 210, speed); - configFont(p, "Open Sans", 66, "Regular"); + configFont(p, "Inter", 176, "Bold"); + drawText(p, rect().center().x(), 210, speedStr); + configFont(p, "Inter", 66, "Regular"); drawText(p, rect().center().x(), 290, speedUnit, 200); // engage-ability icon if (engageable) { + SubMaster &sm = *(uiState()->sm); drawIcon(p, rect().right() - radius / 2 - bdr_s * 2, radius / 2 + int(bdr_s * 1.5), - engage_img, bg_colors[status], 1.0); + sm["controlsState"].getControlsState().getExperimentalMode() ? experimental_img : engage_img, blackColor(166), 1.0); } // dm icon if (!hideDM) { - drawIcon(p, radius / 2 + (bdr_s * 2), rect().bottom() - footer_h / 2, - dm_img, QColor(0, 0, 0, 70), dmActive ? 1.0 : 0.2); + int dm_icon_x = rightHandDM ? rect().right() - radius / 2 - (bdr_s * 2) : radius / 2 + (bdr_s * 2); + drawIcon(p, dm_icon_x, rect().bottom() - footer_h / 2, + dm_img, blackColor(70), dmActive ? 1.0 : 0.2); } + p.restore(); } -void OnroadHud::drawText(QPainter &p, int x, int y, const QString &text, int alpha) { - QFontMetrics fm(p.font()); - QRect init_rect = fm.boundingRect(text); - QRect real_rect = fm.boundingRect(init_rect, 0, text); + +// Window that shows camera view and variety of +// info drawn on top + +void AnnotatedCameraWidget::drawText(QPainter &p, int x, int y, const QString &text, int alpha) { + QRect real_rect = getTextRect(p, 0, text); real_rect.moveCenter({x, y - real_rect.height() / 2}); p.setPen(QColor(0xff, 0xff, 0xff, alpha)); p.drawText(real_rect.x(), real_rect.bottom(), text); } -void OnroadHud::drawIcon(QPainter &p, int x, int y, QPixmap &img, QBrush bg, float opacity) { +void AnnotatedCameraWidget::drawIcon(QPainter &p, int x, int y, QPixmap &img, QBrush bg, float opacity) { + p.setOpacity(1.0); // bg dictates opacity of ellipse p.setPen(Qt::NoPen); p.setBrush(bg); p.drawEllipse(x - radius / 2, y - radius / 2, radius, radius); p.setOpacity(opacity); - p.drawPixmap(x - img_size / 2, y - img_size / 2, img); + p.drawPixmap(x - img.size().width() / 2, y - img.size().height() / 2, img); } -// NvgWindow -void NvgWindow::initializeGL() { - CameraViewWidget::initializeGL(); + +void AnnotatedCameraWidget::initializeGL() { + CameraWidget::initializeGL(); qInfo() << "OpenGL version:" << QString((const char*)glGetString(GL_VERSION)); qInfo() << "OpenGL vendor:" << QString((const char*)glGetString(GL_VENDOR)); qInfo() << "OpenGL renderer:" << QString((const char*)glGetString(GL_RENDERER)); @@ -278,49 +426,76 @@ void NvgWindow::initializeGL() { setBackgroundColor(bg_colors[STATUS_DISENGAGED]); } -void NvgWindow::updateFrameMat(int w, int h) { - CameraViewWidget::updateFrameMat(w, h); - +void AnnotatedCameraWidget::updateFrameMat() { + CameraWidget::updateFrameMat(); UIState *s = uiState(); + int w = width(), h = height(); + s->fb_w = w; s->fb_h = h; - auto intrinsic_matrix = s->wide_camera ? ecam_intrinsic_matrix : fcam_intrinsic_matrix; - float zoom = ZOOM / intrinsic_matrix.v[0]; - if (s->wide_camera) { - zoom *= 0.5; - } + // Apply transformation such that video pixel coordinates match video // 1) Put (0, 0) in the middle of the video // 2) Apply same scaling as video // 3) Put (0, 0) in top left corner of video s->car_space_transform.reset(); - s->car_space_transform.translate(w / 2, h / 2 + y_offset) + s->car_space_transform.translate(w / 2 - x_offset, h / 2 - y_offset) .scale(zoom, zoom) .translate(-intrinsic_matrix.v[2], -intrinsic_matrix.v[5]); } -void NvgWindow::drawLaneLines(QPainter &painter, const UIScene &scene) { - if (!scene.end_to_end) { - // lanelines - for (int i = 0; i < std::size(scene.lane_line_vertices); ++i) { - painter.setBrush(QColor::fromRgbF(1.0, 1.0, 1.0, scene.lane_line_probs[i])); - painter.drawPolygon(scene.lane_line_vertices[i].v, scene.lane_line_vertices[i].cnt); - } - // road edges - for (int i = 0; i < std::size(scene.road_edge_vertices); ++i) { - painter.setBrush(QColor::fromRgbF(1.0, 0, 0, std::clamp(1.0 - scene.road_edge_stds[i], 0.0, 1.0))); - painter.drawPolygon(scene.road_edge_vertices[i].v, scene.road_edge_vertices[i].cnt); - } +void AnnotatedCameraWidget::drawLaneLines(QPainter &painter, const UIState *s) { + painter.save(); + + const UIScene &scene = s->scene; + SubMaster &sm = *(s->sm); + + // lanelines + for (int i = 0; i < std::size(scene.lane_line_vertices); ++i) { + painter.setBrush(QColor::fromRgbF(1.0, 1.0, 1.0, std::clamp(scene.lane_line_probs[i], 0.0, 0.7))); + painter.drawPolygon(scene.lane_line_vertices[i]); } + + // road edges + for (int i = 0; i < std::size(scene.road_edge_vertices); ++i) { + painter.setBrush(QColor::fromRgbF(1.0, 0, 0, std::clamp(1.0 - scene.road_edge_stds[i], 0.0, 1.0))); + painter.drawPolygon(scene.road_edge_vertices[i]); + } + // paint path QLinearGradient bg(0, height(), 0, height() / 4); - bg.setColorAt(0, scene.end_to_end ? redColor() : QColor(255, 255, 255)); - bg.setColorAt(1, scene.end_to_end ? redColor(0) : QColor(255, 255, 255, 0)); + float start_hue, end_hue; + if (sm["controlsState"].getControlsState().getExperimentalMode()) { + const auto &acceleration = sm["modelV2"].getModelV2().getAcceleration(); + float acceleration_future = 0; + if (acceleration.getZ().size() > 16) { + acceleration_future = acceleration.getX()[16]; // 2.5 seconds + } + start_hue = 60; + // speed up: 120, slow down: 0 + end_hue = fmax(fmin(start_hue + acceleration_future * 45, 148), 0); + + // FIXME: painter.drawPolygon can be slow if hue is not rounded + end_hue = int(end_hue * 100 + 0.5) / 100; + + bg.setColorAt(0.0, QColor::fromHslF(start_hue / 360., 0.97, 0.56, 0.4)); + bg.setColorAt(0.5, QColor::fromHslF(end_hue / 360., 1.0, 0.68, 0.35)); + bg.setColorAt(1.0, QColor::fromHslF(end_hue / 360., 1.0, 0.68, 0.0)); + } else { + bg.setColorAt(0.0, QColor::fromHslF(148 / 360., 0.94, 0.51, 0.4)); + bg.setColorAt(0.5, QColor::fromHslF(112 / 360., 1.0, 0.68, 0.35)); + bg.setColorAt(1.0, QColor::fromHslF(112 / 360., 1.0, 0.68, 0.0)); + } + painter.setBrush(bg); - painter.drawPolygon(scene.track_vertices.v, scene.track_vertices.cnt); + painter.drawPolygon(scene.track_vertices); + + painter.restore(); } -void NvgWindow::drawLead(QPainter &painter, const cereal::ModelDataV2::LeadDataV3::Reader &lead_data, const QPointF &vd) { +void AnnotatedCameraWidget::drawLead(QPainter &painter, const cereal::ModelDataV2::LeadDataV3::Reader &lead_data, const QPointF &vd) { + painter.save(); + const float speedBuff = 10.; const float leadBuff = 40.; const float d_rel = lead_data.getX()[0]; @@ -350,21 +525,73 @@ void NvgWindow::drawLead(QPainter &painter, const cereal::ModelDataV2::LeadDataV QPointF chevron[] = {{x + (sz * 1.25), y + sz}, {x, y}, {x - (sz * 1.25), y + sz}}; painter.setBrush(redColor(fillAlpha)); painter.drawPolygon(chevron, std::size(chevron)); -} -void NvgWindow::paintGL() { - CameraViewWidget::paintGL(); + painter.restore(); +} +void AnnotatedCameraWidget::paintGL() { UIState *s = uiState(); + SubMaster &sm = *(s->sm); + const double start_draw_t = millis_since_boot(); + const cereal::ModelDataV2::Reader &model = sm["modelV2"].getModelV2(); + + // draw camera frame + { + std::lock_guard lk(frame_lock); + + if (frames.empty()) { + if (skip_frame_count > 0) { + skip_frame_count--; + qDebug() << "skipping frame, not ready"; + return; + } + } else { + // skip drawing up to this many frames if we're + // missing camera frames. this smooths out the + // transitions from the narrow and wide cameras + skip_frame_count = 5; + } + + // Wide or narrow cam dependent on speed + float v_ego = sm["carState"].getCarState().getVEgo(); + if ((v_ego < 10) || s->wide_cam_only) { + wide_cam_requested = true; + } else if (v_ego > 15) { + wide_cam_requested = false; + } + wide_cam_requested = wide_cam_requested && sm["controlsState"].getControlsState().getExperimentalMode(); + // TODO: also detect when ecam vision stream isn't available + // for replay of old routes, never go to widecam + wide_cam_requested = wide_cam_requested && s->scene.calibration_wide_valid; + CameraWidget::setStreamType(wide_cam_requested ? VISION_STREAM_WIDE_ROAD : VISION_STREAM_ROAD); + + s->scene.wide_cam = CameraWidget::getStreamType() == VISION_STREAM_WIDE_ROAD; + if (s->scene.calibration_valid) { + auto calib = s->scene.wide_cam ? s->scene.view_from_wide_calib : s->scene.view_from_calib; + CameraWidget::updateCalibration(calib); + } else { + CameraWidget::updateCalibration(DEFAULT_CALIBRATION); + } + CameraWidget::setFrameId(model.getFrameId()); + CameraWidget::paintGL(); + } + + QPainter painter(this); + painter.setRenderHint(QPainter::Antialiasing); + painter.setPen(Qt::NoPen); + if (s->worldObjectsVisible()) { - QPainter painter(this); - painter.setRenderHint(QPainter::Antialiasing); - painter.setPen(Qt::NoPen); + if (sm.rcv_frame("modelV2") > s->scene.started_frame) { + update_model(s, sm["modelV2"].getModelV2()); + if (sm.rcv_frame("radarState") > s->scene.started_frame) { + update_leads(s, sm["radarState"].getRadarState(), sm["modelV2"].getModelV2().getPosition()); + } + } - drawLaneLines(painter, s->scene); + drawLaneLines(painter, s); if (s->scene.longitudinal_control) { - auto leads = (*s->sm)["modelV2"].getModelV2().getLeadsV3(); + const auto leads = model.getLeadsV3(); if (leads[0].getProb() > .5) { drawLead(painter, leads[0], s->scene.lead_vertices[0]); } @@ -374,17 +601,25 @@ void NvgWindow::paintGL() { } } + drawHud(painter); + double cur_draw_t = millis_since_boot(); double dt = cur_draw_t - prev_draw_t; - if (dt > 66) { - // warn on sub 15fps - LOGW("slow frame time: %.2f", dt); + double fps = fps_filter.update(1. / dt * 1000); + if (fps < 15) { + LOGW("slow frame rate: %.2f fps", fps); } prev_draw_t = cur_draw_t; + + // publish debug msg + MessageBuilder msg; + auto m = msg.initEvent().initUiDebug(); + m.setDrawTimeMillis(cur_draw_t - start_draw_t); + pm->send("uiDebug", msg); } -void NvgWindow::showEvent(QShowEvent *event) { - CameraViewWidget::showEvent(event); +void AnnotatedCameraWidget::showEvent(QShowEvent *event) { + CameraWidget::showEvent(event); ui_update_params(uiState()); prev_draw_t = millis_since_boot(); diff --git a/selfdrive/ui/qt/onroad.h b/selfdrive/ui/qt/onroad.h index 05811c5060..9e18355970 100644 --- a/selfdrive/ui/qt/onroad.h +++ b/selfdrive/ui/qt/onroad.h @@ -3,80 +3,91 @@ #include #include +#include "common/util.h" #include "selfdrive/ui/qt/widgets/cameraview.h" #include "selfdrive/ui/ui.h" // ***** onroad widgets ***** +class OnroadAlerts : public QWidget { + Q_OBJECT + +public: + OnroadAlerts(QWidget *parent = 0) : QWidget(parent) {}; + void updateAlert(const Alert &a, const QColor &color); -class OnroadHud : public QWidget { +protected: + void paintEvent(QPaintEvent*) override; + +private: + QColor bg; + Alert alert = {}; +}; + +// container window for the NVG UI +class AnnotatedCameraWidget : public CameraWidget { Q_OBJECT - Q_PROPERTY(QString speed MEMBER speed NOTIFY valueChanged); - Q_PROPERTY(QString speedUnit MEMBER speedUnit NOTIFY valueChanged); - Q_PROPERTY(QString maxSpeed MEMBER maxSpeed NOTIFY valueChanged); - Q_PROPERTY(bool is_cruise_set MEMBER is_cruise_set NOTIFY valueChanged); - Q_PROPERTY(bool engageable MEMBER engageable NOTIFY valueChanged); - Q_PROPERTY(bool dmActive MEMBER dmActive NOTIFY valueChanged); - Q_PROPERTY(bool hideDM MEMBER hideDM NOTIFY valueChanged); - Q_PROPERTY(int status MEMBER status NOTIFY valueChanged); + Q_PROPERTY(float speed MEMBER speed); + Q_PROPERTY(QString speedUnit MEMBER speedUnit); + Q_PROPERTY(float setSpeed MEMBER setSpeed); + Q_PROPERTY(float speedLimit MEMBER speedLimit); + Q_PROPERTY(bool is_cruise_set MEMBER is_cruise_set); + Q_PROPERTY(bool has_eu_speed_limit MEMBER has_eu_speed_limit); + Q_PROPERTY(bool has_us_speed_limit MEMBER has_us_speed_limit); + Q_PROPERTY(bool is_metric MEMBER is_metric); + + Q_PROPERTY(bool engageable MEMBER engageable); + Q_PROPERTY(bool dmActive MEMBER dmActive); + Q_PROPERTY(bool hideDM MEMBER hideDM); + Q_PROPERTY(bool rightHandDM MEMBER rightHandDM); + Q_PROPERTY(int status MEMBER status); public: - explicit OnroadHud(QWidget *parent); + explicit AnnotatedCameraWidget(VisionStreamType type, QWidget* parent = 0); void updateState(const UIState &s); private: void drawIcon(QPainter &p, int x, int y, QPixmap &img, QBrush bg, float opacity); void drawText(QPainter &p, int x, int y, const QString &text, int alpha = 255); - void paintEvent(QPaintEvent *event) override; QPixmap engage_img; + QPixmap experimental_img; QPixmap dm_img; const int radius = 192; const int img_size = (radius / 2) * 1.5; - QString speed; + float speed; QString speedUnit; - QString maxSpeed; + float setSpeed; + float speedLimit; bool is_cruise_set = false; + bool is_metric = false; bool engageable = false; bool dmActive = false; bool hideDM = false; + bool rightHandDM = false; + bool has_us_speed_limit = false; + bool has_eu_speed_limit = false; + bool v_ego_cluster_seen = false; int status = STATUS_DISENGAGED; + std::unique_ptr pm; -signals: - void valueChanged(); -}; - -class OnroadAlerts : public QWidget { - Q_OBJECT - -public: - OnroadAlerts(QWidget *parent = 0) : QWidget(parent) {}; - void updateAlert(const Alert &a, const QColor &color); - -protected: - void paintEvent(QPaintEvent*) override; - -private: - QColor bg; - Alert alert = {}; -}; - -// container window for the NVG UI -class NvgWindow : public CameraViewWidget { - Q_OBJECT - -public: - explicit NvgWindow(VisionStreamType type, QWidget* parent = 0) : CameraViewWidget("camerad", type, true, parent) {} + int skip_frame_count = 0; + bool wide_cam_requested = false; protected: void paintGL() override; void initializeGL() override; void showEvent(QShowEvent *event) override; - void updateFrameMat(int w, int h) override; - void drawLaneLines(QPainter &painter, const UIScene &scene); + void updateFrameMat() override; + void drawLaneLines(QPainter &painter, const UIState *s); void drawLead(QPainter &painter, const cereal::ModelDataV2::LeadDataV3::Reader &lead_data, const QPointF &vd); + void drawHud(QPainter &p); inline QColor redColor(int alpha = 255) { return QColor(201, 34, 49, alpha); } + inline QColor whiteColor(int alpha = 255) { return QColor(255, 255, 255, alpha); } + inline QColor blackColor(int alpha = 255) { return QColor(0, 0, 0, alpha); } + double prev_draw_t = 0; + FirstOrderFilter fps_filter; }; // container for all onroad widgets @@ -90,9 +101,8 @@ public: private: void paintEvent(QPaintEvent *event); void mousePressEvent(QMouseEvent* e) override; - OnroadHud *hud; OnroadAlerts *alerts; - NvgWindow *nvg; + AnnotatedCameraWidget *nvg; QColor bg = bg_colors[STATUS_DISENGAGED]; QWidget *map = nullptr; QHBoxLayout* split; diff --git a/selfdrive/ui/qt/qt_window.h b/selfdrive/ui/qt/qt_window.h index 2c9a24e55b..02d127e7ff 100644 --- a/selfdrive/ui/qt/qt_window.h +++ b/selfdrive/ui/qt/qt_window.h @@ -12,7 +12,7 @@ #include #endif -#include "selfdrive/hardware/hw.h" +#include "system/hardware/hw.h" const QString ASSET_PATH = ":/"; diff --git a/selfdrive/ui/qt/request_repeater.cc b/selfdrive/ui/qt/request_repeater.cc index 7ef1c833ab..fa37c015f7 100644 --- a/selfdrive/ui/qt/request_repeater.cc +++ b/selfdrive/ui/qt/request_repeater.cc @@ -15,7 +15,7 @@ RequestRepeater::RequestRepeater(QObject *parent, const QString &requestURL, con if (!cacheKey.isEmpty()) { prevResp = QString::fromStdString(params.get(cacheKey.toStdString())); if (!prevResp.isEmpty()) { - QTimer::singleShot(500, [=]() { emit requestDone(prevResp, true); }); + QTimer::singleShot(500, [=]() { emit requestDone(prevResp, true, QNetworkReply::NoError); }); } QObject::connect(this, &HttpRequest::requestDone, [=](const QString &resp, bool success) { if (success && resp != prevResp) { diff --git a/selfdrive/ui/qt/request_repeater.h b/selfdrive/ui/qt/request_repeater.h index fa80100d22..c0e2758273 100644 --- a/selfdrive/ui/qt/request_repeater.h +++ b/selfdrive/ui/qt/request_repeater.h @@ -1,6 +1,6 @@ #pragma once -#include "selfdrive/common/util.h" +#include "common/util.h" #include "selfdrive/ui/qt/api.h" #include "selfdrive/ui/ui.h" diff --git a/selfdrive/ui/qt/setup/reset.cc b/selfdrive/ui/qt/setup/reset.cc index 9ffcf7f6cf..582217c1d7 100644 --- a/selfdrive/ui/qt/setup/reset.cc +++ b/selfdrive/ui/qt/setup/reset.cc @@ -26,16 +26,16 @@ void Reset::doReset() { if (rm == 0 || fmt == 0) { std::system("sudo reboot"); } - body->setText("Reset failed. Reboot to try again."); + body->setText(tr("Reset failed. Reboot to try again.")); rebootBtn->show(); } void Reset::confirm() { - const QString confirm_txt = "Are you sure you want to reset your device?"; + const QString confirm_txt = tr("Are you sure you want to reset your device?"); if (body->text() != confirm_txt) { body->setText(confirm_txt); } else { - body->setText("Resetting device..."); + body->setText(tr("Resetting device...")); rejectBtn->hide(); rebootBtn->hide(); confirmBtn->hide(); @@ -50,13 +50,13 @@ Reset::Reset(bool recover, QWidget *parent) : QWidget(parent) { main_layout->setContentsMargins(45, 220, 45, 45); main_layout->setSpacing(0); - QLabel *title = new QLabel("System Reset"); + QLabel *title = new QLabel(tr("System Reset")); title->setStyleSheet("font-size: 90px; font-weight: 600;"); main_layout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft); main_layout->addSpacing(60); - body = new QLabel("System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot."); + body = new QLabel(tr("System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot.")); body->setWordWrap(true); body->setStyleSheet("font-size: 80px; font-weight: light;"); main_layout->addWidget(body, 1, Qt::AlignTop | Qt::AlignLeft); @@ -65,11 +65,11 @@ Reset::Reset(bool recover, QWidget *parent) : QWidget(parent) { main_layout->addLayout(blayout); blayout->setSpacing(50); - rejectBtn = new QPushButton("Cancel"); + rejectBtn = new QPushButton(tr("Cancel")); blayout->addWidget(rejectBtn); QObject::connect(rejectBtn, &QPushButton::clicked, QCoreApplication::instance(), &QCoreApplication::quit); - rebootBtn = new QPushButton("Reboot"); + rebootBtn = new QPushButton(tr("Reboot")); blayout->addWidget(rebootBtn); #ifdef __aarch64__ QObject::connect(rebootBtn, &QPushButton::clicked, [=]{ @@ -77,7 +77,7 @@ Reset::Reset(bool recover, QWidget *parent) : QWidget(parent) { }); #endif - confirmBtn = new QPushButton("Confirm"); + confirmBtn = new QPushButton(tr("Confirm")); confirmBtn->setStyleSheet("background-color: #465BEA;"); blayout->addWidget(confirmBtn); QObject::connect(confirmBtn, &QPushButton::clicked, this, &Reset::confirm); @@ -85,7 +85,7 @@ Reset::Reset(bool recover, QWidget *parent) : QWidget(parent) { rejectBtn->setVisible(!recover); rebootBtn->setVisible(recover); if (recover) { - body->setText("Unable to mount data partition. Press confirm to reset your device."); + body->setText(tr("Unable to mount data partition. Press confirm to reset your device.")); } setStyleSheet(R"( diff --git a/selfdrive/ui/qt/setup/setup.cc b/selfdrive/ui/qt/setup/setup.cc index 17304665c7..69dafcf741 100644 --- a/selfdrive/ui/qt/setup/setup.cc +++ b/selfdrive/ui/qt/setup/setup.cc @@ -10,8 +10,8 @@ #include -#include "selfdrive/common/util.h" -#include "selfdrive/hardware/hw.h" +#include "common/util.h" +#include "system/hardware/hw.h" #include "selfdrive/ui/qt/api.h" #include "selfdrive/ui/qt/qt_window.h" #include "selfdrive/ui/qt/offroad/networking.h" @@ -70,13 +70,13 @@ QWidget * Setup::low_voltage() { inner_layout->addWidget(triangle, 0, Qt::AlignTop | Qt::AlignLeft); inner_layout->addSpacing(80); - QLabel *title = new QLabel("WARNING: Low Voltage"); + QLabel *title = new QLabel(tr("WARNING: Low Voltage")); title->setStyleSheet("font-size: 90px; font-weight: 500; color: #FF594F;"); inner_layout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft); inner_layout->addSpacing(25); - QLabel *body = new QLabel("Power your device in a car with a harness or proceed at your own risk."); + QLabel *body = new QLabel(tr("Power your device in a car with a harness or proceed at your own risk.")); body->setWordWrap(true); body->setAlignment(Qt::AlignTop | Qt::AlignLeft); body->setStyleSheet("font-size: 80px; font-weight: 300;"); @@ -89,14 +89,14 @@ QWidget * Setup::low_voltage() { blayout->setSpacing(50); main_layout->addLayout(blayout, 0); - QPushButton *poweroff = new QPushButton("Power off"); + QPushButton *poweroff = new QPushButton(tr("Power off")); poweroff->setObjectName("navBtn"); blayout->addWidget(poweroff); QObject::connect(poweroff, &QPushButton::clicked, this, [=]() { Hardware::poweroff(); }); - QPushButton *cont = new QPushButton("Continue"); + QPushButton *cont = new QPushButton(tr("Continue")); cont->setObjectName("navBtn"); blayout->addWidget(cont); QObject::connect(cont, &QPushButton::clicked, this, &Setup::nextPage); @@ -114,12 +114,12 @@ QWidget * Setup::getting_started() { vlayout->setContentsMargins(165, 280, 100, 0); main_layout->addLayout(vlayout); - QLabel *title = new QLabel("Getting Started"); + QLabel *title = new QLabel(tr("Getting Started")); title->setStyleSheet("font-size: 90px; font-weight: 500;"); vlayout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft); vlayout->addSpacing(90); - QLabel *desc = new QLabel("Before we get on the road, let’s finish installation and cover some details."); + QLabel *desc = new QLabel(tr("Before we get on the road, let’s finish installation and cover some details.")); desc->setWordWrap(true); desc->setStyleSheet("font-size: 80px; font-weight: 300;"); vlayout->addWidget(desc, 0, Qt::AlignTop | Qt::AlignLeft); @@ -144,7 +144,7 @@ QWidget * Setup::network_setup() { main_layout->setContentsMargins(55, 50, 55, 50); // title - QLabel *title = new QLabel("Connect to Wi-Fi"); + QLabel *title = new QLabel(tr("Connect to Wi-Fi")); title->setStyleSheet("font-size: 90px; font-weight: 500;"); main_layout->addWidget(title, 0, Qt::AlignLeft | Qt::AlignTop); @@ -162,7 +162,7 @@ QWidget * Setup::network_setup() { main_layout->addLayout(blayout); blayout->setSpacing(50); - QPushButton *back = new QPushButton("Back"); + QPushButton *back = new QPushButton(tr("Back")); back->setObjectName("navBtn"); QObject::connect(back, &QPushButton::clicked, this, &Setup::prevPage); blayout->addWidget(back); @@ -179,9 +179,9 @@ QWidget * Setup::network_setup() { cont->setEnabled(success); if (success) { const bool cell = networking->wifi->currentNetworkType() == NetworkType::CELL; - cont->setText(cell ? "Continue without Wi-Fi" : "Continue"); + cont->setText(cell ? tr("Continue without Wi-Fi") : tr("Continue")); } else { - cont->setText("Waiting for internet"); + cont->setText(tr("Waiting for internet")); } repaint(); }); @@ -235,7 +235,7 @@ QWidget * Setup::software_selection() { main_layout->setSpacing(0); // title - QLabel *title = new QLabel("Choose Software to Install"); + QLabel *title = new QLabel(tr("Choose Software to Install")); title->setStyleSheet("font-size: 90px; font-weight: 500;"); main_layout->addWidget(title, 0, Qt::AlignLeft | Qt::AlignTop); @@ -245,12 +245,12 @@ QWidget * Setup::software_selection() { QButtonGroup *group = new QButtonGroup(widget); group->setExclusive(true); - QWidget *dashcam = radio_button("Dashcam", group); + QWidget *dashcam = radio_button(tr("Dashcam"), group); main_layout->addWidget(dashcam); main_layout->addSpacing(30); - QWidget *custom = radio_button("Custom Software", group); + QWidget *custom = radio_button(tr("Custom Software"), group); main_layout->addWidget(custom); main_layout->addStretch(); @@ -260,12 +260,12 @@ QWidget * Setup::software_selection() { main_layout->addLayout(blayout); blayout->setSpacing(50); - QPushButton *back = new QPushButton("Back"); + QPushButton *back = new QPushButton(tr("Back")); back->setObjectName("navBtn"); QObject::connect(back, &QPushButton::clicked, this, &Setup::prevPage); blayout->addWidget(back); - QPushButton *cont = new QPushButton("Continue"); + QPushButton *cont = new QPushButton(tr("Continue")); cont->setObjectName("navBtn"); cont->setEnabled(false); cont->setProperty("primary", true); @@ -278,7 +278,7 @@ QWidget * Setup::software_selection() { }); QString url = DASHCAM_URL; if (group->checkedButton() != dashcam) { - url = InputDialog::getText("Enter URL", this, "for Custom Software"); + url = InputDialog::getText(tr("Enter URL"), this, tr("for Custom Software")); } if (!url.isEmpty()) { QTimer::singleShot(1000, this, [=]() { @@ -300,7 +300,7 @@ QWidget * Setup::software_selection() { QWidget * Setup::downloading() { QWidget *widget = new QWidget(); QVBoxLayout *main_layout = new QVBoxLayout(widget); - QLabel *txt = new QLabel("Downloading..."); + QLabel *txt = new QLabel(tr("Downloading...")); txt->setStyleSheet("font-size: 90px; font-weight: 500;"); main_layout->addWidget(txt, 0, Qt::AlignCenter); return widget; @@ -312,13 +312,13 @@ QWidget * Setup::download_failed() { main_layout->setContentsMargins(55, 225, 55, 55); main_layout->setSpacing(0); - QLabel *title = new QLabel("Download Failed"); + QLabel *title = new QLabel(tr("Download Failed")); title->setStyleSheet("font-size: 90px; font-weight: 500;"); main_layout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft); main_layout->addSpacing(67); - QLabel *body = new QLabel("Ensure the entered URL is valid, and the device’s internet connection is good."); + QLabel *body = new QLabel(tr("Ensure the entered URL is valid, and the device’s internet connection is good.")); body->setWordWrap(true); body->setAlignment(Qt::AlignTop | Qt::AlignLeft); body->setStyleSheet("font-size: 80px; font-weight: 300; margin-right: 100px;"); @@ -331,14 +331,14 @@ QWidget * Setup::download_failed() { blayout->setSpacing(50); main_layout->addLayout(blayout, 0); - QPushButton *reboot = new QPushButton("Reboot device"); + QPushButton *reboot = new QPushButton(tr("Reboot device")); reboot->setObjectName("navBtn"); blayout->addWidget(reboot); QObject::connect(reboot, &QPushButton::clicked, this, [=]() { Hardware::reboot(); }); - QPushButton *restart = new QPushButton("Start over"); + QPushButton *restart = new QPushButton(tr("Start over")); restart->setObjectName("navBtn"); restart->setProperty("primary", true); blayout->addWidget(restart); diff --git a/selfdrive/ui/qt/setup/updater.cc b/selfdrive/ui/qt/setup/updater.cc index dfa63fca11..fd7148c534 100644 --- a/selfdrive/ui/qt/setup/updater.cc +++ b/selfdrive/ui/qt/setup/updater.cc @@ -2,14 +2,11 @@ #include #include -#include "selfdrive/hardware/hw.h" +#include "system/hardware/hw.h" #include "selfdrive/ui/qt/util.h" #include "selfdrive/ui/qt/qt_window.h" #include "selfdrive/ui/qt/setup/updater.h" - -#ifndef QCOM #include "selfdrive/ui/qt/offroad/networking.h" -#endif Updater::Updater(const QString &updater_path, const QString &manifest_path, QWidget *parent) : updater(updater_path), manifest(manifest_path), QStackedWidget(parent) { @@ -23,13 +20,13 @@ Updater::Updater(const QString &updater_path, const QString &manifest_path, QWid QVBoxLayout *layout = new QVBoxLayout(prompt); layout->setContentsMargins(100, 250, 100, 100); - QLabel *title = new QLabel("Update Required"); + QLabel *title = new QLabel(tr("Update Required")); title->setStyleSheet("font-size: 80px; font-weight: bold;"); layout->addWidget(title); layout->addSpacing(75); - QLabel *desc = new QLabel("An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB."); + QLabel *desc = new QLabel(tr("An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB.")); desc->setWordWrap(true); desc->setStyleSheet("font-size: 65px;"); layout->addWidget(desc); @@ -40,18 +37,14 @@ Updater::Updater(const QString &updater_path, const QString &manifest_path, QWid hlayout->setSpacing(30); layout->addLayout(hlayout); - QPushButton *connect = new QPushButton("Connect to Wi-Fi"); + QPushButton *connect = new QPushButton(tr("Connect to Wi-Fi")); connect->setObjectName("navBtn"); QObject::connect(connect, &QPushButton::clicked, [=]() { -#ifndef QCOM setCurrentWidget(wifi); -#else - HardwareEon::launch_wifi(); -#endif }); hlayout->addWidget(connect); - QPushButton *install = new QPushButton("Install"); + QPushButton *install = new QPushButton(tr("Install")); install->setObjectName("navBtn"); install->setStyleSheet("background-color: #465BEA;"); QObject::connect(install, &QPushButton::clicked, this, &Updater::installUpdate); @@ -64,13 +57,11 @@ Updater::Updater(const QString &updater_path, const QString &manifest_path, QWid QVBoxLayout *layout = new QVBoxLayout(wifi); layout->setContentsMargins(100, 100, 100, 100); -#ifndef QCOM Networking *networking = new Networking(this, false); networking->setStyleSheet("Networking { background-color: #292929; border-radius: 13px; }"); layout->addWidget(networking, 1); -#endif - QPushButton *back = new QPushButton("Back"); + QPushButton *back = new QPushButton(tr("Back")); back->setObjectName("navBtn"); back->setStyleSheet("padding-left: 60px; padding-right: 60px;"); QObject::connect(back, &QPushButton::clicked, [=]() { @@ -86,7 +77,7 @@ Updater::Updater(const QString &updater_path, const QString &manifest_path, QWid layout->setContentsMargins(150, 330, 150, 150); layout->setSpacing(0); - text = new QLabel("Loading..."); + text = new QLabel(tr("Loading...")); text->setStyleSheet("font-size: 90px; font-weight: 600;"); layout->addWidget(text, 0, Qt::AlignTop); @@ -100,7 +91,7 @@ Updater::Updater(const QString &updater_path, const QString &manifest_path, QWid layout->addStretch(); - reboot = new QPushButton("Reboot"); + reboot = new QPushButton(tr("Reboot")); reboot->setObjectName("navBtn"); reboot->setStyleSheet("padding-left: 60px; padding-right: 60px;"); QObject::connect(reboot, &QPushButton::clicked, [=]() { @@ -170,27 +161,13 @@ void Updater::updateFinished(int exitCode, QProcess::ExitStatus exitStatus) { if (exitCode == 0) { Hardware::reboot(); } else { - text->setText("Update failed"); + text->setText(tr("Update failed")); reboot->show(); } } -bool Updater::eventFilter(QObject *obj, QEvent *event) { -#ifdef QCOM - // filter out touches while in android activity - const static QSet filter_events({QEvent::MouseButtonPress, QEvent::MouseMove, QEvent::TouchBegin, QEvent::TouchUpdate, QEvent::TouchEnd}); - if (HardwareEon::launched_activity && filter_events.contains(event->type())) { - HardwareEon::check_activity(); - if (HardwareEon::launched_activity) { - return true; - } - } -#endif - return false; -} - int main(int argc, char *argv[]) { - initApp(); + initApp(argc, argv); QApplication a(argc, argv); Updater updater(argv[1], argv[2]); setMainWindow(&updater); diff --git a/selfdrive/ui/qt/setup/updater.h b/selfdrive/ui/qt/setup/updater.h index 32aef43f59..ce46c0aabd 100644 --- a/selfdrive/ui/qt/setup/updater.h +++ b/selfdrive/ui/qt/setup/updater.h @@ -19,8 +19,6 @@ private slots: void updateFinished(int exitCode, QProcess::ExitStatus exitStatus); private: - bool eventFilter(QObject *obj, QEvent *event) override; - QProcess proc; QString updater, manifest; diff --git a/selfdrive/ui/qt/sidebar.cc b/selfdrive/ui/qt/sidebar.cc index cdff1fce86..212f195625 100644 --- a/selfdrive/ui/qt/sidebar.cc +++ b/selfdrive/ui/qt/sidebar.cc @@ -4,13 +4,13 @@ #include "selfdrive/ui/qt/util.h" -void Sidebar::drawMetric(QPainter &p, const QString &label, QColor c, int y) { - const QRect rect = {30, y, 240, label.contains("\n") ? 124 : 100}; +void Sidebar::drawMetric(QPainter &p, const QPair &label, QColor c, int y) { + const QRect rect = {30, y, 240, 126}; p.setPen(Qt::NoPen); p.setBrush(QBrush(c)); - p.setClipRect(rect.x() + 6, rect.y(), 18, rect.height(), Qt::ClipOperation::ReplaceClip); - p.drawRoundedRect(QRect(rect.x() + 6, rect.y() + 6, 100, rect.height() - 12), 10, 10); + p.setClipRect(rect.x() + 4, rect.y(), 18, rect.height(), Qt::ClipOperation::ReplaceClip); + p.drawRoundedRect(QRect(rect.x() + 4, rect.y() + 4, 100, 118), 18, 18); p.setClipping(false); QPen pen = QPen(QColor(0xff, 0xff, 0xff, 0x55)); @@ -20,13 +20,21 @@ void Sidebar::drawMetric(QPainter &p, const QString &label, QColor c, int y) { p.drawRoundedRect(rect, 20, 20); p.setPen(QColor(0xff, 0xff, 0xff)); - configFont(p, "Open Sans", 35, "Bold"); - const QRect r = QRect(rect.x() + 30, rect.y(), rect.width() - 40, rect.height()); - p.drawText(r, Qt::AlignCenter, label); + configFont(p, "Inter", 35, "SemiBold"); + + QRect label_rect = getTextRect(p, Qt::AlignCenter, label.first); + label_rect.setWidth(218); + label_rect.moveLeft(rect.left() + 22); + label_rect.moveTop(rect.top() + 19); + p.drawText(label_rect, Qt::AlignCenter, label.first); + + label_rect.moveTop(rect.top() + 65); + p.drawText(label_rect, Qt::AlignCenter, label.second); } -Sidebar::Sidebar(QWidget *parent) : QFrame(parent) { - home_img = loadPixmap("../assets/images/button_home.png", {180, 180}); +Sidebar::Sidebar(QWidget *parent) : QFrame(parent), onroad(false), flag_pressed(false), settings_pressed(false) { + home_img = loadPixmap("../assets/images/button_home.png", home_btn.size()); + flag_img = loadPixmap("../assets/images/button_flag.png", home_btn.size()); settings_img = loadPixmap("../assets/images/button_settings.png", settings_btn.size(), Qt::IgnoreAspectRatio); connect(this, &Sidebar::valueChanged, [=] { update(); }); @@ -36,14 +44,39 @@ Sidebar::Sidebar(QWidget *parent) : QFrame(parent) { setFixedWidth(300); QObject::connect(uiState(), &UIState::uiUpdate, this, &Sidebar::updateState); + + pm = std::make_unique>({"userFlag"}); +} + +void Sidebar::mousePressEvent(QMouseEvent *event) { + if (onroad && home_btn.contains(event->pos())) { + flag_pressed = true; + update(); + } else if (settings_btn.contains(event->pos())) { + settings_pressed = true; + update(); + } } void Sidebar::mouseReleaseEvent(QMouseEvent *event) { - if (settings_btn.contains(event->pos())) { + if (flag_pressed || settings_pressed) { + flag_pressed = settings_pressed = false; + update(); + } + if (home_btn.contains(event->pos())) { + MessageBuilder msg; + msg.initEvent().initUserFlag(); + pm->send("userFlag", msg); + } else if (settings_btn.contains(event->pos())) { emit openSettings(); } } +void Sidebar::offroadTransition(bool offroad) { + onroad = !offroad; + update(); +} + void Sidebar::updateState(const UIState &s) { if (!isVisible()) return; @@ -57,26 +90,26 @@ void Sidebar::updateState(const UIState &s) { ItemStatus connectStatus; auto last_ping = deviceState.getLastAthenaPingTime(); if (last_ping == 0) { - connectStatus = params.getBool("PrimeRedirected") ? ItemStatus{"NO\nPRIME", danger_color} : ItemStatus{"CONNECT\nOFFLINE", warning_color}; + connectStatus = ItemStatus{{tr("CONNECT"), tr("OFFLINE")}, warning_color}; } else { - connectStatus = nanos_since_boot() - last_ping < 80e9 ? ItemStatus{"CONNECT\nONLINE", good_color} : ItemStatus{"CONNECT\nERROR", danger_color}; + connectStatus = nanos_since_boot() - last_ping < 80e9 ? ItemStatus{{tr("CONNECT"), tr("ONLINE")}, good_color} : ItemStatus{{tr("CONNECT"), tr("ERROR")}, danger_color}; } setProperty("connectStatus", QVariant::fromValue(connectStatus)); - ItemStatus tempStatus = {"TEMP\nHIGH", danger_color}; + ItemStatus tempStatus = {{tr("TEMP"), tr("HIGH")}, danger_color}; auto ts = deviceState.getThermalStatus(); if (ts == cereal::DeviceState::ThermalStatus::GREEN) { - tempStatus = {"TEMP\nGOOD", good_color}; + tempStatus = {{tr("TEMP"), tr("GOOD")}, good_color}; } else if (ts == cereal::DeviceState::ThermalStatus::YELLOW) { - tempStatus = {"TEMP\nOK", warning_color}; + tempStatus = {{tr("TEMP"), tr("OK")}, warning_color}; } setProperty("tempStatus", QVariant::fromValue(tempStatus)); - ItemStatus pandaStatus = {"VEHICLE\nONLINE", good_color}; + ItemStatus pandaStatus = {{tr("VEHICLE"), tr("ONLINE")}, good_color}; if (s.scene.pandaType == cereal::PandaState::PandaType::UNKNOWN) { - pandaStatus = {"NO\nPANDA", danger_color}; + pandaStatus = {{tr("NO"), tr("PANDA")}, danger_color}; } else if (s.scene.started && !sm["liveLocationKalman"].getLiveLocationKalman().getGpsOK()) { - pandaStatus = {"GPS\nSEARCHING", warning_color}; + pandaStatus = {{tr("GPS"), tr("SEARCH")}, warning_color}; } setProperty("pandaStatus", QVariant::fromValue(pandaStatus)); } @@ -88,11 +121,12 @@ void Sidebar::paintEvent(QPaintEvent *event) { p.fillRect(rect(), QColor(57, 57, 57)); - // static imgs - p.setOpacity(0.65); + // buttons + p.setOpacity(settings_pressed ? 0.65 : 1.0); p.drawPixmap(settings_btn.x(), settings_btn.y(), settings_img); + p.setOpacity(onroad && flag_pressed ? 0.65 : 1.0); + p.drawPixmap(home_btn.x(), home_btn.y(), onroad ? flag_img : home_img); p.setOpacity(1.0); - p.drawPixmap(60, 1080 - 180 - 40, home_img); // network int x = 58; @@ -103,7 +137,7 @@ void Sidebar::paintEvent(QPaintEvent *event) { x += 37; } - configFont(p, "Open Sans", 35, "Regular"); + configFont(p, "Inter", 35, "Regular"); p.setPen(QColor(0xff, 0xff, 0xff)); const QRect r = QRect(50, 247, 100, 50); p.drawText(r, Qt::AlignCenter, net_type); diff --git a/selfdrive/ui/qt/sidebar.h b/selfdrive/ui/qt/sidebar.h index 5d1b921750..fb96e1d540 100644 --- a/selfdrive/ui/qt/sidebar.h +++ b/selfdrive/ui/qt/sidebar.h @@ -3,10 +3,9 @@ #include #include -#include "selfdrive/common/params.h" #include "selfdrive/ui/ui.h" -typedef QPair ItemStatus; +typedef QPair, QColor> ItemStatus; Q_DECLARE_METATYPE(ItemStatus); class Sidebar : public QFrame { @@ -21,35 +20,41 @@ public: explicit Sidebar(QWidget* parent = 0); signals: - void openSettings(); + void openSettings(int index = 0, const QString ¶m = ""); void valueChanged(); public slots: + void offroadTransition(bool offroad); void updateState(const UIState &s); protected: void paintEvent(QPaintEvent *event) override; + void mousePressEvent(QMouseEvent *event) override; void mouseReleaseEvent(QMouseEvent *event) override; - void drawMetric(QPainter &p, const QString &label, QColor c, int y); + void drawMetric(QPainter &p, const QPair &label, QColor c, int y); - QPixmap home_img, settings_img; + QPixmap home_img, flag_img, settings_img; + bool onroad, flag_pressed, settings_pressed; const QMap network_type = { - {cereal::DeviceState::NetworkType::NONE, "--"}, - {cereal::DeviceState::NetworkType::WIFI, "Wi-Fi"}, - {cereal::DeviceState::NetworkType::ETHERNET, "ETH"}, - {cereal::DeviceState::NetworkType::CELL2_G, "2G"}, - {cereal::DeviceState::NetworkType::CELL3_G, "3G"}, - {cereal::DeviceState::NetworkType::CELL4_G, "LTE"}, - {cereal::DeviceState::NetworkType::CELL5_G, "5G"} + {cereal::DeviceState::NetworkType::NONE, tr("--")}, + {cereal::DeviceState::NetworkType::WIFI, tr("Wi-Fi")}, + {cereal::DeviceState::NetworkType::ETHERNET, tr("ETH")}, + {cereal::DeviceState::NetworkType::CELL2_G, tr("2G")}, + {cereal::DeviceState::NetworkType::CELL3_G, tr("3G")}, + {cereal::DeviceState::NetworkType::CELL4_G, tr("LTE")}, + {cereal::DeviceState::NetworkType::CELL5_G, tr("5G")} }; + const QRect home_btn = QRect(60, 860, 180, 180); const QRect settings_btn = QRect(50, 35, 200, 117); const QColor good_color = QColor(255, 255, 255); const QColor warning_color = QColor(218, 202, 37); const QColor danger_color = QColor(201, 34, 49); - Params params; ItemStatus connect_status, panda_status, temp_status; QString net_type; int net_strength = 0; + +private: + std::unique_ptr pm; }; diff --git a/selfdrive/ui/qt/spinner.cc b/selfdrive/ui/qt/spinner.cc index b9868f6035..8f13576fb2 100644 --- a/selfdrive/ui/qt/spinner.cc +++ b/selfdrive/ui/qt/spinner.cc @@ -10,7 +10,7 @@ #include #include -#include "selfdrive/hardware/hw.h" +#include "system/hardware/hw.h" #include "selfdrive/ui/qt/qt_window.h" #include "selfdrive/ui/qt/util.h" @@ -111,7 +111,7 @@ void Spinner::update(int n) { } int main(int argc, char *argv[]) { - initApp(); + initApp(argc, argv); QApplication a(argc, argv); Spinner spinner; setMainWindow(&spinner); diff --git a/selfdrive/ui/qt/spinner_aarch64 b/selfdrive/ui/qt/spinner_aarch64 deleted file mode 100755 index 71a52bc9f1..0000000000 Binary files a/selfdrive/ui/qt/spinner_aarch64 and /dev/null differ diff --git a/selfdrive/ui/qt/text.cc b/selfdrive/ui/qt/text.cc index cb69cc082b..21ec5eedcf 100644 --- a/selfdrive/ui/qt/text.cc +++ b/selfdrive/ui/qt/text.cc @@ -5,13 +5,13 @@ #include #include -#include "selfdrive/hardware/hw.h" +#include "system/hardware/hw.h" #include "selfdrive/ui/qt/util.h" #include "selfdrive/ui/qt/qt_window.h" #include "selfdrive/ui/qt/widgets/scrollview.h" int main(int argc, char *argv[]) { - initApp(); + initApp(argc, argv); QApplication a(argc, argv); QWidget window; setMainWindow(&window); @@ -33,12 +33,12 @@ int main(int argc, char *argv[]) { QPushButton *btn = new QPushButton(); #ifdef __aarch64__ - btn->setText("Reboot"); + btn->setText(QObject::tr("Reboot")); QObject::connect(btn, &QPushButton::clicked, [=]() { Hardware::reboot(); }); #else - btn->setText("Exit"); + btn->setText(QObject::tr("Exit")); QObject::connect(btn, &QPushButton::clicked, &a, &QApplication::quit); #endif main_layout->addWidget(btn, 0, 0, Qt::AlignRight | Qt::AlignBottom); diff --git a/selfdrive/ui/qt/text_aarch64 b/selfdrive/ui/qt/text_aarch64 deleted file mode 100755 index dbce56d59f..0000000000 Binary files a/selfdrive/ui/qt/text_aarch64 and /dev/null differ diff --git a/selfdrive/ui/qt/util.cc b/selfdrive/ui/qt/util.cc index 16d5c174b5..59903e3376 100644 --- a/selfdrive/ui/qt/util.cc +++ b/selfdrive/ui/qt/util.cc @@ -1,12 +1,16 @@ #include "selfdrive/ui/qt/util.h" #include +#include +#include +#include #include #include +#include -#include "selfdrive/common/params.h" -#include "selfdrive/common/swaglog.h" -#include "selfdrive/hardware/hw.h" +#include "common/params.h" +#include "common/swaglog.h" +#include "system/hardware/hw.h" QString getVersion() { static QString version = QString::fromStdString(Params().get("Version")); @@ -14,11 +18,7 @@ QString getVersion() { } QString getBrand() { - return Params().getBool("Passive") ? "dashcam" : "openpilot"; -} - -QString getBrandVersion() { - return getBrand() + " v" + getVersion().left(14).trimmed(); + return Params().getBool("Passive") ? QObject::tr("dashcam") : QObject::tr("openpilot"); } QString getUserAgent() { @@ -35,6 +35,19 @@ std::optional getDongleId() { } } +QMap getSupportedLanguages() { + QFile f("translations/languages.json"); + f.open(QIODevice::ReadOnly | QIODevice::Text); + QString val = f.readAll(); + + QJsonObject obj = QJsonDocument::fromJson(val.toUtf8()).object(); + QMap map; + for (auto key : obj.keys()) { + map[key] = obj[key].toString(); + } + return map; +} + void configFont(QPainter &p, const QString &family, int size, const QString &style) { QFont f(family); f.setPixelSize(size); @@ -62,13 +75,13 @@ QString timeAgo(const QDateTime &date) { s = "now"; } else if (diff < 60 * 60) { int minutes = diff / 60; - s = QString("%1 minute%2 ago").arg(minutes).arg(minutes > 1 ? "s" : ""); + s = QObject::tr("%n minute(s) ago", "", minutes); } else if (diff < 60 * 60 * 24) { int hours = diff / (60 * 60); - s = QString("%1 hour%2 ago").arg(hours).arg(hours > 1 ? "s" : ""); + s = QObject::tr("%n hour(s) ago", "", hours); } else if (diff < 3600 * 24 * 7) { int days = diff / (60 * 60 * 24); - s = QString("%1 day%2 ago").arg(days).arg(days > 1 ? "s" : ""); + s = QObject::tr("%n day(s) ago", "", days); } else { s = date.date().toString(); } @@ -89,13 +102,28 @@ void setQtSurfaceFormat() { QSurfaceFormat::setDefaultFormat(fmt); } -void initApp() { +void sigTermHandler(int s) { + std::signal(s, SIG_DFL); + qApp->quit(); +} + +void initApp(int argc, char *argv[]) { Hardware::set_display_power(true); Hardware::set_brightness(65); - setQtSurfaceFormat(); - if (Hardware::EON()) { - QApplication::setAttribute(Qt::AA_ShareOpenGLContexts); + + // setup signal handlers to exit gracefully + std::signal(SIGINT, sigTermHandler); + std::signal(SIGTERM, sigTermHandler); + +#ifdef __APPLE__ + { + // Get the devicePixelRatio, and scale accordingly to maintain 1:1 rendering + QApplication tmp(argc, argv); + qputenv("QT_SCALE_FACTOR", QString::number(1.0 / tmp.devicePixelRatio() ).toLocal8Bit()); } +#endif + + setQtSurfaceFormat(); } void swagLogMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) { @@ -129,3 +157,64 @@ QPixmap loadPixmap(const QString &fileName, const QSize &size, Qt::AspectRatioMo return QPixmap(fileName).scaled(size, aspectRatioMode, Qt::SmoothTransformation); } } + +QRect getTextRect(QPainter &p, int flags, const QString &text) { + QFontMetrics fm(p.font()); + QRect init_rect = fm.boundingRect(text); + return fm.boundingRect(init_rect, flags, text); +} + +void drawRoundedRect(QPainter &painter, const QRectF &rect, qreal xRadiusTop, qreal yRadiusTop, qreal xRadiusBottom, qreal yRadiusBottom){ + qreal w_2 = rect.width() / 2; + qreal h_2 = rect.height() / 2; + + xRadiusTop = 100 * qMin(xRadiusTop, w_2) / w_2; + yRadiusTop = 100 * qMin(yRadiusTop, h_2) / h_2; + + xRadiusBottom = 100 * qMin(xRadiusBottom, w_2) / w_2; + yRadiusBottom = 100 * qMin(yRadiusBottom, h_2) / h_2; + + qreal x = rect.x(); + qreal y = rect.y(); + qreal w = rect.width(); + qreal h = rect.height(); + + qreal rxx2Top = w*xRadiusTop/100; + qreal ryy2Top = h*yRadiusTop/100; + + qreal rxx2Bottom = w*xRadiusBottom/100; + qreal ryy2Bottom = h*yRadiusBottom/100; + + QPainterPath path; + path.arcMoveTo(x, y, rxx2Top, ryy2Top, 180); + path.arcTo(x, y, rxx2Top, ryy2Top, 180, -90); + path.arcTo(x+w-rxx2Top, y, rxx2Top, ryy2Top, 90, -90); + path.arcTo(x+w-rxx2Bottom, y+h-ryy2Bottom, rxx2Bottom, ryy2Bottom, 0, -90); + path.arcTo(x, y+h-ryy2Bottom, rxx2Bottom, ryy2Bottom, 270, -90); + path.closeSubpath(); + + painter.drawPath(path); +} + +QColor interpColor(float xv, std::vector xp, std::vector fp) { + assert(xp.size() == fp.size()); + + int N = xp.size(); + int hi = 0; + + while (hi < N and xv > xp[hi]) hi++; + int low = hi - 1; + + if (hi == N && xv > xp[low]) { + return fp[fp.size() - 1]; + } else if (hi == 0){ + return fp[0]; + } else { + return QColor( + (xv - xp[low]) * (fp[hi].red() - fp[low].red()) / (xp[hi] - xp[low]) + fp[low].red(), + (xv - xp[low]) * (fp[hi].green() - fp[low].green()) / (xp[hi] - xp[low]) + fp[low].green(), + (xv - xp[low]) * (fp[hi].blue() - fp[low].blue()) / (xp[hi] - xp[low]) + fp[low].blue(), + (xv - xp[low]) * (fp[hi].alpha() - fp[low].alpha()) / (xp[hi] - xp[low]) + fp[low].alpha() + ); + } +} diff --git a/selfdrive/ui/qt/util.h b/selfdrive/ui/qt/util.h index 1b9461fabf..61a27a8669 100644 --- a/selfdrive/ui/qt/util.h +++ b/selfdrive/ui/qt/util.h @@ -11,14 +11,18 @@ QString getVersion(); QString getBrand(); -QString getBrandVersion(); QString getUserAgent(); std::optional getDongleId(); +QMap getSupportedLanguages(); void configFont(QPainter &p, const QString &family, int size, const QString &style); void clearLayout(QLayout* layout); void setQtSurfaceFormat(); QString timeAgo(const QDateTime &date); void swagLogMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg); -void initApp(); +void initApp(int argc, char *argv[]); QWidget* topWidget (QWidget* widget); QPixmap loadPixmap(const QString &fileName, const QSize &size = {}, Qt::AspectRatioMode aspectRatioMode = Qt::KeepAspectRatio); + +QRect getTextRect(QPainter &p, int flags, const QString &text); +void drawRoundedRect(QPainter &painter, const QRectF &rect, qreal xRadiusTop, qreal yRadiusTop, qreal xRadiusBottom, qreal yRadiusBottom); +QColor interpColor(float xv, std::vector xp, std::vector fp); diff --git a/selfdrive/ui/qt/widgets/cameraview.cc b/selfdrive/ui/qt/widgets/cameraview.cc index fbd425b025..347cdb1dca 100644 --- a/selfdrive/ui/qt/widgets/cameraview.cc +++ b/selfdrive/ui/qt/widgets/cameraview.cc @@ -6,6 +6,8 @@ #include #endif +#include + #include #include @@ -13,65 +15,62 @@ namespace { const char frame_vertex_shader[] = #ifdef __APPLE__ - "#version 150 core\n" + "#version 330 core\n" #else "#version 300 es\n" #endif - "in vec4 aPosition;\n" - "in vec4 aTexCoord;\n" + "layout(location = 0) in vec4 aPosition;\n" + "layout(location = 1) in vec2 aTexCoord;\n" "uniform mat4 uTransform;\n" - "out vec4 vTexCoord;\n" + "out vec2 vTexCoord;\n" "void main() {\n" " gl_Position = uTransform * aPosition;\n" " vTexCoord = aTexCoord;\n" "}\n"; +#ifdef QCOM2 +const char frame_fragment_shader[] = + "#version 300 es\n" + "#extension GL_OES_EGL_image_external_essl3 : enable\n" + "precision mediump float;\n" + "uniform samplerExternalOES uTexture;\n" + "in vec2 vTexCoord;\n" + "out vec4 colorOut;\n" + "void main() {\n" + " colorOut = texture(uTexture, vTexCoord);\n" + "}\n"; +#else const char frame_fragment_shader[] = #ifdef __APPLE__ - "#version 150 core\n" + "#version 330 core\n" #else "#version 300 es\n" "precision mediump float;\n" #endif - "uniform sampler2D uTexture;\n" - "in vec4 vTexCoord;\n" + "uniform sampler2D uTextureY;\n" + "uniform sampler2D uTextureUV;\n" + "in vec2 vTexCoord;\n" "out vec4 colorOut;\n" "void main() {\n" - " colorOut = texture(uTexture, vTexCoord.xy);\n" -#ifdef QCOM - " vec3 dz = vec3(0.0627f, 0.0627f, 0.0627f);\n" - " colorOut.rgb = ((vec3(1.0f, 1.0f, 1.0f) - dz) * colorOut.rgb / vec3(1.0f, 1.0f, 1.0f)) + dz;\n" -#endif + " float y = texture(uTextureY, vTexCoord).r;\n" + " vec2 uv = texture(uTextureUV, vTexCoord).rg - 0.5;\n" + " float r = y + 1.402 * uv.y;\n" + " float g = y - 0.344 * uv.x - 0.714 * uv.y;\n" + " float b = y + 1.772 * uv.x;\n" + " colorOut = vec4(r, g, b, 1.0);\n" "}\n"; - -const mat4 device_transform = {{ - 1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, -}}; +#endif mat4 get_driver_view_transform(int screen_width, int screen_height, int stream_width, int stream_height) { - const float driver_view_ratio = 1.333; - mat4 transform; - if (stream_width == TICI_CAM_WIDTH) { - const float yscale = stream_height * driver_view_ratio / tici_dm_crop::width; - const float xscale = yscale*screen_height/screen_width*stream_width/stream_height; - transform = (mat4){{ - xscale, 0.0, 0.0, xscale*tici_dm_crop::x_offset/stream_width*2, - 0.0, yscale, 0.0, yscale*tici_dm_crop::y_offset/stream_height*2, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, - }}; - } else { - // frame from 4/3 to 16/9 display - transform = (mat4){{ - driver_view_ratio * screen_height / screen_width, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, - }}; - } + const float driver_view_ratio = 2.0; + const float yscale = stream_height * driver_view_ratio / stream_width; + const float xscale = yscale*screen_height/screen_width*stream_width/stream_height; + mat4 transform = (mat4){{ + xscale, 0.0, 0.0, 0.0, + 0.0, yscale, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0, + }}; return transform; } @@ -94,23 +93,26 @@ mat4 get_fit_view_transform(float widget_aspect_ratio, float frame_aspect_ratio) } // namespace -CameraViewWidget::CameraViewWidget(std::string stream_name, VisionStreamType type, bool zoom, QWidget* parent) : - stream_name(stream_name), stream_type(type), zoomed_view(zoom), QOpenGLWidget(parent) { +CameraWidget::CameraWidget(std::string stream_name, VisionStreamType type, bool zoom, QWidget* parent) : + stream_name(stream_name), requested_stream_type(type), zoomed_view(zoom), QOpenGLWidget(parent) { setAttribute(Qt::WA_OpaquePaintEvent); - connect(this, &CameraViewWidget::vipcThreadConnected, this, &CameraViewWidget::vipcConnected, Qt::BlockingQueuedConnection); + QObject::connect(this, &CameraWidget::vipcThreadConnected, this, &CameraWidget::vipcConnected, Qt::BlockingQueuedConnection); + QObject::connect(this, &CameraWidget::vipcThreadFrameReceived, this, &CameraWidget::vipcFrameReceived, Qt::QueuedConnection); } -CameraViewWidget::~CameraViewWidget() { +CameraWidget::~CameraWidget() { makeCurrent(); + stopVipcThread(); if (isValid()) { glDeleteVertexArrays(1, &frame_vao); glDeleteBuffers(1, &frame_vbo); glDeleteBuffers(1, &frame_ibo); + glDeleteBuffers(2, textures); } doneCurrent(); } -void CameraViewWidget::initializeGL() { +void CameraWidget::initializeGL() { initializeOpenGLFunctions(); program = std::make_unique(context()); @@ -123,7 +125,7 @@ void CameraViewWidget::initializeGL() { GLint frame_pos_loc = program->attributeLocation("aPosition"); GLint frame_texcoord_loc = program->attributeLocation("aTexCoord"); - auto [x1, x2, y1, y2] = stream_type == VISION_STREAM_RGB_FRONT ? std::tuple(0.f, 1.f, 1.f, 0.f) : std::tuple(1.f, 0.f, 1.f, 0.f); + auto [x1, x2, y1, y2] = requested_stream_type == VISION_STREAM_DRIVER ? std::tuple(0.f, 1.f, 1.f, 0.f) : std::tuple(1.f, 0.f, 1.f, 0.f); const uint8_t frame_indicies[] = {0, 1, 2, 0, 2, 3}; const float frame_coords[4][4] = { {-1.0, -1.0, x2, y1}, // bl @@ -148,11 +150,21 @@ void CameraViewWidget::initializeGL() { glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(frame_indicies), frame_indicies, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); + + glUseProgram(program->programId()); + +#ifdef QCOM2 + glUniform1i(program->uniformLocation("uTexture"), 0); +#else + glGenTextures(2, textures); + glUniform1i(program->uniformLocation("uTextureY"), 0); + glUniform1i(program->uniformLocation("uTextureUV"), 1); +#endif } -void CameraViewWidget::showEvent(QShowEvent *event) { - latest_texture_id = -1; +void CameraWidget::showEvent(QShowEvent *event) { if (!vipc_thread) { + clearFrames(); vipc_thread = new QThread(); connect(vipc_thread, &QThread::started, [=]() { vipcThread(); }); connect(vipc_thread, &QThread::finished, vipc_thread, &QObject::deleteLater); @@ -160,7 +172,7 @@ void CameraViewWidget::showEvent(QShowEvent *event) { } } -void CameraViewWidget::hideEvent(QHideEvent *event) { +void CameraWidget::stopVipcThread() { if (vipc_thread) { vipc_thread->requestInterruption(); vipc_thread->quit(); @@ -169,164 +181,219 @@ void CameraViewWidget::hideEvent(QHideEvent *event) { } } -void CameraViewWidget::updateFrameMat(int w, int h) { +void CameraWidget::updateFrameMat() { + int w = width(), h = height(); + if (zoomed_view) { - if (stream_type == VISION_STREAM_RGB_FRONT) { - frame_mat = matmul(device_transform, get_driver_view_transform(w, h, stream_width, stream_height)); + if (active_stream_type == VISION_STREAM_DRIVER) { + frame_mat = get_driver_view_transform(w, h, stream_width, stream_height); } else { - auto intrinsic_matrix = stream_type == VISION_STREAM_RGB_WIDE ? ecam_intrinsic_matrix : fcam_intrinsic_matrix; - float zoom = ZOOM / intrinsic_matrix.v[0]; - if (stream_type == VISION_STREAM_RGB_WIDE) { - zoom *= 0.5; + // Project point at "infinity" to compute x and y offsets + // to ensure this ends up in the middle of the screen + // for narrow come and a little lower for wide cam. + // TODO: use proper perspective transform? + if (active_stream_type == VISION_STREAM_WIDE_ROAD) { + intrinsic_matrix = ecam_intrinsic_matrix; + zoom = 2.0; + } else { + intrinsic_matrix = fcam_intrinsic_matrix; + zoom = 1.1; } - float zx = zoom * 2 * intrinsic_matrix.v[2] / width(); - float zy = zoom * 2 * intrinsic_matrix.v[5] / height(); + const vec3 inf = {{1000., 0., 0.}}; + const vec3 Ep = matvecmul3(calibration, inf); + const vec3 Kep = matvecmul3(intrinsic_matrix, Ep); + + float x_offset_ = (Kep.v[0] / Kep.v[2] - intrinsic_matrix.v[2]) * zoom; + float y_offset_ = (Kep.v[1] / Kep.v[2] - intrinsic_matrix.v[5]) * zoom; + + float max_x_offset = intrinsic_matrix.v[2] * zoom - w / 2 - 5; + float max_y_offset = intrinsic_matrix.v[5] * zoom - h / 2 - 5; + x_offset = std::clamp(x_offset_, -max_x_offset, max_x_offset); + y_offset = std::clamp(y_offset_, -max_y_offset, max_y_offset); + + float zx = zoom * 2 * intrinsic_matrix.v[2] / w; + float zy = zoom * 2 * intrinsic_matrix.v[5] / h; const mat4 frame_transform = {{ - zx, 0.0, 0.0, 0.0, - 0.0, zy, 0.0, -y_offset / height() * 2, + zx, 0.0, 0.0, -x_offset / w * 2, + 0.0, zy, 0.0, y_offset / h * 2, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, }}; - frame_mat = matmul(device_transform, frame_transform); + frame_mat = frame_transform; } } else if (stream_width > 0 && stream_height > 0) { // fit frame to widget size - float widget_aspect_ratio = (float)width() / height(); + float widget_aspect_ratio = (float)w / h; float frame_aspect_ratio = (float)stream_width / stream_height; - frame_mat = matmul(device_transform, get_fit_view_transform(widget_aspect_ratio, frame_aspect_ratio)); + frame_mat = get_fit_view_transform(widget_aspect_ratio, frame_aspect_ratio); } } -void CameraViewWidget::paintGL() { +void CameraWidget::updateCalibration(const mat3 &calib) { + calibration = calib; +} + +void CameraWidget::paintGL() { glClearColor(bg.redF(), bg.greenF(), bg.blueF(), bg.alphaF()); glClear(GL_STENCIL_BUFFER_BIT | GL_COLOR_BUFFER_BIT); - std::lock_guard lk(lock); + std::lock_guard lk(frame_lock); + if (frames.empty()) return; - if (latest_texture_id == -1) return; + int frame_idx = frames.size() - 1; - glViewport(0, 0, width(), height()); - // sync with the PBO - if (wait_fence) { - wait_fence->wait(); + // Always draw latest frame until sync logic is more stable + // for (frame_idx = 0; frame_idx < frames.size() - 1; frame_idx++) { + // if (frames[frame_idx].first == draw_frame_id) break; + // } + + // Log duplicate/dropped frames + if (frames[frame_idx].first == prev_frame_id) { + qDebug() << "Drawing same frame twice" << frames[frame_idx].first; + } else if (frames[frame_idx].first != prev_frame_id + 1) { + qDebug() << "Skipped frame" << frames[frame_idx].first; } + prev_frame_id = frames[frame_idx].first; + VisionBuf *frame = frames[frame_idx].second; + assert(frame != nullptr); - glBindVertexArray(frame_vao); - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, texture[latest_texture_id]->frame_tex); + updateFrameMat(); + glViewport(0, 0, width(), height()); + glBindVertexArray(frame_vao); glUseProgram(program->programId()); - glUniform1i(program->uniformLocation("uTexture"), 0); - glUniformMatrix4fv(program->uniformLocation("uTransform"), 1, GL_TRUE, frame_mat.v); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + +#ifdef QCOM2 + // no frame copy + glActiveTexture(GL_TEXTURE0); + glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, egl_images[frame->idx]); + assert(glGetError() == GL_NO_ERROR); +#else + // fallback to copy + glPixelStorei(GL_UNPACK_ROW_LENGTH, stream_stride); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, textures[0]); + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, stream_width, stream_height, GL_RED, GL_UNSIGNED_BYTE, frame->y); + assert(glGetError() == GL_NO_ERROR); + glPixelStorei(GL_UNPACK_ROW_LENGTH, stream_stride/2); + glActiveTexture(GL_TEXTURE0 + 1); + glBindTexture(GL_TEXTURE_2D, textures[1]); + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, stream_width/2, stream_height/2, GL_RG, GL_UNSIGNED_BYTE, frame->uv); assert(glGetError() == GL_NO_ERROR); +#endif + + glUniformMatrix4fv(program->uniformLocation("uTransform"), 1, GL_TRUE, frame_mat.v); glEnableVertexAttribArray(0); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, (const void *)0); glDisableVertexAttribArray(0); glBindVertexArray(0); + glBindTexture(GL_TEXTURE_2D, 0); + glActiveTexture(GL_TEXTURE0); + glPixelStorei(GL_UNPACK_ALIGNMENT, 4); + glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); } -void CameraViewWidget::vipcConnected(VisionIpcClient *vipc_client) { +void CameraWidget::vipcConnected(VisionIpcClient *vipc_client) { makeCurrent(); - for (int i = 0; i < vipc_client->num_buffers; i++) { - texture[i].reset(new EGLImageTexture(&vipc_client->buffers[i])); - - glBindTexture(GL_TEXTURE_2D, texture[i]->frame_tex); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - - // BGR - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_BLUE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_GREEN); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED); - assert(glGetError() == GL_NO_ERROR); - } - latest_texture_id = -1; stream_width = vipc_client->buffers[0].width; stream_height = vipc_client->buffers[0].height; - updateFrameMat(width(), height()); -} + stream_stride = vipc_client->buffers[0].stride; -void CameraViewWidget::vipcThread() { - VisionStreamType cur_stream_type = stream_type; - std::unique_ptr vipc_client; +#ifdef QCOM2 + egl_display = eglGetCurrentDisplay(); - std::unique_ptr ctx; - std::unique_ptr surface; - std::unique_ptr gl_buffer; - - if (!Hardware::EON()) { - ctx = std::make_unique(); - ctx->setFormat(context()->format()); - ctx->setShareContext(context()); - ctx->create(); - assert(ctx->isValid()); - - surface = std::make_unique(); - surface->setFormat(ctx->format()); - surface->create(); - ctx->makeCurrent(surface.get()); - assert(QOpenGLContext::currentContext() == ctx.get()); - initializeOpenGLFunctions(); + for (auto &pair : egl_images) { + eglDestroyImageKHR(egl_display, pair.second); + } + egl_images.clear(); + + for (int i = 0; i < vipc_client->num_buffers; i++) { // import buffers into OpenGL + int fd = dup(vipc_client->buffers[i].fd); // eglDestroyImageKHR will close, so duplicate + EGLint img_attrs[] = { + EGL_WIDTH, (int)vipc_client->buffers[i].width, + EGL_HEIGHT, (int)vipc_client->buffers[i].height, + EGL_LINUX_DRM_FOURCC_EXT, DRM_FORMAT_NV12, + EGL_DMA_BUF_PLANE0_FD_EXT, fd, + EGL_DMA_BUF_PLANE0_OFFSET_EXT, 0, + EGL_DMA_BUF_PLANE0_PITCH_EXT, (int)vipc_client->buffers[i].stride, + EGL_DMA_BUF_PLANE1_FD_EXT, fd, + EGL_DMA_BUF_PLANE1_OFFSET_EXT, (int)vipc_client->buffers[i].uv_offset, + EGL_DMA_BUF_PLANE1_PITCH_EXT, (int)vipc_client->buffers[i].stride, + EGL_NONE + }; + egl_images[i] = eglCreateImageKHR(egl_display, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, 0, img_attrs); + assert(eglGetError() == EGL_SUCCESS); } +#else + glBindTexture(GL_TEXTURE_2D, textures[0]); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, stream_width, stream_height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr); + assert(glGetError() == GL_NO_ERROR); + + glBindTexture(GL_TEXTURE_2D, textures[1]); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, stream_width/2, stream_height/2, 0, GL_RG, GL_UNSIGNED_BYTE, nullptr); + assert(glGetError() == GL_NO_ERROR); +#endif +} + +void CameraWidget::vipcFrameReceived() { + update(); +} + +void CameraWidget::vipcThread() { + VisionStreamType cur_stream = requested_stream_type; + std::unique_ptr vipc_client; + VisionIpcBufExtra meta_main = {0}; while (!QThread::currentThread()->isInterruptionRequested()) { - if (!vipc_client || cur_stream_type != stream_type) { - cur_stream_type = stream_type; - vipc_client.reset(new VisionIpcClient(stream_name, cur_stream_type, true)); + if (!vipc_client || cur_stream != requested_stream_type) { + clearFrames(); + qDebug() << "connecting to stream " << requested_stream_type << ", was connected to " << cur_stream; + cur_stream = requested_stream_type;; + vipc_client.reset(new VisionIpcClient(stream_name, cur_stream, false)); } + active_stream_type = cur_stream; if (!vipc_client->connected) { + clearFrames(); if (!vipc_client->connect(false)) { QThread::msleep(100); continue; } - - if (!Hardware::EON()) { - gl_buffer.reset(new QOpenGLBuffer(QOpenGLBuffer::PixelUnpackBuffer)); - gl_buffer->create(); - gl_buffer->bind(); - gl_buffer->setUsagePattern(QOpenGLBuffer::StreamDraw); - gl_buffer->allocate(vipc_client->buffers[0].len); - } - emit vipcThreadConnected(vipc_client.get()); } - if (VisionBuf *buf = vipc_client->recv(nullptr, 1000)) { + if (VisionBuf *buf = vipc_client->recv(&meta_main, 1000)) { { - std::lock_guard lk(lock); - if (!Hardware::EON()) { - void *texture_buffer = gl_buffer->map(QOpenGLBuffer::WriteOnly); - - if (texture_buffer == nullptr) { - LOGE("gl_buffer->map returned nullptr"); - continue; - } - - memcpy(texture_buffer, buf->addr, buf->len); - gl_buffer->unmap(); - - // copy pixels from PBO to texture object - glBindTexture(GL_TEXTURE_2D, texture[buf->idx]->frame_tex); - glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, buf->width, buf->height, GL_RGB, GL_UNSIGNED_BYTE, 0); - glBindTexture(GL_TEXTURE_2D, 0); - assert(glGetError() == GL_NO_ERROR); - - wait_fence.reset(new WaitFence()); - - // Ensure the fence is in the GPU command queue, or waiting on it might block - // https://www.khronos.org/opengl/wiki/Sync_Object#Flushing_and_contexts - glFlush(); + std::lock_guard lk(frame_lock); + frames.push_back(std::make_pair(meta_main.frame_id, buf)); + while (frames.size() > FRAME_BUFFER_SIZE) { + frames.pop_front(); } - latest_texture_id = buf->idx; } - // Schedule update. update() will be invoked on the gui thread. - QMetaObject::invokeMethod(this, "update"); - - // TODO: remove later, it's only connected by DriverView. - emit vipcThreadFrameReceived(buf); + emit vipcThreadFrameReceived(); } } + +#ifdef QCOM2 + for (auto &pair : egl_images) { + eglDestroyImageKHR(egl_display, pair.second); + } + egl_images.clear(); +#endif +} + +void CameraWidget::clearFrames() { + std::lock_guard lk(frame_lock); + frames.clear(); } diff --git a/selfdrive/ui/qt/widgets/cameraview.h b/selfdrive/ui/qt/widgets/cameraview.h index 03709cbdd8..7cc3847f99 100644 --- a/selfdrive/ui/qt/widgets/cameraview.h +++ b/selfdrive/ui/qt/widgets/cameraview.h @@ -1,64 +1,91 @@ #pragma once #include +#include #include #include #include #include + +#ifdef QCOM2 +#define EGL_EGLEXT_PROTOTYPES +#define EGL_NO_X11 +#define GL_TEXTURE_EXTERNAL_OES 0x8D65 +#include +#include +#include +#endif + #include "cereal/visionipc/visionipc_client.h" -#include "selfdrive/camerad/cameras/camera_common.h" -#include "selfdrive/common/visionimg.h" +#include "system/camerad/cameras/camera_common.h" #include "selfdrive/ui/ui.h" -class CameraViewWidget : public QOpenGLWidget, protected QOpenGLFunctions { +const int FRAME_BUFFER_SIZE = 5; +static_assert(FRAME_BUFFER_SIZE <= YUV_BUFFER_COUNT); + +class CameraWidget : public QOpenGLWidget, protected QOpenGLFunctions { Q_OBJECT public: using QOpenGLWidget::QOpenGLWidget; - explicit CameraViewWidget(std::string stream_name, VisionStreamType stream_type, bool zoom, QWidget* parent = nullptr); - ~CameraViewWidget(); - void setStreamType(VisionStreamType type) { stream_type = type; } + explicit CameraWidget(std::string stream_name, VisionStreamType stream_type, bool zoom, QWidget* parent = nullptr); + ~CameraWidget(); void setBackgroundColor(const QColor &color) { bg = color; } + void setFrameId(int frame_id) { draw_frame_id = frame_id; } + void setStreamType(VisionStreamType type) { requested_stream_type = type; } + VisionStreamType getStreamType() { return active_stream_type; } signals: void clicked(); void vipcThreadConnected(VisionIpcClient *); - void vipcThreadFrameReceived(VisionBuf *); + void vipcThreadFrameReceived(); protected: void paintGL() override; void initializeGL() override; - void resizeGL(int w, int h) override { updateFrameMat(w, h); } + void resizeGL(int w, int h) override { updateFrameMat(); } void showEvent(QShowEvent *event) override; - void hideEvent(QHideEvent *event) override; void mouseReleaseEvent(QMouseEvent *event) override { emit clicked(); } - virtual void updateFrameMat(int w, int h); + virtual void updateFrameMat(); + void updateCalibration(const mat3 &calib); void vipcThread(); - - struct WaitFence { - WaitFence() { sync = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); } - ~WaitFence() { glDeleteSync(sync); } - void wait() { glWaitSync(sync, 0, GL_TIMEOUT_IGNORED); } - GLsync sync = 0; - }; + void clearFrames(); + void stopVipcThread(); bool zoomed_view; - std::mutex lock; - int latest_texture_id = -1; GLuint frame_vao, frame_vbo, frame_ibo; + GLuint textures[2]; mat4 frame_mat; - std::unique_ptr texture[UI_BUF_COUNT]; - std::unique_ptr wait_fence; std::unique_ptr program; QColor bg = QColor("#000000"); +#ifdef QCOM2 + EGLDisplay egl_display; + std::map egl_images; +#endif + std::string stream_name; int stream_width = 0; int stream_height = 0; - std::atomic stream_type; + int stream_stride = 0; + std::atomic active_stream_type; + std::atomic requested_stream_type; QThread *vipc_thread = nullptr; + // Calibration + float x_offset = 0; + float y_offset = 0; + float zoom = 1.0; + mat3 calibration = DEFAULT_CALIBRATION; + mat3 intrinsic_matrix = fcam_intrinsic_matrix; + + std::recursive_mutex frame_lock; + std::deque> frames; + uint32_t draw_frame_id = 0; + uint32_t prev_frame_id = 0; + protected slots: void vipcConnected(VisionIpcClient *vipc_client); + void vipcFrameReceived(); }; diff --git a/selfdrive/ui/qt/widgets/controls.cc b/selfdrive/ui/qt/widgets/controls.cc index 89c95843fb..456cf748f4 100644 --- a/selfdrive/ui/qt/widgets/controls.cc +++ b/selfdrive/ui/qt/widgets/controls.cc @@ -18,8 +18,6 @@ QFrame *horizontal_line(QWidget *parent) { } AbstractControl::AbstractControl(const QString &title, const QString &desc, const QString &icon, QWidget *parent) : QFrame(parent) { - setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum); - QVBoxLayout *main_layout = new QVBoxLayout(this); main_layout->setMargin(0); @@ -28,10 +26,10 @@ AbstractControl::AbstractControl(const QString &title, const QString &desc, cons hlayout->setSpacing(20); // left icon + icon_label = new QLabel(); if (!icon.isEmpty()) { - QPixmap pix(icon); - QLabel *icon_label = new QLabel(); - icon_label->setPixmap(pix.scaledToWidth(80, Qt::SmoothTransformation)); + icon_pixmap = QPixmap(icon).scaledToWidth(80, Qt::SmoothTransformation); + icon_label->setPixmap(icon_pixmap); icon_label->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); hlayout->addWidget(icon_label); } @@ -40,31 +38,39 @@ AbstractControl::AbstractControl(const QString &title, const QString &desc, cons title_label = new QPushButton(title); title_label->setFixedHeight(120); title_label->setStyleSheet("font-size: 50px; font-weight: 400; text-align: left"); - hlayout->addWidget(title_label); + hlayout->addWidget(title_label, 1); + + // value next to control button + value = new ElidedLabel(); + value->setAlignment(Qt::AlignRight | Qt::AlignVCenter); + value->setStyleSheet("color: #aaaaaa"); + hlayout->addWidget(value); main_layout->addLayout(hlayout); // description - if (!desc.isEmpty()) { - description = new QLabel(desc); - description->setContentsMargins(40, 20, 40, 20); - description->setStyleSheet("font-size: 40px; color: grey"); - description->setWordWrap(true); - description->setVisible(false); - main_layout->addWidget(description); - - connect(title_label, &QPushButton::clicked, [=]() { - if (!description->isVisible()) { - emit showDescription(); - } + description = new QLabel(desc); + description->setContentsMargins(40, 20, 40, 20); + description->setStyleSheet("font-size: 40px; color: grey"); + description->setWordWrap(true); + description->setVisible(false); + main_layout->addWidget(description); + + connect(title_label, &QPushButton::clicked, [=]() { + if (!description->isVisible()) { + emit showDescriptionEvent(); + } + + if (!description->text().isEmpty()) { description->setVisible(!description->isVisible()); - }); - } + } + }); + main_layout->addStretch(); } void AbstractControl::hideEvent(QHideEvent *e) { - if(description != nullptr) { + if (description != nullptr) { description->hide(); } } @@ -125,7 +131,9 @@ void ElidedLabel::paintEvent(QPaintEvent *event) { ClickableWidget::ClickableWidget(QWidget *parent) : QWidget(parent) { } void ClickableWidget::mouseReleaseEvent(QMouseEvent *event) { - emit clicked(); + if (rect().contains(event->pos())) { + emit clicked(); + } } // Fix stylesheets diff --git a/selfdrive/ui/qt/widgets/controls.h b/selfdrive/ui/qt/widgets/controls.h index 13cd55ff3b..770b9b92dd 100644 --- a/selfdrive/ui/qt/widgets/controls.h +++ b/selfdrive/ui/qt/widgets/controls.h @@ -6,7 +6,8 @@ #include #include -#include "selfdrive/common/params.h" +#include "common/params.h" +#include "selfdrive/ui/qt/widgets/input.h" #include "selfdrive/ui/qt/widgets/toggle.h" QFrame *horizontal_line(QWidget *parent = nullptr); @@ -24,7 +25,11 @@ signals: protected: void paintEvent(QPaintEvent *event) override; void resizeEvent(QResizeEvent* event) override; - void mouseReleaseEvent(QMouseEvent *event) override { emit clicked(); } + void mouseReleaseEvent(QMouseEvent *event) override { + if (rect().contains(event->pos())) { + emit clicked(); + } + } QString lastText_, elidedText_; }; @@ -41,8 +46,24 @@ public: title_label->setText(title); } + void setValue(const QString &val) { + value->setText(val); + } + + const QString getDescription() { + return description->text(); + } + + QLabel *icon_label; + QPixmap icon_pixmap; + +public slots: + void showDescription() { + description->setVisible(true); + }; + signals: - void showDescription(); + void showDescriptionEvent(); protected: AbstractControl(const QString &title, const QString &desc = "", const QString &icon = "", QWidget *parent = nullptr); @@ -50,6 +71,9 @@ protected: QHBoxLayout *hlayout; QPushButton *title_label; + +private: + ElidedLabel *value; QLabel *description = nullptr; }; @@ -101,7 +125,10 @@ public: QObject::connect(&toggle, &Toggle::stateChanged, this, &ToggleControl::toggleFlipped); } - void setEnabled(bool enabled) { toggle.setEnabled(enabled); } + void setEnabled(bool enabled) { + toggle.setEnabled(enabled); + toggle.update(); + } signals: void toggleFlipped(bool state); @@ -117,20 +144,57 @@ class ParamControl : public ToggleControl { public: ParamControl(const QString ¶m, const QString &title, const QString &desc, const QString &icon, QWidget *parent = nullptr) : ToggleControl(title, desc, icon, false, parent) { key = param.toStdString(); - QObject::connect(this, &ToggleControl::toggleFlipped, [=](bool state) { - params.putBool(key, state); + QObject::connect(this, &ParamControl::toggleFlipped, [=](bool state) { + QString content("

" + title + "


" + "

" + getDescription() + "

"); + ConfirmationDialog dialog(content, tr("Enable"), tr("Cancel"), true, this); + + bool confirmed = store_confirm && params.getBool(key + "Confirmed"); + if (!confirm || confirmed || !state || dialog.exec()) { + if (store_confirm && state) params.putBool(key + "Confirmed", true); + params.putBool(key, state); + setIcon(state); + } else { + toggle.togglePosition(); + } }); } - void showEvent(QShowEvent *event) override { - if (params.getBool(key) != toggle.on) { + void setConfirmation(bool _confirm, bool _store_confirm) { + confirm = _confirm; + store_confirm = _store_confirm; + }; + + void setActiveIcon(const QString &icon) { + active_icon_pixmap = QPixmap(icon).scaledToWidth(80, Qt::SmoothTransformation); + } + + void refresh() { + bool state = params.getBool(key); + if (state != toggle.on) { toggle.togglePosition(); + setIcon(state); } }; + void showEvent(QShowEvent *event) override { + refresh(); + }; + private: + void setIcon(bool state) { + if (state && !active_icon_pixmap.isNull()) { + icon_label->setPixmap(active_icon_pixmap); + } else if (!icon_pixmap.isNull()) { + icon_label->setPixmap(icon_pixmap); + } + }; + std::string key; Params params; + QPixmap active_icon_pixmap; + bool confirm = false; + bool store_confirm = false; }; class ListWidget : public QWidget { @@ -153,9 +217,12 @@ private: QPainter p(this); p.setPen(Qt::gray); for (int i = 0; i < inner_layout.count() - 1; ++i) { - QRect r = inner_layout.itemAt(i)->geometry(); - int bottom = r.bottom() + inner_layout.spacing() / 2; - p.drawLine(r.left() + 40, bottom, r.right() - 40, bottom); + QWidget *widget = inner_layout.itemAt(i)->widget(); + if (widget == nullptr || widget->isVisible()) { + QRect r = inner_layout.itemAt(i)->geometry(); + int bottom = r.bottom() + inner_layout.spacing() / 2; + p.drawLine(r.left() + 40, bottom, r.right() - 40, bottom); + } } } QVBoxLayout outer_layout; diff --git a/selfdrive/ui/qt/widgets/drive_stats.cc b/selfdrive/ui/qt/widgets/drive_stats.cc index f4c8f502a3..31009f03ca 100644 --- a/selfdrive/ui/qt/widgets/drive_stats.cc +++ b/selfdrive/ui/qt/widgets/drive_stats.cc @@ -5,7 +5,7 @@ #include #include -#include "selfdrive/common/params.h" +#include "common/params.h" #include "selfdrive/ui/qt/request_repeater.h" #include "selfdrive/ui/qt/util.h" @@ -34,16 +34,16 @@ DriveStats::DriveStats(QWidget* parent) : QFrame(parent) { grid_layout->addWidget(labels.distance = newLabel("0", "number"), row, 1, Qt::AlignLeft); grid_layout->addWidget(labels.hours = newLabel("0", "number"), row, 2, Qt::AlignLeft); - grid_layout->addWidget(newLabel("Drives", "unit"), row + 1, 0, Qt::AlignLeft); + grid_layout->addWidget(newLabel((tr("Drives")), "unit"), row + 1, 0, Qt::AlignLeft); grid_layout->addWidget(labels.distance_unit = newLabel(getDistanceUnit(), "unit"), row + 1, 1, Qt::AlignLeft); - grid_layout->addWidget(newLabel("Hours ", "unit"), row + 1, 2, Qt::AlignLeft); + grid_layout->addWidget(newLabel(tr("Hours"), "unit"), row + 1, 2, Qt::AlignLeft); main_layout->addLayout(grid_layout); }; - add_stats_layouts("ALL TIME", all_); + add_stats_layouts(tr("ALL TIME"), all_); main_layout->addStretch(); - add_stats_layouts("PAST WEEK", week_); + add_stats_layouts(tr("PAST WEEK"), week_); if (auto dongleId = getDongleId()) { QString url = CommaApi::BASE_URL + "/v1.1/devices/" + *dongleId + "/stats"; diff --git a/selfdrive/ui/qt/widgets/drive_stats.h b/selfdrive/ui/qt/widgets/drive_stats.h index 9446294516..5e2d96b240 100644 --- a/selfdrive/ui/qt/widgets/drive_stats.h +++ b/selfdrive/ui/qt/widgets/drive_stats.h @@ -12,7 +12,7 @@ public: private: void showEvent(QShowEvent *event) override; void updateStats(); - inline QString getDistanceUnit() const { return metric_ ? "KM" : "Miles"; } + inline QString getDistanceUnit() const { return metric_ ? tr("KM") : tr("Miles"); } bool metric_; QJsonDocument stats_; diff --git a/selfdrive/ui/qt/widgets/input.cc b/selfdrive/ui/qt/widgets/input.cc index 1122faf4c7..75453e1b90 100644 --- a/selfdrive/ui/qt/widgets/input.cc +++ b/selfdrive/ui/qt/widgets/input.cc @@ -1,8 +1,9 @@ #include "selfdrive/ui/qt/widgets/input.h" #include +#include -#include "selfdrive/hardware/hw.h" +#include "system/hardware/hw.h" #include "selfdrive/ui/qt/util.h" #include "selfdrive/ui/qt/qt_window.h" #include "selfdrive/ui/qt/widgets/scrollview.h" @@ -67,7 +68,7 @@ InputDialog::InputDialog(const QString &title, QWidget *parent, const QString &s vlayout->addWidget(sublabel, 1, Qt::AlignTop | Qt::AlignLeft); } - QPushButton* cancel_btn = new QPushButton("Cancel"); + QPushButton* cancel_btn = new QPushButton(tr("Cancel")); cancel_btn->setFixedSize(386, 125); cancel_btn->setStyleSheet(R"( font-size: 48px; @@ -164,7 +165,7 @@ void InputDialog::handleEnter() { done(QDialog::Accepted); emitText(line->text()); } else { - setMessage("Need at least "+QString::number(minLength)+" characters!", false); + setMessage(tr("Need at least %n character(s)!", "", minLength), false); } } @@ -182,17 +183,21 @@ void InputDialog::setMinLength(int length) { // ConfirmationDialog ConfirmationDialog::ConfirmationDialog(const QString &prompt_text, const QString &confirm_text, const QString &cancel_text, - QWidget *parent) : QDialogBase(parent) { + const bool rich, QWidget *parent) : QDialogBase(parent) { QFrame *container = new QFrame(this); - container->setStyleSheet("QFrame { border-radius: 0; background-color: #ECECEC; }"); + container->setStyleSheet(R"( + QFrame { background-color: #1B1B1B; color: #C9C9C9; } + #confirm_btn { background-color: #465BEA; } + #confirm_btn:pressed { background-color: #3049F4; } + )"); QVBoxLayout *main_layout = new QVBoxLayout(container); - main_layout->setContentsMargins(32, 120, 32, 32); + main_layout->setContentsMargins(32, rich ? 32 : 120, 32, 32); QLabel *prompt = new QLabel(prompt_text, this); prompt->setWordWrap(true); - prompt->setAlignment(Qt::AlignHCenter); - prompt->setStyleSheet("font-size: 70px; font-weight: bold; color: black;"); - main_layout->addWidget(prompt, 1, Qt::AlignTop | Qt::AlignHCenter); + prompt->setAlignment(rich ? Qt::AlignLeft : Qt::AlignHCenter); + prompt->setStyleSheet((rich ? "font-size: 42px; font-weight: light;" : "font-size: 70px; font-weight: bold;") + QString(" margin: 45px;")); + main_layout->addWidget(rich ? (QWidget*)new ScrollView(prompt, this) : (QWidget*)prompt, 1, Qt::AlignTop); // cancel + confirm buttons QHBoxLayout *btn_layout = new QHBoxLayout(); @@ -207,53 +212,118 @@ ConfirmationDialog::ConfirmationDialog(const QString &prompt_text, const QString if (confirm_text.length()) { QPushButton* confirm_btn = new QPushButton(confirm_text); + confirm_btn->setObjectName("confirm_btn"); btn_layout->addWidget(confirm_btn); QObject::connect(confirm_btn, &QPushButton::clicked, this, &ConfirmationDialog::accept); } QVBoxLayout *outer_layout = new QVBoxLayout(this); - outer_layout->setContentsMargins(210, 170, 210, 170); + int margin = rich ? 100 : 200; + outer_layout->setContentsMargins(margin, margin, margin, margin); outer_layout->addWidget(container); } bool ConfirmationDialog::alert(const QString &prompt_text, QWidget *parent) { - ConfirmationDialog d = ConfirmationDialog(prompt_text, "Ok", "", parent); + ConfirmationDialog d = ConfirmationDialog(prompt_text, tr("Ok"), "", false, parent); return d.exec(); } -bool ConfirmationDialog::confirm(const QString &prompt_text, QWidget *parent) { - ConfirmationDialog d = ConfirmationDialog(prompt_text, "Ok", "Cancel", parent); +bool ConfirmationDialog::confirm(const QString &prompt_text, const QString &confirm_text, QWidget *parent) { + ConfirmationDialog d = ConfirmationDialog(prompt_text, confirm_text, tr("Cancel"), false, parent); return d.exec(); } +bool ConfirmationDialog::rich(const QString &prompt_text, QWidget *parent) { + ConfirmationDialog d = ConfirmationDialog(prompt_text, tr("Ok"), "", true, parent); + return d.exec(); +} -// RichTextDialog +// MultiOptionDialog -RichTextDialog::RichTextDialog(const QString &prompt_text, const QString &btn_text, - QWidget *parent) : QDialogBase(parent) { +MultiOptionDialog::MultiOptionDialog(const QString &prompt_text, const QStringList &l, const QString ¤t, QWidget *parent) : QDialogBase(parent) { QFrame *container = new QFrame(this); - container->setStyleSheet("QFrame { background-color: #1B1B1B; }"); + container->setStyleSheet(R"( + QFrame { background-color: #1B1B1B; } + #confirm_btn[enabled="false"] { background-color: #2B2B2B; } + #confirm_btn:enabled { background-color: #465BEA; } + #confirm_btn:enabled:pressed { background-color: #3049F4; } + )"); + QVBoxLayout *main_layout = new QVBoxLayout(container); - main_layout->setContentsMargins(32, 32, 32, 32); + main_layout->setContentsMargins(55, 50, 55, 50); - QLabel *prompt = new QLabel(prompt_text, this); - prompt->setWordWrap(true); - prompt->setAlignment(Qt::AlignLeft); - prompt->setTextFormat(Qt::RichText); - prompt->setStyleSheet("font-size: 42px; font-weight: light; color: #C9C9C9; margin: 45px;"); - main_layout->addWidget(new ScrollView(prompt, this), 1, Qt::AlignTop); + QLabel *title = new QLabel(prompt_text, this); + title->setStyleSheet("font-size: 70px; font-weight: 500;"); + main_layout->addWidget(title, 0, Qt::AlignLeft | Qt::AlignTop); + main_layout->addSpacing(25); + + QWidget *listWidget = new QWidget(this); + QVBoxLayout *listLayout = new QVBoxLayout(listWidget); + listLayout->setSpacing(20); + listWidget->setStyleSheet(R"( + QPushButton { + height: 135; + padding: 0px 50px; + text-align: left; + font-size: 55px; + font-weight: 300; + border-radius: 10px; + background-color: #4F4F4F; + } + QPushButton:checked { background-color: #465BEA; } + )"); + + QButtonGroup *group = new QButtonGroup(listWidget); + group->setExclusive(true); + + QPushButton *confirm_btn = new QPushButton(tr("Select")); + confirm_btn->setObjectName("confirm_btn"); + confirm_btn->setEnabled(false); + + for (const QString &s : l) { + QPushButton *selectionLabel = new QPushButton(s); + selectionLabel->setCheckable(true); + selectionLabel->setChecked(s == current); + QObject::connect(selectionLabel, &QPushButton::toggled, [=](bool checked) { + if (checked) selection = s; + if (selection != current) { + confirm_btn->setEnabled(true); + } else { + confirm_btn->setEnabled(false); + } + }); + + group->addButton(selectionLabel); + listLayout->addWidget(selectionLabel); + } - // confirm button - QPushButton* confirm_btn = new QPushButton(btn_text); - main_layout->addWidget(confirm_btn); - QObject::connect(confirm_btn, &QPushButton::clicked, this, &QDialog::accept); + ScrollView *scroll_view = new ScrollView(listWidget, this); + scroll_view->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); + + main_layout->addWidget(scroll_view); + main_layout->addStretch(1); + main_layout->addSpacing(35); + + // cancel + confirm buttons + QHBoxLayout *blayout = new QHBoxLayout; + main_layout->addLayout(blayout); + blayout->setSpacing(50); + + QPushButton *cancel_btn = new QPushButton(tr("Cancel")); + QObject::connect(cancel_btn, &QPushButton::clicked, this, &ConfirmationDialog::reject); + QObject::connect(confirm_btn, &QPushButton::clicked, this, &ConfirmationDialog::accept); + blayout->addWidget(cancel_btn); + blayout->addWidget(confirm_btn); QVBoxLayout *outer_layout = new QVBoxLayout(this); - outer_layout->setContentsMargins(100, 100, 100, 100); + outer_layout->setContentsMargins(50, 50, 50, 50); outer_layout->addWidget(container); } -bool RichTextDialog::alert(const QString &prompt_text, QWidget *parent) { - auto d = RichTextDialog(prompt_text, "Ok", parent); - return d.exec(); +QString MultiOptionDialog::getSelection(const QString &prompt_text, const QStringList &l, const QString ¤t, QWidget *parent) { + MultiOptionDialog d = MultiOptionDialog(prompt_text, l, current, parent); + if (d.exec()) { + return d.selection; + } + return ""; } diff --git a/selfdrive/ui/qt/widgets/input.h b/selfdrive/ui/qt/widgets/input.h index f81211d0ee..e6c0fba86d 100644 --- a/selfdrive/ui/qt/widgets/input.h +++ b/selfdrive/ui/qt/widgets/input.h @@ -55,16 +55,17 @@ class ConfirmationDialog : public QDialogBase { public: explicit ConfirmationDialog(const QString &prompt_text, const QString &confirm_text, - const QString &cancel_text, QWidget* parent); + const QString &cancel_text, const bool rich, QWidget* parent); static bool alert(const QString &prompt_text, QWidget *parent); - static bool confirm(const QString &prompt_text, QWidget *parent); + static bool confirm(const QString &prompt_text, const QString &confirm_text, QWidget *parent); + static bool rich(const QString &prompt_text, QWidget *parent); }; -// larger ConfirmationDialog for rich text -class RichTextDialog : public QDialogBase { +class MultiOptionDialog : public QDialogBase { Q_OBJECT public: - explicit RichTextDialog(const QString &prompt_text, const QString &btn_text, QWidget* parent); - static bool alert(const QString &prompt_text, QWidget *parent); + explicit MultiOptionDialog(const QString &prompt_text, const QStringList &l, const QString ¤t, QWidget *parent); + static QString getSelection(const QString &prompt_text, const QStringList &l, const QString ¤t, QWidget *parent); + QString selection; }; diff --git a/selfdrive/ui/qt/widgets/offroad_alerts.cc b/selfdrive/ui/qt/widgets/offroad_alerts.cc index 2d7ae39c36..ceb823fb2b 100644 --- a/selfdrive/ui/qt/widgets/offroad_alerts.cc +++ b/selfdrive/ui/qt/widgets/offroad_alerts.cc @@ -4,8 +4,8 @@ #include #include -#include "selfdrive/common/util.h" -#include "selfdrive/hardware/hw.h" +#include "common/util.h" +#include "system/hardware/hw.h" #include "selfdrive/ui/qt/widgets/scrollview.h" AbstractAlert::AbstractAlert(bool hasRebootBtn, QWidget *parent) : QFrame(parent) { @@ -22,12 +22,12 @@ AbstractAlert::AbstractAlert(bool hasRebootBtn, QWidget *parent) : QFrame(parent QHBoxLayout *footer_layout = new QHBoxLayout(); main_layout->addLayout(footer_layout); - QPushButton *dismiss_btn = new QPushButton("Close"); + QPushButton *dismiss_btn = new QPushButton(tr("Close")); dismiss_btn->setFixedSize(400, 125); footer_layout->addWidget(dismiss_btn, 0, Qt::AlignBottom | Qt::AlignLeft); QObject::connect(dismiss_btn, &QPushButton::clicked, this, &AbstractAlert::dismiss); - snooze_btn = new QPushButton("Snooze Update"); + snooze_btn = new QPushButton(tr("Snooze Update")); snooze_btn->setVisible(false); snooze_btn->setFixedSize(550, 125); footer_layout->addWidget(snooze_btn, 0, Qt::AlignBottom | Qt::AlignRight); @@ -38,7 +38,7 @@ AbstractAlert::AbstractAlert(bool hasRebootBtn, QWidget *parent) : QFrame(parent snooze_btn->setStyleSheet(R"(color: white; background-color: #4F4F4F;)"); if (hasRebootBtn) { - QPushButton *rebootBtn = new QPushButton("Reboot and Update"); + QPushButton *rebootBtn = new QPushButton(tr("Reboot and Update")); rebootBtn->setFixedSize(600, 125); footer_layout->addWidget(rebootBtn, 0, Qt::AlignBottom | Qt::AlignRight); QObject::connect(rebootBtn, &QPushButton::clicked, [=]() { Hardware::reboot(); }); @@ -112,7 +112,7 @@ UpdateAlert::UpdateAlert(QWidget *parent) : AbstractAlert(true, parent) { bool UpdateAlert::refresh() { bool updateAvailable = params.getBool("UpdateAvailable"); if (updateAvailable) { - releaseNotes->setText(params.get("ReleaseNotes").c_str()); + releaseNotes->setText(params.get("UpdaterNewReleaseNotes").c_str()); } return updateAvailable; } diff --git a/selfdrive/ui/qt/widgets/offroad_alerts.h b/selfdrive/ui/qt/widgets/offroad_alerts.h index 4110bdaa4e..69c12b0602 100644 --- a/selfdrive/ui/qt/widgets/offroad_alerts.h +++ b/selfdrive/ui/qt/widgets/offroad_alerts.h @@ -6,7 +6,7 @@ #include #include -#include "selfdrive/common/params.h" +#include "common/params.h" class AbstractAlert : public QFrame { Q_OBJECT diff --git a/selfdrive/ui/qt/widgets/prime.cc b/selfdrive/ui/qt/widgets/prime.cc index 27d472535b..da2f4e60d1 100644 --- a/selfdrive/ui/qt/widgets/prime.cc +++ b/selfdrive/ui/qt/widgets/prime.cc @@ -18,21 +18,24 @@ using qrcodegen::QrCode; PairingQRWidget::PairingQRWidget(QWidget* parent) : QWidget(parent) { - QTimer* timer = new QTimer(this); - timer->start(5 * 60 * 1000); + timer = new QTimer(this); connect(timer, &QTimer::timeout, this, &PairingQRWidget::refresh); } void PairingQRWidget::showEvent(QShowEvent *event) { refresh(); + timer->start(5 * 60 * 1000); +} + +void PairingQRWidget::hideEvent(QHideEvent *event) { + timer->stop(); } void PairingQRWidget::refresh() { - if (isVisible()) { - QString pairToken = CommaApi::create_jwt({{"pair", true}}); - QString qrString = "https://connect.comma.ai/?pair=" + pairToken; - this->updateQrCode(qrString); - } + QString pairToken = CommaApi::create_jwt({{"pair", true}}); + QString qrString = "https://connect.comma.ai/?pair=" + pairToken; + this->updateQrCode(qrString); + update(); } void PairingQRWidget::updateQrCode(const QString &text) { @@ -83,18 +86,21 @@ PairingPopup::PairingPopup(QWidget *parent) : QDialogBase(parent) { vlayout->addSpacing(30); - QLabel *title = new QLabel("Pair your device to your comma account", this); + QLabel *title = new QLabel(tr("Pair your device to your comma account"), this); title->setStyleSheet("font-size: 75px; color: black;"); title->setWordWrap(true); vlayout->addWidget(title); - QLabel *instructions = new QLabel(R"( + QLabel *instructions = new QLabel(QString(R"(
    -
  1. Go to https://connect.comma.ai on your phone
  2. -
  3. Click "add new device" and scan the QR code on the right
  4. -
  5. Bookmark connect.comma.ai to your home screen to use it like an app
  6. +
  7. %1
  8. +
  9. %2
  10. +
  11. %3
- )", this); + )").arg(tr("Go to https://connect.comma.ai on your phone")) + .arg(tr("Click \"add new device\" and scan the QR code on the right")) + .arg(tr("Bookmark connect.comma.ai to your home screen to use it like an app")), this); + instructions->setStyleSheet("font-size: 47px; font-weight: bold; color: black;"); instructions->setWordWrap(true); vlayout->addWidget(instructions); @@ -120,19 +126,19 @@ PrimeUserWidget::PrimeUserWidget(QWidget* parent) : QWidget(parent) { primeLayout->setMargin(0); primeWidget->setContentsMargins(60, 50, 60, 50); - QLabel* subscribed = new QLabel("✓ SUBSCRIBED"); + QLabel* subscribed = new QLabel(tr("✓ SUBSCRIBED")); subscribed->setStyleSheet("font-size: 41px; font-weight: bold; color: #86FF4E;"); primeLayout->addWidget(subscribed, 0, Qt::AlignTop); primeLayout->addSpacing(60); - QLabel* commaPrime = new QLabel("comma prime"); + QLabel* commaPrime = new QLabel(tr("comma prime")); commaPrime->setStyleSheet("font-size: 75px; font-weight: bold;"); primeLayout->addWidget(commaPrime, 0, Qt::AlignTop); primeLayout->addSpacing(20); - QLabel* connectUrl = new QLabel("CONNECT.COMMA.AI"); + QLabel* connectUrl = new QLabel(tr("CONNECT.COMMA.AI")); connectUrl->setStyleSheet("font-size: 41px; font-family: Inter SemiBold; color: #A0A0A0;"); primeLayout->addWidget(connectUrl, 0, Qt::AlignTop); @@ -145,7 +151,7 @@ PrimeUserWidget::PrimeUserWidget(QWidget* parent) : QWidget(parent) { pointsLayout->setMargin(0); pointsWidget->setContentsMargins(60, 50, 60, 50); - QLabel* commaPoints = new QLabel("COMMA POINTS"); + QLabel* commaPoints = new QLabel(tr("COMMA POINTS")); commaPoints->setStyleSheet("font-size: 41px; font-family: Inter SemiBold;"); pointsLayout->addWidget(commaPoints, 0, Qt::AlignTop); @@ -181,24 +187,24 @@ PrimeAdWidget::PrimeAdWidget(QWidget* parent) : QFrame(parent) { main_layout->setContentsMargins(80, 90, 80, 60); main_layout->setSpacing(0); - QLabel *upgrade = new QLabel("Upgrade Now"); + QLabel *upgrade = new QLabel(tr("Upgrade Now")); upgrade->setStyleSheet("font-size: 75px; font-weight: bold;"); main_layout->addWidget(upgrade, 0, Qt::AlignTop); main_layout->addSpacing(50); - QLabel *description = new QLabel("Become a comma prime member at connect.comma.ai"); + QLabel *description = new QLabel(tr("Become a comma prime member at connect.comma.ai")); description->setStyleSheet("font-size: 60px; font-weight: light; color: white;"); description->setWordWrap(true); main_layout->addWidget(description, 0, Qt::AlignTop); main_layout->addStretch(); - QLabel *features = new QLabel("PRIME FEATURES:"); + QLabel *features = new QLabel(tr("PRIME FEATURES:")); features->setStyleSheet("font-size: 41px; font-weight: bold; color: #E5E5E5;"); main_layout->addWidget(features, 0, Qt::AlignBottom); main_layout->addSpacing(30); - QVector bullets = {"Remote access", "14 days of storage", "Developer perks"}; + QVector bullets = {tr("Remote access"), tr("1 year of storage"), tr("Developer perks")}; for (auto &b: bullets) { const QString check = " "; QLabel *l = new QLabel(check + b); @@ -227,20 +233,20 @@ SetupWidget::SetupWidget(QWidget* parent) : QFrame(parent) { finishRegistationLayout->setContentsMargins(30, 75, 30, 45); finishRegistationLayout->setSpacing(0); - QLabel* registrationTitle = new QLabel("Finish Setup"); + QLabel* registrationTitle = new QLabel(tr("Finish Setup")); registrationTitle->setStyleSheet("font-size: 75px; font-weight: bold; margin-left: 55px;"); finishRegistationLayout->addWidget(registrationTitle); finishRegistationLayout->addSpacing(30); - QLabel* registrationDescription = new QLabel("Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer."); + QLabel* registrationDescription = new QLabel(tr("Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer.")); registrationDescription->setWordWrap(true); registrationDescription->setStyleSheet("font-size: 55px; font-weight: light; margin-left: 55px;"); finishRegistationLayout->addWidget(registrationDescription); finishRegistationLayout->addStretch(); - QPushButton* pair = new QPushButton("Pair device"); + QPushButton* pair = new QPushButton(tr("Pair device")); pair->setFixedHeight(220); pair->setStyleSheet(R"( QPushButton { @@ -271,7 +277,7 @@ SetupWidget::SetupWidget(QWidget* parent) : QFrame(parent) { primeUser = new PrimeUserWidget; mainLayout->addWidget(primeUser); - mainLayout->setCurrentWidget(primeAd); + mainLayout->setCurrentWidget(uiState()->prime_type ? (QWidget*)primeUser : (QWidget*)primeAd); setFixedWidth(750); setStyleSheet(R"( @@ -293,11 +299,9 @@ SetupWidget::SetupWidget(QWidget* parent) : QFrame(parent) { QObject::connect(repeater, &RequestRepeater::requestDone, this, &SetupWidget::replyFinished); } - hide(); // Only show when first request comes back } void SetupWidget::replyFinished(const QString &response, bool success) { - show(); if (!success) return; QJsonDocument doc = QJsonDocument::fromJson(response.toUtf8()); @@ -308,11 +312,7 @@ void SetupWidget::replyFinished(const QString &response, bool success) { QJsonObject json = doc.object(); int prime_type = json["prime_type"].toInt(); - - if (uiState()->prime_type != prime_type) { - uiState()->prime_type = prime_type; - Params().put("PrimeType", std::to_string(prime_type)); - } + uiState()->prime_type = prime_type; if (!json["is_paired"].toBool()) { mainLayout->setCurrentIndex(0); diff --git a/selfdrive/ui/qt/widgets/prime.h b/selfdrive/ui/qt/widgets/prime.h index 566238fc33..0a1d93250d 100644 --- a/selfdrive/ui/qt/widgets/prime.h +++ b/selfdrive/ui/qt/widgets/prime.h @@ -9,8 +9,10 @@ enum PrimeType { NONE = 0, - MAGENTA, - LITE, + MAGENTA = 1, + LITE = 2, + BLUE = 3, + MAGENTA_NEW = 4, }; // pairing QR code @@ -23,8 +25,10 @@ public: private: QPixmap img; + QTimer *timer; void updateQrCode(const QString &text); void showEvent(QShowEvent *event) override; + void hideEvent(QHideEvent *event) override; private slots: void refresh(); diff --git a/selfdrive/ui/qt/widgets/scrollview.cc b/selfdrive/ui/qt/widgets/scrollview.cc index 1aa05b4157..5536593016 100644 --- a/selfdrive/ui/qt/widgets/scrollview.cc +++ b/selfdrive/ui/qt/widgets/scrollview.cc @@ -3,6 +3,8 @@ #include #include +// TODO: disable horizontal scrolling and resize + ScrollView::ScrollView(QWidget *w, QWidget *parent) : QScrollArea(parent) { setWidget(w); setWidgetResizable(true); @@ -37,7 +39,7 @@ ScrollView::ScrollView(QWidget *w, QWidget *parent) : QScrollArea(parent) { sp.setScrollMetric(QScrollerProperties::VerticalOvershootPolicy, QVariant::fromValue(QScrollerProperties::OvershootAlwaysOff)); sp.setScrollMetric(QScrollerProperties::HorizontalOvershootPolicy, QVariant::fromValue(QScrollerProperties::OvershootAlwaysOff)); - + sp.setScrollMetric(QScrollerProperties::MousePressEventDelay, 0.01); scroller->grabGesture(this->viewport(), QScroller::LeftMouseButtonGesture); scroller->setScrollerProperties(sp); } diff --git a/selfdrive/ui/qt/widgets/ssh_keys.cc b/selfdrive/ui/qt/widgets/ssh_keys.cc index 7630e65731..1097a89268 100644 --- a/selfdrive/ui/qt/widgets/ssh_keys.cc +++ b/selfdrive/ui/qt/widgets/ssh_keys.cc @@ -1,19 +1,15 @@ #include "selfdrive/ui/qt/widgets/ssh_keys.h" -#include "selfdrive/common/params.h" +#include "common/params.h" #include "selfdrive/ui/qt/api.h" #include "selfdrive/ui/qt/widgets/input.h" -SshControl::SshControl() : ButtonControl("SSH Keys", "", "Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username.") { - username_label.setAlignment(Qt::AlignRight | Qt::AlignVCenter); - username_label.setStyleSheet("color: #aaaaaa"); - hlayout->insertWidget(1, &username_label); - +SshControl::SshControl() : ButtonControl(tr("SSH Keys"), "", tr("Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username.")) { QObject::connect(this, &ButtonControl::clicked, [=]() { - if (text() == "ADD") { - QString username = InputDialog::getText("Enter your GitHub username", this); + if (text() == tr("ADD")) { + QString username = InputDialog::getText(tr("Enter your GitHub username"), this); if (username.length() > 0) { - setText("LOADING"); + setText(tr("LOADING")); setEnabled(false); getUserKeys(username); } @@ -30,11 +26,11 @@ SshControl::SshControl() : ButtonControl("SSH Keys", "", "Warning: This grants S void SshControl::refresh() { QString param = QString::fromStdString(params.get("GithubSshKeys")); if (param.length()) { - username_label.setText(QString::fromStdString(params.get("GithubUsername"))); - setText("REMOVE"); + setValue(QString::fromStdString(params.get("GithubUsername"))); + setText(tr("REMOVE")); } else { - username_label.setText(""); - setText("ADD"); + setValue(""); + setText(tr("ADD")); } setEnabled(true); } @@ -47,13 +43,13 @@ void SshControl::getUserKeys(const QString &username) { params.put("GithubUsername", username.toStdString()); params.put("GithubSshKeys", resp.toStdString()); } else { - ConfirmationDialog::alert(QString("Username '%1' has no keys on GitHub").arg(username), this); + ConfirmationDialog::alert(tr("Username '%1' has no keys on GitHub").arg(username), this); } } else { if (request->timeout()) { - ConfirmationDialog::alert("Request timed out", this); + ConfirmationDialog::alert(tr("Request timed out"), this); } else { - ConfirmationDialog::alert(QString("Username '%1' doesn't exist on GitHub").arg(username), this); + ConfirmationDialog::alert(tr("Username '%1' doesn't exist on GitHub").arg(username), this); } } diff --git a/selfdrive/ui/qt/widgets/ssh_keys.h b/selfdrive/ui/qt/widgets/ssh_keys.h index 0614e8c1d8..920bd651e2 100644 --- a/selfdrive/ui/qt/widgets/ssh_keys.h +++ b/selfdrive/ui/qt/widgets/ssh_keys.h @@ -2,7 +2,7 @@ #include -#include "selfdrive/hardware/hw.h" +#include "system/hardware/hw.h" #include "selfdrive/ui/qt/widgets/controls.h" // SSH enable toggle @@ -10,7 +10,7 @@ class SshToggle : public ToggleControl { Q_OBJECT public: - SshToggle() : ToggleControl("Enable SSH", "", "", Hardware::get_ssh_enabled()) { + SshToggle() : ToggleControl(tr("Enable SSH"), "", "", Hardware::get_ssh_enabled()) { QObject::connect(this, &SshToggle::toggleFlipped, [=](bool state) { Hardware::set_ssh_enabled(state); }); @@ -27,8 +27,6 @@ public: private: Params params; - QLabel username_label; - void refresh(); void getUserKeys(const QString &username); }; diff --git a/selfdrive/ui/qt/window.cc b/selfdrive/ui/qt/window.cc index 76d5a39d44..198b1edbf6 100644 --- a/selfdrive/ui/qt/window.cc +++ b/selfdrive/ui/qt/window.cc @@ -2,7 +2,7 @@ #include -#include "selfdrive/hardware/hw.h" +#include "system/hardware/hw.h" MainWindow::MainWindow(QWidget *parent) : QWidget(parent) { main_layout = new QStackedLayout(this); @@ -45,9 +45,6 @@ MainWindow::MainWindow(QWidget *parent) : QWidget(parent) { }); // load fonts - QFontDatabase::addApplicationFont("../assets/fonts/opensans_regular.ttf"); - QFontDatabase::addApplicationFont("../assets/fonts/opensans_bold.ttf"); - QFontDatabase::addApplicationFont("../assets/fonts/opensans_semibold.ttf"); QFontDatabase::addApplicationFont("../assets/fonts/Inter-Black.ttf"); QFontDatabase::addApplicationFont("../assets/fonts/Inter-Bold.ttf"); QFontDatabase::addApplicationFont("../assets/fonts/Inter-ExtraBold.ttf"); @@ -56,6 +53,7 @@ MainWindow::MainWindow(QWidget *parent) : QWidget(parent) { QFontDatabase::addApplicationFont("../assets/fonts/Inter-Regular.ttf"); QFontDatabase::addApplicationFont("../assets/fonts/Inter-SemiBold.ttf"); QFontDatabase::addApplicationFont("../assets/fonts/Inter-Thin.ttf"); + QFontDatabase::addApplicationFont("../assets/fonts/JetBrainsMono-Medium.ttf"); // no outline to prevent the focus rectangle setStyleSheet(R"( @@ -67,8 +65,9 @@ MainWindow::MainWindow(QWidget *parent) : QWidget(parent) { setAttribute(Qt::WA_NoSystemBackground); } -void MainWindow::openSettings() { +void MainWindow::openSettings(int index, const QString ¶m) { main_layout->setCurrentWidget(settingsWindow); + settingsWindow->setCurrentPanel(index, param); } void MainWindow::closeSettings() { @@ -85,15 +84,6 @@ bool MainWindow::eventFilter(QObject *obj, QEvent *event) { if (evts.contains(event->type())) { device.resetInteractiveTimout(); -#ifdef QCOM - // filter out touches while in android activity - if (HardwareEon::launched_activity) { - HardwareEon::check_activity(); - if (HardwareEon::launched_activity) { - return true; - } - } -#endif } return false; } diff --git a/selfdrive/ui/qt/window.h b/selfdrive/ui/qt/window.h index 0bd328aa8a..71fc466c20 100644 --- a/selfdrive/ui/qt/window.h +++ b/selfdrive/ui/qt/window.h @@ -15,7 +15,7 @@ public: private: bool eventFilter(QObject *obj, QEvent *event) override; - void openSettings(); + void openSettings(int index = 0, const QString ¶m = ""); void closeSettings(); Device device; diff --git a/selfdrive/ui/soundd/sound.cc b/selfdrive/ui/soundd/sound.cc index f303aa92bf..d07b6b6efd 100644 --- a/selfdrive/ui/soundd/sound.cc +++ b/selfdrive/ui/soundd/sound.cc @@ -7,12 +7,12 @@ #include #include "cereal/messaging/messaging.h" -#include "selfdrive/common/util.h" +#include "common/util.h" // TODO: detect when we can't play sounds // TODO: detect when we can't display the UI -Sound::Sound(QObject *parent) : sm({"carState", "controlsState", "deviceState"}) { +Sound::Sound(QObject *parent) : sm({"controlsState", "deviceState", "microphone"}) { qInfo() << "default audio device: " << QAudioDeviceInfo::defaultOutputDevice().deviceName(); for (auto &[alert, fn, loops] : sound_list) { @@ -20,7 +20,6 @@ Sound::Sound(QObject *parent) : sm({"carState", "controlsState", "deviceState"}) QObject::connect(s, &QSoundEffect::statusChanged, [=]() { assert(s->status() != QSoundEffect::Error); }); - s->setVolume(Hardware::MIN_VOLUME); s->setSource(QUrl::fromLocalFile("../../assets/sounds/" + fn)); sounds[alert] = {s, loops}; } @@ -47,14 +46,11 @@ void Sound::update() { return; } - // scale volume with speed - if (sm.updated("carState")) { - float volume = util::map_val(sm["carState"].getCarState().getVEgo(), 11.f, 20.f, 0.f, 1.0f); + // scale volume using ambient noise level + if (sm.updated("microphone")) { + float volume = util::map_val(sm["microphone"].getMicrophone().getFilteredSoundPressureWeightedDb(), 30.f, 52.f, 0.f, 1.f); volume = QAudio::convertVolume(volume, QAudio::LogarithmicVolumeScale, QAudio::LinearVolumeScale); - volume = util::map_val(volume, 0.f, 1.f, Hardware::MIN_VOLUME, Hardware::MAX_VOLUME); - for (auto &[s, loops] : sounds) { - s->setVolume(std::round(100 * volume) / 100); - } + Hardware::set_volume(volume); } setAlert(Alert::get(sm, started_frame)); diff --git a/selfdrive/ui/soundd/sound.h b/selfdrive/ui/soundd/sound.h index 82b360fd38..7e009d28ad 100644 --- a/selfdrive/ui/soundd/sound.h +++ b/selfdrive/ui/soundd/sound.h @@ -2,7 +2,7 @@ #include #include -#include "selfdrive/hardware/hw.h" +#include "system/hardware/hw.h" #include "selfdrive/ui/ui.h" const std::tuple sound_list[] = { diff --git a/selfdrive/ui/spinner b/selfdrive/ui/spinner index 4a75ca25a4..6c8e533cc8 100755 --- a/selfdrive/ui/spinner +++ b/selfdrive/ui/spinner @@ -1,8 +1,6 @@ #!/bin/sh -if [ -f /EON ] && [ ! -f qt/spinner ]; then - cp qt/spinner_aarch64 qt/spinner -elif [ -f /TICI ] && [ ! -f qt/spinner ]; then +if [ -f /TICI ] && [ ! -f qt/spinner ]; then cp qt/spinner_larch64 qt/spinner fi diff --git a/selfdrive/ui/tests/.gitignore b/selfdrive/ui/tests/.gitignore index 7765bab17d..26335744f3 100644 --- a/selfdrive/ui/tests/.gitignore +++ b/selfdrive/ui/tests/.gitignore @@ -1,3 +1,4 @@ test playsound test_sound +test_translations diff --git a/selfdrive/ui/tests/body.py b/selfdrive/ui/tests/body.py new file mode 100755 index 0000000000..c34e717eaf --- /dev/null +++ b/selfdrive/ui/tests/body.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 +import time +import cereal.messaging as messaging + +if __name__ == "__main__": + while True: + pm = messaging.PubMaster(['carParams', 'carState']) + batt = 1. + while True: + msg = messaging.new_message('carParams') + msg.carParams.carName = "COMMA BODY" + msg.carParams.notCar = True + pm.send('carParams', msg) + + for b in range(100, 0, -1): + msg = messaging.new_message('carState') + msg.carState.charging = True + msg.carState.fuelGauge = b / 100. + pm.send('carState', msg) + time.sleep(0.1) + + time.sleep(1) diff --git a/selfdrive/ui/tests/create_test_translations.sh b/selfdrive/ui/tests/create_test_translations.sh new file mode 100755 index 0000000000..451a3cbfb0 --- /dev/null +++ b/selfdrive/ui/tests/create_test_translations.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +set -e + +UI_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )"/.. +TEST_TEXT="(WRAPPED_SOURCE_TEXT)" +TEST_TS_FILE=$UI_DIR/translations/main_test_en.ts +TEST_QM_FILE=$UI_DIR/translations/main_test_en.qm + +# translation strings +UNFINISHED="<\/translation>" +TRANSLATED="$TEST_TEXT<\/translation>" + +mkdir -p $UI_DIR/translations +rm -f $TEST_TS_FILE $TEST_QM_FILE +lupdate -recursive "$UI_DIR" -ts $TEST_TS_FILE +sed -i "s/$UNFINISHED/$TRANSLATED/" $TEST_TS_FILE +lrelease $TEST_TS_FILE diff --git a/selfdrive/ui/tests/cycle_offroad_alerts.py b/selfdrive/ui/tests/cycle_offroad_alerts.py index 6b6aea4477..8a3d9ec45a 100755 --- a/selfdrive/ui/tests/cycle_offroad_alerts.py +++ b/selfdrive/ui/tests/cycle_offroad_alerts.py @@ -20,7 +20,7 @@ if __name__ == "__main__": params.put_bool("UpdateAvailable", True) r = open(os.path.join(BASEDIR, "RELEASES.md")).read() r = r[:r.find('\n\n')] # Slice latest release notes - params.put("ReleaseNotes", r + "\n") + params.put("UpdaterNewReleaseNotes", r + "\n") time.sleep(t) params.put_bool("UpdateAvailable", False) diff --git a/selfdrive/ui/tests/test_runner.cc b/selfdrive/ui/tests/test_runner.cc index b20ac86c64..ac63139d17 100644 --- a/selfdrive/ui/tests/test_runner.cc +++ b/selfdrive/ui/tests/test_runner.cc @@ -1,10 +1,25 @@ #define CATCH_CONFIG_RUNNER #include "catch2/catch.hpp" -#include + +#include +#include +#include +#include int main(int argc, char **argv) { // unit tests for Qt - QCoreApplication app(argc, argv); + QApplication app(argc, argv); + + QString language_file = "main_test_en"; + qDebug() << "Loading language:" << language_file; + + QTranslator translator; + QString translationsPath = QDir::cleanPath(qApp->applicationDirPath() + "/../translations"); + if (!translator.load(language_file, translationsPath)) { + qDebug() << "Failed to load translation file!"; + } + app.installTranslator(&translator); + const int res = Catch::Session().run(argc, argv); return (res < 0xff ? res : 0xff); } diff --git a/selfdrive/ui/tests/test_soundd.py b/selfdrive/ui/tests/test_soundd.py index cba0f6dbd1..8cc9215b74 100755 --- a/selfdrive/ui/tests/test_soundd.py +++ b/selfdrive/ui/tests/test_soundd.py @@ -8,7 +8,7 @@ import cereal.messaging as messaging from selfdrive.test.helpers import phone_only, with_processes # TODO: rewrite for unittest from common.realtime import DT_CTRL -from selfdrive.hardware import HARDWARE +from system.hardware import HARDWARE AudibleAlert = car.CarControl.HUDControl.AudibleAlert diff --git a/selfdrive/ui/tests/test_translations.cc b/selfdrive/ui/tests/test_translations.cc new file mode 100644 index 0000000000..fcefc5784f --- /dev/null +++ b/selfdrive/ui/tests/test_translations.cc @@ -0,0 +1,48 @@ +#include "catch2/catch.hpp" + +#include "common/params.h" +#include "selfdrive/ui/qt/window.h" + +const QString TEST_TEXT = "(WRAPPED_SOURCE_TEXT)"; // what each string should be translated to +QRegExp RE_NUM("\\d*"); + +QStringList getParentWidgets(QWidget* widget){ + QStringList parentWidgets; + while (widget->parentWidget() != Q_NULLPTR) { + widget = widget->parentWidget(); + parentWidgets.append(widget->metaObject()->className()); + } + return parentWidgets; +} + +template +void checkWidgetTrWrap(MainWindow &w) { + for (auto widget : w.findChildren()) { + const QString text = widget->text(); + bool isNumber = RE_NUM.exactMatch(text); + bool wrapped = text.contains(TEST_TEXT); + QString parentWidgets = getParentWidgets(widget).join("->"); + + if (!text.isEmpty() && !isNumber && !wrapped) { + FAIL(("\"" + text + "\" must be wrapped. Parent widgets: " + parentWidgets).toStdString()); + } + + // warn if source string wrapped, but UI adds text + // TODO: add way to ignore this + if (wrapped && text != TEST_TEXT) { + WARN(("\"" + text + "\" is dynamic and needs a custom retranslate function. Parent widgets: " + parentWidgets).toStdString()); + } + } +} + +// Tests all strings in the UI are wrapped with tr() +TEST_CASE("UI: test all strings wrapped") { + Params().remove("LanguageSetting"); + Params().remove("HardwareSerial"); + Params().remove("DongleId"); + qputenv("TICI", "1"); + + MainWindow w; + checkWidgetTrWrap(w); + checkWidgetTrWrap(w); +} diff --git a/selfdrive/ui/tests/test_translations.py b/selfdrive/ui/tests/test_translations.py new file mode 100755 index 0000000000..26d6c39349 --- /dev/null +++ b/selfdrive/ui/tests/test_translations.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +import json +import os +import re +import shutil +import unittest +import xml.etree.ElementTree as ET + +from selfdrive.ui.update_translations import TRANSLATIONS_DIR, LANGUAGES_FILE, update_translations + +TMP_TRANSLATIONS_DIR = os.path.join(TRANSLATIONS_DIR, "tmp") +UNFINISHED_TRANSLATION_TAG = "" not in cur_translations, + f"{file} ({name}) translation file has obsolete translations. Run selfdrive/ui/update_translations.py --vanish to remove them") + + def test_plural_translations(self): + """ + Tests: + - that any numerus (plural) translations marked "finished" have all plural forms non-empty + - that the correct format specifier is used (%n) + """ + for name, file in self.translation_files.items(): + with self.subTest(name=name, file=file): + tr_xml = ET.parse(os.path.join(TRANSLATIONS_DIR, f"{file}.ts")) + + for context in tr_xml.getroot(): + for message in context.iterfind("message"): + if message.get("numerus") == "yes": + translation = message.find("translation") + numerusform = [t.text for t in translation.findall("numerusform")] + + # Do not assert finished translations + if translation.get("type") == "unfinished": + continue + + self.assertNotIn(None, numerusform, "Ensure all plural translation forms are completed.") + self.assertTrue(all([re.search("%[0-9]+", t) is None for t in numerusform]), + "Plural translations must use %n, not %1, %2, etc.: {}".format(numerusform)) + + def test_no_locations(self): + for name, file in self.translation_files.items(): + with self.subTest(name=name, file=file): + for line in self._read_translation_file(TRANSLATIONS_DIR, file).splitlines(): + self.assertFalse(line.strip().startswith(LOCATION_TAG), + f"Line contains location tag: {line.strip()}, remove all line numbers.") + + +if __name__ == "__main__": + unittest.main() diff --git a/selfdrive/ui/text b/selfdrive/ui/text index a7177c656f..2577e3006b 100755 --- a/selfdrive/ui/text +++ b/selfdrive/ui/text @@ -1,8 +1,6 @@ #!/bin/sh -if [ -f /EON ] && [ ! -f qt/text ]; then - cp qt/text_aarch64 qt/text -elif [ -f /TICI ] && [ ! -f qt/text ]; then +if [ -f /TICI ] && [ ! -f qt/text ]; then cp qt/text_larch64 qt/text fi diff --git a/selfdrive/ui/translations/README.md b/selfdrive/ui/translations/README.md new file mode 100644 index 0000000000..91a6c3ca2f --- /dev/null +++ b/selfdrive/ui/translations/README.md @@ -0,0 +1,60 @@ +# Multilanguage + +[![languages](https://raw.githubusercontent.com/commaai/openpilot/badges/translation_badge.svg)](#) + +## Contributing + +Before getting started, make sure you have set up the openpilot Ubuntu development environment by reading the [tools README.md](/tools/README.md). + +### Policy + +Most of the languages supported by openpilot come from and are maintained by the community via pull requests. A pull request likely to be merged is one that [fixes a translation or adds missing translations.](https://github.com/commaai/openpilot/blob/master/selfdrive/ui/translations/README.md#improving-an-existing-language) + +We also generally merge pull requests adding support for a new language if there are community members willing to maintain it. Maintaining a language is ensuring quality and completion of translations before each openpilot release. + +comma may remove or hide language support from releases depending on translation quality and completeness. + +### Adding a New Language + +openpilot provides a few tools to help contributors manage their translations and to ensure quality. To get started: + +1. Add your new language to [languages.json](/selfdrive/ui/translations/languages.json) with the appropriate [language code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) and the localized language name (Traditional Chinese is `中文(繁體)`). +2. Generate the XML translation file (`*.ts`): + ```shell + selfdrive/ui/update_translations.py + ``` +3. Edit the translation file, marking each translation as completed: + ```shell + linguist selfdrive/ui/translations/your_language_file.ts + ``` +4. View your finished translations by compiling and starting the UI, then find it in the language selector: + ```shell + scons -j$(nproc) selfdrive/ui && selfdrive/ui/ui + ``` + +### Improving an Existing Language + +Follow step 3. above, you can review existing translations and add missing ones. Once you're done, just open a pull request to openpilot. + +### Updating the UI + +Any time you edit source code in the UI, you need to update the translations to ensure the line numbers and contexts are up to date (first step above). + +### Testing + +openpilot has a few unit tests to make sure all translations are up-to-date and that all strings are wrapped in a translation marker. They are run in CI, but you can also run them locally. + +Tests translation files up to date: + +```shell +selfdrive/ui/tests/test_translations.py +``` + +Tests all static source strings are wrapped: + +```shell +selfdrive/ui/tests/create_test_translations.sh && selfdrive/ui/tests/test_translations +``` + +--- +![multilanguage_onroad](https://user-images.githubusercontent.com/25857203/178912800-2c798af8-78e3-498e-9e19-35906e0bafff.png) diff --git a/selfdrive/ui/translations/create_badges.py b/selfdrive/ui/translations/create_badges.py new file mode 100755 index 0000000000..575584dd50 --- /dev/null +++ b/selfdrive/ui/translations/create_badges.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +import json +import os +import requests +import xml.etree.ElementTree as ET + +from common.basedir import BASEDIR +from selfdrive.ui.tests.test_translations import UNFINISHED_TRANSLATION_TAG +from selfdrive.ui.update_translations import LANGUAGES_FILE, TRANSLATIONS_DIR + +TRANSLATION_TAG = " 90 else "red" + + # Download badge + badge_label = f"LANGUAGE {name}" + badge_message = f"{percent_finished}% complete" + if unfinished_translations != 0: + badge_message += f" ({unfinished_translations} unfinished)" + + r = requests.get(f"{SHIELDS_URL}/{badge_label}-{badge_message}-{color}", timeout=10) + assert r.status_code == 200, "Error downloading badge" + content_svg = r.content.decode("utf-8") + + xml = ET.fromstring(content_svg) + assert "width" in xml.attrib + max_badge_width = max(max_badge_width, int(xml.attrib["width"])) + + # Make tag ids in each badge unique to combine them into one svg + for tag in ("r", "s"): + content_svg = content_svg.replace(f'id="{tag}"', f'id="{tag}{idx}"') + content_svg = content_svg.replace(f'"url(#{tag})"', f'"url(#{tag}{idx})"') + + badge_svg.extend([f'', content_svg, ""]) + + badge_svg.insert(0, f'') + badge_svg.append("") + + with open(os.path.join(BASEDIR, "translation_badge.svg"), "w") as badge_f: + badge_f.write("\n".join(badge_svg)) diff --git a/selfdrive/ui/translations/languages.json b/selfdrive/ui/translations/languages.json new file mode 100644 index 0000000000..072d320c13 --- /dev/null +++ b/selfdrive/ui/translations/languages.json @@ -0,0 +1,8 @@ +{ + "English": "main_en", + "Português": "main_pt-BR", + "中文(繁體)": "main_zh-CHT", + "中文(简体)": "main_zh-CHS", + "한국어": "main_ko", + "日本語": "main_ja" +} diff --git a/selfdrive/ui/translations/main_ar.ts b/selfdrive/ui/translations/main_ar.ts new file mode 100644 index 0000000000..07a84fca08 --- /dev/null +++ b/selfdrive/ui/translations/main_ar.ts @@ -0,0 +1,1136 @@ + + + + + AbstractAlert + + Close + أغلق + + + Snooze Update + تأخير التحديث + + + Reboot and Update + إعادة التشغيل والتحديث + + + + AdvancedNetworking + + Back + خلف + + + Enable Tethering + تمكين الربط + + + Tethering Password + كلمة مرور للربط + + + EDIT + تعديل + + + Enter new tethering password + أدخل كلمة مرور جديدة للربط + + + IP Address + عنوان IP + + + Enable Roaming + تمكين التجوال + + + APN Setting + إعداد APN + + + Enter APN + أدخل APN + + + leave blank for automatic configuration + اتركه فارغا للتكوين التلقائي + + + Cellular Metered + + + + Prevent large data uploads when on a metered connection + + + + + AnnotatedCameraWidget + + km/h + km/h + + + mph + mph + + + MAX + الأعلى + + + SPEED + سرعة + + + LIMIT + حد + + + + ConfirmationDialog + + Ok + موافق + + + Cancel + إلغاء + + + + DeclinePage + + You must accept the Terms and Conditions in order to use openpilot. + يجب عليك قبول الشروط والأحكام من أجل استخدام openpilot. + + + Back + خلف + + + Decline, uninstall %1 + رفض ، قم بإلغاء تثبيت %1 + + + + DevicePanel + + Dongle ID + معرف دونجل + + + N/A + غير متاح + + + Serial + التسلسلي + + + Driver Camera + كاميرا السائق + + + PREVIEW + لمح + + + Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) + قم بمعاينة الكاميرا المواجهة للسائق للتأكد من أن نظام مراقبة السائق يتمتع برؤية جيدة. (يجب أن تكون السيارة معطلة) + + + Reset Calibration + إعادة ضبط المعايرة + + + RESET + إعادة تعيين + + + Are you sure you want to reset calibration? + هل أنت متأكد أنك تريد إعادة ضبط المعايرة؟ + + + Review Training Guide + مراجعة دليل التدريب + + + REVIEW + مراجعة + + + Review the rules, features, and limitations of openpilot + راجع القواعد والميزات والقيود الخاصة بـ openpilot + + + Are you sure you want to review the training guide? + هل أنت متأكد أنك تريد مراجعة دليل التدريب؟ + + + Regulatory + تنظيمية + + + VIEW + عرض + + + Change Language + تغيير اللغة + + + CHANGE + تغيير + + + Select a language + اختر لغة + + + Reboot + اعادة التشغيل + + + Power Off + أطفاء + + + openpilot requires the device to be mounted within 4° left or right and within 5° up or 8° down. openpilot is continuously calibrating, resetting is rarely required. + يتطلب openpilot أن يتم تركيب الجهاز في حدود 4 درجات يسارًا أو يمينًا و 5 درجات لأعلى أو 8 درجات لأسفل. يقوم برنامج openpilot بالمعايرة بشكل مستمر ، ونادراً ما تكون إعادة الضبط مطلوبة. + + + Your device is pointed %1° %2 and %3° %4. + جهازك يشير %1° %2 و %3° %4. + + + down + لأسفل + + + up + إلى أعلى + + + left + إلى اليسار + + + right + إلى اليمين + + + Are you sure you want to reboot? + هل أنت متأكد أنك تريد إعادة التشغيل؟ + + + Disengage to Reboot + فك الارتباط لإعادة التشغيل + + + Are you sure you want to power off? + هل أنت متأكد أنك تريد إيقاف التشغيل؟ + + + Disengage to Power Off + فك الارتباط لإيقاف التشغيل + + + + DriveStats + + Drives + أرقام القيادة + + + Hours + ساعات + + + ALL TIME + في كل وقت + + + PAST WEEK + الأسبوع الماضي + + + KM + كم + + + Miles + اميال + + + + DriverViewScene + + camera starting + بدء تشغيل الكاميرا + + + + InputDialog + + Cancel + إلغاء + + + Need at least %n character(s)! + + تحتاج على الأقل %n حرف! + تحتاج على الأقل %n حرف! + تحتاج على الأقل %n احرف! + تحتاج على الأقل %n احرف! + تحتاج على الأقل %n احرف! + تحتاج على الأقل %n احرف! + + + + + Installer + + Installing... + جارٍ التثبيت ... + + + Receiving objects: + استقبال الكائنات: + + + Resolving deltas: + حل دلتا: + + + Updating files: + جارٍ تحديث الملفات: + + + + MapETA + + eta + eta + + + min + دق + + + hr + سع + + + km + كم + + + mi + مل + + + + MapInstructions + + km + كم + + + m + م + + + mi + مل + + + ft + قد + + + + MapPanel + + Current Destination + الوجهة الحالية + + + CLEAR + مسح + + + Recent Destinations + الوجهات الأخيرة + + + Try the Navigation Beta + جرب التنقل التجريبي + + + Get turn-by-turn directions displayed and more with a comma +prime subscription. Sign up now: https://connect.comma.ai + احصل على الاتجاهات خطوة بخطوة معروضة والمزيد باستخدام comma +الاشتراك الرئيسي. اشترك الآن: https://connect.comma.ai + + + No home +location set + لم يتم تعيين +موقع المنزل + + + No work +location set + لم يتم تعيين +موقع العمل + + + no recent destinations + لا توجد وجهات حديثة + + + + MapWindow + + Map Loading + تحميل الخريطة + + + Waiting for GPS + في انتظار GPS + + + + MultiOptionDialog + + Select + اختر + + + Cancel + إلغاء + + + + Networking + + Advanced + متقدم + + + Enter password + أدخل كلمة المرور + + + for "%1" + ل "%1" + + + Wrong password + كلمة مرور خاطئة + + + + OffroadHome + + UPDATE + تحديث + + + ALERTS + تنبيهات + + + ALERT + تنبيه + + + + PairingPopup + + Pair your device to your comma account + قم بإقران جهازك بحساب comma الخاص بك + + + Go to https://connect.comma.ai on your phone + اذهب إلى https://connect.comma.ai من هاتفك + + + Click "add new device" and scan the QR code on the right + انقر على "إضافة جهاز جديد" وامسح رمز الاستجابة السريعة على اليمين + + + Bookmark connect.comma.ai to your home screen to use it like an app + ضع إشارة مرجعية على connect.comma.ai على شاشتك الرئيسية لاستخدامه مثل أي تطبيق + + + + PrimeAdWidget + + Upgrade Now + قم بالترقية الآن + + + Become a comma prime member at connect.comma.ai + كن عضوًا comme prime في connect.comma.ai + + + PRIME FEATURES: + ميزات PRIME: + + + Remote access + الوصول عن بعد + + + 1 year of storage + سنة واحدة من التخزين + + + Developer perks + امتيازات المطور + + + + PrimeUserWidget + + ✓ SUBSCRIBED + ✓ مشترك + + + comma prime + comma prime + + + CONNECT.COMMA.AI + CONNECT.COMMA.AI + + + COMMA POINTS + COMMA POINTS + + + + QObject + + Reboot + اعادة التشغيل + + + Exit + أغلق + + + dashcam + dashcam + + + openpilot + openpilot + + + %n minute(s) ago + + منذ %n دقيقة + منذ %n دقيقة + منذ %n دقائق + منذ %n دقائق + منذ %n دقائق + منذ %n دقائق + + + + %n hour(s) ago + + منذ %n ساعة + منذ %n ساعة + منذ %n ساعات + منذ %n ساعات + منذ %n ساعات + منذ %n ساعات + + + + %n day(s) ago + + منذ %n يوم + منذ %n يوم + منذ %n ايام + منذ %n ايام + منذ %n ايام + منذ %n ايام + + + + + Reset + + Reset failed. Reboot to try again. + فشل إعادة التعيين. أعد التشغيل للمحاولة مرة أخرى. + + + Are you sure you want to reset your device? + هل أنت متأكد أنك تريد إعادة ضبط جهازك؟ + + + Resetting device... + جارٍ إعادة ضبط الجهاز ... + + + System Reset + إعادة تعيين النظام + + + System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. + تم تشغيل إعادة تعيين النظام. اضغط على تأكيد لمسح كل المحتوى والإعدادات. اضغط على إلغاء لاستئناف التمهيد. + + + Cancel + إلغاء + + + Reboot + اعادة التشغيل + + + Confirm + تأكيد + + + Unable to mount data partition. Press confirm to reset your device. + تعذر تحميل قسم البيانات. اضغط على تأكيد لإعادة ضبط جهازك. + + + + RichTextDialog + + Ok + موافق + + + + SettingsWindow + + × + x + + + Device + جهاز + + + Network + شبكة الاتصال + + + Toggles + التبديل + + + Software + برمجة + + + Navigation + ملاحة + + + + Setup + + WARNING: Low Voltage + تحذير: الجهد المنخفض + + + Power your device in a car with a harness or proceed at your own risk. + قم بتشغيل جهازك في سيارة باستخدام أداة تثبيت أو المضي قدمًا على مسؤوليتك الخاصة. + + + Power off + اطفئ الجهاز + + + Continue + أكمل + + + Getting Started + ابدء + + + Before we get on the road, let’s finish installation and cover some details. + قبل أن ننطلق على الطريق ، دعنا ننتهي من التثبيت ونغطي بعض التفاصيل. + + + Connect to Wi-Fi + اتصل بشبكة Wi-Fi + + + Back + خلف + + + Continue without Wi-Fi + استمر بدون Wi-Fi + + + Waiting for internet + في انتظار الاتصال بالإنترنت + + + Choose Software to Install + اختر البرنامج المراد تثبيته + + + Dashcam + Dashcam + + + Custom Software + برامج مخصصة + + + Enter URL + إدخال عنوان الموقع + + + for Custom Software + للبرامج المخصصة + + + Downloading... + جارى التحميل... + + + Download Failed + فشل التنزيل + + + Ensure the entered URL is valid, and the device’s internet connection is good. + تأكد من أن عنوان موقع الويب الذي تم إدخاله صالح ، وأن اتصال الجهاز بالإنترنت جيد. + + + Reboot device + إعادة تشغيل الجهاز + + + Start over + ابدأ من جديد + + + + SetupWidget + + Finish Setup + إنهاء الإعداد + + + Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. + قم بإقران جهازك بفاصلة connect (connect.comma.ai) واطلب عرض comma prime الخاص بك. + + + Pair device + إقران الجهاز + + + + Sidebar + + CONNECT + الاتصال + + + OFFLINE + غير متصل + + + ONLINE + متصل + + + ERROR + خطأ + + + TEMP + درجة الحرارة + + + HIGH + عالي + + + GOOD + جيد + + + OK + موافق + + + VEHICLE + مركبة + + + NO + لا + + + PANDA + PANDA + + + GPS + GPS + + + SEARCH + بحث + + + -- + -- + + + Wi-Fi + Wi-Fi + + + ETH + ETH + + + 2G + 2G + + + 3G + 3G + + + LTE + LTE + + + 5G + 5G + + + + SoftwarePanel + + Git Branch + Git Branch + + + Git Commit + Git Commit + + + OS Version + إصدار نظام التشغيل + + + Version + إصدار + + + Last Update Check + التحقق من آخر تحديث + + + The last time openpilot successfully checked for an update. The updater only runs while the car is off. + آخر مرة نجح برنامج openpilot في التحقق من التحديث. يعمل المحدث فقط أثناء إيقاف تشغيل السيارة. + + + Check for Update + فحص التحديثات + + + CHECKING + تدقيق + + + Switch Branch + تبديل الفرع + + + ENTER + أدخل + + + The new branch will be pulled the next time the updater runs. + سيتم سحب الفرع الجديد في المرة التالية التي يتم فيها تشغيل أداة التحديث. + + + Enter branch name + أدخل اسم الفرع + + + UNINSTALL + الغاء التثبيت + + + Uninstall %1 + الغاء التثبيت %1 + + + Are you sure you want to uninstall? + هل أنت متأكد أنك تريد إلغاء التثبيت؟ + + + failed to fetch update + فشل في جلب التحديث + + + CHECK + تأكد الان + + + Updates are only downloaded while the car is off. + + + + Current Version + + + + Download + + + + Install Update + + + + INSTALL + + + + Target Branch + + + + SELECT + + + + Select a branch + + + + + SshControl + + SSH Keys + SSH Keys + + + Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. + تحذير: هذا يمنح SSH الوصول إلى جميع المفاتيح العامة في إعدادات GitHub. لا تدخل أبدًا اسم مستخدم GitHub بخلاف اسم المستخدم الخاص بك. لن يطلب منك موظف comma أبدًا إضافة اسم مستخدم GitHub الخاص به. + + + ADD + أضف + + + Enter your GitHub username + أدخل اسم مستخدم GitHub الخاص بك + + + LOADING + جار التحميل + + + REMOVE + نزع + + + Username '%1' has no keys on GitHub + لا يحتوي اسم المستخدم '%1' على مفاتيح على GitHub + + + Request timed out + انتهت مهلة الطلب + + + Username '%1' doesn't exist on GitHub + اسم المستخدم '%1' غير موجود على GitHub + + + + SshToggle + + Enable SSH + تفعيل SSH + + + + TermsPage + + Terms & Conditions + البنود و الظروف + + + Decline + انحدار + + + Scroll to accept + قم بالتمرير للقبول + + + Agree + موافق + + + + TogglesPanel + + Enable openpilot + تمكين openpilot + + + Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off. + استخدم نظام الطيار المفتوح للتحكم التكيفي في ثبات السرعة والحفاظ على مساعدة السائق. انتباهك مطلوب في جميع الأوقات لاستخدام هذه الميزة. يسري تغيير هذا الإعداد عند إيقاف تشغيل السيارة. + + + Enable Lane Departure Warnings + قم بتمكين تحذيرات مغادرة حارة السير + + + Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). + تلقي تنبيهات للتوجه مرة أخرى إلى الحارة عندما تنجرف سيارتك فوق خط المسار المكتشف دون تنشيط إشارة الانعطاف أثناء القيادة لمسافة تزيد عن 31 ميلاً في الساعة (50 كم / ساعة). + + + Use Metric System + استخدم النظام المتري + + + Display speed in km/h instead of mph. + عرض السرعة بالكيلو متر في الساعة بدلاً من ميل في الساعة. + + + Record and Upload Driver Camera + تسجيل وتحميل كاميرا السائق + + + Upload data from the driver facing camera and help improve the driver monitoring algorithm. + قم بتحميل البيانات من الكاميرا المواجهة للسائق وساعد في تحسين خوارزمية مراقبة السائق. + + + Disengage on Accelerator Pedal + فك الارتباط على دواسة التسريع + + + When enabled, pressing the accelerator pedal will disengage openpilot. + عند التمكين ، سيؤدي الضغط على دواسة الوقود إلى فصل الطيار المفتوح. + + + Show ETA in 24h Format + إظهار الوقت المقدر للوصول بتنسيق 24 ساعة + + + Use 24h format instead of am/pm + استخدم تنسيق 24 ساعة بدلاً من صباحًا / مساءً + + + Show Map on Left Side of UI + إظهار الخريطة على الجانب الأيسر من واجهة المستخدم + + + Show map on left side when in split screen view. + إظهار الخريطة على الجانب الأيسر عندما تكون في طريقة عرض الشاشة المنقسمة. + + + openpilot Longitudinal Control + openpilot التحكم الطولي + + + openpilot will disable the car's radar and will take over control of gas and brakes. Warning: this disables AEB! + سوف يقوم برنامج openpilot بتعطيل رادار السيارة وسيتولى التحكم في الغاز والمكابح. تحذير: هذا يعطل AEB! + + + 🌮 End-to-end longitudinal (extremely alpha) 🌮 + + + + Experimental openpilot Longitudinal Control + + + + <b>WARNING: openpilot longitudinal control is experimental for this car and will disable AEB.</b> + + + + Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would. Super experimental. + + + + openpilot longitudinal control is not currently available for this car. + + + + Enable experimental longitudinal control to enable this. + + + + + Updater + + Update Required + مطلوب التحديث + + + An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. + مطلوب تحديث نظام التشغيل. قم بتوصيل جهازك بشبكة Wi-Fi للحصول على أسرع تجربة تحديث. حجم التنزيل 1 غيغابايت تقريبًا. + + + Connect to Wi-Fi + اتصل بشبكة Wi-Fi + + + Install + ثبيت + + + Back + خلف + + + Loading... + جار التحميل... + + + Reboot + اعادة التشغيل + + + Update failed + فشل التحديث + + + + WifiUI + + Scanning for networks... + جارٍ البحث عن شبكات ... + + + CONNECTING... + جارٍ الاتصال ... + + + FORGET + نزع + + + Forget Wi-Fi Network "%1"? + نزع شبكة اWi-Fi "%1"? + + + diff --git a/selfdrive/ui/translations/main_en.ts b/selfdrive/ui/translations/main_en.ts new file mode 100644 index 0000000000..3f9692e5fa --- /dev/null +++ b/selfdrive/ui/translations/main_en.ts @@ -0,0 +1,38 @@ + + + + + InputDialog + + Need at least %n character(s)! + + Need at least %n character! + Need at least %n characters! + + + + + QObject + + %n minute(s) ago + + %n minute ago + %n minutes ago + + + + %n hour(s) ago + + %n hour ago + %n hours ago + + + + %n day(s) ago + + %n day ago + %n days ago + + + + diff --git a/selfdrive/ui/translations/main_ja.ts b/selfdrive/ui/translations/main_ja.ts new file mode 100644 index 0000000000..8226dd59f9 --- /dev/null +++ b/selfdrive/ui/translations/main_ja.ts @@ -0,0 +1,1107 @@ + + + + + AbstractAlert + + Close + 閉じる + + + Snooze Update + 更新の一時停止 + + + Reboot and Update + 再起動してアップデート + + + + AdvancedNetworking + + Back + 戻る + + + Enable Tethering + テザリングを有効化 + + + Tethering Password + テザリングパスワード + + + EDIT + 編集 + + + Enter new tethering password + 新しいテザリングパスワードを入力 + + + IP Address + IP アドレス + + + Enable Roaming + ローミングを有効化 + + + APN Setting + APN 設定 + + + Enter APN + APN を入力 + + + leave blank for automatic configuration + 自動で設定するには、空白のままにしてください。 + + + Cellular Metered + 従量制通信設定 + + + Prevent large data uploads when on a metered connection + 大量のデータのアップロードを防止します。 + + + + AnnotatedCameraWidget + + km/h + km/h + + + mph + mph + + + MAX + 最高速度 + + + SPEED + 速度 + + + LIMIT + 制限速度 + + + + ConfirmationDialog + + Ok + OK + + + Cancel + キャンセル + + + + DeclinePage + + You must accept the Terms and Conditions in order to use openpilot. + openpilot をご利用される前に、利用規約に同意する必要があります。 + + + Back + 戻る + + + Decline, uninstall %1 + 拒否して %1 をアンインストール + + + + DevicePanel + + Dongle ID + ドングル番号 (Dongle ID) + + + N/A + N/A + + + Serial + シリアル番号 + + + Driver Camera + 車内カメラ + + + PREVIEW + プレビュー + + + Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) + 車内カメラをプレビューして、ドライバー監視システムの視界を確認ができます。(車両の電源を切る必要があります) + + + Reset Calibration + キャリブレーションをリセット + + + RESET + リセット + + + Are you sure you want to reset calibration? + キャリブレーションをリセットしてもよろしいですか? + + + Review Training Guide + 使い方の確認 + + + REVIEW + 見る + + + Review the rules, features, and limitations of openpilot + openpilot の特徴を見る + + + Are you sure you want to review the training guide? + 使い方の確認をしますか? + + + Regulatory + 認証情報 + + + VIEW + 見る + + + Change Language + 言語を変更 + + + CHANGE + 変更 + + + Select a language + 言語を選択 + + + Reboot + 再起動 + + + Power Off + 電源を切る + + + openpilot requires the device to be mounted within 4° left or right and within 5° up or 8° down. openpilot is continuously calibrating, resetting is rarely required. + openpilotの本体は、左右4°以内、上5°、下8°以内の角度で取付ける必要があります。継続してキャリブレーションを続けているので、手動でリセットを行う必要はほぼありません。 + + + Your device is pointed %1° %2 and %3° %4. + このデバイスは%2 %1°、%4 %3°の向きに設置されています。 + + + down + + + + up + + + + left + + + + right + + + + Are you sure you want to reboot? + 再起動してもよろしいですか? + + + Disengage to Reboot + openpilot をキャンセルして再起動ができます + + + Are you sure you want to power off? + シャットダウンしてもよろしいですか? + + + Disengage to Power Off + openpilot をキャンセルしてシャットダウンができます + + + Reset + リセット + + + Review + 確認 + + + + DriveStats + + Drives + 運転履歴 + + + Hours + 時間 + + + ALL TIME + 累計 + + + PAST WEEK + 先週 + + + KM + km + + + Miles + マイル + + + + DriverViewScene + + camera starting + カメラを起動しています + + + + ExperimentalModeButton + + EXPERIMENTAL MODE ON + 実験モード + + + CHILL MODE ON + チルモード + + + + InputDialog + + Cancel + キャンセル + + + Need at least %n character(s)! + + %n文字以上でお願いします! + + + + + Installer + + Installing... + インストールしています... + + + Receiving objects: + オブジェクトをダウンロードしています: + + + Resolving deltas: + デルタを解決しています: + + + Updating files: + ファイルを更新しています: + + + + MapETA + + eta + 到着予定時間 + + + min + + + + hr + 時間 + + + km + キロメートル + + + mi + マイル + + + + MapInstructions + + km + キロメートル + + + m + メートル + + + mi + マイル + + + ft + フィート + + + + MapPanel + + Current Destination + 現在の目的地 + + + CLEAR + 削除 + + + Recent Destinations + 最近の目的地 + + + Try the Navigation Beta + β版ナビゲーションを試す + + + Get turn-by-turn directions displayed and more with a comma +prime subscription. Sign up now: https://connect.comma.ai + より詳細な案内情報を得ることができます。 +詳しくはこちら:https://connect.comma.ai + + + No home +location set + 自宅の住所はまだ +設定されていません + + + No work +location set + 職場の住所はまだ +設定されていません + + + no recent destinations + 最近の目的地履歴がありません + + + + MapWindow + + Map Loading + マップを読み込んでいます + + + Waiting for GPS + GPS信号を探しています + + + + MultiOptionDialog + + Select + 選択 + + + Cancel + キャンセル + + + + Networking + + Advanced + 詳細 + + + Enter password + パスワードを入力 + + + for "%1" + ネットワーク名:%1 + + + Wrong password + パスワードが間違っています + + + + OffroadHome + + UPDATE + 更新 + + + ALERTS + 警告 + + + ALERT + 警告 + + + + PairingPopup + + Pair your device to your comma account + デバイスと comma アカウントを連携する + + + Go to https://connect.comma.ai on your phone + スマートフォンで「https://connect.comma.ai」にアクセスしてください。 + + + Click "add new device" and scan the QR code on the right + 「新しいデバイスを追加」を押し、右側のQRコードをスキャンしてください。 + + + Bookmark connect.comma.ai to your home screen to use it like an app + 「connect.comma.ai」をホーム画面に追加して、アプリのように使うことができます。 + + + + ParamControl + + Cancel + キャンセル + + + Enable + を有効化 + + + + PrimeAdWidget + + Upgrade Now + 今すぐアップグレート + + + Become a comma prime member at connect.comma.ai + connect.comma.ai でプライム会員に登録できます + + + PRIME FEATURES: + 特典: + + + Remote access + リモートアクセス + + + 1 year of storage + 一年間の保存期間 + + + Developer perks + 開発者向け特典 + + + + PrimeUserWidget + + ✓ SUBSCRIBED + ✓ 入会しました + + + comma prime + comma prime + + + CONNECT.COMMA.AI + CONNECT.COMMA.AI + + + COMMA POINTS + COMMA POINTS + + + + QObject + + Reboot + 再起動 + + + Exit + 閉じる + + + dashcam + ドライブレコーダー + + + openpilot + openpilot + + + %n minute(s) ago + + %n 分前 + + + + %n hour(s) ago + + %n 時間前 + + + + %n day(s) ago + + %n 日前 + + + + + Reset + + Reset failed. Reboot to try again. + 初期化に失敗しました。再起動後に再試行してください。 + + + Are you sure you want to reset your device? + 初期化してもよろしいですか? + + + Resetting device... + デバイスが初期化されます... + + + System Reset + システムを初期化 + + + System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. + システムの初期化をリクエストしました。「確認」ボタンを押すとデバイスが初期化されます。「キャンセル」ボタンを押すと起動を続行します。 + + + Cancel + キャンセル + + + Reboot + 再起動 + + + Confirm + 確認 + + + Unable to mount data partition. Press confirm to reset your device. + 「data」パーティションをマウントできません。「確認」ボタンを押すとデバイスが初期化されます。 + + + + SettingsWindow + + × + × + + + Device + デバイス + + + Network + ネットワーク + + + Toggles + 機能設定 + + + Software + ソフトウェア + + + Navigation + ナビゲーション + + + + Setup + + WARNING: Low Voltage + 警告:低電圧 + + + Power your device in a car with a harness or proceed at your own risk. + 自己責任で実行を継続するか、ハーネスから電源を供給してください。 + + + Power off + 電源を切る + + + Continue + 続ける + + + Getting Started + はじめに + + + Before we get on the road, let’s finish installation and cover some details. + 道路に向かう前に、インストールを完了して使い方を確認しましょう。 + + + Connect to Wi-Fi + Wi-Fi に接続 + + + Back + 戻る + + + Continue without Wi-Fi + Wi-Fi に接続せずに続行 + + + Waiting for internet + インターネット接続を待機中 + + + Choose Software to Install + インストールするソフトウェアを選択してください + + + Dashcam + ドライブレコーダー + + + Custom Software + カスタムソフトウェア + + + Enter URL + URL を入力 + + + for Custom Software + カスタムソフトウェア + + + Downloading... + ダウンロード中... + + + Download Failed + ダウンロード失敗 + + + Ensure the entered URL is valid, and the device’s internet connection is good. + 入力された URL を確認し、デバイスがインターネットに接続されていることを確認してください。 + + + Reboot device + デバイスを再起動 + + + Start over + 最初からやり直す + + + + SetupWidget + + Finish Setup + セットアップ完了 + + + Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. + デバイスを comma connect (connect.comma.ai)でペアリングし、comma primeの特典を申請してください。 + + + Pair device + デバイスをペアリング + + + + Sidebar + + CONNECT + 接続 + + + OFFLINE + オフライン + + + ONLINE + オンライン + + + ERROR + エラー + + + TEMP + 温度 + + + HIGH + 高温 + + + GOOD + 最適 + + + OK + OK + + + VEHICLE + 車両 + + + NO + NO + + + PANDA + PANDA + + + GPS + GPS + + + SEARCH + 検索 + + + -- + -- + + + Wi-Fi + Wi-Fi + + + ETH + ETH + + + 2G + 2G + + + 3G + 3G + + + LTE + LTE + + + 5G + 5G + + + + SoftwarePanel + + Updates are only downloaded while the car is off. + 車の電源がオフの間のみ、アップデートのダウンロードが行われます。 + + + Current Version + 現在のバージョン + + + Download + ダウンロード + + + Install Update + アップデート + + + INSTALL + インストール + + + Target Branch + 対象のブランチ + + + SELECT + 選択 + + + Select a branch + ブランチを選択 + + + UNINSTALL + 実行 + + + Uninstall %1 + %1をアンインストール + + + Are you sure you want to uninstall? + アンインストールしてもよろしいですか? + + + CHECK + 確認 + + + Uninstall + アンインストール + + + + SshControl + + SSH Keys + SSH 鍵 + + + Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. + 警告: これは、GitHub の設定にあるすべての公開鍵への SSH アクセスを許可するものです。自分以外の GitHub のユーザー名を入力しないでください。commaのスタッフが GitHub のユーザー名を追加するようお願いすることはありません。 + + + ADD + 追加 + + + Enter your GitHub username + GitHub のユーザー名を入力してください + + + LOADING + 読み込み中 + + + REMOVE + 削除 + + + Username '%1' has no keys on GitHub + ユーザー名 “%1” は GitHub に鍵がありません + + + Request timed out + リクエストタイムアウト + + + Username '%1' doesn't exist on GitHub + ユーザー名 '%1' は GitHub に存在しません + + + + SshToggle + + Enable SSH + SSH を有効化 + + + + TermsPage + + Terms & Conditions + 利用規約 + + + Decline + 拒否 + + + Scroll to accept + スクロールして同意 + + + Agree + 同意 + + + + TogglesPanel + + Enable openpilot + openpilot を有効化 + + + Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off. + openpilotによるアダプティブクルーズコントロールとレーンキーピングドライバーアシストを利用します。この機能を利用する際は、常に前方への注意が必要です。この設定を変更すると、車の電源が切れた時に反映されます。 + + + Enable Lane Departure Warnings + 車線逸脱警報機能を有効化 + + + Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). + 時速31マイル(50km)を超えるスピードで走行中、ウインカーを作動させずに検出された車線ライン上に車両が触れた場合、手動で車線内に戻るように警告を行います。 + + + Use Metric System + メートル法を使用 + + + Display speed in km/h instead of mph. + 速度は mph ではなく km/h で表示されます。 + + + Record and Upload Driver Camera + 車内カメラの録画とアップロード + + + Upload data from the driver facing camera and help improve the driver monitoring algorithm. + 車内カメラの映像をアップロードし、ドライバー監視システムのアルゴリズムの向上に役立てます。 + + + Experimental openpilot Longitudinal Control + 実験段階のopenpilotによるアクセル制御 + + + Disengage on Accelerator Pedal + アクセルを踏むと openpilot を中断 + + + When enabled, pressing the accelerator pedal will disengage openpilot. + この機能を有効化すると、openpilotを利用中にアクセルを踏むとopenpilotによる運転サポートを中断します。 + + + Show ETA in 24h Format + 24時間表示 + + + Use 24h format instead of am/pm + AM/PM の代わりに24時間形式を使用します + + + Show Map on Left Side of UI + ディスプレイの左側にマップを表示 + + + Show map on left side when in split screen view. + 分割画面表示の場合、ディスプレイの左側にマップを表示します。 + + + Experimental Mode + 実験モード + + + WARNING: openpilot longitudinal control is experimental for this car and will disable Automatic Emergency Braking (AEB). + 警告: この車種でのopenpilotによるアクセル制御は実験段階であり、衝突被害軽減ブレーキ(AEB)を無効化します。 + + + On this car, openpilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when using experimental openpilot longitudinal control. + openpilotはこの車の場合、車に内蔵されているACCを標準で利用します。この機能を有効にすることで実験段階のopenpilotによるアクセル制御を利用できます。実験モードと合わせて利用することをお勧めします。 + + + Experimental mode is currently unavailable on this car, since the car's stock ACC is used for longitudinal control. + この車のACCがアクセル制御を行うため、実験モードを利用することができません。 + + + Enable experimental longitudinal control to allow experimental mode. + 実験段階のopenpilotによるアクセル制御を有効にしてください。 + + + openpilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: + openpilotは標準ではゆっくりとくつろげる運転を提供します。この実験モードを有効にすると、以下のくつろげる段階ではない開発中の機能を利用する事ができます。 + + + 🌮 End-to-End Longitudinal Control 🌮 + 🌮 エンドツーエンドアクセル制御 🌮 + + + Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. + openpilotにアクセルとブレーキを任せます。openpilotは赤信号や一時停止サインでの停止を含み、人間と同じように考えて運転を行います。openpilotが運転速度を決定するため、あなたが設定する速度は上限速度になります。この機能は実験段階のため、openpilotの運転ミスに常に備えて注意してください。 + + + New Driving Visualization + 新しい運転画面 + + + The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. + 新しい運転画面では、低速時に広角カメラの映像を表示することで、曲がる際の道路の視覚を向上します。実験段階を表すマークが右上に表示されます。 + + + + Updater + + Update Required + アップデートが必要です + + + An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. + オペレーティングシステムのアップデートが必要です。Wi-Fi に接続してアップデートする事をお勧めします。ダウンロードサイズは約 1GB です。 + + + Connect to Wi-Fi + Wi-Fi に接続 + + + Install + インストール + + + Back + 戻る + + + Loading... + 読み込み中... + + + Reboot + 再起動 + + + Update failed + 更新失敗 + + + + WifiUI + + Scanning for networks... + ネットワークをスキャン中... + + + CONNECTING... + 接続中... + + + FORGET + 削除 + + + Forget Wi-Fi Network "%1"? + Wi-Fiネットワーク%1を削除してもよろしいですか? + + + Forget + 削除 + + + diff --git a/selfdrive/ui/translations/main_ko.ts b/selfdrive/ui/translations/main_ko.ts new file mode 100644 index 0000000000..bda64c53ab --- /dev/null +++ b/selfdrive/ui/translations/main_ko.ts @@ -0,0 +1,1107 @@ + + + + + AbstractAlert + + Close + 닫기 + + + Snooze Update + 업데이트 일시중지 + + + Reboot and Update + 업데이트 및 재부팅 + + + + AdvancedNetworking + + Back + 뒤로 + + + Enable Tethering + 테더링 사용 + + + Tethering Password + 테더링 비밀번호 + + + EDIT + 편집 + + + Enter new tethering password + 새 테더링 비밀번호를 입력하세요 + + + IP Address + IP 주소 + + + Enable Roaming + 로밍 사용 + + + APN Setting + APN 설정 + + + Enter APN + APN 입력 + + + leave blank for automatic configuration + 자동설정하려면 공백으로 두세요 + + + Cellular Metered + 데이터 요금제 + + + Prevent large data uploads when on a metered connection + 데이터 요금제 연결 시 대용량 데이터 업로드 방지 + + + + AnnotatedCameraWidget + + km/h + km/h + + + mph + mph + + + MAX + MAX + + + SPEED + SPEED + + + LIMIT + LIMIT + + + + ConfirmationDialog + + Ok + 확인 + + + Cancel + 취소 + + + + DeclinePage + + You must accept the Terms and Conditions in order to use openpilot. + openpilot을 사용하려면 이용약관에 동의해야 합니다. + + + Back + 뒤로 + + + Decline, uninstall %1 + 거절, %1 제거 + + + + DevicePanel + + Dongle ID + Dongle ID + + + N/A + N/A + + + Serial + Serial + + + Driver Camera + 운전자 카메라 + + + PREVIEW + 미리보기 + + + Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) + 운전자 모니터링이 좋은 가시성을 갖도록 운전자를 향한 카메라를 미리 봅니다. (차량연결은 해제되어있어야 합니다) + + + Reset Calibration + 캘리브레이션 + + + RESET + 재설정 + + + Are you sure you want to reset calibration? + 캘리브레이션을 재설정하시겠습니까? + + + Review Training Guide + 트레이닝 가이드 + + + REVIEW + 다시보기 + + + Review the rules, features, and limitations of openpilot + openpilot의 규칙, 기능 및 제한 다시보기 + + + Are you sure you want to review the training guide? + 트레이닝 가이드를 다시보시겠습니까? + + + Regulatory + 규제 + + + VIEW + 보기 + + + Change Language + 언어 변경 + + + CHANGE + 변경 + + + Select a language + 언어를 선택하세요 + + + Reboot + 재부팅 + + + Power Off + 전원 종료 + + + openpilot requires the device to be mounted within 4° left or right and within 5° up or 8° down. openpilot is continuously calibrating, resetting is rarely required. + openpilot은 좌우측은 4° 이내, 위쪽은 5° 아래쪽은 8° 이내로 장치를 설치해야 합니다. openpilot은 지속적으로 보정되므로 리셋은 거의 필요하지 않습니다. + + + Your device is pointed %1° %2 and %3° %4. + 사용자의 장치가 %1° %2 및 %3° %4 위치에 설치되어있습니다. + + + down + 아래로 + + + up + 위로 + + + left + 좌측으로 + + + right + 우측으로 + + + Are you sure you want to reboot? + 재부팅 하시겠습니까? + + + Disengage to Reboot + 재부팅 하려면 해제하세요 + + + Are you sure you want to power off? + 전원을 종료하시겠습니까? + + + Disengage to Power Off + 전원을 종료하려면 해제하세요 + + + Reset + 리셋 + + + Review + 다시보기 + + + + DriveStats + + Drives + 주행 + + + Hours + 시간 + + + ALL TIME + 전체 + + + PAST WEEK + 지난주 + + + KM + Km + + + Miles + Miles + + + + DriverViewScene + + camera starting + 카메라 시작중 + + + + ExperimentalModeButton + + EXPERIMENTAL MODE ON + 실험적 모드 사용 + + + CHILL MODE ON + 안정적 모드 사용 + + + + InputDialog + + Cancel + 취소 + + + Need at least %n character(s)! + + 최소 %n 자가 필요합니다! + + + + + Installer + + Installing... + 설치중... + + + Receiving objects: + 수신중: + + + Resolving deltas: + 델타병합: + + + Updating files: + 파일갱신: + + + + MapETA + + eta + 도착 + + + min + + + + hr + 시간 + + + km + km + + + mi + mi + + + + MapInstructions + + km + km + + + m + m + + + mi + mi + + + ft + ft + + + + MapPanel + + Current Destination + 현재 목적지 + + + CLEAR + 삭제 + + + Recent Destinations + 최근 목적지 + + + Try the Navigation Beta + 네비게이션(베타)를 사용해보세요 + + + Get turn-by-turn directions displayed and more with a comma +prime subscription. Sign up now: https://connect.comma.ai + 자세한 경로안내를 원하시면 comma prime을 구독하세요. +등록:https://connect.comma.ai + + + No home +location set + 집 +설정되지않음 + + + No work +location set + 회사 +설정되지않음 + + + no recent destinations + 최근 목적지 없음 + + + + MapWindow + + Map Loading + 지도 로딩 + + + Waiting for GPS + GPS를 기다리는 중 + + + + MultiOptionDialog + + Select + 선택 + + + Cancel + 취소 + + + + Networking + + Advanced + 고급 설정 + + + Enter password + 비밀번호를 입력하세요 + + + for "%1" + "%1"에 접속하려면 인증이 필요합니다 + + + Wrong password + 비밀번호가 틀렸습니다 + + + + OffroadHome + + UPDATE + 업데이트 + + + ALERTS + 알림 + + + ALERT + 알림 + + + + PairingPopup + + Pair your device to your comma account + 장치를 콤마 계정과 페어링합니다 + + + Go to https://connect.comma.ai on your phone + https://connect.comma.ai에 접속하세요 + + + Click "add new device" and scan the QR code on the right + "새 장치 추가"를 클릭하고 오른쪽 QR 코드를 검색합니다 + + + Bookmark connect.comma.ai to your home screen to use it like an app + connect.comma.ai을 앱처럼 사용하려면 홈 화면에 바로가기를 만드십시오 + + + + ParamControl + + Cancel + 취소 + + + Enable + 사용 + + + + PrimeAdWidget + + Upgrade Now + 지금 업그레이드 + + + Become a comma prime member at connect.comma.ai + connect.comma.ai에서 comma prime에 가입합니다 + + + PRIME FEATURES: + PRIME 기능: + + + Remote access + 원격 접속 + + + 1 year of storage + 1년간 저장 + + + Developer perks + 개발자 혜택 + + + + PrimeUserWidget + + ✓ SUBSCRIBED + ✓ 구독함 + + + comma prime + comma prime + + + CONNECT.COMMA.AI + CONNECT.COMMA.AI + + + COMMA POINTS + COMMA POINTS + + + + QObject + + Reboot + 재부팅 + + + Exit + 종료 + + + dashcam + dashcam + + + openpilot + openpilot + + + %n minute(s) ago + + %n 분전 + + + + %n hour(s) ago + + %n 시간전 + + + + %n day(s) ago + + %n 일전 + + + + + Reset + + Reset failed. Reboot to try again. + 초기화 실패. 재부팅후 다시 시도하세요. + + + Are you sure you want to reset your device? + 장치를 초기화 하시겠습니까? + + + Resetting device... + 장치 초기화중... + + + System Reset + 장치 초기화 + + + System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. + 장치를 초기화 합니다. 확인버튼을 누르면 모든 내용과 설정이 초기화됩니다. 부팅을 재개하려면 취소를 누르세요. + + + Cancel + 취소 + + + Reboot + 재부팅 + + + Confirm + 확인 + + + Unable to mount data partition. Press confirm to reset your device. + 데이터 파티션을 마운트할 수 없습니다. 확인 버튼을 눌러 장치를 리셋합니다. + + + + SettingsWindow + + × + × + + + Device + 장치 + + + Network + 네트워크 + + + Toggles + 토글 + + + Software + 소프트웨어 + + + Navigation + 네비게이션 + + + + Setup + + WARNING: Low Voltage + 경고: 전압이 낮습니다 + + + Power your device in a car with a harness or proceed at your own risk. + 하네스 보드에 차량의 전원을 연결하세요. + + + Power off + 전원 종료 + + + Continue + 계속 + + + Getting Started + 설정 시작 + + + Before we get on the road, let’s finish installation and cover some details. + 출발하기 전에 설정을 완료하고 몇 가지 세부 사항을 살펴보겠습니다. + + + Connect to Wi-Fi + wifi 연결 + + + Back + 뒤로 + + + Continue without Wi-Fi + wifi 연결없이 계속하기 + + + Waiting for internet + 네트워크 접속을 기다립니다 + + + Choose Software to Install + 설치할 소프트웨어를 선택하세요 + + + Dashcam + Dashcam + + + Custom Software + Custom Software + + + Enter URL + URL 입력 + + + for Custom Software + for Custom Software + + + Downloading... + 다운로드중... + + + Download Failed + 다운로드 실패 + + + Ensure the entered URL is valid, and the device’s internet connection is good. + 입력된 URL이 유효하고 장치의 네트워크 연결이 잘 되어 있는지 확인하세요. + + + Reboot device + 재부팅 + + + Start over + 다시 시작 + + + + SetupWidget + + Finish Setup + 설정 완료 + + + Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. + 장치를 (connect.comma.ai)에서 페어링하고 comma prime 오퍼를 청구합니다. + + + Pair device + 장치 페어링 + + + + Sidebar + + CONNECT + 연결 + + + OFFLINE + 오프라인 + + + ONLINE + 온라인 + + + ERROR + 오류 + + + TEMP + 온도 + + + HIGH + 높음 + + + GOOD + 좋음 + + + OK + 경고 + + + VEHICLE + 차량 + + + NO + NO + + + PANDA + PANDA + + + GPS + GPS + + + SEARCH + 검색중 + + + -- + -- + + + Wi-Fi + Wi-Fi + + + ETH + 이더넷 + + + 2G + 2G + + + 3G + 3G + + + LTE + LTE + + + 5G + 5G + + + + SoftwarePanel + + Updates are only downloaded while the car is off. + 업데이트는 차량 연결이 해제되어 있는 동안에만 다운로드됩니다. + + + Current Version + 현재 버전 + + + Download + 다운로드 + + + Install Update + 업데이트 설치 + + + INSTALL + 설치 + + + Target Branch + 대상 브랜치 + + + SELECT + 선택 + + + Select a branch + 브랜치 선택 + + + UNINSTALL + 제거 + + + Uninstall %1 + %1 제거 + + + Are you sure you want to uninstall? + 제거하시겠습니까? + + + CHECK + 확인 + + + Uninstall + 제거 + + + + SshControl + + SSH Keys + SSH 키 + + + Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. + 경고: 허용으로 설정하면 GitHub 설정의 모든 공용 키에 대한 SSH 액세스 권한이 부여됩니다. GitHub 사용자 ID 이외에는 입력하지 마십시오. comma에서는 GitHub ID를 추가하라는 요청을 하지 않습니다. + + + ADD + 추가 + + + Enter your GitHub username + GitHub 사용자 ID + + + LOADING + 로딩 + + + REMOVE + 제거 + + + Username '%1' has no keys on GitHub + '%1'의 키가 GitHub에 없습니다 + + + Request timed out + 요청 시간 초과 + + + Username '%1' doesn't exist on GitHub + '%1'은 GitHub에 없습니다 + + + + SshToggle + + Enable SSH + SSH 사용 + + + + TermsPage + + Terms & Conditions + 약관 + + + Decline + 거절 + + + Scroll to accept + 허용하려면 아래로 스크롤하세요 + + + Agree + 동의 + + + + TogglesPanel + + Enable openpilot + openpilot 사용 + + + Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off. + 어댑티브 크루즈 컨트롤 및 차선 유지 운전자 보조를 위해 openpilot 시스템을 사용하십시오. 이 기능을 사용하려면 항상 주의를 기울여야 합니다. 설정변경은 장치 재부팅후 적용됩니다. + + + Enable Lane Departure Warnings + 차선 이탈 경고 사용 + + + Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). + 차량이 50km/h(31mph) 이상의 속도로 주행하는 동안 방향지시등 없이 감지된 차선 위를 주행할 경우 차선이탈 경고를 표시합니다. + + + Use Metric System + 미터법 사용 + + + Display speed in km/h instead of mph. + mph 대신 km/h로 속도를 표시합니다. + + + Record and Upload Driver Camera + 운전자 카메라 녹화 및 업로드 + + + Upload data from the driver facing camera and help improve the driver monitoring algorithm. + 운전자 카메라에서 데이터를 업로드하고 운전자 모니터링 알고리즘을 개선합니다. + + + Experimental openpilot Longitudinal Control + openpilot 롱컨트롤 (실험적) + + + Disengage on Accelerator Pedal + 가속페달 조작시 해제 + + + When enabled, pressing the accelerator pedal will disengage openpilot. + 활성화된 경우 가속 페달을 누르면 openpilot이 해제됩니다. + + + Show ETA in 24h Format + 24시간 형식으로 도착예정시간 표시 + + + Use 24h format instead of am/pm + 오전/오후 대신 24시간 형식 사용 + + + Show Map on Left Side of UI + UI 왼쪽에 지도 표시 + + + Show map on left side when in split screen view. + 분할 화면 보기에서 지도를 왼쪽에 표시합니다. + + + Experimental Mode + 실험적 모드 + + + WARNING: openpilot longitudinal control is experimental for this car and will disable Automatic Emergency Braking (AEB). + 경고: openpilot 롱컨트롤은 실험적인 기능으로 차량의 자동긴급제동(AEB)를 비활성화합니다. + + + On this car, openpilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when using experimental openpilot longitudinal control. + 이 차량은 openpilot 롱컨트롤 대신 차량의 내장 ACC로 기본 설정됩니다. openpilot 롱컨트롤을 사용하려면 이 옵션을 활성화하세요. 실험적 openpilot 롱컨트롤을 사용하는 경우 실험적 모드를 활성화 하세요. + + + Experimental mode is currently unavailable on this car, since the car's stock ACC is used for longitudinal control. + 차량의 기본 ACC가 롱컨트롤에 사용되기 때문에 현재 이 차량에서는 실험적 모드를 사용할수 없습니다. + + + Enable experimental longitudinal control to allow experimental mode. + 실험적 롱컨트롤을 사용하려면 실험적 모드를 활성화 하세요. + + + openpilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: + openpilot은 기본적으로 <b>안정적 모드</b>로 주행합니다. 실험적 모드는 안정적 모드에 준비되지 않은 <b>알파 수준 기능</b>을 활성화 합니다. 실험 모드의 특징은 아래에 나열되어 있습니다 + + + 🌮 End-to-End Longitudinal Control 🌮 + 🌮 E2E 롱컨트롤 🌮 + + + Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. + 주행모델이 가속과 감속을 제어하도록 합니다. openpilot은 신호등과 정지표지판을 보고 멈추는 것을 포함하여 운전자가 생각하는것처럼 주행합니다. 주행 모델이 주행할 속도를 결정하므로 설정된 속도는 상한선으로만 작용합니다. 이것은 알파 기능이므로 사용에 주의해야 합니다. + + + New Driving Visualization + 새로운 주행 시각화 + + + The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. + 주행 시각화는 저속에서 도로를 향하는 광각 카메라로 전환되어 일부 회전을 더 잘 보여줍니다. 실험적 모드 로고도 우측상단에 표시됩니다. + + + + Updater + + Update Required + 업데이트 필요 + + + An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. + OS 업데이트가 필요합니다. 장치를 wifi에 연결하면 가장 빠른 업데이트 경험을 제공합니다. 다운로드 크기는 약 1GB입니다. + + + Connect to Wi-Fi + wifi 연결 + + + Install + 설치 + + + Back + 뒤로 + + + Loading... + 로딩중... + + + Reboot + 재부팅 + + + Update failed + 업데이트 실패 + + + + WifiUI + + Scanning for networks... + 네트워크 검색 중... + + + CONNECTING... + 연결중... + + + FORGET + 저장안함 + + + Forget Wi-Fi Network "%1"? + wifi 네트워크 저장안함 "%1"? + + + Forget + 저장안함 + + + diff --git a/selfdrive/ui/translations/main_nl.ts b/selfdrive/ui/translations/main_nl.ts new file mode 100644 index 0000000000..10651a4160 --- /dev/null +++ b/selfdrive/ui/translations/main_nl.ts @@ -0,0 +1,1120 @@ + + + + + AbstractAlert + + Close + Sluit + + + Snooze Update + Update uitstellen + + + Reboot and Update + Opnieuw Opstarten en Updaten + + + + AdvancedNetworking + + Back + Terug + + + Enable Tethering + Tethering Inschakelen + + + Tethering Password + Tethering Wachtwoord + + + EDIT + AANPASSEN + + + Enter new tethering password + Voer nieuw tethering wachtwoord in + + + IP Address + IP Adres + + + Enable Roaming + Roaming Inschakelen + + + APN Setting + APN Instelling + + + Enter APN + Voer APN in + + + leave blank for automatic configuration + laat leeg voor automatische configuratie + + + Cellular Metered + + + + Prevent large data uploads when on a metered connection + + + + + AnnotatedCameraWidget + + km/h + km/u + + + mph + mph + + + MAX + MAX + + + SPEED + SPEED + + + LIMIT + LIMIT + + + + ConfirmationDialog + + Ok + Ok + + + Cancel + Annuleren + + + + DeclinePage + + You must accept the Terms and Conditions in order to use openpilot. + U moet de Algemene Voorwaarden accepteren om openpilot te gebruiken. + + + Back + Terug + + + Decline, uninstall %1 + Afwijzen, verwijder %1 + + + + DevicePanel + + Dongle ID + Dongle ID + + + N/A + Nvt + + + Serial + Serienummer + + + Driver Camera + Bestuurders Camera + + + PREVIEW + BEKIJKEN + + + Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) + Bekijk de naar de bestuurder gerichte camera om ervoor te zorgen dat het monitoren van de bestuurder goed zicht heeft. (Voertuig moet uitgschakeld zijn) + + + Reset Calibration + Kalibratie Resetten + + + RESET + RESET + + + Are you sure you want to reset calibration? + Weet u zeker dat u de kalibratie wilt resetten? + + + Review Training Guide + Doorloop de Training Opnieuw + + + REVIEW + BEKIJKEN + + + Review the rules, features, and limitations of openpilot + Bekijk de regels, functies en beperkingen van openpilot + + + Are you sure you want to review the training guide? + Weet u zeker dat u de training opnieuw wilt doorlopen? + + + Regulatory + Regelgeving + + + VIEW + BEKIJKEN + + + Change Language + Taal Wijzigen + + + CHANGE + WIJZIGEN + + + Select a language + Selecteer een taal + + + Reboot + Opnieuw Opstarten + + + Power Off + Uitschakelen + + + openpilot requires the device to be mounted within 4° left or right and within 5° up or 8° down. openpilot is continuously calibrating, resetting is rarely required. + openpilot vereist dat het apparaat binnen 4° links of rechts en binnen 5° omhoog of 8° omlaag wordt gemonteerd. openpilot kalibreert continu, resetten is zelden nodig. + + + Your device is pointed %1° %2 and %3° %4. + Uw apparaat is gericht op %1° %2 en %3° %4. + + + down + omlaag + + + up + omhoog + + + left + links + + + right + rechts + + + Are you sure you want to reboot? + Weet u zeker dat u opnieuw wilt opstarten? + + + Disengage to Reboot + Deactiveer openpilot om opnieuw op te starten + + + Are you sure you want to power off? + Weet u zeker dat u wilt uitschakelen? + + + Disengage to Power Off + Deactiveer openpilot om uit te schakelen + + + + DriveStats + + Drives + Ritten + + + Hours + Uren + + + ALL TIME + TOTAAL + + + PAST WEEK + AFGELOPEN WEEK + + + KM + Km + + + Miles + Mijl + + + + DriverViewScene + + camera starting + Camera wordt gestart + + + + InputDialog + + Cancel + Annuleren + + + Need at least %n character(s)! + + Heeft minstens %n karakter nodig! + Heeft minstens %n karakters nodig! + + + + + Installer + + Installing... + Installeren... + + + Receiving objects: + Objecten ontvangen: + + + Resolving deltas: + Deltas verwerken: + + + Updating files: + Bestanden bijwerken: + + + + MapETA + + eta + eta + + + min + min + + + hr + uur + + + km + km + + + mi + mi + + + + MapInstructions + + km + km + + + m + m + + + mi + mi + + + ft + ft + + + + MapPanel + + Current Destination + Huidige Bestemming + + + CLEAR + LEEGMAKEN + + + Recent Destinations + Recente Bestemmingen + + + Try the Navigation Beta + Probeer de Navigatie Bèta + + + Get turn-by-turn directions displayed and more with a comma +prime subscription. Sign up now: https://connect.comma.ai + Krijg stapsgewijze routebeschrijving en meer met een comma +prime abonnement. Meld u nu aan: https://connect.comma.ai + + + No home +location set + Geen thuislocatie +ingesteld + + + No work +location set + Geen werklocatie +ingesteld + + + no recent destinations + geen recente bestemmingen + + + + MapWindow + + Map Loading + Kaart wordt geladen + + + Waiting for GPS + Wachten op GPS + + + + MultiOptionDialog + + Select + Selecteer + + + Cancel + Annuleren + + + + Networking + + Advanced + Geavanceerd + + + Enter password + Voer wachtwoord in + + + for "%1" + voor "%1" + + + Wrong password + Verkeerd wachtwoord + + + + OffroadHome + + UPDATE + UPDATE + + + ALERTS + WAARSCHUWINGEN + + + ALERT + WAARSCHUWING + + + + PairingPopup + + Pair your device to your comma account + Koppel uw apparaat aan uw comma-account + + + Go to https://connect.comma.ai on your phone + Ga naar https://connect.comma.ai op uw telefoon + + + Click "add new device" and scan the QR code on the right + Klik op "add new device" en scan de QR-code aan de rechterkant + + + Bookmark connect.comma.ai to your home screen to use it like an app + Voeg connect.comma.ai toe op uw startscherm om het als een app te gebruiken + + + + PrimeAdWidget + + Upgrade Now + Upgrade nu + + + Become a comma prime member at connect.comma.ai + Word een comma prime lid op connect.comma.ai + + + PRIME FEATURES: + PRIME BEVAT: + + + Remote access + Toegang op afstand + + + 1 year of storage + 1 jaar lang opslag + + + Developer perks + Voordelen voor ontwikkelaars + + + + PrimeUserWidget + + ✓ SUBSCRIBED + ✓ GEABONNEERD + + + comma prime + comma prime + + + CONNECT.COMMA.AI + CONNECT.COMMA.AI + + + COMMA POINTS + COMMA PUNTEN + + + + QObject + + Reboot + Opnieuw Opstarten + + + Exit + Afsluiten + + + dashcam + dashcam + + + openpilot + openpilot + + + %n minute(s) ago + + %n minuut geleden + %n minuten geleden + + + + %n hour(s) ago + + %n uur geleden + %n uur geleden + + + + %n day(s) ago + + %n dag geleden + %n dagen geleden + + + + + Reset + + Reset failed. Reboot to try again. + Opnieuw instellen mislukt. Start opnieuw op om opnieuw te proberen. + + + Are you sure you want to reset your device? + Weet u zeker dat u uw apparaat opnieuw wilt instellen? + + + Resetting device... + Apparaat opnieuw instellen... + + + System Reset + Systeemreset + + + System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. + Systeemreset geactiveerd. Druk op bevestigen om alle inhoud en instellingen te wissen. Druk op Annuleren om het opstarten te hervatten. + + + Cancel + Annuleren + + + Reboot + Opnieuw Opstarten + + + Confirm + Bevestigen + + + Unable to mount data partition. Press confirm to reset your device. + Kan gegevenspartitie niet koppelen. Druk op bevestigen om uw apparaat te resetten. + + + + RichTextDialog + + Ok + Ok + + + + SettingsWindow + + × + × + + + Device + Apparaat + + + Network + Netwerk + + + Toggles + Opties + + + Software + Software + + + Navigation + Navigatie + + + + Setup + + WARNING: Low Voltage + WAARCHUWING: Lage Spanning + + + Power your device in a car with a harness or proceed at your own risk. + Voorzie uw apparaat van stroom in een auto met een harnas (car harness) of ga op eigen risico verder. + + + Power off + Uitschakelen + + + Continue + Doorgaan + + + Getting Started + Aan de slag + + + Before we get on the road, let’s finish installation and cover some details. + Laten we, voordat we op pad gaan, de installatie afronden en enkele details bespreken. + + + Connect to Wi-Fi + Maak verbinding met Wi-Fi + + + Back + Terug + + + Continue without Wi-Fi + Doorgaan zonder Wi-Fi + + + Waiting for internet + Wachten op internet + + + Choose Software to Install + Kies Software om te Installeren + + + Dashcam + Dashcam + + + Custom Software + Andere Software + + + Enter URL + Voer URL in + + + for Custom Software + voor Andere Software + + + Downloading... + Downloaden... + + + Download Failed + Downloaden Mislukt + + + Ensure the entered URL is valid, and the device’s internet connection is good. + Zorg ervoor dat de ingevoerde URL geldig is en dat de internetverbinding van het apparaat goed is. + + + Reboot device + Apparaat opnieuw opstarten + + + Start over + Begin opnieuw + + + + SetupWidget + + Finish Setup + Installatie voltooien + + + Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. + Koppel uw apparaat met comma connect (connect.comma.ai) en claim uw comma prime-aanbieding. + + + Pair device + Apparaat koppelen + + + + Sidebar + + CONNECT + VERBINDING + + + OFFLINE + OFFLINE + + + ONLINE + ONLINE + + + ERROR + FOUT + + + TEMP + TEMP + + + HIGH + HOOG + + + GOOD + GOED + + + OK + OK + + + VEHICLE + VOERTUIG + + + NO + GEEN + + + PANDA + PANDA + + + GPS + GPS + + + SEARCH + ZOEKEN + + + -- + -- + + + Wi-Fi + Wi-Fi + + + ETH + ETH + + + 2G + 2G + + + 3G + 3G + + + LTE + 4G + + + 5G + 5G + + + + SoftwarePanel + + Git Branch + Git Branch + + + Git Commit + Git Commit + + + OS Version + OS Versie + + + Version + Versie + + + Last Update Check + Laatste Updatecontrole + + + The last time openpilot successfully checked for an update. The updater only runs while the car is off. + De laatste keer dat openpilot met succes heeft gecontroleerd op een update. De updater werkt alleen als de auto is uitgeschakeld. + + + Check for Update + Controleer op Updates + + + CHECKING + CONTROLEER + + + Switch Branch + Branch Verwisselen + + + ENTER + INVOEREN + + + The new branch will be pulled the next time the updater runs. + Tijdens de volgende update wordt de nieuwe branch opgehaald. + + + Enter branch name + Voer branch naam in + + + Uninstall %1 + Verwijder %1 + + + UNINSTALL + VERWIJDER + + + Are you sure you want to uninstall? + Weet u zeker dat u de installatie ongedaan wilt maken? + + + failed to fetch update + ophalen van update mislukt + + + CHECK + CONTROLEER + + + Updates are only downloaded while the car is off. + + + + Current Version + + + + Download + + + + Install Update + + + + INSTALL + + + + Target Branch + + + + SELECT + + + + Select a branch + + + + + SshControl + + SSH Keys + SSH Sleutels + + + Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. + Waarschuwing: dit geeft SSH toegang tot alle openbare sleutels in uw GitHub-instellingen. Voer nooit een andere GitHub-gebruikersnaam in dan die van uzelf. Een medewerker van comma zal u NOOIT vragen om zijn GitHub-gebruikersnaam toe te voegen. + + + ADD + TOEVOEGEN + + + Enter your GitHub username + Voer uw GitHub gebruikersnaam in + + + LOADING + LADEN + + + REMOVE + VERWIJDEREN + + + Username '%1' has no keys on GitHub + Gebruikersnaam '%1' heeft geen SSH sleutels op GitHub + + + Request timed out + Time-out van aanvraag + + + Username '%1' doesn't exist on GitHub + Gebruikersnaam '%1' bestaat niet op GitHub + + + + SshToggle + + Enable SSH + SSH Inschakelen + + + + TermsPage + + Terms & Conditions + Algemene Voorwaarden + + + Decline + Afwijzen + + + Scroll to accept + Scroll om te accepteren + + + Agree + Akkoord + + + + TogglesPanel + + Enable openpilot + openpilot Inschakelen + + + Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off. + Gebruik het openpilot-systeem voor adaptieve cruisecontrol en rijstrookassistentie. Uw aandacht is te allen tijde vereist om deze functie te gebruiken. Het wijzigen van deze instelling wordt van kracht wanneer de auto wordt uitgeschakeld. + + + Enable Lane Departure Warnings + Waarschuwingen bij Verlaten Rijstrook Inschakelen + + + Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). + Ontvang waarschuwingen om terug naar de rijstrook te sturen wanneer uw voertuig over een gedetecteerde rijstrookstreep drijft zonder dat de richtingaanwijzer wordt geactiveerd terwijl u harder rijdt dan 50 km/u (31 mph). + + + Use Metric System + Gebruik Metrisch Systeem + + + Display speed in km/h instead of mph. + Geef snelheid weer in km/u in plaats van mph. + + + Record and Upload Driver Camera + Opnemen en Uploaden van de Bestuurders Camera + + + Upload data from the driver facing camera and help improve the driver monitoring algorithm. + Upload gegevens van de bestuurders camera en help het algoritme voor het monitoren van de bestuurder te verbeteren. + + + Disengage on Accelerator Pedal + Deactiveren Met Gaspedaal + + + When enabled, pressing the accelerator pedal will disengage openpilot. + Indien ingeschakeld, zal het indrukken van het gaspedaal openpilot deactiveren. + + + Show ETA in 24h Format + Toon verwachte aankomsttijd in 24-uurs formaat + + + Use 24h format instead of am/pm + Gebruik 24-uurs formaat in plaats van AM en PM + + + Show Map on Left Side of UI + Toon kaart aan linkerkant van het scherm + + + Show map on left side when in split screen view. + Toon kaart links in gesplitste schermweergave. + + + openpilot Longitudinal Control + openpilot Longitudinale Controle + + + openpilot will disable the car's radar and will take over control of gas and brakes. Warning: this disables AEB! + openpilot zal de radar van de auto uitschakelen en de controle over gas en remmen overnemen. Waarschuwing: hierdoor wordt AEB (automatische noodrem) uitgeschakeld! + + + 🌮 End-to-end longitudinal (extremely alpha) 🌮 + + + + Experimental openpilot Longitudinal Control + + + + <b>WARNING: openpilot longitudinal control is experimental for this car and will disable AEB.</b> + + + + Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would. Super experimental. + + + + openpilot longitudinal control is not currently available for this car. + + + + Enable experimental longitudinal control to enable this. + + + + + Updater + + Update Required + Update Vereist + + + An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. + Een update van het besturingssysteem is vereist. Verbind je apparaat met Wi-Fi voor de snelste update-ervaring. De downloadgrootte is ongeveer 1 GB. + + + Connect to Wi-Fi + Maak verbinding met Wi-Fi + + + Install + Installeer + + + Back + Terug + + + Loading... + Aan het laden... + + + Reboot + Opnieuw Opstarten + + + Update failed + Update mislukt + + + + WifiUI + + Scanning for networks... + Scannen naar netwerken... + + + CONNECTING... + VERBINDEN... + + + FORGET + VERGETEN + + + Forget Wi-Fi Network "%1"? + Vergeet Wi-Fi Netwerk "%1"? + + + diff --git a/selfdrive/ui/translations/main_pl.ts b/selfdrive/ui/translations/main_pl.ts new file mode 100644 index 0000000000..4f8b03ef50 --- /dev/null +++ b/selfdrive/ui/translations/main_pl.ts @@ -0,0 +1,1124 @@ + + + + + AbstractAlert + + Close + Zamknij + + + Snooze Update + Zaktualizuj później + + + Reboot and Update + Uruchom ponownie i zaktualizuj + + + + AdvancedNetworking + + Back + Wróć + + + Enable Tethering + Włącz hotspot osobisty + + + Tethering Password + Hasło do hotspotu + + + EDIT + EDYTUJ + + + Enter new tethering password + Wprowadź nowe hasło do hotspotu + + + IP Address + Adres IP + + + Enable Roaming + Włącz roaming danych + + + APN Setting + Ustawienia APN + + + Enter APN + Wprowadź APN + + + leave blank for automatic configuration + Pozostaw puste, aby użyć domyślnej konfiguracji + + + Cellular Metered + + + + Prevent large data uploads when on a metered connection + + + + + AnnotatedCameraWidget + + km/h + km/h + + + mph + mph + + + MAX + MAX + + + SPEED + PRĘDKOŚĆ + + + LIMIT + OGRANICZENIE + + + + ConfirmationDialog + + Ok + Ok + + + Cancel + Anuluj + + + + DeclinePage + + You must accept the Terms and Conditions in order to use openpilot. + Aby korzystać z openpilota musisz zaakceptować regulamin. + + + Back + Wróć + + + Decline, uninstall %1 + Odrzuć, odinstaluj %1 + + + + DevicePanel + + Dongle ID + ID adaptera + + + N/A + N/A + + + Serial + Numer seryjny + + + Driver Camera + Kamera kierowcy + + + PREVIEW + PODGLĄD + + + Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) + Wyświetl podgląd z kamery skierowanej na kierowcę, aby upewnić się, że monitoring kierowcy ma dobry zakres widzenia. (pojazd musi być wyłączony) + + + Reset Calibration + Zresetuj kalibrację + + + RESET + ZRESETUJ + + + Are you sure you want to reset calibration? + Czy na pewno chcesz zresetować kalibrację? + + + Review Training Guide + Zapoznaj się z samouczkiem + + + REVIEW + ZAPOZNAJ SIĘ + + + Review the rules, features, and limitations of openpilot + Zapoznaj się z zasadami, funkcjami i ograniczeniami openpilota + + + Are you sure you want to review the training guide? + Czy na pewno chcesz się zapoznać z samouczkiem? + + + Regulatory + Regulacja + + + VIEW + WIDOK + + + Change Language + Zmień język + + + CHANGE + ZMIEŃ + + + Select a language + Wybierz język + + + Reboot + Uruchom ponownie + + + Power Off + Wyłącz + + + openpilot requires the device to be mounted within 4° left or right and within 5° up or 8° down. openpilot is continuously calibrating, resetting is rarely required. + openpilot wymaga, aby urządzenie było zamontowane z maksymalnym odchyłem 4° poziomo, 5° w górę oraz 8° w dół. openpilot jest ciągle kalibrowany, rzadko konieczne jest resetowania urządzenia. + + + Your device is pointed %1° %2 and %3° %4. + Twoje urządzenie jest skierowane %1° %2 oraz %3° %4. + + + down + w dół + + + up + w górę + + + left + w lewo + + + right + w prawo + + + Are you sure you want to reboot? + Czy na pewno chcesz uruchomić ponownie urządzenie? + + + Disengage to Reboot + Aby uruchomić ponownie, odłącz sterowanie + + + Are you sure you want to power off? + Czy na pewno chcesz wyłączyć urządzenie? + + + Disengage to Power Off + Aby wyłączyć urządzenie, odłącz sterowanie + + + + DriveStats + + Drives + Przejazdy + + + Hours + Godziny + + + ALL TIME + CAŁKOWICIE + + + PAST WEEK + OSTATNI TYDZIEŃ + + + KM + KM + + + Miles + Mile + + + + DriverViewScene + + camera starting + uruchamianie kamery + + + + InputDialog + + Cancel + Anuluj + + + Need at least %n character(s)! + + Wpisana wartość powinna składać się przynajmniej z %n znaku! + Wpisana wartość powinna skłądać się przynajmniej z %n znaków! + Wpisana wartość powinna skłądać się przynajmniej z %n znaków! + + + + + Installer + + Installing... + Instalowanie... + + + Receiving objects: + Odbieranie obiektów: + + + Resolving deltas: + Rozwiązywanie różnic: + + + Updating files: + Aktualizacja plików: + + + + MapETA + + eta + przewidywany czas + + + min + min + + + hr + godz + + + km + km + + + mi + mi + + + + MapInstructions + + km + km + + + m + m + + + mi + mi + + + ft + ft + + + + MapPanel + + Current Destination + Miejsce docelowe + + + CLEAR + WYCZYŚĆ + + + Recent Destinations + Ostatnie miejsca docelowe + + + Try the Navigation Beta + Wypróbuj nawigację w wersji beta + + + Get turn-by-turn directions displayed and more with a comma +prime subscription. Sign up now: https://connect.comma.ai + Odblokuj nawigację zakręt po zakęcie i wiele więcej subskrybując +comma prime. Zarejestruj się teraz: https://connect.comma.ai + + + No home +location set + Lokalizacja domu +nie została ustawiona + + + No work +location set + Miejsce pracy +nie zostało ustawione + + + no recent destinations + brak ostatnich miejsc docelowych + + + + MapWindow + + Map Loading + Ładowanie Mapy + + + Waiting for GPS + Oczekiwanie na sygnał GPS + + + + MultiOptionDialog + + Select + Wybierz + + + Cancel + Anuluj + + + + Networking + + Advanced + Zaawansowane + + + Enter password + Wprowadź hasło + + + for "%1" + do "%1" + + + Wrong password + Niepoprawne hasło + + + + OffroadHome + + UPDATE + UAKTUALNIJ + + + ALERTS + ALERTY + + + ALERT + ALERT + + + + PairingPopup + + Pair your device to your comma account + Sparuj swoje urzadzenie ze swoim kontem comma + + + Go to https://connect.comma.ai on your phone + Wejdź na stronę https://connect.comma.ai na swoim telefonie + + + Click "add new device" and scan the QR code on the right + Kliknij "add new device" i zeskanuj kod QR znajdujący się po prawej stronie + + + Bookmark connect.comma.ai to your home screen to use it like an app + Dodaj connect.comma.ai do zakładek na swoim ekranie początkowym, aby korzystać z niej jak z aplikacji + + + + PrimeAdWidget + + Upgrade Now + Uaktualnij teraz + + + Become a comma prime member at connect.comma.ai + Zostań członkiem comma prime na connect.comma.ai + + + PRIME FEATURES: + FUNKCJE PRIME: + + + Remote access + Zdalny dostęp + + + 1 year of storage + 1 rok przechowywania danych + + + Developer perks + Udogodnienia dla programistów + + + + PrimeUserWidget + + ✓ SUBSCRIBED + ✓ ZASUBSKRYBOWANO + + + comma prime + comma prime + + + CONNECT.COMMA.AI + CONNECT.COMMA.AI + + + COMMA POINTS + COMMA POINTS + + + + QObject + + Reboot + Uruchom Ponownie + + + Exit + Wyjdź + + + dashcam + wideorejestrator + + + openpilot + openpilot + + + %n minute(s) ago + + %n minutę temu + %n minuty temu + %n minut temu + + + + %n hour(s) ago + + % godzinę temu + %n godziny temu + %n godzin temu + + + + %n day(s) ago + + %n dzień temu + %n dni temu + %n dni temu + + + + + Reset + + Reset failed. Reboot to try again. + Wymazywanie zakończone niepowodzeniem. Aby spróbować ponownie, uruchom ponownie urządzenie. + + + Are you sure you want to reset your device? + Czy na pewno chcesz wymazać urządzenie? + + + Resetting device... + Wymazywanie urządzenia... + + + System Reset + Przywróć do ustawień fabrycznych + + + System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. + Przywracanie do ustawień fabrycznych. Wciśnij potwierdź, aby usunąć wszystkie dane oraz ustawienia. Wciśnij anuluj, aby wznowić uruchamianie. + + + Cancel + Anuluj + + + Reboot + Uruchom ponownie + + + Confirm + Potwiedź + + + Unable to mount data partition. Press confirm to reset your device. + Partycja nie została zamontowana poprawnie. Wciśnij potwierdź, aby uruchomić ponownie urządzenie. + + + + RichTextDialog + + Ok + Ok + + + + SettingsWindow + + × + x + + + Device + Urządzenie + + + Network + Sieć + + + Toggles + Przełączniki + + + Software + Oprogramowanie + + + Navigation + Nawigacja + + + + Setup + + WARNING: Low Voltage + OSTRZEŻENIE: Niskie Napięcie + + + Power your device in a car with a harness or proceed at your own risk. + Podłącz swoje urządzenie do zasilania poprzez podłączenienie go do pojazdu lub kontynuuj na własną odpowiedzialność. + + + Power off + Wyłącz + + + Continue + Kontynuuj + + + Getting Started + Zacznij + + + Before we get on the road, let’s finish installation and cover some details. + Zanim ruszysz w drogę, dokończ instalację i podaj kilka szczegółów. + + + Connect to Wi-Fi + Połącz z Wi-Fi + + + Back + Wróć + + + Continue without Wi-Fi + Kontynuuj bez połączenia z Wif-Fi + + + Waiting for internet + Oczekiwanie na połączenie sieciowe + + + Choose Software to Install + Wybierz oprogramowanie do instalacji + + + Dashcam + Wideorejestrator + + + Custom Software + Własne oprogramowanie + + + Enter URL + Wprowadź adres URL + + + for Custom Software + do własnego oprogramowania + + + Downloading... + Pobieranie... + + + Download Failed + Pobieranie nie powiodło się + + + Ensure the entered URL is valid, and the device’s internet connection is good. + Upewnij się, że wpisany adres URL jest poprawny, a połączenie internetowe działa poprawnie. + + + Reboot device + Uruchom ponownie + + + Start over + Zacznij od początku + + + + SetupWidget + + Finish Setup + Zakończ konfigurację + + + Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. + Sparuj swoje urządzenie z comma connect (connect.comma.ai) i wybierz swoją ofertę comma prime. + + + Pair device + Sparuj urządzenie + + + + Sidebar + + CONNECT + POŁĄCZENIE + + + OFFLINE + OFFLINE + + + ONLINE + ONLINE + + + ERROR + BŁĄD + + + TEMP + TEMP + + + HIGH + WYSOKA + + + GOOD + DOBRA + + + OK + OK + + + VEHICLE + POJAZD + + + NO + BRAK + + + PANDA + PANDA + + + GPS + GPS + + + SEARCH + SZUKAJ + + + -- + -- + + + Wi-Fi + Wi-FI + + + ETH + ETH + + + 2G + 2G + + + 3G + 3G + + + LTE + LTE + + + 5G + 5G + + + + SoftwarePanel + + Git Branch + Gałąź Git + + + Git Commit + Git commit + + + OS Version + Wersja systemu + + + Version + Wersja + + + Last Update Check + Ostatnie sprawdzenie aktualizacji + + + The last time openpilot successfully checked for an update. The updater only runs while the car is off. + Ostatni raz kiedy openpilot znalazł aktualizację. Aktualizator może być uruchomiony wyłącznie wtedy, kiedy pojazd jest wyłączony. + + + Check for Update + Sprawdź uaktualnienia + + + CHECKING + SPRAWDZANIE + + + Switch Branch + Zmień gąłąź + + + ENTER + WPROWADŹ + + + The new branch will be pulled the next time the updater runs. + Nowa gałąź będzie pobrana przy następnym uruchomieniu aktualizatora. + + + Enter branch name + Wprowadź nazwę gałęzi + + + Uninstall %1 + Odinstaluj %1 + + + UNINSTALL + ODINSTALUJ + + + Are you sure you want to uninstall? + Czy na pewno chcesz odinstalować? + + + failed to fetch update + pobieranie aktualizacji zakończone niepowodzeniem + + + CHECK + SPRAWDŹ + + + Updates are only downloaded while the car is off. + + + + Current Version + + + + Download + + + + Install Update + + + + INSTALL + + + + Target Branch + + + + SELECT + + + + Select a branch + + + + + SshControl + + SSH Keys + Klucze SSH + + + Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. + Ostrzeżenie: To spowoduje przekazanie dostępu do wszystkich Twoich publicznych kuczy z ustawień GitHuba. Nigdy nie wprowadzaj nazwy użytkownika innej niż swoja. Pracownik comma NIGDY nie poprosi o dodanie swojej nazwy uzytkownika. + + + ADD + DODAJ + + + Enter your GitHub username + Wpisz swoją nazwę użytkownika GitHub + + + LOADING + ŁADOWANIE + + + REMOVE + USUŃ + + + Username '%1' has no keys on GitHub + Użytkownik '%1' nie posiada żadnych kluczy na GitHubie + + + Request timed out + Limit czasu rządania + + + Username '%1' doesn't exist on GitHub + Użytkownik '%1' nie istnieje na GitHubie + + + + SshToggle + + Enable SSH + Włącz SSH + + + + TermsPage + + Terms & Conditions + Regulamin + + + Decline + Odrzuć + + + Scroll to accept + Przewiń w dół, aby zaakceptować + + + Agree + Zaakceptuj + + + + TogglesPanel + + Enable openpilot + Włącz openpilota + + + Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off. + Użyj openpilota do zachowania bezpiecznego odstępu między pojazdami i do asystowania w utrzymywaniu pasa ruchu. Twoja pełna uwaga jest wymagana przez cały czas korzystania z tej funkcji. Ustawienie to może być wdrożone wyłącznie wtedy, gdy pojazd jest wyłączony. + + + Enable Lane Departure Warnings + Włącz ostrzeganie przed zmianą pasa ruchu + + + Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). + Otrzymuj alerty o powrocie na właściwy pas, kiedy Twój pojazd przekroczy linię bez włączonego kierunkowskazu jadąc powyżej 50 km/h (31 mph). + + + Use Metric System + Korzystaj z systemu metrycznego + + + Display speed in km/h instead of mph. + Wyświetl prędkość w km/h zamiast mph. + + + Record and Upload Driver Camera + Nagraj i prześlij nagranie z kamery kierowcy + + + Upload data from the driver facing camera and help improve the driver monitoring algorithm. + Prześlij dane z kamery skierowanej na kierowcę i pomóż poprawiać algorytm monitorowania kierowcy. + + + Disengage on Accelerator Pedal + Odłącz poprzez naciśnięcie gazu + + + When enabled, pressing the accelerator pedal will disengage openpilot. + Po włączeniu, naciśnięcie na pedał gazu odłączy openpilota. + + + Show ETA in 24h Format + Pokaż oczekiwany czas dojazdu w formacie 24-godzinnym + + + Use 24h format instead of am/pm + Korzystaj z formatu 24-godzinnego zamiast 12-godzinnego + + + Show Map on Left Side of UI + Pokaż mapę po lewej stronie ekranu + + + Show map on left side when in split screen view. + Pokaż mapę po lewej stronie kiedy ekran jest podzielony. + + + openpilot Longitudinal Control + Kontrola wzdłużna openpilota + + + openpilot will disable the car's radar and will take over control of gas and brakes. Warning: this disables AEB! + openpilot wyłączy radar samochodu i przejmie kontrolę nad gazem i hamulcem. Ostrzeżenie: wyłączony zostanie system AEB! + + + 🌮 End-to-end longitudinal (extremely alpha) 🌮 + + + + Experimental openpilot Longitudinal Control + + + + <b>WARNING: openpilot longitudinal control is experimental for this car and will disable AEB.</b> + + + + Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would. Super experimental. + + + + openpilot longitudinal control is not currently available for this car. + + + + Enable experimental longitudinal control to enable this. + + + + + Updater + + Update Required + Wymagana Aktualizacja + + + An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. + Wymagana aktualizacja systemu operacyjnego. Aby przyspieszyć proces aktualizacji połącz swoje urzeądzenie do Wi-Fi. Rozmiar pobieranej paczki wynosi około 1GB. + + + Connect to Wi-Fi + Połącz się z Wi-Fi + + + Install + Zainstaluj + + + Back + Wróć + + + Loading... + Ładowanie... + + + Reboot + Uruchom ponownie + + + Update failed + Aktualizacja nie powiodła się + + + + WifiUI + + Scanning for networks... + Wyszukiwanie sieci... + + + CONNECTING... + ŁĄCZENIE... + + + FORGET + ZAPOMNIJ + + + Forget Wi-Fi Network "%1"? + Czy chcesz zapomnieć sieć "%1"? + + + diff --git a/selfdrive/ui/translations/main_pt-BR.ts b/selfdrive/ui/translations/main_pt-BR.ts new file mode 100644 index 0000000000..105d6f77f0 --- /dev/null +++ b/selfdrive/ui/translations/main_pt-BR.ts @@ -0,0 +1,1111 @@ + + + + + AbstractAlert + + Close + Fechar + + + Snooze Update + Adiar Atualização + + + Reboot and Update + Reiniciar e Atualizar + + + + AdvancedNetworking + + Back + Voltar + + + Enable Tethering + Ativar Tether + + + Tethering Password + Senha Tethering + + + EDIT + EDITAR + + + Enter new tethering password + Insira nova senha tethering + + + IP Address + Endereço IP + + + Enable Roaming + Ativar Roaming + + + APN Setting + APN Config + + + Enter APN + Insira APN + + + leave blank for automatic configuration + deixe em branco para configuração automática + + + Cellular Metered + Plano de Dados Limitado + + + Prevent large data uploads when on a metered connection + Evite grandes uploads de dados quando estiver em uma conexão limitada + + + + AnnotatedCameraWidget + + km/h + km/h + + + mph + mph + + + MAX + LIMITE + + + SPEED + MAX + + + LIMIT + VELO + + + + ConfirmationDialog + + Ok + OK + + + Cancel + Cancelar + + + + DeclinePage + + You must accept the Terms and Conditions in order to use openpilot. + Você precisa aceitar os Termos e Condições para utilizar openpilot. + + + Back + Voltar + + + Decline, uninstall %1 + Rejeitar, desintalar %1 + + + + DevicePanel + + Dongle ID + Dongle ID + + + N/A + N/A + + + Serial + Serial + + + Driver Camera + Câmera voltada para o Motorista + + + PREVIEW + PREVISUAL + + + Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) + Pré-visualizar a câmera voltada para o motorista para garantir que monitor tem uma boa visibilidade (veículo precisa estar desligado) + + + Reset Calibration + Resetar Calibragem + + + RESET + RESET + + + Are you sure you want to reset calibration? + Tem certeza que quer resetar a calibragem? + + + Review Training Guide + Revisar Guia de Treinamento + + + REVIEW + REVISAR + + + Review the rules, features, and limitations of openpilot + Revisar regras, aprimoramentos e limitações do openpilot + + + Are you sure you want to review the training guide? + Tem certeza que quer rever o treinamento? + + + Regulatory + Regulatório + + + VIEW + VER + + + Change Language + Alterar Idioma + + + CHANGE + ALTERAR + + + Select a language + Selecione o Idioma + + + Reboot + Reiniciar + + + Power Off + Desligar + + + openpilot requires the device to be mounted within 4° left or right and within 5° up or 8° down. openpilot is continuously calibrating, resetting is rarely required. + o openpilot requer que o dispositivo seja montado dentro de 4° esquerda ou direita e dentro de 5° para cima ou 8° para baixo. o openpilot está continuamente calibrando, resetar raramente é necessário. + + + Your device is pointed %1° %2 and %3° %4. + Seu dispositivo está montado %1° %2 e %3° %4. + + + down + baixo + + + up + cima + + + left + esquerda + + + right + direita + + + Are you sure you want to reboot? + Tem certeza que quer reiniciar? + + + Disengage to Reboot + Desacione para Reiniciar + + + Are you sure you want to power off? + Tem certeza que quer desligar? + + + Disengage to Power Off + Desacione para Desligar + + + Reset + Resetar + + + Review + Revisar + + + + DriveStats + + Drives + Dirigidas + + + Hours + Horas + + + ALL TIME + TOTAL + + + PAST WEEK + SEMANA PASSADA + + + KM + KM + + + Miles + Milhas + + + + DriverViewScene + + camera starting + câmera iniciando + + + + ExperimentalModeButton + + EXPERIMENTAL MODE ON + MODO EXPERIMENTAL ATIVADO + + + CHILL MODE ON + MODO CHILL ATIVADO + + + + InputDialog + + Cancel + Cancelar + + + Need at least %n character(s)! + + Necessita no mínimo %n caractere! + Necessita no mínimo %n caracteres! + + + + + Installer + + Installing... + Instalando... + + + Receiving objects: + Recebendo objetos: + + + Resolving deltas: + Resolvendo deltas: + + + Updating files: + Atualizando arquivos: + + + + MapETA + + eta + eta + + + min + min + + + hr + hr + + + km + km + + + mi + mi + + + + MapInstructions + + km + km + + + m + m + + + mi + milha + + + ft + pés + + + + MapPanel + + Current Destination + Destino Atual + + + CLEAR + LIMPAR + + + Recent Destinations + Destinos Recentes + + + Try the Navigation Beta + Experimente a Navegação Beta + + + Get turn-by-turn directions displayed and more with a comma +prime subscription. Sign up now: https://connect.comma.ai + Obtenha instruções passo a passo exibidas e muito mais com +uma assinatura prime Inscreva-se agora: https://connect.comma.ai + + + No home +location set + Sem local +residência definido + + + No work +location set + Sem local de +trabalho definido + + + no recent destinations + sem destinos recentes + + + + MapWindow + + Map Loading + Carregando Mapa + + + Waiting for GPS + Esperando por GPS + + + + MultiOptionDialog + + Select + Selecione + + + Cancel + Cancelar + + + + Networking + + Advanced + Avançado + + + Enter password + Insira a senha + + + for "%1" + para "%1" + + + Wrong password + Senha incorreta + + + + OffroadHome + + UPDATE + ATUALIZAÇÃO + + + ALERTS + ALERTAS + + + ALERT + ALERTA + + + + PairingPopup + + Pair your device to your comma account + Pareie seu dispositivo à sua conta comma + + + Go to https://connect.comma.ai on your phone + navegue até https://connect.comma.ai no seu telefone + + + Click "add new device" and scan the QR code on the right + Clique "add new device" e escaneie o QR code a seguir + + + Bookmark connect.comma.ai to your home screen to use it like an app + Salve connect.comma.ai como sua página inicial para utilizar como um app + + + + ParamControl + + Cancel + Cancelar + + + Enable + Ativar + + + + PrimeAdWidget + + Upgrade Now + Atualizar Agora + + + Become a comma prime member at connect.comma.ai + Torne-se um membro comma prime em connect.comma.ai + + + PRIME FEATURES: + BENEFÍCIOS PRIME: + + + Remote access + Acesso remoto + + + 1 year of storage + 1 ano de armazenamento + + + Developer perks + Benefícios para desenvolvedor + + + + PrimeUserWidget + + ✓ SUBSCRIBED + ✓ INSCRITO + + + comma prime + comma prime + + + CONNECT.COMMA.AI + CONNECT.COMMA.AI + + + COMMA POINTS + PONTOS COMMA + + + + QObject + + Reboot + Reiniciar + + + Exit + Sair + + + dashcam + dashcam + + + openpilot + openpilot + + + %n minute(s) ago + + há %n minuto + há %n minutos + + + + %n hour(s) ago + + há %n hora + há %n horas + + + + %n day(s) ago + + há %n dia + há %n dias + + + + + Reset + + Reset failed. Reboot to try again. + Reset falhou. Reinicie para tentar novamente. + + + Are you sure you want to reset your device? + Tem certeza que quer resetar seu dispositivo? + + + Resetting device... + Resetando dispositivo... + + + System Reset + Resetar Sistema + + + System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. + Solicitado reset do sistema. Confirme para apagar todo conteúdo e configurações. Aperte cancelar para continuar boot. + + + Cancel + Cancelar + + + Reboot + Reiniciar + + + Confirm + Confirmar + + + Unable to mount data partition. Press confirm to reset your device. + Não foi possível montar a partição de dados. Pressione confirmar para resetar seu dispositivo. + + + + SettingsWindow + + × + × + + + Device + Dispositivo + + + Network + Rede + + + Toggles + Ajustes + + + Software + Software + + + Navigation + Navegação + + + + Setup + + WARNING: Low Voltage + ALERTA: Baixa Voltagem + + + Power your device in a car with a harness or proceed at your own risk. + Ligue seu dispositivo em um carro com um chicote ou prossiga por sua conta e risco. + + + Power off + Desligar + + + Continue + Continuar + + + Getting Started + Começando + + + Before we get on the road, let’s finish installation and cover some details. + Antes de pegarmos a estrada, vamos terminar a instalação e cobrir alguns detalhes. + + + Connect to Wi-Fi + Conectar ao Wi-Fi + + + Back + Voltar + + + Continue without Wi-Fi + Continuar sem Wi-Fi + + + Waiting for internet + Esperando pela internet + + + Choose Software to Install + Escolher Software para Instalar + + + Dashcam + Dashcam + + + Custom Software + Sofware Customizado + + + Enter URL + Preencher URL + + + for Custom Software + para o Software Customizado + + + Downloading... + Baixando... + + + Download Failed + Download Falhou + + + Ensure the entered URL is valid, and the device’s internet connection is good. + Garanta que a URL inserida é valida, e uma boa conexão à internet. + + + Reboot device + Reiniciar Dispositivo + + + Start over + Inicializar + + + + SetupWidget + + Finish Setup + Concluir + + + Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. + Pareie seu dispositivo com comma connect (connect.comma.ai) e reivindique sua oferta de comma prime. + + + Pair device + Parear dispositivo + + + + Sidebar + + CONNECT + CONEXÃO + + + OFFLINE + OFFLINE + + + ONLINE + ONLINE + + + ERROR + ERRO + + + TEMP + TEMP + + + HIGH + ALTA + + + GOOD + BOA + + + OK + OK + + + VEHICLE + VEÍCULO + + + NO + SEM + + + PANDA + PANDA + + + GPS + GPS + + + SEARCH + PROCURA + + + -- + -- + + + Wi-Fi + Wi-Fi + + + ETH + ETH + + + 2G + 2G + + + 3G + 3G + + + LTE + LTE + + + 5G + 5G + + + + SoftwarePanel + + Updates are only downloaded while the car is off. + Atualizações baixadas durante o motor desligado. + + + Current Version + Versao Atual + + + Download + Download + + + Install Update + Instalar Atualização + + + INSTALL + INSTALAR + + + Target Branch + Alterar Branch + + + SELECT + SELECIONE + + + Select a branch + Selecione uma branch + + + UNINSTALL + DESINSTAL + + + Uninstall %1 + Desintalar o %1 + + + Are you sure you want to uninstall? + Tem certeza que quer desinstalar? + + + CHECK + VERIFICAR + + + Uninstall + Desinstalar + + + + SshControl + + SSH Keys + Chave SSH + + + Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. + Aviso: isso concede acesso SSH a todas as chaves públicas nas configurações do GitHub. Nunca insira um nome de usuário do GitHub que não seja o seu. Um funcionário da comma NUNCA pedirá que você adicione seu nome de usuário do GitHub. + + + ADD + ADICIONAR + + + Enter your GitHub username + Insira seu nome de usuário do GitHub + + + LOADING + CARREGANDO + + + REMOVE + REMOVER + + + Username '%1' has no keys on GitHub + Usuário "%1” não possui chaves no GitHub + + + Request timed out + A solicitação expirou + + + Username '%1' doesn't exist on GitHub + Usuário '%1' não existe no GitHub + + + + SshToggle + + Enable SSH + Habilitar SSH + + + + TermsPage + + Terms & Conditions + Termos & Condições + + + Decline + Declinar + + + Scroll to accept + Role a tela para aceitar + + + Agree + Concordo + + + + TogglesPanel + + Enable openpilot + Ativar openpilot + + + Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off. + Use o sistema openpilot para controle de cruzeiro adaptativo e assistência ao motorista de manutenção de faixa. Sua atenção é necessária o tempo todo para usar esse recurso. A alteração desta configuração tem efeito quando o carro é desligado. + + + Enable Lane Departure Warnings + Ativar Avisos de Saída de Faixa + + + Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). + Receba alertas para voltar para a pista se o seu veículo sair da faixa e a seta não tiver sido acionada previamente quando em velocidades superiores a 50 km/h. + + + Use Metric System + Usar Sistema Métrico + + + Display speed in km/h instead of mph. + Exibir velocidade em km/h invés de mph. + + + Record and Upload Driver Camera + Gravar e Upload Câmera Motorista + + + Upload data from the driver facing camera and help improve the driver monitoring algorithm. + Upload dados da câmera voltada para o motorista e ajude a melhorar o algoritmo de monitoramentor. + + + Experimental openpilot Longitudinal Control + Controle longitudinal experimental openpilot + + + Disengage on Accelerator Pedal + Desacionar Com Pedal Do Acelerador + + + When enabled, pressing the accelerator pedal will disengage openpilot. + Quando ativado, pressionar o pedal do acelerador desacionará o openpilot. + + + Show ETA in 24h Format + Mostrar ETA em formato 24h + + + Use 24h format instead of am/pm + Use o formato 24h em vez de am/pm + + + Show Map on Left Side of UI + Exibir Mapa no Lado Esquerdo + + + Show map on left side when in split screen view. + Exibir mapa do lado esquerdo quando a tela for dividida. + + + Experimental Mode + Modo Experimental + + + WARNING: openpilot longitudinal control is experimental for this car and will disable Automatic Emergency Braking (AEB). + ATENÇÃO: o controle longitudinal do openpilot é experimental para este carro e desativará a Frenagem Automática de Emergência (AEB). + + + On this car, openpilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when using experimental openpilot longitudinal control. + Neste carro o penpilot por padrão utiliza o ACC nativo do veículo ao invés de controlar longitudinalmente. Ative isto para mudar para o controle longitudinal do openpilot. Ativar o Modo Experimental é recomendado quando em uso do controle longitudinal experimental do openpilot. + + + Experimental mode is currently unavailable on this car, since the car's stock ACC is used for longitudinal control. + O Modo Experimental está atualmente indisponível para este carro, já que o ACC original do carro é usado para controle longitudinal. + + + Enable experimental longitudinal control to allow experimental mode. + Ative o controle longitudinal experimental para permitir o modo experimental. + + + openpilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: + openpilot por padrão funciona em <b>modo chill</b>. modo Experimental ativa <b>recursos de nível-alfa</b> que não estão prontos para o modo chill. Recursos experimentais estão listados abaixo: + + + 🌮 End-to-End Longitudinal Control 🌮 + 🌮 Controle Longitudinal de Ponta a Ponta 🌮 + + + Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. + Deixe o modelo de IA controlar o acelerador e os freios. O openpilot irá dirigir como pensa que um humano faria, incluindo parar em sinais vermelhos e sinais de parada. Uma vez que o modelo de condução decide a velocidade a conduzir, a velocidade definida apenas funcionará como um limite superior. Este é um recurso de qualidade alfa; erros devem ser esperados. + + + New Driving Visualization + Nova Visualização de Condução + + + The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. + A visualização da direção fará a transição para a câmera grande angular voltada para a estrada em baixas velocidades para mostrar melhor algumas curvas. O logotipo do modo Experimental também será exibido no canto superior direito. + + + + Updater + + Update Required + Atualização Necessária + + + An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. + Uma atualização do sistema operacional é necessária. Conecte seu dispositivo ao Wi-Fi para a experiência de atualização mais rápida. O tamanho do download é de aproximadamente 1GB. + + + Connect to Wi-Fi + Conecte-se ao Wi-Fi + + + Install + Instalar + + + Back + Voltar + + + Loading... + Carregando... + + + Reboot + Reiniciar + + + Update failed + Falha na atualização + + + + WifiUI + + Scanning for networks... + Procurando redes... + + + CONNECTING... + CONECTANDO... + + + FORGET + ESQUECER + + + Forget Wi-Fi Network "%1"? + Esquecer Rede Wi-Fi "%1"? + + + Forget + Esquecer + + + diff --git a/selfdrive/ui/translations/main_th.ts b/selfdrive/ui/translations/main_th.ts new file mode 100644 index 0000000000..0de0ba5f9a --- /dev/null +++ b/selfdrive/ui/translations/main_th.ts @@ -0,0 +1,1056 @@ + + + + + AbstractAlert + + Close + ปิด + + + Snooze Update + เลื่อนการอัปเดต + + + Reboot and Update + รีบูตและอัปเดต + + + + AdvancedNetworking + + Back + ย้อนกลับ + + + Enable Tethering + ปล่อยฮอตสปอต + + + Tethering Password + รหัสผ่านฮอตสปอต + + + EDIT + แก้ไข + + + Enter new tethering password + ป้อนรหัสผ่านฮอตสปอตใหม่ + + + IP Address + หมายเลขไอพี + + + Enable Roaming + เปิดใช้งานโรมมิ่ง + + + APN Setting + ตั้งค่า APN + + + Enter APN + ป้อนค่า APN + + + leave blank for automatic configuration + เว้นว่างเพื่อตั้งค่าอัตโนมัติ + + + Cellular Metered + ลดการส่งข้อมูลผ่านเซลลูล่าร์ + + + Prevent large data uploads when on a metered connection + ปิดการอัพโหลดข้อมูลขนาดใหญ่เมื่อเชื่อมต่อผ่านเซลลูล่าร์ + + + + AnnotatedCameraWidget + + km/h + กม./ชม. + + + mph + ไมล์/ชม. + + + MAX + สูงสุด + + + SPEED + ความเร็ว + + + LIMIT + จำกัด + + + + ConfirmationDialog + + Ok + ตกลง + + + Cancel + ยกเลิก + + + + DeclinePage + + You must accept the Terms and Conditions in order to use openpilot. + คุณต้องยอมรับเงื่อนไขและข้อตกลง เพื่อใช้งาน openpilot + + + Back + ย้อนกลับ + + + Decline, uninstall %1 + ปฏิเสธ และถอนการติดตั้ง %1 + + + + DevicePanel + + Dongle ID + Dongle ID + + + N/A + ไม่มี + + + Serial + ซีเรียล + + + Driver Camera + กล้องฝั่งคนขับ + + + PREVIEW + แสดงภาพ + + + Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) + ดูภาพตัวอย่างกล้องที่หันเข้าหาคนขับเพื่อให้แน่ใจว่าการตรวจสอบคนขับมีทัศนวิสัยที่ดี (รถต้องดับเครื่องยนต์) + + + Reset Calibration + รีเซ็ตการคาลิเบรท + + + RESET + รีเซ็ต + + + Are you sure you want to reset calibration? + คุณแน่ใจหรือไม่ว่าต้องการรีเซ็ตการคาลิเบรท? + + + Review Training Guide + ทบทวนคู่มือการใช้งาน + + + REVIEW + ทบทวน + + + Review the rules, features, and limitations of openpilot + ตรวจสอบกฎ คุณสมบัติ และข้อจำกัดของ openpilot + + + Are you sure you want to review the training guide? + คุณแน่ใจหรือไม่ว่าต้องการทบทวนคู่มือการใช้งาน? + + + Regulatory + ระเบียบข้อบังคับ + + + VIEW + ดู + + + Change Language + เปลี่ยนภาษา + + + CHANGE + เปลี่ยน + + + Select a language + เลือกภาษา + + + Reboot + รีบูต + + + Power Off + ปิดเครื่อง + + + openpilot requires the device to be mounted within 4° left or right and within 5° up or 8° down. openpilot is continuously calibrating, resetting is rarely required. + openpilot กำหนดให้ติดตั้งอุปกรณ์ โดยสามารถเอียงด้านซ้ายหรือขวาไม่เกิน 4° และเอียงขึ้นด้านบนไม่เกิน 5° หรือเอียงลงด้านล่างไม่เกิน 8° openpilot ทำการคาลิเบรทอย่างต่อเนื่อง แทบจะไม่จำเป็นต้องทำการรีเซ็ตการคาลิเบรท + + + Your device is pointed %1° %2 and %3° %4. + อุปกรณ์ของคุณเอียงไปทาง %2 %1° และ %4 %3° + + + down + ด้านล่าง + + + up + ด้านบน + + + left + ด้านซ้าย + + + right + ด้านขวา + + + Are you sure you want to reboot? + คุณแน่ใจหรือไม่ว่าต้องการรีบูต? + + + Disengage to Reboot + ยกเลิกระบบช่วยขับเพื่อรีบูต + + + Are you sure you want to power off? + คุณแน่ใจหรือไม่ว่าต้องการปิดเครื่อง? + + + Disengage to Power Off + ยกเลิกระบบช่วยขับเพื่อปิดเครื่อง + + + + DriveStats + + Drives + การขับขี่ + + + Hours + ชั่วโมง + + + ALL TIME + ทั้งหมด + + + PAST WEEK + สัปดาห์ที่ผ่านมา + + + KM + กิโลเมตร + + + Miles + ไมล์ + + + + DriverViewScene + + camera starting + กำลังเปิดกล้อง + + + + InputDialog + + Cancel + ยกเลิก + + + Need at least %n character(s)! + + ต้องการอย่างน้อย %n ตัวอักษร! + + + + + Installer + + Installing... + กำลังติดตั้ง... + + + Receiving objects: + กำลังรับข้อมูล: + + + Resolving deltas: + การแก้ไขเดลต้า: + + + Updating files: + กำลังอัปเดตไฟล์: + + + + MapETA + + eta + eta + + + min + นาที + + + hr + ชม. + + + km + กม. + + + mi + ไมล์ + + + + MapInstructions + + km + กม. + + + m + ม. + + + mi + ไมล์ + + + ft + ฟุต + + + + MapPanel + + Current Destination + ปลายทางปัจจุบัน + + + CLEAR + ล้างข้อมูล + + + Recent Destinations + ปลายทางล่าสุด + + + Try the Navigation Beta + ลองใช้ระบบนำทาง (เบต้า) + + + Get turn-by-turn directions displayed and more with a comma +prime subscription. Sign up now: https://connect.comma.ai + รับการแสดงเส้นทางแบบเลี้ยวต่อเลี้ยว และอื่นๆ ด้วยการสมัครบริการ +comma prime สมัครเลย: https://connect.comma.ai + + + No home +location set + ยังไม่ได้กำหนด +ตำแหน่งของบ้าน + + + No work +location set + ยังไม่ได้กำหนด +ตำแหน่งของที่ทำงาน + + + no recent destinations + ไม่พบปลายทางล่าสุด + + + + MapWindow + + Map Loading + กำลังโหลดแผนที่ + + + Waiting for GPS + กำลังรอสัญญาณ GPS + + + + MultiOptionDialog + + Select + เลือก + + + Cancel + ยกเลิก + + + + Networking + + Advanced + ขั้นสูง + + + Enter password + ใส่รหัสผ่าน + + + for "%1" + สำหรับ "%1" + + + Wrong password + รหัสผ่านผิด + + + + OffroadHome + + UPDATE + อัปเดต + + + ALERTS + การแจ้งเตือน + + + ALERT + การแจ้งเตือน + + + + PairingPopup + + Pair your device to your comma account + จับคู่อุปกรณ์ของคุณกับบัญชี comma ของคุณ + + + Go to https://connect.comma.ai on your phone + ไปที่ https://connect.comma.ai ด้วยโทรศัพท์ของคุณ + + + Click "add new device" and scan the QR code on the right + กดที่ "add new device" และสแกนคิวอาร์โค้ดทางด้านขวา + + + Bookmark connect.comma.ai to your home screen to use it like an app + จดจำ connect.comma.ai โดยการเพิ่มไปยังหน้าจอโฮม เพื่อใช้งานเหมือนเป็นแอปพลิเคชัน + + + + PrimeAdWidget + + Upgrade Now + อัพเกรดเดี๋ยวนี้ + + + Become a comma prime member at connect.comma.ai + สมัครสมาชิก comma prime ได้ที่ connect.comma.ai + + + PRIME FEATURES: + คุณสมบัติของ PRIME: + + + Remote access + การเข้าถึงระยะไกล + + + 1 year of storage + จัดเก็บข้อมูลนาน 1 ปี + + + Developer perks + สิทธิพิเศษสำหรับนักพัฒนา + + + + PrimeUserWidget + + ✓ SUBSCRIBED + ✓ สมัครสำเร็จ + + + comma prime + comma prime + + + CONNECT.COMMA.AI + CONNECT.COMMA.AI + + + COMMA POINTS + คะแนน COMMA + + + + QObject + + Reboot + รีบูต + + + Exit + ปิด + + + dashcam + กล้องติดรถยนต์ + + + openpilot + openpilot + + + %n minute(s) ago + + %n นาทีที่แล้ว + + + + %n hour(s) ago + + %n ชั่วโมงที่แล้ว + + + + %n day(s) ago + + %n วันที่แล้ว + + + + + Reset + + Reset failed. Reboot to try again. + การรีเซ็ตล้มเหลว รีบูตเพื่อลองอีกครั้ง + + + Are you sure you want to reset your device? + คุณแน่ใจหรือไม่ว่าต้องการรีเซ็ตอุปกรณ์? + + + Resetting device... + กำลังรีเซ็ตอุปกรณ์... + + + System Reset + รีเซ็ตระบบ + + + System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. + มีการสั่งรีเซ็ตระบบ กดยืนยันเพื่อลบข้อมูลและการตั้งค่าทั้งหมด กดยกเลิกเพื่อบูตเข้าระบบตามปกติ + + + Cancel + ยกเลิก + + + Reboot + รีบูต + + + Confirm + ยืนยัน + + + Unable to mount data partition. Press confirm to reset your device. + ไม่สามารถเมานต์พาร์ติชั่นข้อมูล กดยืนยันเพื่อรีเซ็ตอุปกรณ์ของคุณ + + + + RichTextDialog + + Ok + ตกลง + + + + SettingsWindow + + × + × + + + Device + อุปกรณ์ + + + Network + เครือข่าย + + + Toggles + ตัวเลือก + + + Software + ซอฟต์แวร์ + + + Navigation + การนำทาง + + + + Setup + + WARNING: Low Voltage + คำเตือน: แรงดันแบตเตอรี่ต่ำ + + + Power your device in a car with a harness or proceed at your own risk. + โปรดต่ออุปกรณ์ของคุณเข้ากับสายควบคุมในรถยนต์ หรือดำเนินการด้วยความเสี่ยงของคุณเอง + + + Power off + ปิดเครื่อง + + + Continue + ดำเนินการต่อ + + + Getting Started + เริ่มกันเลย + + + Before we get on the road, let’s finish installation and cover some details. + ก่อนออกเดินทาง เรามาทำการติดตั้งซอฟต์แวร์ และตรวจสอบการตั้งค่า + + + Connect to Wi-Fi + เชื่อมต่อ Wi-Fi + + + Back + ย้อนกลับ + + + Continue without Wi-Fi + ดำเนินการต่อโดยไม่ใช้ Wi-Fi + + + Waiting for internet + กำลังรอสัญญาณอินเตอร์เน็ต + + + Choose Software to Install + เลือกซอฟต์แวร์ที่จะติดตั้ง + + + Dashcam + กล้องติดรถยนต์ + + + Custom Software + ซอฟต์แวร์ที่กำหนดเอง + + + Enter URL + ป้อน URL + + + for Custom Software + สำหรับซอฟต์แวร์ที่กำหนดเอง + + + Downloading... + กำลังดาวน์โหลด... + + + Download Failed + ดาวน์โหลดล้มเหลว + + + Ensure the entered URL is valid, and the device’s internet connection is good. + ตรวจสอบให้แน่ใจว่า URL ที่ป้อนนั้นถูกต้อง และอุปกรณ์เชื่อมต่ออินเทอร์เน็ตอยู่ + + + Reboot device + รีบูตอุปกรณ์ + + + Start over + เริ่มต้นใหม่ + + + + SetupWidget + + Finish Setup + ตั้งค่าเสร็จสิ้น + + + Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. + จับคู่อุปกรณ์ของคุณกับ comma connect (connect.comma.ai) และรับข้อเสนอ comma prime ของคุณ + + + Pair device + จับคู่อุปกรณ์ + + + + Sidebar + + CONNECT + เชื่อมต่อ + + + OFFLINE + ออฟไลน์ + + + ONLINE + ออนไลน์ + + + ERROR + เกิดข้อผิดพลาด + + + TEMP + อุณหภูมิ + + + HIGH + สูง + + + GOOD + ดี + + + OK + พอใช้ + + + VEHICLE + รถยนต์ + + + NO + ไม่พบ + + + PANDA + PANDA + + + GPS + จีพีเอส + + + SEARCH + ค้นหา + + + -- + -- + + + Wi-Fi + Wi-Fi + + + ETH + ETH + + + 2G + 2G + + + 3G + 3G + + + LTE + LTE + + + 5G + 5G + + + + SoftwarePanel + + Uninstall %1 + ถอนการติดตั้ง %1 + + + UNINSTALL + ถอนการติดตั้ง + + + Are you sure you want to uninstall? + คุณแน่ใจหรือไม่ว่าต้องการถอนการติดตั้ง? + + + CHECK + ตรวจสอบ + + + Updates are only downloaded while the car is off. + ตัวอัปเดตจะดำเนินการดาวน์โหลดเมื่อรถดับเครื่องยนต์อยู่เท่านั้น + + + Current Version + เวอร์ชั่นปัจจุบัน + + + Download + ดาวน์โหลด + + + Install Update + ติดตั้งตัวอัปเดต + + + INSTALL + ติดตั้ง + + + Target Branch + Branch ที่เลือก + + + SELECT + เลือก + + + Select a branch + เลือก Branch + + + + SshControl + + SSH Keys + คีย์ SSH + + + Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. + คำเตือน: สิ่งนี้ให้สิทธิ์ SSH เข้าถึงคีย์สาธารณะทั้งหมดใน GitHub ของคุณ อย่าป้อนชื่อผู้ใช้ GitHub อื่นนอกเหนือจากของคุณเอง พนักงาน comma จะไม่ขอให้คุณเพิ่มชื่อผู้ใช้ GitHub ของพวกเขา + + + ADD + เพิ่ม + + + Enter your GitHub username + ป้อนชื่อผู้ใช้ GitHub ของคุณ + + + LOADING + กำลังโหลด + + + REMOVE + ลบ + + + Username '%1' has no keys on GitHub + ชื่อผู้ใช้ '%1' ไม่มีคีย์บน GitHub + + + Request timed out + ตรวจสอบไม่สำเร็จ เนื่องจากใช้เวลามากเกินไป + + + Username '%1' doesn't exist on GitHub + ไม่พบชื่อผู้ใช้ '%1' บน GitHub + + + + SshToggle + + Enable SSH + เปิดใช้งาน SSH + + + + TermsPage + + Terms & Conditions + ข้อตกลงและเงื่อนไข + + + Decline + ปฏิเสธ + + + Scroll to accept + เลื่อนเพื่อตอบรับข้อตกลง + + + Agree + ยอมรับ + + + + TogglesPanel + + Enable openpilot + เปิดใช้งาน openpilot + + + Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off. + ใช้ระบบ openpilot สำหรับระบบควบคุมความเร็วอัตโนมัติ และระบบช่วยควบคุมรถให้อยู่ในเลน คุณจำเป็นต้องให้ความสนใจตลอดเวลาที่ใช้คุณสมบัตินี้ การเปลี่ยนการตั้งค่านี้จะมีผลเมื่อคุณดับเครื่องยนต์ + + + Enable Lane Departure Warnings + เปิดใช้งานการเตือนการออกนอกเลน + + + Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). + รับการแจ้งเตือนให้เลี้ยวกลับเข้าเลนเมื่อรถของคุณตรวจพบการข้ามช่องจราจรโดยไม่เปิดสัญญาณไฟเลี้ยวในขณะขับขี่ที่ความเร็วเกิน 31 ไมล์ต่อชั่วโมง (50 กม./ชม) + + + Use Metric System + ใช้ระบบเมตริก + + + Display speed in km/h instead of mph. + แสดงความเร็วเป็น กม./ชม. แทน ไมล์/ชั่วโมง + + + Record and Upload Driver Camera + บันทึกและอัปโหลดภาพจากกล้องคนขับ + + + Upload data from the driver facing camera and help improve the driver monitoring algorithm. + อัปโหลดข้อมูลจากกล้องที่หันหน้าไปทางคนขับ และช่วยปรับปรุงอัลกอริธึมการตรวจสอบผู้ขับขี่ + + + Disengage on Accelerator Pedal + ยกเลิกระบบช่วยขับเมื่อเหยียบคันเร่ง + + + When enabled, pressing the accelerator pedal will disengage openpilot. + เมื่อเปิดใช้งาน การกดแป้นคันเร่งจะเป็นการยกเลิกระบบช่วยขับโดย openpilot + + + Show ETA in 24h Format + แสดงเวลา ETA ในรูปแบบ 24 ชั่วโมง + + + Use 24h format instead of am/pm + ใช้รูปแบบเวลา 24 ชั่วโมง แทน am/pm + + + Show Map on Left Side of UI + แสดงแผนที่ที่ด้านซ้ายของหน้าจอ + + + Show map on left side when in split screen view. + แสดงแผนที่ด้านซ้ายของหน้าจอเมื่ออยู่ในโหมดแบ่งหน้าจอ + + + 🌮 End-to-end longitudinal (extremely alpha) 🌮 + 🌮 ควบคุมเร่ง/เบรคแบบ End-to-end (อยู่ขั้นพัฒนา) 🌮 + + + Experimental openpilot Longitudinal Control + ทดลองใช้ระบบควบคุมการเร่ง/เบรคโดย openpilot + + + <b>WARNING: openpilot longitudinal control is experimental for this car and will disable AEB.</b> + <b>คำเตือน: การควบคุมการเร่ง/เบรคโดย openpilot สำหรับรถคันนี้ยังอยู่ในขั้นทดลอง และระบบเบรคฉุกเฉินอัตโนมัติ (AEB) จะถูกปิด</b> + + + Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would. Super experimental. + ให้ openpilot ควบคุมการเร่ง/เบรคแบบ end-to-end โดย openpilot จะขับอย่างที่มนุษย์คิด ระบบยังอยู่ในขั้นทดลอง + + + openpilot longitudinal control is not currently available for this car. + ขณะนี้ยังไม่มีระบบควบคุมการเร่ง/เบรคโดย openpilot สำหรับรถคันนี้ + + + Enable experimental longitudinal control to enable this. + เปิดใช้งานระบบควบคุมการเร่ง/เบรคขั้นทดลอง เพื่อเปิดใช้งานสิ่งนี้ + + + + Updater + + Update Required + จำเป็นต้องอัปเดต + + + An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. + จำเป็นต้องมีการอัปเดตระบบปฏิบัติการ เชื่อมต่ออุปกรณ์ของคุณกับ Wi-Fi เพื่อประสบการณ์การอัปเดตที่เร็วที่สุด ขนาดดาวน์โหลดประมาณ 1GB + + + Connect to Wi-Fi + เชื่อมต่อกับ Wi-Fi + + + Install + ติดตั้ง + + + Back + ย้อนกลับ + + + Loading... + กำลังโหลด... + + + Reboot + รีบูต + + + Update failed + การอัปเดตล้มเหลว + + + + WifiUI + + Scanning for networks... + กำลังสแกนหาเครือข่าย... + + + CONNECTING... + กำลังเชื่อมต่อ... + + + FORGET + เลิกใช้ + + + Forget Wi-Fi Network "%1"? + เลิกใช้เครือข่าย Wi-Fi "%1"? + + + diff --git a/selfdrive/ui/translations/main_zh-CHS.ts b/selfdrive/ui/translations/main_zh-CHS.ts new file mode 100644 index 0000000000..31202e45f2 --- /dev/null +++ b/selfdrive/ui/translations/main_zh-CHS.ts @@ -0,0 +1,1105 @@ + + + + + AbstractAlert + + Close + 关闭 + + + Snooze Update + 暂停更新 + + + Reboot and Update + 重启并更新 + + + + AdvancedNetworking + + Back + 返回 + + + Enable Tethering + 启用WiFi热点 + + + Tethering Password + WiFi热点密码 + + + EDIT + 编辑 + + + Enter new tethering password + 输入新的WiFi热点密码 + + + IP Address + IP地址 + + + Enable Roaming + 启用数据漫游 + + + APN Setting + APN设置 + + + Enter APN + 输入APN + + + leave blank for automatic configuration + 留空以自动配置 + + + Cellular Metered + 按流量计费的手机移动网络 + + + Prevent large data uploads when on a metered connection + 当使用按流量计费的连接时,避免上传大流量数据 + + + + AnnotatedCameraWidget + + km/h + km/h + + + mph + mph + + + MAX + 最高定速 + + + SPEED + SPEED + + + LIMIT + LIMIT + + + + ConfirmationDialog + + Ok + 好的 + + + Cancel + 取消 + + + + DeclinePage + + You must accept the Terms and Conditions in order to use openpilot. + 您必须接受条款和条件以使用openpilot。 + + + Back + 返回 + + + Decline, uninstall %1 + 拒绝并卸载%1 + + + + DevicePanel + + Dongle ID + 设备ID(Dongle ID) + + + N/A + N/A + + + Serial + 序列号 + + + Driver Camera + 驾驶员摄像头 + + + PREVIEW + 预览 + + + Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) + 打开并预览驾驶员摄像头,以确保驾驶员监控具有良好视野。(仅熄火时可用) + + + Reset Calibration + 重置设备校准 + + + RESET + 重置 + + + Are you sure you want to reset calibration? + 您确定要重置设备校准吗? + + + Review Training Guide + 新手指南 + + + REVIEW + 查看 + + + Review the rules, features, and limitations of openpilot + 查看openpilot的使用规则,以及其功能和限制。 + + + Are you sure you want to review the training guide? + 您确定要查看新手指南吗? + + + Regulatory + 监管信息 + + + VIEW + 查看 + + + Change Language + 切换语言 + + + CHANGE + 切换 + + + Select a language + 选择语言 + + + Reboot + 重启 + + + Power Off + 关机 + + + openpilot requires the device to be mounted within 4° left or right and within 5° up or 8° down. openpilot is continuously calibrating, resetting is rarely required. + openpilot要求设备安装的偏航角在左4°和右4°之间,俯仰角在上5°和下8°之间。一般来说,openpilot会持续更新校准,很少需要重置。 + + + Your device is pointed %1° %2 and %3° %4. + 您的设备校准为%1° %2、%3° %4。 + + + down + 朝下 + + + up + 朝上 + + + left + 朝左 + + + right + 朝右 + + + Are you sure you want to reboot? + 您确定要重新启动吗? + + + Disengage to Reboot + 取消openpilot以重新启动 + + + Are you sure you want to power off? + 您确定要关机吗? + + + Disengage to Power Off + 取消openpilot以关机 + + + Reset + 重置 + + + Review + 预览 + + + + DriveStats + + Drives + 旅程数 + + + Hours + 小时 + + + ALL TIME + 全部 + + + PAST WEEK + 过去一周 + + + KM + 公里 + + + Miles + 英里 + + + + DriverViewScene + + camera starting + 正在启动相机 + + + + ExperimentalModeButton + + EXPERIMENTAL MODE ON + 试验模式运行 + + + CHILL MODE ON + 轻松模式运行 + + + + InputDialog + + Cancel + 取消 + + + Need at least %n character(s)! + + 至少需要 %n 个字符! + + + + + Installer + + Installing... + 正在安装…… + + + Receiving objects: + 正在接收: + + + Resolving deltas: + 正在处理: + + + Updating files: + 正在更新文件: + + + + MapETA + + eta + 埃塔 + + + min + 分钟 + + + hr + 小时 + + + km + km + + + mi + mi + + + + MapInstructions + + km + km + + + m + m + + + mi + mi + + + ft + ft + + + + MapPanel + + Current Destination + 当前目的地 + + + CLEAR + 清空 + + + Recent Destinations + 最近目的地 + + + Try the Navigation Beta + 试用导航测试版 + + + Get turn-by-turn directions displayed and more with a comma +prime subscription. Sign up now: https://connect.comma.ai + 订阅comma prime以获取导航。 +立即注册:https://connect.comma.ai + + + No home +location set + 家:未设定 + + + No work +location set + 工作:未设定 + + + no recent destinations + 无最近目的地 + + + + MapWindow + + Map Loading + 地图加载中 + + + Waiting for GPS + 等待 GPS + + + + MultiOptionDialog + + Select + 选择 + + + Cancel + 取消 + + + + Networking + + Advanced + 高级 + + + Enter password + 输入密码 + + + for "%1" + 网络名称:"%1" + + + Wrong password + 密码错误 + + + + OffroadHome + + UPDATE + 更新 + + + ALERTS + 警报 + + + ALERT + 警报 + + + + PairingPopup + + Pair your device to your comma account + 将您的设备与comma账号配对 + + + Go to https://connect.comma.ai on your phone + 在手机上访问 https://connect.comma.ai + + + Click "add new device" and scan the QR code on the right + 点击“添加新设备”,扫描右侧二维码 + + + Bookmark connect.comma.ai to your home screen to use it like an app + 将 connect.comma.ai 收藏到您的主屏幕,以便像应用程序一样使用它 + + + + ParamControl + + Cancel + 取消 + + + Enable + 启用 + + + + PrimeAdWidget + + Upgrade Now + 现在升级 + + + Become a comma prime member at connect.comma.ai + 打开connect.comma.ai以注册comma prime会员 + + + PRIME FEATURES: + comma prime特权: + + + Remote access + 远程访问 + + + 1 year of storage + 1年数据存储 + + + Developer perks + 开发者福利 + + + + PrimeUserWidget + + ✓ SUBSCRIBED + ✓ 已订阅 + + + comma prime + comma prime + + + CONNECT.COMMA.AI + CONNECT.COMMA.AI + + + COMMA POINTS + COMMA POINTS点数 + + + + QObject + + Reboot + 重启 + + + Exit + 退出 + + + dashcam + 行车记录仪 + + + openpilot + openpilot + + + %n minute(s) ago + + %n 分钟前 + + + + %n hour(s) ago + + %n 小时前 + + + + %n day(s) ago + + %n 天前 + + + + + Reset + + Reset failed. Reboot to try again. + 重置失败。 重新启动以重试。 + + + Are you sure you want to reset your device? + 您确定要重置您的设备吗? + + + Resetting device... + 正在重置设备…… + + + System Reset + 恢复出厂设置 + + + System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. + 已触发系统重置:确认以删除所有内容和设置。取消以正常启动设备。 + + + Cancel + 取消 + + + Reboot + 重启 + + + Confirm + 确认 + + + Unable to mount data partition. Press confirm to reset your device. + 无法挂载数据分区。 确认以重置您的设备。 + + + + SettingsWindow + + × + × + + + Device + 设备 + + + Network + 网络 + + + Toggles + 设定 + + + Software + 软件 + + + Navigation + 导航 + + + + Setup + + WARNING: Low Voltage + 警告:低电压 + + + Power your device in a car with a harness or proceed at your own risk. + 请使用car harness线束为您的设备供电,或自行承担风险。 + + + Power off + 关机 + + + Continue + 继续 + + + Getting Started + 开始设置 + + + Before we get on the road, let’s finish installation and cover some details. + 开始旅程之前,让我们完成安装并介绍一些细节。 + + + Connect to Wi-Fi + 连接到WiFi + + + Back + 返回 + + + Continue without Wi-Fi + 不连接WiFi并继续 + + + Waiting for internet + 等待网络连接 + + + Choose Software to Install + 选择要安装的软件 + + + Dashcam + Dashcam(行车记录仪) + + + Custom Software + 自定义软件 + + + Enter URL + 输入网址 + + + for Custom Software + 以下载自定义软件 + + + Downloading... + 正在下载…… + + + Download Failed + 下载失败 + + + Ensure the entered URL is valid, and the device’s internet connection is good. + 请确保互联网连接良好且输入的URL有效。 + + + Reboot device + 重启设备 + + + Start over + 重来 + + + + SetupWidget + + Finish Setup + 完成设置 + + + Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. + 将您的设备与comma connect (connect.comma.ai)配对并领取您的comma prime优惠。 + + + Pair device + 配对设备 + + + + Sidebar + + CONNECT + CONNECT + + + OFFLINE + 离线 + + + ONLINE + 在线 + + + ERROR + 连接出错 + + + TEMP + 设备温度 + + + HIGH + 过热 + + + GOOD + 良好 + + + OK + 一般 + + + VEHICLE + 车辆连接 + + + NO + + + + PANDA + PANDA + + + GPS + GPS + + + SEARCH + 搜索中 + + + -- + -- + + + Wi-Fi + Wi-Fi + + + ETH + 以太网 + + + 2G + 2G + + + 3G + 3G + + + LTE + LTE + + + 5G + 5G + + + + SoftwarePanel + + Updates are only downloaded while the car is off. + 车辆熄火时才能下载升级文件。 + + + Current Version + 当前版本 + + + Download + 下载 + + + Install Update + 安装更新 + + + INSTALL + 安装 + + + Target Branch + 目标分支 + + + SELECT + 选择 + + + Select a branch + 选择分支 + + + UNINSTALL + 卸载 + + + Uninstall %1 + 卸载 %1 + + + Are you sure you want to uninstall? + 您确定要卸载吗? + + + CHECK + 查看 + + + Uninstall + 卸载 + + + + SshControl + + SSH Keys + SSH密钥 + + + Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. + 警告:这将授予SSH访问权限给您GitHub设置中的所有公钥。切勿输入您自己以外的GitHub用户名。comma员工永远不会要求您添加他们的GitHub用户名。 + + + ADD + 添加 + + + Enter your GitHub username + 输入您的GitHub用户名 + + + LOADING + 正在加载 + + + REMOVE + 删除 + + + Username '%1' has no keys on GitHub + 用户名“%1”在GitHub上没有密钥 + + + Request timed out + 请求超时 + + + Username '%1' doesn't exist on GitHub + GitHub上不存在用户名“%1” + + + + SshToggle + + Enable SSH + 启用SSH + + + + TermsPage + + Terms & Conditions + 条款和条件 + + + Decline + 拒绝 + + + Scroll to accept + 滑动以接受 + + + Agree + 同意 + + + + TogglesPanel + + Enable openpilot + 启用openpilot + + + Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off. + 使用openpilot进行自适应巡航和车道保持辅助。使用此功能时您必须时刻保持注意力。该设置的更改在熄火时生效。 + + + Enable Lane Departure Warnings + 启用车道偏离警告 + + + Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). + 车速超过31mph(50km/h)时,若检测到车辆越过车道线且未打转向灯,系统将发出警告以提醒您返回车道。 + + + Use Metric System + 使用公制单位 + + + Display speed in km/h instead of mph. + 显示车速时,以km/h代替mph。 + + + Record and Upload Driver Camera + 录制并上传驾驶员摄像头 + + + Upload data from the driver facing camera and help improve the driver monitoring algorithm. + 上传驾驶员摄像头的数据,帮助改进驾驶员监控算法。 + + + Experimental openpilot Longitudinal Control + 试验性的openpilot纵向控制 + + + Disengage on Accelerator Pedal + 踩油门时取消控制 + + + When enabled, pressing the accelerator pedal will disengage openpilot. + 启用后,踩下油门踏板将取消openpilot。 + + + Show ETA in 24h Format + 以24小时格式显示预计到达时间 + + + Use 24h format instead of am/pm + 使用24小时制代替am/pm + + + Show Map on Left Side of UI + 在介面左侧显示地图 + + + Show map on left side when in split screen view. + 在分屏模式中,将地图置于屏幕左侧。 + + + Experimental Mode + 测试模式 + + + WARNING: openpilot longitudinal control is experimental for this car and will disable Automatic Emergency Braking (AEB). + 警告: 此车辆的openpilot纵向控制是试验性功能,且将禁用AEB自动刹车功能。 + + + On this car, openpilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when using experimental openpilot longitudinal control. + 针对此车辆,openpilot默认使用车辆自带的ACC,而非openpilot的纵向控制。启用此选项将切换到openpilot纵向控制。当使用试验性的openpilot纵向控制时,建议同时启用试验模式。 + + + Experimental mode is currently unavailable on this car, since the car's stock ACC is used for longitudinal control. + 由于此车辆使用自带的ACC纵向控制,当前无法使用试验模式。 + + + Enable experimental longitudinal control to allow experimental mode. + 启用试验性的纵向控制,以便允许使用试验模式。 + + + openpilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: + openpilot 默认 <b>轻松模式</b>驾驶车辆。试验模式启用一些轻松模式之外的 <b>试验性功能</b>。试验性功能包括: + + + 🌮 End-to-End Longitudinal Control 🌮 + 🌮 端到端(End-to-End) 纵向控制 🌮 + + + Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. + 允许驾驶模型控制加速和制动,openpilot将模仿人类驾驶车辆,包括在红灯和停车让行标识前停车。鉴于驾驶模型确定行驶车速,所设定的车速仅作为上限。此功能尚处于早期测试状态,有可能会出现操作错误。 + + + New Driving Visualization + 新驾驶视角 + + + The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. + 当低速行驶时,驾驶视角将切换到前向广角摄像头,便于更完整地显示转向路径。右上角将显示试验模式图标。 + + + + Updater + + Update Required + 需要更新 + + + An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. + 操作系统需要更新。请将您的设备连接到WiFi以获取更快的更新体验。下载大小约为1GB。 + + + Connect to Wi-Fi + 连接到WiFi + + + Install + 安装 + + + Back + 返回 + + + Loading... + 正在加载…… + + + Reboot + 重启 + + + Update failed + 更新失败 + + + + WifiUI + + Scanning for networks... + 正在扫描网络…… + + + CONNECTING... + 正在连接…… + + + FORGET + 忽略 + + + Forget Wi-Fi Network "%1"? + 忽略WiFi网络 "%1"? + + + Forget + 忽略 + + + diff --git a/selfdrive/ui/translations/main_zh-CHT.ts b/selfdrive/ui/translations/main_zh-CHT.ts new file mode 100644 index 0000000000..0379e926c4 --- /dev/null +++ b/selfdrive/ui/translations/main_zh-CHT.ts @@ -0,0 +1,1107 @@ + + + + + AbstractAlert + + Close + 關閉 + + + Snooze Update + 暫停更新 + + + Reboot and Update + 重啟並更新 + + + + AdvancedNetworking + + Back + 回上頁 + + + Enable Tethering + 啟用網路分享 + + + Tethering Password + 網路分享密碼 + + + EDIT + 編輯 + + + Enter new tethering password + 輸入新的網路分享密碼 + + + IP Address + IP 地址 + + + Enable Roaming + 啟用漫遊 + + + APN Setting + APN 設置 + + + Enter APN + 輸入 APN + + + leave blank for automatic configuration + 留空白將自動配置 + + + Cellular Metered + 行動網路 + + + Prevent large data uploads when on a metered connection + 防止使用行動網路上傳大量的數據 + + + + AnnotatedCameraWidget + + km/h + km/h + + + mph + mph + + + MAX + 最高 + + + SPEED + 速度 + + + LIMIT + 速限 + + + + ConfirmationDialog + + Ok + 確定 + + + Cancel + 取消 + + + + DeclinePage + + You must accept the Terms and Conditions in order to use openpilot. + 您必須先接受條款和條件才能使用 openpilot。 + + + Back + 回上頁 + + + Decline, uninstall %1 + 拒絕並解除安裝 %1 + + + + DevicePanel + + Dongle ID + Dongle ID + + + N/A + 無法使用 + + + Serial + 序號 + + + Driver Camera + 駕駛員監控鏡頭 + + + PREVIEW + 預覽 + + + Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) + 預覽駕駛員監控鏡頭畫面,以確保其具有良好視野。(僅在熄火時可用) + + + Reset Calibration + 重置校準 + + + RESET + 重置 + + + Are you sure you want to reset calibration? + 您確定要重置校準嗎? + + + Review Training Guide + 觀看使用教學 + + + REVIEW + 觀看 + + + Review the rules, features, and limitations of openpilot + 觀看 openpilot 的使用規則、功能和限制 + + + Are you sure you want to review the training guide? + 您確定要觀看使用教學嗎? + + + Regulatory + 法規/監管 + + + VIEW + 觀看 + + + Change Language + 更改語言 + + + CHANGE + 更改 + + + Select a language + 選擇語言 + + + Reboot + 重新啟動 + + + Power Off + 關機 + + + openpilot requires the device to be mounted within 4° left or right and within 5° up or 8° down. openpilot is continuously calibrating, resetting is rarely required. + openpilot 需要將裝置固定在左右偏差 4° 以內,朝上偏差 5° 以内或朝下偏差 8° 以内。鏡頭在後台會持續自動校準,很少有需要重置的情况。 + + + Your device is pointed %1° %2 and %3° %4. + 你的設備目前朝%2 %1° 以及朝%4 %3° 。 + + + down + + + + up + + + + left + + + + right + + + + Are you sure you want to reboot? + 您確定要重新啟動嗎? + + + Disengage to Reboot + 請先取消控車才能重新啟動 + + + Are you sure you want to power off? + 您確定您要關機嗎? + + + Disengage to Power Off + 請先取消控車才能關機 + + + Reset + 重設 + + + Review + 回顧 + + + + DriveStats + + Drives + 旅程 + + + Hours + 小時 + + + ALL TIME + 總共 + + + PAST WEEK + 上周 + + + KM + 公里 + + + Miles + 英里 + + + + DriverViewScene + + camera starting + 開啟相機中 + + + + ExperimentalModeButton + + EXPERIMENTAL MODE ON + 實驗模式 ON + + + CHILL MODE ON + 輕鬆模式 ON + + + + InputDialog + + Cancel + 取消 + + + Need at least %n character(s)! + + 需要至少 %n 個字元! + + + + + Installer + + Installing... + 安裝中… + + + Receiving objects: + 接收對象: + + + Resolving deltas: + 分析差異: + + + Updating files: + 更新檔案: + + + + MapETA + + eta + 抵達 + + + min + 分鐘 + + + hr + 小時 + + + km + km + + + mi + mi + + + + MapInstructions + + km + km + + + m + m + + + mi + mi + + + ft + ft + + + + MapPanel + + Current Destination + 當前目的地 + + + CLEAR + 清除 + + + Recent Destinations + 最近目的地 + + + Try the Navigation Beta + 試用導航功能 + + + Get turn-by-turn directions displayed and more with a comma +prime subscription. Sign up now: https://connect.comma.ai + 成為 comma 高級會員來使用導航功能 +立即註冊:https://connect.comma.ai + + + No home +location set + 未設定 +住家位置 + + + No work +location set + 未設定 +工作位置 + + + no recent destinations + 沒有最近的導航記錄 + + + + MapWindow + + Map Loading + 地圖加載中 + + + Waiting for GPS + 等待 GPS + + + + MultiOptionDialog + + Select + 選擇 + + + Cancel + 取消 + + + + Networking + + Advanced + 進階 + + + Enter password + 輸入密碼 + + + for "%1" + 給 "%1" + + + Wrong password + 密碼錯誤 + + + + OffroadHome + + UPDATE + 更新 + + + ALERTS + 提醒 + + + ALERT + 提醒 + + + + PairingPopup + + Pair your device to your comma account + 將設備與您的 comma 帳號配對 + + + Go to https://connect.comma.ai on your phone + 用手機連至 https://connect.comma.ai + + + Click "add new device" and scan the QR code on the right + 點選 "add new device" 後掃描右邊的二維碼 + + + Bookmark connect.comma.ai to your home screen to use it like an app + 將 connect.comma.ai 加入您的主屏幕,以便像手機 App 一樣使用它 + + + + ParamControl + + Cancel + 取消 + + + Enable + 啟用 + + + + PrimeAdWidget + + Upgrade Now + 馬上升級 + + + Become a comma prime member at connect.comma.ai + 成為 connect.comma.ai 的高級會員 + + + PRIME FEATURES: + 高級會員特點: + + + Remote access + 遠程訪問 + + + 1 year of storage + 一年的雲端行車記錄 + + + Developer perks + 開發者福利 + + + + PrimeUserWidget + + ✓ SUBSCRIBED + ✓ 已訂閱 + + + comma prime + comma 高級會員 + + + CONNECT.COMMA.AI + CONNECT.COMMA.AI + + + COMMA POINTS + COMMA 積分 + + + + QObject + + Reboot + 重新啟動 + + + Exit + 離開 + + + dashcam + 行車記錄器 + + + openpilot + openpilot + + + %n minute(s) ago + + %n 分鐘前 + + + + %n hour(s) ago + + %n 小時前 + + + + %n day(s) ago + + %n 天前 + + + + + Reset + + Reset failed. Reboot to try again. + 重置失敗。請重新啟動後再試。 + + + Are you sure you want to reset your device? + 您確定要重置你的設備嗎? + + + Resetting device... + 重置設備中… + + + System Reset + 系統重置 + + + System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. + 系統重置已觸發。請按確認刪除所有內容和設置。按取消恢復啟動。 + + + Cancel + 取消 + + + Reboot + 重新啟動 + + + Confirm + 確認 + + + Unable to mount data partition. Press confirm to reset your device. + 無法掛載數據分區。請按確認重置您的設備。 + + + + SettingsWindow + + × + × + + + Device + 設備 + + + Network + 網路 + + + Toggles + 設定 + + + Software + 軟體 + + + Navigation + 導航 + + + + Setup + + WARNING: Low Voltage + 警告:電壓過低 + + + Power your device in a car with a harness or proceed at your own risk. + 請使用車上 harness 提供的電源,若繼續的話您需要自擔風險。 + + + Power off + 關機 + + + Continue + 繼續 + + + Getting Started + 入門 + + + Before we get on the road, let’s finish installation and cover some details. + 在我們上路之前,讓我們完成安裝並介紹一些細節。 + + + Connect to Wi-Fi + 連接到無線網絡 + + + Back + 回上頁 + + + Continue without Wi-Fi + 在沒有 Wi-Fi 的情況下繼續 + + + Waiting for internet + 連接至網路中 + + + Choose Software to Install + 選擇要安裝的軟體 + + + Dashcam + 行車記錄器 + + + Custom Software + 定制的軟體 + + + Enter URL + 輸入網址 + + + for Custom Software + 定制的軟體 + + + Downloading... + 下載中… + + + Download Failed + 下載失敗 + + + Ensure the entered URL is valid, and the device’s internet connection is good. + 請確定您輸入的是有效的安裝網址,並且確定設備的網路連線狀態良好。 + + + Reboot device + 重新啟動 + + + Start over + 重新開始 + + + + SetupWidget + + Finish Setup + 完成設置 + + + Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. + 將您的設備與 comma connect (connect.comma.ai) 配對並領取您的 comma 高級會員優惠。 + + + Pair device + 配對設備 + + + + Sidebar + + CONNECT + 雲端服務 + + + OFFLINE + 已離線 + + + ONLINE + 已連線 + + + ERROR + 錯誤 + + + TEMP + 溫度 + + + HIGH + 偏高 + + + GOOD + 正常 + + + OK + 一般 + + + VEHICLE + 車輛通訊 + + + NO + 未連線 + + + PANDA + 車輛通訊 + + + GPS + GPS + + + SEARCH + 車輛通訊 + + + -- + -- + + + Wi-Fi + + + + ETH + + + + 2G + + + + 3G + + + + LTE + + + + 5G + + + + + SoftwarePanel + + Updates are only downloaded while the car is off. + 系統更新只會在熄火時下載。 + + + Current Version + 當前版本 + + + Download + 下載 + + + Install Update + 安裝更新 + + + INSTALL + 安裝 + + + Target Branch + 目標分支 + + + SELECT + 選取 + + + Select a branch + 選取一個分支 + + + UNINSTALL + 解除安裝 + + + Uninstall %1 + 解除安裝 %1 + + + Are you sure you want to uninstall? + 您確定您要解除安裝嗎? + + + CHECK + 檢查 + + + Uninstall + 解除安裝 + + + + SshControl + + SSH Keys + SSH 密鑰 + + + Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. + 警告:這將授權給 GitHub 帳號中所有公鑰 SSH 訪問權限。切勿輸入非您自己的 GitHub 用戶名。comma 員工「永遠不會」要求您添加他們的 GitHub 用戶名。 + + + ADD + 新增 + + + Enter your GitHub username + 請輸入您 GitHub 的用戶名 + + + LOADING + 載入中 + + + REMOVE + 移除 + + + Username '%1' has no keys on GitHub + GitHub 用戶 '%1' 沒有設定任何密鑰 + + + Request timed out + 請求超時 + + + Username '%1' doesn't exist on GitHub + GitHub 用戶 '%1' 不存在 + + + + SshToggle + + Enable SSH + 啟用 SSH 服務 + + + + TermsPage + + Terms & Conditions + 條款和條件 + + + Decline + 拒絕 + + + Scroll to accept + 滑動至頁尾接受條款 + + + Agree + 接受 + + + + TogglesPanel + + Enable openpilot + 啟用 openpilot + + + Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off. + 使用 openpilot 的主動式巡航和車道保持功能,開啟後您需要持續集中注意力,設定變更在重新啟動車輛後生效。 + + + Enable Lane Departure Warnings + 啟用車道偏離警告 + + + Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). + 車速在時速 50 公里 (31 英里) 以上且未打方向燈的情況下,如果偵測到車輛駛出目前車道線時,發出車道偏離警告。 + + + Use Metric System + 使用公制單位 + + + Display speed in km/h instead of mph. + 啟用後,速度單位顯示將從 mp/h 改為 km/h。 + + + Record and Upload Driver Camera + 記錄並上傳駕駛監控影像 + + + Upload data from the driver facing camera and help improve the driver monitoring algorithm. + 上傳駕駛監控的錄像來協助我們提升駕駛監控的準確率。 + + + Experimental openpilot Longitudinal Control + 使用 openpilot 縱向控制(實驗) + + + Disengage on Accelerator Pedal + 油門取消控車 + + + When enabled, pressing the accelerator pedal will disengage openpilot. + 啟用後,踩踏油門將會取消 openpilot 控制。 + + + Show ETA in 24h Format + 預計到達時間單位改用 24 小時制 + + + Use 24h format instead of am/pm + 使用 24 小時制。(預設值為 12 小時制) + + + Show Map on Left Side of UI + 將地圖顯示在畫面的左側 + + + Show map on left side when in split screen view. + 進入分割畫面後,地圖將會顯示在畫面的左側。 + + + Experimental Mode + 實驗模式 + + + WARNING: openpilot longitudinal control is experimental for this car and will disable Automatic Emergency Braking (AEB). + 警告:openpilot 縱向控制在這輛車上仍屬實驗性質,啟用後會喪失自動緊急煞車 (AEB) 功能。 + + + On this car, openpilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when using experimental openpilot longitudinal control. + 在本車輛中,openpilot預設將使用原車內建的ACC系統,而非openpilot縱向控制。開啟此開關來啟用openpilot縱向控制,使用此選項時建議一併啟用實驗模式。 + + + Experimental mode is currently unavailable on this car, since the car's stock ACC is used for longitudinal control. + 因車輛使用內建ACC系統,無法在本車輛上啟動實驗模式。 + + + Enable experimental longitudinal control to allow experimental mode. + 啟用實驗性縱向控制以使用實驗模式。 + + + openpilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: + openpilot 預設以 <b>輕鬆模式</b> 駕駛。 實驗模式啟用了尚未準備好進入輕鬆模式的 <b>alpha 級功能</b>。實驗功能如下: + + + 🌮 End-to-End Longitudinal Control 🌮 + 🌮端到端縱向控制🌮 + + + Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. + 讓駕駛模型來控制油門及煞車。openpilot將會模擬人類的駕駛行為,包含在看見紅燈及停止標示時停車。由於車速將由駕駛模型決定,因此您設定的時速將成為速度上限。本功能仍在早期實驗階段,請預期模型有犯錯的可能性。 + + + New Driving Visualization + 新的駕駛視覺介面 + + + The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. + 低速行駛時,將會切換成路側廣角鏡頭,以完整顯示轉彎路徑,右上角將出現實驗模式圖案。 + + + + Updater + + Update Required + 系統更新 + + + An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. + 設備的操作系統需要更新。請將您的設備連接到 Wi-Fi 以獲得最快的更新體驗。下載大小約為 1GB。 + + + Connect to Wi-Fi + 連接到無線網絡 + + + Install + 安裝 + + + Back + 回上頁 + + + Loading... + 載入中… + + + Reboot + 重新啟動 + + + Update failed + 更新失敗 + + + + WifiUI + + Scanning for networks... + 掃描無線網路中... + + + CONNECTING... + 連線中... + + + FORGET + 清除 + + + Forget Wi-Fi Network "%1"? + 清除 Wi-Fi 網路 "%1"? + + + Forget + 清除 + + + diff --git a/selfdrive/ui/ui b/selfdrive/ui/ui index 68c8c2cad5..c9f81c0539 100755 --- a/selfdrive/ui/ui +++ b/selfdrive/ui/ui @@ -1,5 +1,5 @@ #!/bin/sh cd "$(dirname "$0")" export LD_LIBRARY_PATH="/system/lib64:$LD_LIBRARY_PATH" -export QT_PLUGIN_PATH="../../third_party/qt-plugins/$(uname -m)" +export QT_DBL_CLICK_DIST=150 exec ./_ui diff --git a/selfdrive/ui/ui.cc b/selfdrive/ui/ui.cc index bbdd6d4f30..c62d737481 100644 --- a/selfdrive/ui/ui.cc +++ b/selfdrive/ui/ui.cc @@ -6,11 +6,11 @@ #include #include "common/transformations/orientation.hpp" -#include "selfdrive/common/params.h" -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/util.h" -#include "selfdrive/common/watchdog.h" -#include "selfdrive/hardware/hw.h" +#include "common/params.h" +#include "common/swaglog.h" +#include "common/util.h" +#include "common/watchdog.h" +#include "system/hardware/hw.h" #define BACKLIGHT_DT 0.05 #define BACKLIGHT_TS 10.00 @@ -23,8 +23,8 @@ static bool calib_frame_to_full_frame(const UIState *s, float in_x, float in_y, const QRectF clip_region{-margin, -margin, s->fb_w + 2 * margin, s->fb_h + 2 * margin}; const vec3 pt = (vec3){{in_x, in_y, in_z}}; - const vec3 Ep = matvecmul3(s->scene.view_from_calib, pt); - const vec3 KEp = matvecmul3(s->wide_camera ? ecam_intrinsic_matrix : fcam_intrinsic_matrix, Ep); + const vec3 Ep = matvecmul3(s->scene.wide_cam ? s->scene.view_from_wide_calib : s->scene.view_from_calib, pt); + const vec3 KEp = matvecmul3(s->scene.wide_cam ? ecam_intrinsic_matrix : fcam_intrinsic_matrix, Ep); // Project. QPointF point = s->car_space_transform.map(QPointF{KEp.v[0] / KEp.v[2], KEp.v[1] / KEp.v[2]}); @@ -35,7 +35,7 @@ static bool calib_frame_to_full_frame(const UIState *s, float in_x, float in_y, return false; } -static int get_path_length_idx(const cereal::ModelDataV2::XYZTData::Reader &line, const float path_height) { +int get_path_length_idx(const cereal::ModelDataV2::XYZTData::Reader &line, const float path_height) { const auto line_x = line.getX(); int max_idx = 0; for (int i = 1; i < TRAJECTORY_SIZE && line_x[i] <= path_height; ++i) { @@ -44,7 +44,7 @@ static int get_path_length_idx(const cereal::ModelDataV2::XYZTData::Reader &line return max_idx; } -static void update_leads(UIState *s, const cereal::RadarState::Reader &radar_state, const cereal::ModelDataV2::XYZTData::Reader &line) { +void update_leads(UIState *s, const cereal::RadarState::Reader &radar_state, const cereal::ModelDataV2::XYZTData::Reader &line) { for (int i = 0; i < 2; ++i) { auto lead_data = (i == 0) ? radar_state.getLeadOne() : radar_state.getLeadTwo(); if (lead_data.getStatus()) { @@ -54,21 +54,32 @@ static void update_leads(UIState *s, const cereal::RadarState::Reader &radar_sta } } -static void update_line_data(const UIState *s, const cereal::ModelDataV2::XYZTData::Reader &line, - float y_off, float z_off, line_vertices_data *pvd, int max_idx) { +void update_line_data(const UIState *s, const cereal::ModelDataV2::XYZTData::Reader &line, + float y_off, float z_off, QPolygonF *pvd, int max_idx, bool allow_invert=true) { const auto line_x = line.getX(), line_y = line.getY(), line_z = line.getZ(); - QPointF *v = &pvd->v[0]; + QPolygonF left_points, right_points; + left_points.reserve(max_idx + 1); + right_points.reserve(max_idx + 1); + for (int i = 0; i <= max_idx; i++) { - v += calib_frame_to_full_frame(s, line_x[i], line_y[i] - y_off, line_z[i] + z_off, v); - } - for (int i = max_idx; i >= 0; i--) { - v += calib_frame_to_full_frame(s, line_x[i], line_y[i] + y_off, line_z[i] + z_off, v); + // highly negative x positions are drawn above the frame and cause flickering, clip to zy plane of camera + if (line_x[i] < 0) continue; + QPointF left, right; + bool l = calib_frame_to_full_frame(s, line_x[i], line_y[i] - y_off, line_z[i] + z_off, &left); + bool r = calib_frame_to_full_frame(s, line_x[i], line_y[i] + y_off, line_z[i] + z_off, &right); + if (l && r) { + // For wider lines the drawn polygon will "invert" when going over a hill and cause artifacts + if (!allow_invert && left_points.size() && left.y() > left_points.back().y()) { + continue; + } + left_points.push_back(left); + right_points.push_front(right); + } } - pvd->cnt = v - pvd->v; - assert(pvd->cnt <= std::size(pvd->v)); + *pvd = left_points + right_points; } -static void update_model(UIState *s, const cereal::ModelDataV2::Reader &model) { +void update_model(UIState *s, const cereal::ModelDataV2::Reader &model) { UIScene &scene = s->scene; auto model_position = model.getPosition(); float max_distance = std::clamp(model_position.getX()[TRAJECTORY_SIZE - 1], @@ -98,7 +109,7 @@ static void update_model(UIState *s, const cereal::ModelDataV2::Reader &model) { max_distance = std::clamp((float)(lead_d - fmin(lead_d * 0.35, 10.)), 0.0f, max_distance); } max_idx = get_path_length_idx(model_position, max_distance); - update_line_data(s, model_position, 0.5, 1.22, &scene.track_vertices, max_idx); + update_line_data(s, model_position, 0.9, 1.22, &scene.track_vertices, max_idx, false); } static void update_sockets(UIState *s) { @@ -111,27 +122,27 @@ static void update_state(UIState *s) { if (sm.updated("liveCalibration")) { auto rpy_list = sm["liveCalibration"].getLiveCalibration().getRpyCalib(); + auto wfde_list = sm["liveCalibration"].getLiveCalibration().getWideFromDeviceEuler(); Eigen::Vector3d rpy; - rpy << rpy_list[0], rpy_list[1], rpy_list[2]; + Eigen::Vector3d wfde; + if (rpy_list.size() == 3) rpy << rpy_list[0], rpy_list[1], rpy_list[2]; + if (wfde_list.size() == 3) wfde << wfde_list[0], wfde_list[1], wfde_list[2]; Eigen::Matrix3d device_from_calib = euler2rot(rpy); + Eigen::Matrix3d wide_from_device = euler2rot(wfde); Eigen::Matrix3d view_from_device; view_from_device << 0,1,0, 0,0,1, 1,0,0; Eigen::Matrix3d view_from_calib = view_from_device * device_from_calib; + Eigen::Matrix3d view_from_wide_calib = view_from_device * wide_from_device * device_from_calib ; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { scene.view_from_calib.v[i*3 + j] = view_from_calib(i,j); + scene.view_from_wide_calib.v[i*3 + j] = view_from_wide_calib(i,j); } } - } - if (s->worldObjectsVisible()) { - if (sm.updated("modelV2")) { - update_model(s, sm["modelV2"].getModelV2()); - } - if (sm.updated("radarState") && sm.rcv_frame("modelV2") > s->scene.started_frame) { - update_leads(s, sm["radarState"].getRadarState(), sm["modelV2"].getModelV2().getPosition()); - } + scene.calibration_valid = sm["liveCalibration"].getLiveCalibration().getCalStatus() == 1; + scene.calibration_wide_valid = wfde_list.size() == 3; } if (sm.updated("pandaStates")) { auto pandaStates = sm["pandaStates"].getPandaStates(); @@ -151,57 +162,30 @@ static void update_state(UIState *s) { if (sm.updated("carParams")) { scene.longitudinal_control = sm["carParams"].getCarParams().getOpenpilotLongitudinalControl(); } - if (!scene.started && sm.updated("sensorEvents")) { - for (auto sensor : sm["sensorEvents"].getSensorEvents()) { - if (sensor.which() == cereal::SensorEventData::ACCELERATION) { - auto accel = sensor.getAcceleration().getV(); - if (accel.totalSize().wordCount) { // TODO: sometimes empty lists are received. Figure out why - scene.accel_sensor = accel[2]; - } - } else if (sensor.which() == cereal::SensorEventData::GYRO_UNCALIBRATED) { - auto gyro = sensor.getGyroUncalibrated().getV(); - if (gyro.totalSize().wordCount) { - scene.gyro_sensor = gyro[1]; - } - } - } - } - if (!Hardware::TICI() && sm.updated("roadCameraState")) { - auto camera_state = sm["roadCameraState"].getRoadCameraState(); - - float max_lines = Hardware::EON() ? 5408 : 1904; - float max_gain = Hardware::EON() ? 1.0: 10.0; - float max_ev = max_lines * max_gain; - - float ev = camera_state.getGain() * float(camera_state.getIntegLines()); - - scene.light_sensor = std::clamp(1.0 - (ev / max_ev), 0.0, 1.0); - } else if (Hardware::TICI() && sm.updated("wideRoadCameraState")) { - auto camera_state = sm["wideRoadCameraState"].getWideRoadCameraState(); - - float max_lines = 1904; - float max_gain = 10.0; - float max_ev = max_lines * max_gain / 6; - - float ev = camera_state.getGain() * float(camera_state.getIntegLines()); - - scene.light_sensor = std::clamp(1.0 - (ev / max_ev), 0.0, 1.0); + if (sm.updated("wideRoadCameraState")) { + float scale = (sm["wideRoadCameraState"].getWideRoadCameraState().getSensor() == cereal::FrameData::ImageSensor::AR0321) ? 6.0f : 1.0f; + scene.light_sensor = std::max(100.0f - scale * sm["wideRoadCameraState"].getWideRoadCameraState().getExposureValPercent(), 0.0f); } scene.started = sm["deviceState"].getDeviceState().getStarted() && scene.ignition; } void ui_update_params(UIState *s) { - s->scene.is_metric = Params().getBool("IsMetric"); + auto params = Params(); + s->scene.is_metric = params.getBool("IsMetric"); + s->scene.map_on_left = params.getBool("NavSettingLeftSide"); } void UIState::updateStatus() { if (scene.started && sm->updated("controlsState")) { auto controls_state = (*sm)["controlsState"].getControlsState(); auto alert_status = controls_state.getAlertStatus(); + auto state = controls_state.getState(); if (alert_status == cereal::ControlsState::AlertStatus::USER_PROMPT) { status = STATUS_WARNING; } else if (alert_status == cereal::ControlsState::AlertStatus::CRITICAL) { status = STATUS_ALERT; + } else if (state == cereal::ControlsState::OpenpilotState::PRE_ENABLED || state == cereal::ControlsState::OpenpilotState::OVERRIDING) { + status = STATUS_OVERRIDE; } else { status = controls_state.getEnabled() ? STATUS_ENGAGED : STATUS_DISENGAGED; } @@ -212,24 +196,31 @@ void UIState::updateStatus() { if (scene.started) { status = STATUS_DISENGAGED; scene.started_frame = sm->frame; - scene.end_to_end = Params().getBool("EndToEndToggle"); - wide_camera = Hardware::TICI() ? Params().getBool("EnableWideCamera") : false; + wide_cam_only = Params().getBool("WideCameraOnly"); } started_prev = scene.started; emit offroadTransition(!scene.started); } + + // Handle prime type change + if (prime_type != prime_type_prev) { + prime_type_prev = prime_type; + emit primeTypeChanged(prime_type); + Params().put("PrimeType", std::to_string(prime_type)); + } } UIState::UIState(QObject *parent) : QObject(parent) { sm = std::make_unique>({ "modelV2", "controlsState", "liveCalibration", "radarState", "deviceState", "roadCameraState", - "pandaStates", "carParams", "driverMonitoringState", "sensorEvents", "carState", "liveLocationKalman", - "wideRoadCameraState", + "pandaStates", "carParams", "driverMonitoringState", "carState", "liveLocationKalman", + "wideRoadCameraState", "managerState", "navInstruction", "navRoute", "gnssMeasurements", }); Params params; - wide_camera = Hardware::TICI() ? params.getBool("EnableWideCamera") : false; + wide_cam_only = params.getBool("WideCameraOnly"); prime_type = std::atoi(params.get("PrimeType").c_str()); + language = QString::fromStdString(params.get("LanguageSetting")); // update timer timer = new QTimer(this); @@ -243,7 +234,7 @@ void UIState::update() { updateStatus(); if (sm->frame % UI_FREQ == 0) { - watchdog_kick(); + watchdog_kick(nanos_since_boot()); } emit uiUpdate(*this); } @@ -279,8 +270,7 @@ void Device::resetInteractiveTimout() { void Device::updateBrightness(const UIState &s) { float clipped_brightness = BACKLIGHT_OFFROAD; if (s.scene.started) { - // Scale to 0% to 100% - clipped_brightness = 100.0 * s.scene.light_sensor; + clipped_brightness = s.scene.light_sensor; // CIE 1931 - https://www.photonstophotos.net/GeneralTopics/Exposure/Psychometric_Lightness_and_Gamma.htm if (clipped_brightness <= 8) { @@ -306,24 +296,11 @@ void Device::updateBrightness(const UIState &s) { } } -bool Device::motionTriggered(const UIState &s) { - static float accel_prev = 0; - static float gyro_prev = 0; - - bool accel_trigger = abs(s.scene.accel_sensor - accel_prev) > 0.2; - bool gyro_trigger = abs(s.scene.gyro_sensor - gyro_prev) > 0.15; - - gyro_prev = s.scene.gyro_sensor; - accel_prev = (accel_prev * (accel_samples - 1) + s.scene.accel_sensor) / accel_samples; - - return (!awake && accel_trigger && gyro_trigger); -} - void Device::updateWakefulness(const UIState &s) { bool ignition_just_turned_off = !s.scene.ignition && ignition_on; ignition_on = s.scene.ignition; - if (ignition_just_turned_off || motionTriggered(s)) { + if (ignition_just_turned_off) { resetInteractiveTimout(); } else if (interactive_timeout > 0 && --interactive_timeout == 0) { emit interactiveTimout(); diff --git a/selfdrive/ui/ui.h b/selfdrive/ui/ui.h index 382a7df5ed..9e1c54948b 100644 --- a/selfdrive/ui/ui.h +++ b/selfdrive/ui/ui.h @@ -8,24 +8,22 @@ #include #include #include +#include #include #include "cereal/messaging/messaging.h" -#include "selfdrive/common/modeldata.h" -#include "selfdrive/common/params.h" -#include "selfdrive/common/timing.h" +#include "common/modeldata.h" +#include "common/params.h" +#include "common/timing.h" const int bdr_s = 30; const int header_h = 420; const int footer_h = 280; -const int UI_FREQ = 20; // Hz +const int UI_FREQ = 20; // Hz typedef cereal::CarControl::HUDControl::AudibleAlert AudibleAlert; -// TODO: this is also hardcoded in common/transformations/camera.py -// TODO: choose based on frame input size -const float y_offset = Hardware::EON() ? 0.0 : 150.0; -const float ZOOM = Hardware::EON() ? 2138.5 : 2912.8; +const mat3 DEFAULT_CALIBRATION = {{ 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0 }}; struct Alert { QString text1; @@ -54,7 +52,7 @@ struct Alert { return {"openpilot Unavailable", "Waiting for controls to start", "controlsWaiting", cereal::ControlsState::AlertSize::MID, AudibleAlert::NONE}; - } else if (controls_missing > CONTROLS_TIMEOUT) { + } else if (controls_missing > CONTROLS_TIMEOUT && !Hardware::PC()) { // car is started, but controls is lagging or died if (cs.getEnabled() && (controls_missing - CONTROLS_TIMEOUT) < 10) { return {"TAKE CONTROL IMMEDIATELY", "Controls Unresponsive", @@ -73,39 +71,40 @@ struct Alert { typedef enum UIStatus { STATUS_DISENGAGED, + STATUS_OVERRIDE, STATUS_ENGAGED, STATUS_WARNING, STATUS_ALERT, } UIStatus; const QColor bg_colors [] = { - [STATUS_DISENGAGED] = QColor(0x17, 0x33, 0x49, 0xc8), + [STATUS_DISENGAGED] = QColor(0x17, 0x33, 0x49, 0xc8), + [STATUS_OVERRIDE] = QColor(0x91, 0x9b, 0x95, 0xf1), [STATUS_ENGAGED] = QColor(0x17, 0x86, 0x44, 0xf1), [STATUS_WARNING] = QColor(0xDA, 0x6F, 0x25, 0xf1), [STATUS_ALERT] = QColor(0xC9, 0x22, 0x31, 0xf1), }; -typedef struct { - QPointF v[TRAJECTORY_SIZE * 2]; - int cnt; -} line_vertices_data; - typedef struct UIScene { - mat3 view_from_calib; + bool calibration_valid = false; + bool calibration_wide_valid = false; + bool wide_cam = true; + mat3 view_from_calib = DEFAULT_CALIBRATION; + mat3 view_from_wide_calib = DEFAULT_CALIBRATION; cereal::PandaState::PandaType pandaType; // modelV2 float lane_line_probs[4]; float road_edge_stds[2]; - line_vertices_data track_vertices; - line_vertices_data lane_line_vertices[4]; - line_vertices_data road_edge_vertices[2]; + QPolygonF track_vertices; + QPolygonF lane_line_vertices[4]; + QPolygonF road_edge_vertices[2]; // lead QPointF lead_vertices[2]; - float light_sensor, accel_sensor, gyro_sensor; - bool started, ignition, is_metric, longitudinal_control, end_to_end; + float light_sensor; + bool started, ignition, is_metric, map_on_left, longitudinal_control; uint64_t started_frame; } UIScene; @@ -130,14 +129,16 @@ public: UIScene scene = {}; bool awake; - int prime_type = 0; + int prime_type; + QString language; QTransform car_space_transform; - bool wide_camera; + bool wide_cam_only; signals: void uiUpdate(const UIState &s); void offroadTransition(bool offroad); + void primeTypeChanged(int prime_type); private slots: void update(); @@ -145,12 +146,12 @@ private slots: private: QTimer *timer; bool started_prev = false; + int prime_type_prev = -1; }; UIState *uiState(); // device management class - class Device : public QObject { Q_OBJECT @@ -158,9 +159,6 @@ public: Device(QObject *parent = 0); private: - // auto brightness - const float accel_samples = 5*UI_FREQ; - bool awake = false; int interactive_timeout = 0; bool ignition_on = false; @@ -183,3 +181,8 @@ public slots: }; void ui_update_params(UIState *s); +int get_path_length_idx(const cereal::ModelDataV2::XYZTData::Reader &line, const float path_height); +void update_model(UIState *s, const cereal::ModelDataV2::Reader &model); +void update_leads(UIState *s, const cereal::RadarState::Reader &radar_state, const cereal::ModelDataV2::XYZTData::Reader &line); +void update_line_data(const UIState *s, const cereal::ModelDataV2::XYZTData::Reader &line, + float y_off, float z_off, QPolygonF *pvd, int max_idx, bool allow_invert); diff --git a/selfdrive/ui/update_translations.py b/selfdrive/ui/update_translations.py new file mode 100755 index 0000000000..e15d4c3433 --- /dev/null +++ b/selfdrive/ui/update_translations.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 +import argparse +import json +import os + +from common.basedir import BASEDIR + +UI_DIR = os.path.join(BASEDIR, "selfdrive", "ui") +TRANSLATIONS_DIR = os.path.join(UI_DIR, "translations") +LANGUAGES_FILE = os.path.join(TRANSLATIONS_DIR, "languages.json") + + +def update_translations(vanish=False, plural_only=None, translations_dir=TRANSLATIONS_DIR): + if plural_only is None: + plural_only = [] + + with open(LANGUAGES_FILE, "r") as f: + translation_files = json.load(f) + + for file in translation_files.values(): + tr_file = os.path.join(translations_dir, f"{file}.ts") + args = f"lupdate -locations none -recursive {UI_DIR} -ts {tr_file}" + if vanish: + args += " -no-obsolete" + if file in plural_only: + args += " -pluralonly" + ret = os.system(args) + assert ret == 0 + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Update translation files for UI", + formatter_class=argparse.ArgumentDefaultsHelpFormatter) + parser.add_argument("--vanish", action="store_true", help="Remove translations with source text no longer found") + parser.add_argument("--plural-only", type=str, nargs="*", default=["main_en"], help="Translation codes to only create plural translations for (ie. the base language)") + args = parser.parse_args() + + update_translations(args.vanish, args.plural_only) diff --git a/selfdrive/ui/watch3.cc b/selfdrive/ui/watch3.cc index 73c8e11318..ec35c29b6b 100644 --- a/selfdrive/ui/watch3.cc +++ b/selfdrive/ui/watch3.cc @@ -6,9 +6,7 @@ #include "selfdrive/ui/qt/widgets/cameraview.h" int main(int argc, char *argv[]) { - QSurfaceFormat fmt; - fmt.setRenderableType(QSurfaceFormat::OpenGLES); - QSurfaceFormat::setDefaultFormat(fmt); + initApp(argc, argv); QApplication a(argc, argv); QWidget w; @@ -21,15 +19,15 @@ int main(int argc, char *argv[]) { { QHBoxLayout *hlayout = new QHBoxLayout(); layout->addLayout(hlayout); - hlayout->addWidget(new CameraViewWidget("navd", VISION_STREAM_RGB_MAP, false)); - hlayout->addWidget(new CameraViewWidget("camerad", VISION_STREAM_RGB_BACK, false)); + hlayout->addWidget(new CameraWidget("navd", VISION_STREAM_MAP, false)); + hlayout->addWidget(new CameraWidget("camerad", VISION_STREAM_ROAD, false)); } { QHBoxLayout *hlayout = new QHBoxLayout(); layout->addLayout(hlayout); - hlayout->addWidget(new CameraViewWidget("camerad", VISION_STREAM_RGB_FRONT, false)); - hlayout->addWidget(new CameraViewWidget("camerad", VISION_STREAM_RGB_WIDE, false)); + hlayout->addWidget(new CameraWidget("camerad", VISION_STREAM_DRIVER, false)); + hlayout->addWidget(new CameraWidget("camerad", VISION_STREAM_WIDE_ROAD, false)); } return a.exec(); diff --git a/selfdrive/updated.py b/selfdrive/updated.py index 1a87798619..9da2a05a11 100755 --- a/selfdrive/updated.py +++ b/selfdrive/updated.py @@ -1,28 +1,6 @@ #!/usr/bin/env python3 - -# Safe Update: A simple service that waits for network access and tries to -# update every 10 minutes. It's intended to make the OP update process more -# robust against Git repository corruption. This service DOES NOT try to fix -# an already-corrupt BASEDIR Git repo, only prevent it from happening. -# -# During normal operation, both onroad and offroad, the update process makes -# no changes to the BASEDIR install of OP. All update attempts are performed -# in a disposable staging area provided by OverlayFS. It assumes the deleter -# process provides enough disk space to carry out the process. -# -# If an update succeeds, a flag is set, and the update is swapped in at the -# next reboot. If an update is interrupted or otherwise fails, the OverlayFS -# upper layer and metadata can be discarded before trying again. -# -# The swap on boot is triggered by launch_chffrplus.sh -# gated on the existence of $FINALIZED/.overlay_consistent and also the -# existence and mtime of $BASEDIR/.overlay_init. -# -# Other than build byproducts, BASEDIR should not be modified while this -# service is running. Developers modifying code directly in BASEDIR should -# disable this service. - import os +import re import datetime import subprocess import psutil @@ -31,63 +9,53 @@ import signal import fcntl import time import threading +from collections import defaultdict from pathlib import Path -from typing import List, Tuple, Optional +from typing import List, Union, Optional +from markdown_it import MarkdownIt from common.basedir import BASEDIR -from common.markdown import parse_markdown from common.params import Params -from selfdrive.hardware import EON, TICI, HARDWARE -from selfdrive.swaglog import cloudlog +from system.hardware import AGNOS, HARDWARE +from system.swaglog import cloudlog from selfdrive.controls.lib.alertmanager import set_offroad_alert -from selfdrive.version import is_tested_branch +from system.version import is_tested_branch LOCK_FILE = os.getenv("UPDATER_LOCK_FILE", "/tmp/safe_staging_overlay.lock") STAGING_ROOT = os.getenv("UPDATER_STAGING_ROOT", "/data/safe_staging") -NEOSUPDATE_DIR = os.getenv("UPDATER_NEOSUPDATE_DIR", "/data/neoupdate") - OVERLAY_UPPER = os.path.join(STAGING_ROOT, "upper") OVERLAY_METADATA = os.path.join(STAGING_ROOT, "metadata") OVERLAY_MERGED = os.path.join(STAGING_ROOT, "merged") FINALIZED = os.path.join(STAGING_ROOT, "finalized") +OVERLAY_INIT = Path(os.path.join(BASEDIR, ".overlay_init")) + DAYS_NO_CONNECTIVITY_MAX = 14 # do not allow to engage after this many days DAYS_NO_CONNECTIVITY_PROMPT = 10 # send an offroad prompt after this many days class WaitTimeHelper: - def __init__(self, proc): - self.proc = proc + def __init__(self): self.ready_event = threading.Event() - self.shutdown = False - signal.signal(signal.SIGTERM, self.graceful_shutdown) - signal.signal(signal.SIGINT, self.graceful_shutdown) + self.only_check_for_update = False signal.signal(signal.SIGHUP, self.update_now) + signal.signal(signal.SIGUSR1, self.check_now) - def graceful_shutdown(self, signum: int, frame) -> None: - # umount -f doesn't appear effective in avoiding "device busy" on NEOS, - # so don't actually die until the next convenient opportunity in main(). - cloudlog.info("caught SIGINT/SIGTERM, dismounting overlay at next opportunity") - - # forward the signal to all our child processes - child_procs = self.proc.children(recursive=True) - for p in child_procs: - p.send_signal(signum) - - self.shutdown = True + def update_now(self, signum: int, frame) -> None: + cloudlog.info("caught SIGHUP, attempting to downloading update") + self.only_check_for_update = False self.ready_event.set() - def update_now(self, signum: int, frame) -> None: - cloudlog.info("caught SIGHUP, running update check immediately") + def check_now(self, signum: int, frame) -> None: + cloudlog.info("caught SIGUSR1, checking for updates") + self.only_check_for_update = True self.ready_event.set() def sleep(self, t: float) -> None: self.ready_event.wait(timeout=t) -def run(cmd: List[str], cwd: Optional[str] = None, low_priority: bool = False): - if low_priority: - cmd = ["nice", "-n", "19"] + cmd +def run(cmd: List[str], cwd: Optional[str] = None) -> str: return subprocess.check_output(cmd, cwd=cwd, stderr=subprocess.STDOUT, encoding='utf8') @@ -100,59 +68,19 @@ def set_consistent_flag(consistent: bool) -> None: consistent_file.unlink(missing_ok=True) os.sync() - -def set_params(new_version: bool, failed_count: int, exception: Optional[str]) -> None: - params = Params() - - params.put("UpdateFailedCount", str(failed_count)) - - last_update = datetime.datetime.utcnow() - if failed_count == 0: - t = last_update.isoformat() - params.put("LastUpdateTime", t.encode('utf8')) - else: - try: - t = params.get("LastUpdateTime", encoding='utf8') - last_update = datetime.datetime.fromisoformat(t) - except (TypeError, ValueError): - pass - - if exception is None: - params.delete("LastUpdateException") - else: - params.put("LastUpdateException", exception) - - # Write out release notes for new versions - if new_version: +def parse_release_notes(basedir: str) -> bytes: + try: + with open(os.path.join(basedir, "RELEASES.md"), "rb") as f: + r = f.read().split(b'\n\n', 1)[0] # Slice latest release notes try: - with open(os.path.join(FINALIZED, "RELEASES.md"), "rb") as f: - r = f.read().split(b'\n\n', 1)[0] # Slice latest release notes - try: - params.put("ReleaseNotes", parse_markdown(r.decode("utf-8"))) - except Exception: - params.put("ReleaseNotes", r + b"\n") + return bytes(MarkdownIt().render(r.decode("utf-8")), encoding="utf-8") except Exception: - params.put("ReleaseNotes", "") - params.put_bool("UpdateAvailable", True) - - # Handle user prompt - for alert in ("Offroad_UpdateFailed", "Offroad_ConnectivityNeeded", "Offroad_ConnectivityNeededPrompt"): - set_offroad_alert(alert, False) - - now = datetime.datetime.utcnow() - dt = now - last_update - if failed_count > 15 and exception is not None: - if is_tested_branch(): - extra_text = "Ensure the software is correctly installed" - else: - extra_text = exception - set_offroad_alert("Offroad_UpdateFailed", True, extra_text=extra_text) - elif dt.days > DAYS_NO_CONNECTIVITY_MAX and failed_count > 1: - set_offroad_alert("Offroad_ConnectivityNeeded", True) - elif dt.days > DAYS_NO_CONNECTIVITY_PROMPT: - remaining = max(DAYS_NO_CONNECTIVITY_MAX - dt.days, 1) - set_offroad_alert("Offroad_ConnectivityNeededPrompt", True, extra_text=f"{remaining} day{'' if remaining == 1 else 's'}.") - + return r + b"\n" + except FileNotFoundError: + pass + except Exception: + cloudlog.exception("failed to parse release notes") + return b"" def setup_git_options(cwd: str) -> None: # We sync FS object atimes (which NEOS doesn't use) and mtimes, but ctimes @@ -163,9 +91,15 @@ def setup_git_options(cwd: str) -> None: # We are using copytree to copy the directory, which also changes # inode numbers. Ignore those changes too. + + # Set protocol to the new version (default after git 2.26) to reduce data + # usage on git fetch --dry-run from about 400KB to 18KB. git_cfg = [ ("core.trustctime", "false"), ("core.checkStat", "minimal"), + ("protocol.version", "2"), + ("gc.auto", "0"), + ("gc.autoDetach", "false"), ] for option, value in git_cfg: run(["git", "config", option, value], cwd) @@ -174,20 +108,15 @@ def setup_git_options(cwd: str) -> None: def dismount_overlay() -> None: if os.path.ismount(OVERLAY_MERGED): cloudlog.info("unmounting existing overlay") - args = ["umount", "-l", OVERLAY_MERGED] - if TICI: - args = ["sudo"] + args - run(args) + run(["sudo", "umount", "-l", OVERLAY_MERGED]) def init_overlay() -> None: - overlay_init_file = Path(os.path.join(BASEDIR, ".overlay_init")) - # Re-create the overlay if BASEDIR/.git has changed since we created the overlay - if overlay_init_file.is_file(): + if OVERLAY_INIT.is_file() and os.path.ismount(OVERLAY_MERGED): git_dir_path = os.path.join(BASEDIR, ".git") - new_files = run(["find", git_dir_path, "-newer", str(overlay_init_file)]) + new_files = run(["find", git_dir_path, "-newer", str(OVERLAY_INIT)]) if not len(new_files.splitlines()): # A valid overlay already exists return @@ -200,8 +129,7 @@ def init_overlay() -> None: params.put_bool("UpdateAvailable", False) set_consistent_flag(False) dismount_overlay() - if TICI: - run(["sudo", "rm", "-rf", STAGING_ROOT]) + run(["sudo", "rm", "-rf", STAGING_ROOT]) if os.path.isdir(STAGING_ROOT): shutil.rmtree(STAGING_ROOT) @@ -219,19 +147,16 @@ def init_overlay() -> None: consistent_file = Path(os.path.join(BASEDIR, ".overlay_consistent")) if consistent_file.is_file(): consistent_file.unlink() - overlay_init_file.touch() + OVERLAY_INIT.touch() os.sync() overlay_opts = f"lowerdir={BASEDIR},upperdir={OVERLAY_UPPER},workdir={OVERLAY_METADATA}" mount_cmd = ["mount", "-t", "overlay", "-o", overlay_opts, "none", OVERLAY_MERGED] - if TICI: - run(["sudo"] + mount_cmd) - run(["sudo", "chmod", "755", os.path.join(OVERLAY_METADATA, "work")]) - else: - run(mount_cmd) + run(["sudo"] + mount_cmd) + run(["sudo", "chmod", "755", os.path.join(OVERLAY_METADATA, "work")]) - git_diff = run(["git", "diff"], OVERLAY_MERGED, low_priority=True) + git_diff = run(["git", "diff"], OVERLAY_MERGED) params.put("GitDiff", git_diff) cloudlog.info(f"git diff output:\n{git_diff}") @@ -250,14 +175,23 @@ def finalize_update() -> None: shutil.copytree(OVERLAY_MERGED, FINALIZED, symlinks=True) run(["git", "reset", "--hard"], FINALIZED) - run(["git", "submodule", "foreach", "--recursive", "git", "reset"], FINALIZED) + run(["git", "submodule", "foreach", "--recursive", "git", "reset", "--hard"], FINALIZED) + + cloudlog.info("Starting git cleanup in finalized update") + t = time.monotonic() + try: + run(["git", "gc"], FINALIZED) + run(["git", "lfs", "prune"], FINALIZED) + cloudlog.event("Done git cleanup", duration=time.monotonic() - t) + except subprocess.CalledProcessError: + cloudlog.exception(f"Failed git cleanup, took {time.monotonic() - t:.3f} s") set_consistent_flag(True) cloudlog.info("done finalizing overlay") -def handle_agnos_update(wait_helper: WaitTimeHelper) -> None: - from selfdrive.hardware.tici.agnos import flash_agnos_update, get_target_slot_number +def handle_agnos_update() -> None: + from system.hardware.tici.agnos import flash_agnos_update, get_target_slot_number cur_version = HARDWARE.get_os_version() updated_version = run(["bash", "-c", r"unset AGNOS_VERSION && source launch_env.sh && \ @@ -273,101 +207,187 @@ def handle_agnos_update(wait_helper: WaitTimeHelper) -> None: cloudlog.info(f"Beginning background installation for AGNOS {updated_version}") set_offroad_alert("Offroad_NeosUpdate", True) - manifest_path = os.path.join(OVERLAY_MERGED, "selfdrive/hardware/tici/agnos.json") + manifest_path = os.path.join(OVERLAY_MERGED, "system/hardware/tici/agnos.json") target_slot_number = get_target_slot_number() flash_agnos_update(manifest_path, target_slot_number, cloudlog) set_offroad_alert("Offroad_NeosUpdate", False) -def handle_neos_update(wait_helper: WaitTimeHelper) -> None: - from selfdrive.hardware.eon.neos import download_neos_update - cur_neos = HARDWARE.get_os_version() - updated_neos = run(["bash", "-c", r"unset REQUIRED_NEOS_VERSION && source launch_env.sh && \ - echo -n $REQUIRED_NEOS_VERSION"], OVERLAY_MERGED).strip() +class Updater: + def __init__(self): + self.params = Params() + self.branches = defaultdict(lambda: '') + self._has_internet: bool = False + + @property + def has_internet(self) -> bool: + return self._has_internet + + @property + def target_branch(self) -> str: + b: Union[str, None] = self.params.get("UpdaterTargetBranch", encoding='utf-8') + if b is None: + b = self.get_branch(BASEDIR) + self.params.put("UpdaterTargetBranch", b) + return b + + @property + def update_ready(self) -> bool: + consistent_file = Path(os.path.join(FINALIZED, ".overlay_consistent")) + if consistent_file.is_file(): + hash_mismatch = self.get_commit_hash(BASEDIR) != self.branches[self.target_branch] + branch_mismatch = self.get_branch(BASEDIR) != self.target_branch + on_target_branch = self.get_branch(FINALIZED) == self.target_branch + return ((hash_mismatch or branch_mismatch) and on_target_branch) + return False + + @property + def update_available(self) -> bool: + if os.path.isdir(OVERLAY_MERGED): + hash_mismatch = self.get_commit_hash(OVERLAY_MERGED) != self.branches[self.target_branch] + branch_mismatch = self.get_branch(OVERLAY_MERGED) != self.target_branch + return hash_mismatch or branch_mismatch + return False + + def get_branch(self, path: str) -> str: + return run(["git", "rev-parse", "--abbrev-ref", "HEAD"], path).rstrip() + + def get_commit_hash(self, path: str = OVERLAY_MERGED) -> str: + return run(["git", "rev-parse", "HEAD"], path).rstrip() + + def set_params(self, failed_count: int, exception: Optional[str]) -> None: + self.params.put("UpdateFailedCount", str(failed_count)) + + self.params.put_bool("UpdaterFetchAvailable", self.update_available) + self.params.put("UpdaterAvailableBranches", ','.join(self.branches.keys())) + + last_update = datetime.datetime.utcnow() + if failed_count == 0: + t = last_update.isoformat() + self.params.put("LastUpdateTime", t.encode('utf8')) + else: + try: + t = self.params.get("LastUpdateTime", encoding='utf8') + last_update = datetime.datetime.fromisoformat(t) + except (TypeError, ValueError): + pass - cloudlog.info(f"NEOS version check: {cur_neos} vs {updated_neos}") - if cur_neos == updated_neos: - return + if exception is None: + self.params.remove("LastUpdateException") + else: + self.params.put("LastUpdateException", exception) - cloudlog.info(f"Beginning background download for NEOS {updated_neos}") - set_offroad_alert("Offroad_NeosUpdate", True) + # Write out current and new version info + def get_description(basedir: str) -> str: + if not os.path.exists(basedir): + return "" - update_manifest = os.path.join(OVERLAY_MERGED, "selfdrive/hardware/eon/neos.json") + version = "" + branch = "" + commit = "" + commit_date = "" + try: + branch = self.get_branch(basedir) + commit = self.get_commit_hash(basedir)[:7] + with open(os.path.join(basedir, "common", "version.h")) as f: + version = f.read().split('"')[1] + + commit_unix_ts = run(["git", "show", "-s", "--format=%ct", "HEAD"], basedir).rstrip() + dt = datetime.datetime.fromtimestamp(int(commit_unix_ts)) + commit_date = dt.strftime("%b %d") + except Exception: + cloudlog.exception("updater.get_description") + return f"{version} / {branch} / {commit} / {commit_date}" + self.params.put("UpdaterCurrentDescription", get_description(BASEDIR)) + self.params.put("UpdaterCurrentReleaseNotes", parse_release_notes(BASEDIR)) + self.params.put("UpdaterNewDescription", get_description(FINALIZED)) + self.params.put("UpdaterNewReleaseNotes", parse_release_notes(FINALIZED)) + self.params.put_bool("UpdateAvailable", self.update_ready) + + # Handle user prompt + for alert in ("Offroad_UpdateFailed", "Offroad_ConnectivityNeeded", "Offroad_ConnectivityNeededPrompt"): + set_offroad_alert(alert, False) + + now = datetime.datetime.utcnow() + dt = now - last_update + if failed_count > 15 and exception is not None and self.has_internet: + if is_tested_branch(): + extra_text = "Ensure the software is correctly installed. Uninstall and re-install if this error persists." + else: + extra_text = exception + set_offroad_alert("Offroad_UpdateFailed", True, extra_text=extra_text) + elif dt.days > DAYS_NO_CONNECTIVITY_MAX and failed_count > 1: + set_offroad_alert("Offroad_ConnectivityNeeded", True) + elif dt.days > DAYS_NO_CONNECTIVITY_PROMPT: + remaining = max(DAYS_NO_CONNECTIVITY_MAX - dt.days, 1) + set_offroad_alert("Offroad_ConnectivityNeededPrompt", True, extra_text=f"{remaining} day{'' if remaining == 1 else 's'}.") + + def check_for_update(self) -> None: + cloudlog.info("checking for updates") + + excluded_branches = ('release2', 'release2-staging', 'dashcam', 'dashcam-staging') - neos_downloaded = False - start_time = time.monotonic() - # Try to download for one day - while not neos_downloaded and not wait_helper.shutdown and \ - (time.monotonic() - start_time < 60*60*24): - wait_helper.ready_event.clear() try: - download_neos_update(update_manifest, cloudlog) - neos_downloaded = True - except Exception: - cloudlog.info("NEOS background download failed, retrying") - wait_helper.sleep(120) - - # If the download failed, we'll show the alert again when we retry - set_offroad_alert("Offroad_NeosUpdate", False) - if not neos_downloaded: - raise Exception("Failed to download NEOS update") - cloudlog.info(f"NEOS background download successful, took {time.monotonic() - start_time} seconds") - - -def check_git_fetch_result(fetch_txt: str) -> bool: - err_msg = "Failed to add the host to the list of known hosts (/data/data/com.termux/files/home/.ssh/known_hosts).\n" - return len(fetch_txt) > 0 and (fetch_txt != err_msg) - - -def check_for_update() -> Tuple[bool, bool]: - setup_git_options(OVERLAY_MERGED) - try: - git_fetch_output = run(["git", "fetch", "--dry-run"], OVERLAY_MERGED, low_priority=True) - return True, check_git_fetch_result(git_fetch_output) - except subprocess.CalledProcessError: - return False, False - + run(["git", "ls-remote", "origin", "HEAD"], OVERLAY_MERGED) + self._has_internet = True + except subprocess.CalledProcessError: + self._has_internet = False + + setup_git_options(OVERLAY_MERGED) + output = run(["git", "ls-remote", "--heads"], OVERLAY_MERGED) + + self.branches = defaultdict(lambda: None) + for line in output.split('\n'): + ls_remotes_re = r'(?P\b[0-9a-f]{5,40}\b)(\s+)(refs\/heads\/)(?P.*$)' + x = re.fullmatch(ls_remotes_re, line.strip()) + if x is not None and x.group('branch_name') not in excluded_branches: + self.branches[x.group('branch_name')] = x.group('commit_sha') + + cur_branch = self.get_branch(OVERLAY_MERGED) + cur_commit = self.get_commit_hash(OVERLAY_MERGED) + new_branch = self.target_branch + new_commit = self.branches[new_branch] + if (cur_branch, cur_commit) != (new_branch, new_commit): + cloudlog.info(f"update available, {cur_branch} ({str(cur_commit)[:7]}) -> {new_branch} ({str(new_commit)[:7]})") + else: + cloudlog.info(f"up to date on {cur_branch} ({str(cur_commit)[:7]})") -def fetch_update(wait_helper: WaitTimeHelper) -> bool: - cloudlog.info("attempting git fetch inside staging overlay") + def fetch_update(self) -> None: + cloudlog.info("attempting git fetch inside staging overlay") - setup_git_options(OVERLAY_MERGED) + self.params.put("UpdaterState", "downloading...") - git_fetch_output = run(["git", "fetch"], OVERLAY_MERGED, low_priority=True) - cloudlog.info("git fetch success: %s", git_fetch_output) + # TODO: cleanly interrupt this and invalidate old update + set_consistent_flag(False) + self.params.put_bool("UpdateAvailable", False) - cur_hash = run(["git", "rev-parse", "HEAD"], OVERLAY_MERGED).rstrip() - upstream_hash = run(["git", "rev-parse", "@{u}"], OVERLAY_MERGED).rstrip() - new_version = cur_hash != upstream_hash - git_fetch_result = check_git_fetch_result(git_fetch_output) + setup_git_options(OVERLAY_MERGED) - cloudlog.info(f"comparing {cur_hash} to {upstream_hash}") - if new_version or git_fetch_result: - cloudlog.info("Running update") + branch = self.target_branch + git_fetch_output = run(["git", "fetch", "origin", branch], OVERLAY_MERGED) + cloudlog.info("git fetch success: %s", git_fetch_output) - if new_version: - cloudlog.info("git reset in progress") - r = [ - run(["git", "reset", "--hard", "@{u}"], OVERLAY_MERGED, low_priority=True), - run(["git", "clean", "-xdf"], OVERLAY_MERGED, low_priority=True ), - run(["git", "submodule", "init"], OVERLAY_MERGED, low_priority=True), - run(["git", "submodule", "update"], OVERLAY_MERGED, low_priority=True), - ] - cloudlog.info("git reset success: %s", '\n'.join(r)) + cloudlog.info("git reset in progress") + cmds = [ + ["git", "checkout", "--force", "--no-recurse-submodules", "-B", branch, "FETCH_HEAD"], + ["git", "reset", "--hard"], + ["git", "clean", "-xdff"], + ["git", "submodule", "sync"], + ["git", "submodule", "update", "--init", "--recursive"], + ["git", "submodule", "foreach", "--recursive", "git", "reset", "--hard"], + ] + r = [run(cmd, OVERLAY_MERGED) for cmd in cmds] + cloudlog.info("git reset success: %s", '\n'.join(r)) - if EON: - handle_neos_update(wait_helper) - elif TICI: - handle_agnos_update(wait_helper) + # TODO: show agnos download progress + if AGNOS: + handle_agnos_update() # Create the finalized, ready-to-swap update + self.params.put("UpdaterState", "finalizing update...") finalize_update() - cloudlog.info("openpilot update successful!") - else: - cloudlog.info("nothing new from git at this time") - - return new_version + cloudlog.info("finalize success!") def main() -> None: @@ -396,55 +416,37 @@ def main() -> None: t = datetime.datetime.utcnow().isoformat() params.put("InstallDate", t.encode('utf8')) - overlay_init = Path(os.path.join(BASEDIR, ".overlay_init")) - overlay_init.unlink(missing_ok=True) - - first_run = True - last_fetch_time = 0.0 - update_failed_count = 0 - - # Set initial params for offroad alerts - set_params(False, 0, None) + updater = Updater() + update_failed_count = 0 # TODO: Load from param? - # Wait for IsOffroad to be set before our first update attempt - wait_helper = WaitTimeHelper(proc) - wait_helper.sleep(30) + # no fetch on the first time + wait_helper = WaitTimeHelper() + wait_helper.only_check_for_update = True # Run the update loop - # * every 1m, do a lightweight internet/update check - # * every 10m, do a full git fetch - while not wait_helper.shutdown: - update_now = wait_helper.ready_event.is_set() + while True: wait_helper.ready_event.clear() - # Don't run updater while onroad or if the time's wrong - time_wrong = datetime.datetime.utcnow().year < 2019 - is_onroad = not params.get_bool("IsOffroad") - if is_onroad or time_wrong: - wait_helper.sleep(30) - cloudlog.info("not running updater, not offroad") - continue - # Attempt an update exception = None - new_version = False - update_failed_count += 1 try: + # TODO: reuse overlay from previous updated instance if it looks clean init_overlay() - internet_ok, update_available = check_for_update() - if internet_ok and not update_available: - update_failed_count = 0 + # ensure we have some params written soon after startup + updater.set_params(update_failed_count, exception) + update_failed_count += 1 - # Fetch updates at most every 10 minutes - if internet_ok and (update_now or time.monotonic() - last_fetch_time > 60*10): - new_version = fetch_update(wait_helper) - update_failed_count = 0 - last_fetch_time = time.monotonic() + # check for update + params.put("UpdaterState", "checking...") + updater.check_for_update() - if first_run and not new_version and os.path.isdir(NEOSUPDATE_DIR): - shutil.rmtree(NEOSUPDATE_DIR) - first_run = False + # download update + if wait_helper.only_check_for_update: + cloudlog.info("skipping fetch this cycle") + else: + updater.fetch_update() + update_failed_count = 0 except subprocess.CalledProcessError as e: cloudlog.event( "update process failed", @@ -453,20 +455,21 @@ def main() -> None: returncode=e.returncode ) exception = f"command failed: {e.cmd}\n{e.output}" - overlay_init.unlink(missing_ok=True) + OVERLAY_INIT.unlink(missing_ok=True) except Exception as e: cloudlog.exception("uncaught updated exception, shouldn't happen") exception = str(e) - overlay_init.unlink(missing_ok=True) + OVERLAY_INIT.unlink(missing_ok=True) try: - set_params(new_version, update_failed_count, exception) + params.put("UpdaterState", "idle") + updater.set_params(update_failed_count, exception) except Exception: cloudlog.exception("uncaught updated exception while setting params, shouldn't happen") - wait_helper.sleep(60) - - dismount_overlay() + # infrequent attempts if we successfully updated recently + wait_helper.only_check_for_update = False + wait_helper.sleep(5*60 if update_failed_count > 0 else 1.5*60*60) if __name__ == "__main__": diff --git a/system/__init__.py b/system/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/system/camerad/SConscript b/system/camerad/SConscript new file mode 100644 index 0000000000..ddc763b53d --- /dev/null +++ b/system/camerad/SConscript @@ -0,0 +1,18 @@ +Import('env', 'arch', 'cereal', 'messaging', 'common', 'gpucommon', 'visionipc') + +libs = ['m', 'pthread', common, 'jpeg', 'OpenCL', 'yuv', cereal, messaging, 'zmq', 'capnp', 'kj', visionipc, gpucommon, 'atomic'] + +cenv = env.Clone() +cenv['CPPPATH'].append('include/') + +camera_obj = cenv.Object(['cameras/camera_qcom2.cc', 'cameras/camera_common.cc', 'cameras/camera_util.cc']) +cenv.Program('camerad', [ + 'main.cc', + camera_obj, + ], LIBS=libs) + +if GetOption("test") and arch == "x86_64": + cenv.Program('test/ae_gray_test', [ + 'test/ae_gray_test.cc', + camera_obj, + ], LIBS=libs) diff --git a/system/camerad/__init__.py b/system/camerad/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/selfdrive/camerad/cameras/camera_common.cc b/system/camerad/cameras/camera_common.cc similarity index 51% rename from selfdrive/camerad/cameras/camera_common.cc rename to system/camerad/cameras/camera_common.cc index f534cad99c..30e2810ec4 100644 --- a/selfdrive/camerad/cameras/camera_common.cc +++ b/system/camerad/cameras/camera_common.cc @@ -1,4 +1,4 @@ -#include "selfdrive/camerad/cameras/camera_common.h" +#include "system/camerad/cameras/camera_common.h" #include @@ -10,75 +10,48 @@ #include "libyuv.h" #include -#include "selfdrive/camerad/imgproc/utils.h" -#include "selfdrive/common/clutil.h" -#include "selfdrive/common/modeldata.h" -#include "selfdrive/common/params.h" -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/util.h" -#include "selfdrive/hardware/hw.h" +#include "system/camerad/imgproc/utils.h" +#include "common/clutil.h" +#include "common/modeldata.h" +#include "common/swaglog.h" +#include "common/util.h" +#include "system/hardware/hw.h" +#include "msm_media_info.h" -#ifdef QCOM +#include "system/camerad/cameras/camera_qcom2.h" +#ifdef QCOM2 #include "CL/cl_ext_qcom.h" -#include "selfdrive/camerad/cameras/camera_qcom.h" -#elif QCOM2 -#include "CL/cl_ext_qcom.h" -#include "selfdrive/camerad/cameras/camera_qcom2.h" -#elif WEBCAM -#include "selfdrive/camerad/cameras/camera_webcam.h" -#else -#include "selfdrive/camerad/cameras/camera_replay.h" #endif ExitHandler do_exit; class Debayer { public: - Debayer(cl_device_id device_id, cl_context context, const CameraBuf *b, const CameraState *s) { + Debayer(cl_device_id device_id, cl_context context, const CameraBuf *b, const CameraState *s, int buf_width, int uv_offset) { char args[4096]; const CameraInfo *ci = &s->ci; - hdr_ = ci->hdr; snprintf(args, sizeof(args), "-cl-fast-relaxed-math -cl-denorms-are-zero " - "-DFRAME_WIDTH=%d -DFRAME_HEIGHT=%d -DFRAME_STRIDE=%d " - "-DRGB_WIDTH=%d -DRGB_HEIGHT=%d -DRGB_STRIDE=%d " - "-DBAYER_FLIP=%d -DHDR=%d -DCAM_NUM=%d", - ci->frame_width, ci->frame_height, ci->frame_stride, - b->rgb_width, b->rgb_height, b->rgb_stride, - ci->bayer_flip, ci->hdr, s->camera_num); - const char *cl_file = Hardware::TICI() ? "cameras/real_debayer.cl" : "cameras/debayer.cl"; + "-DFRAME_WIDTH=%d -DFRAME_HEIGHT=%d -DFRAME_STRIDE=%d -DFRAME_OFFSET=%d " + "-DRGB_WIDTH=%d -DRGB_HEIGHT=%d -DRGB_STRIDE=%d -DYUV_STRIDE=%d -DUV_OFFSET=%d " + "-DIS_OX=%d -DCAM_NUM=%d%s", + ci->frame_width, ci->frame_height, ci->frame_stride, ci->frame_offset, + b->rgb_width, b->rgb_height, b->rgb_stride, buf_width, uv_offset, + s->camera_id==CAMERA_ID_OX03C10 ? 1 : 0, s->camera_num, s->camera_num==1 ? " -DVIGNETTING" : ""); + const char *cl_file = "cameras/real_debayer.cl"; cl_program prg_debayer = cl_program_from_file(context, device_id, cl_file, args); krnl_ = CL_CHECK_ERR(clCreateKernel(prg_debayer, "debayer10", &err)); CL_CHECK(clReleaseProgram(prg_debayer)); } - void queue(cl_command_queue q, cl_mem cam_buf_cl, cl_mem buf_cl, int width, int height, float gain, cl_event *debayer_event) { + void queue(cl_command_queue q, cl_mem cam_buf_cl, cl_mem buf_cl, int width, int height, cl_event *debayer_event) { CL_CHECK(clSetKernelArg(krnl_, 0, sizeof(cl_mem), &cam_buf_cl)); CL_CHECK(clSetKernelArg(krnl_, 1, sizeof(cl_mem), &buf_cl)); - if (Hardware::TICI()) { - const int debayer_local_worksize = 16; - constexpr int localMemSize = (debayer_local_worksize + 2 * (3 / 2)) * (debayer_local_worksize + 2 * (3 / 2)) * sizeof(short int); - const size_t globalWorkSize[] = {size_t(width), size_t(height)}; - const size_t localWorkSize[] = {debayer_local_worksize, debayer_local_worksize}; - CL_CHECK(clSetKernelArg(krnl_, 2, localMemSize, 0)); - CL_CHECK(clEnqueueNDRangeKernel(q, krnl_, 2, NULL, globalWorkSize, localWorkSize, 0, 0, debayer_event)); - } else { - if (hdr_) { - // HDR requires a 1-D kernel due to the DPCM compression - const size_t debayer_local_worksize = 128; - const size_t debayer_work_size = height; // doesn't divide evenly, is this okay? - CL_CHECK(clSetKernelArg(krnl_, 2, sizeof(float), &gain)); - CL_CHECK(clEnqueueNDRangeKernel(q, krnl_, 1, NULL, &debayer_work_size, &debayer_local_worksize, 0, 0, debayer_event)); - } else { - const int debayer_local_worksize = 32; - assert(width % 2 == 0); - const size_t globalWorkSize[] = {size_t(height), size_t(width / 2)}; - const size_t localWorkSize[] = {debayer_local_worksize, debayer_local_worksize}; - CL_CHECK(clSetKernelArg(krnl_, 2, sizeof(float), &gain)); - CL_CHECK(clEnqueueNDRangeKernel(q, krnl_, 2, NULL, globalWorkSize, localWorkSize, 0, 0, debayer_event)); - } - } + const size_t globalWorkSize[] = {size_t(width / 2), size_t(height / 2)}; + const int debayer_local_worksize = 16; + const size_t localWorkSize[] = {debayer_local_worksize, debayer_local_worksize}; + CL_CHECK(clEnqueueNDRangeKernel(q, krnl_, 2, NULL, globalWorkSize, localWorkSize, 0, 0, debayer_event)); } ~Debayer() { @@ -87,21 +60,16 @@ public: private: cl_kernel krnl_; - bool hdr_; }; -void CameraBuf::init(cl_device_id device_id, cl_context context, CameraState *s, VisionIpcServer * v, int frame_cnt, VisionStreamType init_rgb_type, VisionStreamType init_yuv_type, release_cb init_release_callback) { +void CameraBuf::init(cl_device_id device_id, cl_context context, CameraState *s, VisionIpcServer * v, int frame_cnt, VisionStreamType init_yuv_type) { vipc_server = v; - this->rgb_type = init_rgb_type; this->yuv_type = init_yuv_type; - this->release_callback = init_release_callback; - - const CameraInfo *ci = &s->ci; - camera_state = s; frame_buf_count = frame_cnt; + const CameraInfo *ci = &s->ci; // RAW frame - const int frame_size = ci->frame_height * ci->frame_stride; + const int frame_size = (ci->frame_height + ci->extra_height) * ci->frame_stride; camera_bufs = std::make_unique(frame_buf_count); camera_bufs_metadata = std::make_unique(frame_buf_count); @@ -109,27 +77,23 @@ void CameraBuf::init(cl_device_id device_id, cl_context context, CameraState *s, camera_bufs[i].allocate(frame_size); camera_bufs[i].init_cl(device_id, context); } + LOGD("allocated %d CL buffers", frame_buf_count); rgb_width = ci->frame_width; rgb_height = ci->frame_height; - if (!Hardware::TICI() && ci->bayer) { - // debayering does a 2x downscale - rgb_width = ci->frame_width / 2; - rgb_height = ci->frame_height / 2; - } - - yuv_transform = get_model_yuv_transform(ci->bayer); + yuv_transform = get_model_yuv_transform(); - vipc_server->create_buffers(rgb_type, UI_BUF_COUNT, true, rgb_width, rgb_height); - rgb_stride = vipc_server->get_buffer(rgb_type)->stride; + int nv12_width = VENUS_Y_STRIDE(COLOR_FMT_NV12, rgb_width); + int nv12_height = VENUS_Y_SCANLINES(COLOR_FMT_NV12, rgb_height); + assert(nv12_width == VENUS_UV_STRIDE(COLOR_FMT_NV12, rgb_width)); + assert(nv12_height/2 == VENUS_UV_SCANLINES(COLOR_FMT_NV12, rgb_height)); + size_t nv12_size = 2346 * nv12_width; // comes from v4l2_format.fmt.pix_mp.plane_fmt[0].sizeimage + size_t nv12_uv_offset = nv12_width * nv12_height; + vipc_server->create_buffers_with_sizes(yuv_type, YUV_BUFFER_COUNT, false, rgb_width, rgb_height, nv12_size, nv12_width, nv12_uv_offset); + LOGD("created %d YUV vipc buffers with size %dx%d", YUV_BUFFER_COUNT, nv12_width, nv12_height); - vipc_server->create_buffers(yuv_type, YUV_BUFFER_COUNT, false, rgb_width, rgb_height); - - if (ci->bayer) { - debayer = new Debayer(device_id, context, this, s); - } - rgb2yuv = std::make_unique(context, device_id, rgb_width, rgb_height, rgb_stride); + debayer = new Debayer(device_id, context, this, s, nv12_width, nv12_uv_offset); #ifdef __APPLE__ q = CL_CHECK_ERR(clCreateCommandQueue(context, device_id, 0, &err)); @@ -148,65 +112,42 @@ CameraBuf::~CameraBuf() { } bool CameraBuf::acquire() { - if (!safe_queue.try_pop(cur_buf_idx, 1)) return false; + if (!safe_queue.try_pop(cur_buf_idx, 50)) return false; if (camera_bufs_metadata[cur_buf_idx].frame_id == -1) { LOGE("no frame data? wtf"); - release(); return false; } cur_frame_data = camera_bufs_metadata[cur_buf_idx]; - cur_rgb_buf = vipc_server->get_buffer(rgb_type); - cl_mem camrabuf_cl = camera_bufs[cur_buf_idx].buf_cl; - cl_event event; - - if (debayer) { - float gain = 0.0; - -#ifndef QCOM2 - gain = camera_state->digital_gain; - if ((int)gain == 0) gain = 1.0; -#endif - - debayer->queue(q, camrabuf_cl, cur_rgb_buf->buf_cl, rgb_width, rgb_height, gain, &event); - } else { - assert(rgb_stride == camera_state->ci.frame_stride); - CL_CHECK(clEnqueueCopyBuffer(q, camrabuf_cl, cur_rgb_buf->buf_cl, 0, 0, cur_rgb_buf->len, 0, 0, &event)); - } + cur_yuv_buf = vipc_server->get_buffer(yuv_type); + cur_camera_buf = &camera_bufs[cur_buf_idx]; + double start_time = millis_since_boot(); + cl_event event; + debayer->queue(q, camera_bufs[cur_buf_idx].buf_cl, cur_yuv_buf->buf_cl, rgb_width, rgb_height, &event); clWaitForEvents(1, &event); CL_CHECK(clReleaseEvent(event)); - - cur_yuv_buf = vipc_server->get_buffer(yuv_type); - rgb2yuv->queue(q, cur_rgb_buf->buf_cl, cur_yuv_buf->buf_cl); + cur_frame_data.processing_time = (millis_since_boot() - start_time) / 1000.0; VisionIpcBufExtra extra = { - cur_frame_data.frame_id, - cur_frame_data.timestamp_sof, - cur_frame_data.timestamp_eof, + cur_frame_data.frame_id, + cur_frame_data.timestamp_sof, + cur_frame_data.timestamp_eof, }; - cur_rgb_buf->set_frame_id(cur_frame_data.frame_id); cur_yuv_buf->set_frame_id(cur_frame_data.frame_id); - vipc_server->send(cur_rgb_buf, &extra); vipc_server->send(cur_yuv_buf, &extra); return true; } -void CameraBuf::release() { - if (release_callback) { - release_callback((void*)camera_state, cur_buf_idx); - } -} - void CameraBuf::queue(size_t buf_idx) { safe_queue.push(buf_idx); } // common functions -void fill_frame_data(cereal::FrameData::Builder &framed, const FrameMetadata &frame_data) { +void fill_frame_data(cereal::FrameData::Builder &framed, const FrameMetadata &frame_data, CameraState *c) { framed.setFrameId(frame_data.frame_id); framed.setTimestampEof(frame_data.timestamp_eof); framed.setTimestampSof(frame_data.timestamp_sof); @@ -219,49 +160,53 @@ void fill_frame_data(cereal::FrameData::Builder &framed, const FrameMetadata &fr framed.setLensPos(frame_data.lens_pos); framed.setLensErr(frame_data.lens_err); framed.setLensTruePos(frame_data.lens_true_pos); -} + framed.setProcessingTime(frame_data.processing_time); -kj::Array get_frame_image(const CameraBuf *b) { - static const int x_min = util::getenv("XMIN", 0); - static const int y_min = util::getenv("YMIN", 0); - static const int env_xmax = util::getenv("XMAX", -1); - static const int env_ymax = util::getenv("YMAX", -1); - static const int scale = util::getenv("SCALE", 1); + const float ev = c->cur_ev[frame_data.frame_id % 3]; + const float perc = util::map_val(ev, c->min_ev, c->max_ev, 0.0f, 100.0f); + framed.setExposureValPercent(perc); - assert(b->cur_rgb_buf); + if (c->camera_id == CAMERA_ID_AR0231) { + framed.setSensor(cereal::FrameData::ImageSensor::AR0321); + } else if (c->camera_id == CAMERA_ID_OX03C10) { + framed.setSensor(cereal::FrameData::ImageSensor::OX03C10); + } +} - const int x_max = env_xmax != -1 ? env_xmax : b->rgb_width - 1; - const int y_max = env_ymax != -1 ? env_ymax : b->rgb_height - 1; - const int new_width = (x_max - x_min + 1) / scale; - const int new_height = (y_max - y_min + 1) / scale; - const uint8_t *dat = (const uint8_t *)b->cur_rgb_buf->addr; +kj::Array get_raw_frame_image(const CameraBuf *b) { + const uint8_t *dat = (const uint8_t *)b->cur_camera_buf->addr; - kj::Array frame_image = kj::heapArray(new_width*new_height*3); + kj::Array frame_image = kj::heapArray(b->cur_camera_buf->len); uint8_t *resized_dat = frame_image.begin(); - int goff = x_min*3 + y_min*b->rgb_stride; - for (int r=0;rrgb_stride*scale+c*3*scale], 3*sizeof(uint8_t)); - } - } + + memcpy(resized_dat, dat, b->cur_camera_buf->len); + return kj::mv(frame_image); } static kj::Array yuv420_to_jpeg(const CameraBuf *b, int thumbnail_width, int thumbnail_height) { + int downscale = b->cur_yuv_buf->width / thumbnail_width; + assert(downscale * thumbnail_height == b->cur_yuv_buf->height); + int in_stride = b->cur_yuv_buf->stride; + // make the buffer big enough. jpeg_write_raw_data requires 16-pixels aligned height to be used. std::unique_ptr buf(new uint8_t[(thumbnail_width * ((thumbnail_height + 15) & ~15) * 3) / 2]); uint8_t *y_plane = buf.get(); uint8_t *u_plane = y_plane + thumbnail_width * thumbnail_height; uint8_t *v_plane = u_plane + (thumbnail_width * thumbnail_height) / 4; { - int result = libyuv::I420Scale( - b->cur_yuv_buf->y, b->rgb_width, b->cur_yuv_buf->u, b->rgb_width / 2, b->cur_yuv_buf->v, b->rgb_width / 2, - b->rgb_width, b->rgb_height, - y_plane, thumbnail_width, u_plane, thumbnail_width / 2, v_plane, thumbnail_width / 2, - thumbnail_width, thumbnail_height, libyuv::kFilterNone); - if (result != 0) { - LOGE("Generate YUV thumbnail failed."); - return {}; + // subsampled conversion from nv12 to yuv + for (int hy = 0; hy < thumbnail_height/2; hy++) { + for (int hx = 0; hx < thumbnail_width/2; hx++) { + int ix = hx * downscale + (downscale-1)/2; + int iy = hy * downscale + (downscale-1)/2; + y_plane[(hy*2 + 0)*thumbnail_width + (hx*2 + 0)] = b->cur_yuv_buf->y[(iy*2 + 0) * in_stride + ix*2 + 0]; + y_plane[(hy*2 + 0)*thumbnail_width + (hx*2 + 1)] = b->cur_yuv_buf->y[(iy*2 + 0) * in_stride + ix*2 + 1]; + y_plane[(hy*2 + 1)*thumbnail_width + (hx*2 + 0)] = b->cur_yuv_buf->y[(iy*2 + 1) * in_stride + ix*2 + 0]; + y_plane[(hy*2 + 1)*thumbnail_width + (hx*2 + 1)] = b->cur_yuv_buf->y[(iy*2 + 1) * in_stride + ix*2 + 1]; + u_plane[hy*thumbnail_width/2 + hx] = b->cur_yuv_buf->uv[iy*in_stride + ix*2 + 0]; + v_plane[hy*thumbnail_width/2 + hx] = b->cur_yuv_buf->uv[iy*in_stride + ix*2 + 1]; + } } } @@ -377,7 +322,6 @@ void *processing_thread(MultiCameraState *cameras, CameraState *cs, process_thre // this takes 10ms??? publish_thumbnail(cameras->pm, &(cs->buf)); } - cs->buf.release(); ++cnt; } return NULL; @@ -387,76 +331,26 @@ std::thread start_process_thread(MultiCameraState *cameras, CameraState *cs, pro return std::thread(processing_thread, cameras, cs, callback); } -static void driver_cam_auto_exposure(CameraState *c, SubMaster &sm) { - static const bool is_rhd = Params().getBool("IsRHD"); - struct ExpRect {int x1, x2, x_skip, y1, y2, y_skip;}; - const CameraBuf *b = &c->buf; - - int x_offset = 0, y_offset = 0; - int frame_width = b->rgb_width, frame_height = b->rgb_height; - - - ExpRect def_rect; - if (Hardware::TICI()) { - x_offset = 630, y_offset = 156; - frame_width = 668, frame_height = frame_width / 1.33; - def_rect = {96, 1832, 2, 242, 1148, 4}; - } else { - def_rect = {is_rhd ? 0 : b->rgb_width * 3 / 5, is_rhd ? b->rgb_width * 2 / 5 : b->rgb_width, 2, - b->rgb_height / 3, b->rgb_height, 1}; - } - - static ExpRect rect = def_rect; - // use driver face crop for AE - if (Hardware::EON() && sm.updated("driverState")) { - if (auto state = sm["driverState"].getDriverState(); state.getFaceProb() > 0.4) { - auto face_position = state.getFacePosition(); - int x = is_rhd ? 0 : frame_width - (0.5 * frame_height); - x += (face_position[0] * (is_rhd ? -1.0 : 1.0) + 0.5) * (0.5 * frame_height) + x_offset; - int y = (face_position[1] + 0.5) * frame_height + y_offset; - rect = {std::max(0, x - 72), std::min(b->rgb_width - 1, x + 72), 2, - std::max(0, y - 72), std::min(b->rgb_height - 1, y + 72), 1}; - } - } - - camera_autoexposure(c, set_exposure_target(b, rect.x1, rect.x2, rect.x_skip, rect.y1, rect.y2, rect.y_skip)); -} - -void common_process_driver_camera(MultiCameraState *s, CameraState *c, int cnt) { - int j = Hardware::TICI() ? 1 : 3; - if (cnt % j == 0) { - s->sm->update(0); - driver_cam_auto_exposure(c, *(s->sm)); - } - MessageBuilder msg; - auto framed = msg.initEvent().initDriverCameraState(); - framed.setFrameType(cereal::FrameData::FrameType::FRONT); - fill_frame_data(framed, c->buf.cur_frame_data); - if (env_send_driver) { - framed.setImage(get_frame_image(&c->buf)); - } - s->pm->send("driverCameraState", msg); -} - - void camerad_thread() { cl_device_id device_id = cl_get_device_id(CL_DEVICE_TYPE_DEFAULT); -#if defined(QCOM) || defined(QCOM2) +#ifdef QCOM2 const cl_context_properties props[] = {CL_CONTEXT_PRIORITY_HINT_QCOM, CL_PRIORITY_HINT_HIGH_QCOM, 0}; cl_context context = CL_CHECK_ERR(clCreateContext(props, 1, &device_id, NULL, NULL, &err)); #else cl_context context = CL_CHECK_ERR(clCreateContext(NULL, 1, &device_id, NULL, NULL, &err)); #endif - MultiCameraState cameras = {}; - VisionIpcServer vipc_server("camerad", device_id, context); + { + MultiCameraState cameras = {}; + VisionIpcServer vipc_server("camerad", device_id, context); - cameras_init(&vipc_server, &cameras, device_id, context); - cameras_open(&cameras); + cameras_open(&cameras); + cameras_init(&vipc_server, &cameras, device_id, context); - vipc_server.start_listener(); + vipc_server.start_listener(); - cameras_run(&cameras); + cameras_run(&cameras); + } CL_CHECK(clReleaseContext(context)); } diff --git a/selfdrive/camerad/cameras/camera_common.h b/system/camerad/cameras/camera_common.h similarity index 61% rename from selfdrive/camerad/cameras/camera_common.h rename to system/camerad/cameras/camera_common.h index c2d2904f54..088b9f7939 100644 --- a/selfdrive/camerad/cameras/camera_common.h +++ b/system/camerad/cameras/camera_common.h @@ -9,12 +9,10 @@ #include "cereal/visionipc/visionbuf.h" #include "cereal/visionipc/visionipc.h" #include "cereal/visionipc/visionipc_server.h" -#include "selfdrive/camerad/transforms/rgb_to_yuv.h" -#include "selfdrive/common/mat.h" -#include "selfdrive/common/queue.h" -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/visionimg.h" -#include "selfdrive/hardware/hw.h" +#include "common/mat.h" +#include "common/queue.h" +#include "common/swaglog.h" +#include "system/hardware/hw.h" #define CAMERA_ID_IMX298 0 #define CAMERA_ID_IMX179 1 @@ -25,10 +23,10 @@ #define CAMERA_ID_LGC920 6 #define CAMERA_ID_LGC615 7 #define CAMERA_ID_AR0231 8 -#define CAMERA_ID_MAX 9 +#define CAMERA_ID_OX03C10 9 +#define CAMERA_ID_MAX 10 -const int UI_BUF_COUNT = 4; -const int YUV_BUFFER_COUNT = Hardware::EON() ? 100 : 40; +const int YUV_BUFFER_COUNT = 40; enum CameraType { RoadCam = 0, @@ -36,24 +34,21 @@ enum CameraType { WideRoadCam }; -// TODO: remove these once all the internal tools are moved to vipc -const bool env_send_driver = getenv("SEND_DRIVER") != NULL; -const bool env_send_road = getenv("SEND_ROAD") != NULL; -const bool env_send_wide_road = getenv("SEND_WIDE_ROAD") != NULL; - // for debugging -// note: ONLY_ROAD doesn't work, likely due to a mixup with wideRoad cam in the kernel -const bool env_only_driver = getenv("ONLY_DRIVER") != NULL; +const bool env_disable_road = getenv("DISABLE_ROAD") != NULL; +const bool env_disable_wide_road = getenv("DISABLE_WIDE_ROAD") != NULL; +const bool env_disable_driver = getenv("DISABLE_DRIVER") != NULL; const bool env_debug_frames = getenv("DEBUG_FRAMES") != NULL; - -typedef void (*release_cb)(void *cookie, int buf_idx); +const bool env_log_raw_frames = getenv("LOG_RAW_FRAMES") != NULL; +const bool env_ctrl_exp_from_params = getenv("CTRL_EXP_FROM_PARAMS") != NULL; typedef struct CameraInfo { - int frame_width, frame_height; - int frame_stride; - bool bayer; - int bayer_flip; - bool hdr; + uint32_t frame_width, frame_height; + uint32_t frame_stride; + uint32_t frame_offset = 0; + uint32_t extra_height = 0; + int registers_offset = -1; + int stats_offset = -1; } CameraInfo; typedef struct FrameMetadata { @@ -75,38 +70,28 @@ typedef struct FrameMetadata { unsigned int lens_pos; float lens_err; float lens_true_pos; -} FrameMetadata; -typedef struct CameraExpInfo { - int op_id; - float grey_frac; -} CameraExpInfo; + float processing_time; +} FrameMetadata; struct MultiCameraState; -struct CameraState; +class CameraState; class Debayer; class CameraBuf { private: VisionIpcServer *vipc_server; - CameraState *camera_state; Debayer *debayer = nullptr; - std::unique_ptr rgb2yuv; - - VisionStreamType rgb_type, yuv_type; - + VisionStreamType yuv_type; int cur_buf_idx; - SafeQueue safe_queue; - int frame_buf_count; - release_cb release_callback; public: cl_command_queue q; FrameMetadata cur_frame_data; - VisionBuf *cur_rgb_buf; VisionBuf *cur_yuv_buf; + VisionBuf *cur_camera_buf; std::unique_ptr camera_bufs; std::unique_ptr camera_bufs_metadata; int rgb_width, rgb_height, rgb_stride; @@ -115,25 +100,22 @@ public: CameraBuf() = default; ~CameraBuf(); - void init(cl_device_id device_id, cl_context context, CameraState *s, VisionIpcServer * v, int frame_cnt, VisionStreamType rgb_type, VisionStreamType yuv_type, release_cb release_callback=nullptr); + void init(cl_device_id device_id, cl_context context, CameraState *s, VisionIpcServer * v, int frame_cnt, VisionStreamType yuv_type); bool acquire(); - void release(); void queue(size_t buf_idx); }; typedef void (*process_thread_cb)(MultiCameraState *s, CameraState *c, int cnt); -void fill_frame_data(cereal::FrameData::Builder &framed, const FrameMetadata &frame_data); -kj::Array get_frame_image(const CameraBuf *b); +void fill_frame_data(cereal::FrameData::Builder &framed, const FrameMetadata &frame_data, CameraState *c); +kj::Array get_raw_frame_image(const CameraBuf *b); float set_exposure_target(const CameraBuf *b, int x_start, int x_end, int x_skip, int y_start, int y_end, int y_skip); std::thread start_process_thread(MultiCameraState *cameras, CameraState *cs, process_thread_cb callback); -void common_process_driver_camera(MultiCameraState *s, CameraState *c, int cnt); void cameras_init(VisionIpcServer *v, MultiCameraState *s, cl_device_id device_id, cl_context ctx); void cameras_open(MultiCameraState *s); void cameras_run(MultiCameraState *s); void cameras_close(MultiCameraState *s); -void camera_autoexposure(CameraState *s, float grey_frac); void camerad_thread(); int open_v4l_by_name_and_index(const char name[], int index = 0, int flags = O_RDWR | O_NONBLOCK); diff --git a/system/camerad/cameras/camera_qcom2.cc b/system/camerad/cameras/camera_qcom2.cc new file mode 100644 index 0000000000..df5b9e8bf0 --- /dev/null +++ b/system/camerad/cameras/camera_qcom2.cc @@ -0,0 +1,1310 @@ +#include "system/camerad/cameras/camera_qcom2.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "media/cam_defs.h" +#include "media/cam_isp.h" +#include "media/cam_isp_ife.h" +#include "media/cam_sensor.h" +#include "media/cam_sensor_cmn_header.h" +#include "media/cam_sync.h" +#include "common/swaglog.h" +#include "system/camerad/cameras/sensor2_i2c.h" + +// For debugging: +// echo "4294967295" > /sys/module/cam_debug_util/parameters/debug_mdl + +extern ExitHandler do_exit; + +const size_t FRAME_WIDTH = 1928; +const size_t FRAME_HEIGHT = 1208; +const size_t FRAME_STRIDE = 2896; // for 12 bit output. 1928 * 12 / 8 + 4 (alignment) + +const size_t AR0231_REGISTERS_HEIGHT = 2; +// TODO: this extra height is universal and doesn't apply per camera +const size_t AR0231_STATS_HEIGHT = 2+8; + +const int MIPI_SETTLE_CNT = 33; // Calculated by camera_freqs.py + +CameraInfo cameras_supported[CAMERA_ID_MAX] = { + [CAMERA_ID_AR0231] = { + .frame_width = FRAME_WIDTH, + .frame_height = FRAME_HEIGHT, + .frame_stride = FRAME_STRIDE, + .extra_height = AR0231_REGISTERS_HEIGHT + AR0231_STATS_HEIGHT, + + .registers_offset = 0, + .frame_offset = AR0231_REGISTERS_HEIGHT, + .stats_offset = AR0231_REGISTERS_HEIGHT + FRAME_HEIGHT, + }, + [CAMERA_ID_OX03C10] = { + .frame_width = FRAME_WIDTH, + .frame_height = FRAME_HEIGHT, + .frame_stride = FRAME_STRIDE, // (0xa80*12//8) + .extra_height = 16, // top 2 + bot 14 + .frame_offset = 2, + }, +}; + +const float DC_GAIN_AR0231 = 2.5; +const float DC_GAIN_OX03C10 = 7.32; + +const float DC_GAIN_ON_GREY_AR0231= 0.2; +const float DC_GAIN_OFF_GREY_AR0231 = 0.3; +const float DC_GAIN_ON_GREY_OX03C10= 0.25; +const float DC_GAIN_OFF_GREY_OX03C10 = 0.35; + +const int DC_GAIN_MIN_WEIGHT_AR0231 = 0; +const int DC_GAIN_MAX_WEIGHT_AR0231 = 1; +const int DC_GAIN_MIN_WEIGHT_OX03C10 = 16; +const int DC_GAIN_MAX_WEIGHT_OX03C10 = 32; + +const float TARGET_GREY_FACTOR_AR0231 = 1.0; +const float TARGET_GREY_FACTOR_OX03C10 = 0.02; + +const float sensor_analog_gains_AR0231[] = { + 1.0/8.0, 2.0/8.0, 2.0/7.0, 3.0/7.0, // 0, 1, 2, 3 + 3.0/6.0, 4.0/6.0, 4.0/5.0, 5.0/5.0, // 4, 5, 6, 7 + 5.0/4.0, 6.0/4.0, 6.0/3.0, 7.0/3.0, // 8, 9, 10, 11 + 7.0/2.0, 8.0/2.0, 8.0/1.0}; // 12, 13, 14, 15 = bypass + +const float sensor_analog_gains_OX03C10[] = { + 1.0, 1.0625, 1.125, 1.1875, 1.25, 1.3125, 1.375, 1.4375, 1.5, 1.5625, 1.6875, + 1.8125, 1.9375, 2.0, 2.125, 2.25, 2.375, 2.5, 2.625, 2.75, 2.875, 3.0, + 3.125, 3.375, 3.625, 3.875, 4.0, 4.25, 4.5, 4.75, 5.0, 5.25, 5.5, + 5.75, 6.0, 6.25, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0, + 10.5, 11.0, 11.5, 12.0, 12.5, 13.0, 13.5, 14.0, 14.5, 15.0, 15.5}; + +const uint32_t ox03c10_analog_gains_reg[] = { + 0x100, 0x110, 0x120, 0x130, 0x140, 0x150, 0x160, 0x170, 0x180, 0x190, 0x1B0, + 0x1D0, 0x1F0, 0x200, 0x220, 0x240, 0x260, 0x280, 0x2A0, 0x2C0, 0x2E0, 0x300, + 0x320, 0x360, 0x3A0, 0x3E0, 0x400, 0x440, 0x480, 0x4C0, 0x500, 0x540, 0x580, + 0x5C0, 0x600, 0x640, 0x680, 0x700, 0x780, 0x800, 0x880, 0x900, 0x980, 0xA00, + 0xA80, 0xB00, 0xB80, 0xC00, 0xC80, 0xD00, 0xD80, 0xE00, 0xE80, 0xF00, 0xF80}; + +const int ANALOG_GAIN_MIN_IDX_AR0231 = 0x1; // 0.25x +const int ANALOG_GAIN_REC_IDX_AR0231 = 0x6; // 0.8x +const int ANALOG_GAIN_MAX_IDX_AR0231 = 0xD; // 4.0x +const int ANALOG_GAIN_COST_DELTA_AR0231 = 0; + +const int ANALOG_GAIN_MIN_IDX_OX03C10 = 0x0; +const int ANALOG_GAIN_REC_IDX_OX03C10 = 0x11; // 2.5x +const int ANALOG_GAIN_MAX_IDX_OX03C10 = 0x36; +const int ANALOG_GAIN_COST_DELTA_OX03C10 = -1; + +const int EXPOSURE_TIME_MIN_AR0231 = 2; // with HDR, fastest ss +const int EXPOSURE_TIME_MAX_AR0231 = 0x0855; // with HDR, slowest ss, 40ms + +const int EXPOSURE_TIME_MIN_OX03C10 = 2; // 1x +const int EXPOSURE_TIME_MAX_OX03C10 = 2016; +const uint32_t VS_TIME_MIN_OX03C10 = 1; +const uint32_t VS_TIME_MAX_OX03C10 = 34; // vs < 35 + +int CameraState::clear_req_queue() { + struct cam_req_mgr_flush_info req_mgr_flush_request = {0}; + req_mgr_flush_request.session_hdl = session_handle; + req_mgr_flush_request.link_hdl = link_handle; + req_mgr_flush_request.flush_type = CAM_REQ_MGR_FLUSH_TYPE_ALL; + int ret; + ret = do_cam_control(multi_cam_state->video0_fd, CAM_REQ_MGR_FLUSH_REQ, &req_mgr_flush_request, sizeof(req_mgr_flush_request)); + // LOGD("flushed all req: %d", ret); + return ret; +} + +// ************** high level camera helpers **************** + +void CameraState::sensors_start() { + if (!enabled) return; + LOGD("starting sensor %d", camera_num); + if (camera_id == CAMERA_ID_AR0231) { + sensors_i2c(start_reg_array_ar0231, std::size(start_reg_array_ar0231), CAM_SENSOR_PACKET_OPCODE_SENSOR_CONFIG, true); + } else if (camera_id == CAMERA_ID_OX03C10) { + sensors_i2c(start_reg_array_ox03c10, std::size(start_reg_array_ox03c10), CAM_SENSOR_PACKET_OPCODE_SENSOR_CONFIG, false); + } else { + assert(false); + } +} + +void CameraState::sensors_poke(int request_id) { + uint32_t cam_packet_handle = 0; + int size = sizeof(struct cam_packet); + struct cam_packet *pkt = (struct cam_packet *)mm.alloc(size, &cam_packet_handle); + pkt->num_cmd_buf = 0; + pkt->kmd_cmd_buf_index = -1; + pkt->header.size = size; + pkt->header.op_code = CAM_SENSOR_PACKET_OPCODE_SENSOR_NOP; + pkt->header.request_id = request_id; + + int ret = device_config(sensor_fd, session_handle, sensor_dev_handle, cam_packet_handle); + if (ret != 0) { + LOGE("** sensor %d FAILED poke, disabling", camera_num); + enabled = false; + return; + } + + mm.free(pkt); +} + +void CameraState::sensors_i2c(struct i2c_random_wr_payload* dat, int len, int op_code, bool data_word) { + // LOGD("sensors_i2c: %d", len); + uint32_t cam_packet_handle = 0; + int size = sizeof(struct cam_packet)+sizeof(struct cam_cmd_buf_desc)*1; + struct cam_packet *pkt = (struct cam_packet *)mm.alloc(size, &cam_packet_handle); + pkt->num_cmd_buf = 1; + pkt->kmd_cmd_buf_index = -1; + pkt->header.size = size; + pkt->header.op_code = op_code; + struct cam_cmd_buf_desc *buf_desc = (struct cam_cmd_buf_desc *)&pkt->payload; + + buf_desc[0].size = buf_desc[0].length = sizeof(struct i2c_rdwr_header) + len*sizeof(struct i2c_random_wr_payload); + buf_desc[0].type = CAM_CMD_BUF_I2C; + + struct cam_cmd_i2c_random_wr *i2c_random_wr = (struct cam_cmd_i2c_random_wr *)mm.alloc(buf_desc[0].size, (uint32_t*)&buf_desc[0].mem_handle); + i2c_random_wr->header.count = len; + i2c_random_wr->header.op_code = 1; + i2c_random_wr->header.cmd_type = CAMERA_SENSOR_CMD_TYPE_I2C_RNDM_WR; + i2c_random_wr->header.data_type = data_word ? CAMERA_SENSOR_I2C_TYPE_WORD : CAMERA_SENSOR_I2C_TYPE_BYTE; + i2c_random_wr->header.addr_type = CAMERA_SENSOR_I2C_TYPE_WORD; + memcpy(i2c_random_wr->random_wr_payload, dat, len*sizeof(struct i2c_random_wr_payload)); + + int ret = device_config(sensor_fd, session_handle, sensor_dev_handle, cam_packet_handle); + if (ret != 0) { + LOGE("** sensor %d FAILED i2c, disabling", camera_num); + enabled = false; + return; + } + + mm.free(i2c_random_wr); + mm.free(pkt); +} + +static cam_cmd_power *power_set_wait(cam_cmd_power *power, int16_t delay_ms) { + cam_cmd_unconditional_wait *unconditional_wait = (cam_cmd_unconditional_wait *)((char *)power + (sizeof(struct cam_cmd_power) + (power->count - 1) * sizeof(struct cam_power_settings))); + unconditional_wait->cmd_type = CAMERA_SENSOR_CMD_TYPE_WAIT; + unconditional_wait->delay = delay_ms; + unconditional_wait->op_code = CAMERA_SENSOR_WAIT_OP_SW_UCND; + return (struct cam_cmd_power *)(unconditional_wait + 1); +}; + +int CameraState::sensors_init() { + uint32_t cam_packet_handle = 0; + int size = sizeof(struct cam_packet)+sizeof(struct cam_cmd_buf_desc)*2; + struct cam_packet *pkt = (struct cam_packet *)mm.alloc(size, &cam_packet_handle); + pkt->num_cmd_buf = 2; + pkt->kmd_cmd_buf_index = -1; + pkt->header.op_code = 0x1000000 | CAM_SENSOR_PACKET_OPCODE_SENSOR_PROBE; + pkt->header.size = size; + struct cam_cmd_buf_desc *buf_desc = (struct cam_cmd_buf_desc *)&pkt->payload; + + buf_desc[0].size = buf_desc[0].length = sizeof(struct cam_cmd_i2c_info) + sizeof(struct cam_cmd_probe); + buf_desc[0].type = CAM_CMD_BUF_LEGACY; + struct cam_cmd_i2c_info *i2c_info = (struct cam_cmd_i2c_info *)mm.alloc(buf_desc[0].size, (uint32_t*)&buf_desc[0].mem_handle); + auto probe = (struct cam_cmd_probe *)(i2c_info + 1); + + probe->camera_id = camera_num; + switch (camera_num) { + case 0: + // port 0 + i2c_info->slave_addr = (camera_id == CAMERA_ID_AR0231) ? 0x20 : 0x6C; // 6C = 0x36*2 + break; + case 1: + // port 1 + i2c_info->slave_addr = (camera_id == CAMERA_ID_AR0231) ? 0x30 : 0x20; + break; + case 2: + // port 2 + i2c_info->slave_addr = (camera_id == CAMERA_ID_AR0231) ? 0x20 : 0x6C; + break; + } + + // 0(I2C_STANDARD_MODE) = 100khz, 1(I2C_FAST_MODE) = 400khz + //i2c_info->i2c_freq_mode = I2C_STANDARD_MODE; + i2c_info->i2c_freq_mode = I2C_FAST_MODE; + i2c_info->cmd_type = CAMERA_SENSOR_CMD_TYPE_I2C_INFO; + + probe->data_type = CAMERA_SENSOR_I2C_TYPE_WORD; + probe->addr_type = CAMERA_SENSOR_I2C_TYPE_WORD; + probe->op_code = 3; // don't care? + probe->cmd_type = CAMERA_SENSOR_CMD_TYPE_PROBE; + if (camera_id == CAMERA_ID_AR0231) { + probe->reg_addr = 0x3000; + probe->expected_data = 0x354; + } else if (camera_id == CAMERA_ID_OX03C10) { + probe->reg_addr = 0x300a; + probe->expected_data = 0x5803; + } else { + assert(false); + } + probe->data_mask = 0; + + //buf_desc[1].size = buf_desc[1].length = 148; + buf_desc[1].size = buf_desc[1].length = 196; + buf_desc[1].type = CAM_CMD_BUF_I2C; + struct cam_cmd_power *power_settings = (struct cam_cmd_power *)mm.alloc(buf_desc[1].size, (uint32_t*)&buf_desc[1].mem_handle); + memset(power_settings, 0, buf_desc[1].size); + + // power on + struct cam_cmd_power *power = power_settings; + power->count = 4; + power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_UP; + power->power_settings[0].power_seq_type = 3; // clock?? + power->power_settings[1].power_seq_type = 1; // analog + power->power_settings[2].power_seq_type = 2; // digital + power->power_settings[3].power_seq_type = 8; // reset low + power = power_set_wait(power, 1); + + // set clock + power->count = 1; + power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_UP; + power->power_settings[0].power_seq_type = 0; + power->power_settings[0].config_val_low = (camera_id == CAMERA_ID_AR0231) ? 19200000 : 24000000; //Hz + power = power_set_wait(power, 1); + + // reset high + power->count = 1; + power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_UP; + power->power_settings[0].power_seq_type = 8; + power->power_settings[0].config_val_low = 1; + // wait 650000 cycles @ 19.2 mhz = 33.8 ms + power = power_set_wait(power, 34); + + // probe happens here + + // disable clock + power->count = 1; + power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_DOWN; + power->power_settings[0].power_seq_type = 0; + power->power_settings[0].config_val_low = 0; + power = power_set_wait(power, 1); + + // reset high + power->count = 1; + power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_DOWN; + power->power_settings[0].power_seq_type = 8; + power->power_settings[0].config_val_low = 1; + power = power_set_wait(power, 1); + + // reset low + power->count = 1; + power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_DOWN; + power->power_settings[0].power_seq_type = 8; + power->power_settings[0].config_val_low = 0; + power = power_set_wait(power, 1); + + // power off + power->count = 3; + power->cmd_type = CAMERA_SENSOR_CMD_TYPE_PWR_DOWN; + power->power_settings[0].power_seq_type = 2; + power->power_settings[1].power_seq_type = 1; + power->power_settings[2].power_seq_type = 3; + + int ret = do_cam_control(sensor_fd, CAM_SENSOR_PROBE_CMD, (void *)(uintptr_t)cam_packet_handle, 0); + LOGD("probing the sensor: %d", ret); + + mm.free(i2c_info); + mm.free(power_settings); + mm.free(pkt); + + return ret; +} + +void CameraState::config_isp(int io_mem_handle, int fence, int request_id, int buf0_mem_handle, int buf0_offset) { + uint32_t cam_packet_handle = 0; + int size = sizeof(struct cam_packet)+sizeof(struct cam_cmd_buf_desc)*2; + if (io_mem_handle != 0) { + size += sizeof(struct cam_buf_io_cfg); + } + struct cam_packet *pkt = (struct cam_packet *)mm.alloc(size, &cam_packet_handle); + pkt->num_cmd_buf = 2; + pkt->kmd_cmd_buf_index = 0; + // YUV has kmd_cmd_buf_offset = 1780 + // I guess this is the ISP command + // YUV also has patch_offset = 0x1030 and num_patches = 10 + + if (io_mem_handle != 0) { + pkt->io_configs_offset = sizeof(struct cam_cmd_buf_desc)*pkt->num_cmd_buf; + pkt->num_io_configs = 1; + } + + if (io_mem_handle != 0) { + pkt->header.op_code = 0xf000001; + pkt->header.request_id = request_id; + } else { + pkt->header.op_code = 0xf000000; + } + pkt->header.size = size; + struct cam_cmd_buf_desc *buf_desc = (struct cam_cmd_buf_desc *)&pkt->payload; + struct cam_buf_io_cfg *io_cfg = (struct cam_buf_io_cfg *)((char*)&pkt->payload + pkt->io_configs_offset); + + // TODO: support MMU + buf_desc[0].size = 65624; + buf_desc[0].length = 0; + buf_desc[0].type = CAM_CMD_BUF_DIRECT; + buf_desc[0].meta_data = 3; + buf_desc[0].mem_handle = buf0_mem_handle; + buf_desc[0].offset = buf0_offset; + + // parsed by cam_isp_packet_generic_blob_handler + struct isp_packet { + uint32_t type_0; + cam_isp_resource_hfr_config resource_hfr; + + uint32_t type_1; + cam_isp_clock_config clock; + uint64_t extra_rdi_hz[3]; + + uint32_t type_2; + cam_isp_bw_config bw; + struct cam_isp_bw_vote extra_rdi_vote[6]; + } __attribute__((packed)) tmp; + memset(&tmp, 0, sizeof(tmp)); + + tmp.type_0 = CAM_ISP_GENERIC_BLOB_TYPE_HFR_CONFIG; + tmp.type_0 |= sizeof(cam_isp_resource_hfr_config) << 8; + static_assert(sizeof(cam_isp_resource_hfr_config) == 0x20); + tmp.resource_hfr = { + .num_ports = 1, // 10 for YUV (but I don't think we need them) + .port_hfr_config[0] = { + .resource_type = CAM_ISP_IFE_OUT_RES_RDI_0, // CAM_ISP_IFE_OUT_RES_FULL for YUV + .subsample_pattern = 1, + .subsample_period = 0, + .framedrop_pattern = 1, + .framedrop_period = 0, + }}; + + tmp.type_1 = CAM_ISP_GENERIC_BLOB_TYPE_CLOCK_CONFIG; + tmp.type_1 |= (sizeof(cam_isp_clock_config) + sizeof(tmp.extra_rdi_hz)) << 8; + static_assert((sizeof(cam_isp_clock_config) + sizeof(tmp.extra_rdi_hz)) == 0x38); + tmp.clock = { + .usage_type = 1, // dual mode + .num_rdi = 4, + .left_pix_hz = 404000000, + .right_pix_hz = 404000000, + .rdi_hz[0] = 404000000, + }; + + + tmp.type_2 = CAM_ISP_GENERIC_BLOB_TYPE_BW_CONFIG; + tmp.type_2 |= (sizeof(cam_isp_bw_config) + sizeof(tmp.extra_rdi_vote)) << 8; + static_assert((sizeof(cam_isp_bw_config) + sizeof(tmp.extra_rdi_vote)) == 0xe0); + tmp.bw = { + .usage_type = 1, // dual mode + .num_rdi = 4, + .left_pix_vote = { + .resource_id = 0, + .cam_bw_bps = 450000000, + .ext_bw_bps = 450000000, + }, + .rdi_vote[0] = { + .resource_id = 0, + .cam_bw_bps = 8706200000, + .ext_bw_bps = 8706200000, + }, + }; + + static_assert(offsetof(struct isp_packet, type_2) == 0x60); + + buf_desc[1].size = sizeof(tmp); + buf_desc[1].offset = io_mem_handle != 0 ? 0x60 : 0; + buf_desc[1].length = buf_desc[1].size - buf_desc[1].offset; + buf_desc[1].type = CAM_CMD_BUF_GENERIC; + buf_desc[1].meta_data = CAM_ISP_PACKET_META_GENERIC_BLOB_COMMON; + uint32_t *buf2 = (uint32_t *)mm.alloc(buf_desc[1].size, (uint32_t*)&buf_desc[1].mem_handle); + memcpy(buf2, &tmp, sizeof(tmp)); + + if (io_mem_handle != 0) { + io_cfg[0].mem_handle[0] = io_mem_handle; + io_cfg[0].planes[0] = (struct cam_plane_cfg){ + .width = ci.frame_width, + .height = ci.frame_height + ci.extra_height, + .plane_stride = ci.frame_stride, + .slice_height = ci.frame_height + ci.extra_height, + .meta_stride = 0x0, // YUV has meta(stride=0x400, size=0x5000) + .meta_size = 0x0, + .meta_offset = 0x0, + .packer_config = 0x0, // 0xb for YUV + .mode_config = 0x0, // 0x9ef for YUV + .tile_config = 0x0, + .h_init = 0x0, + .v_init = 0x0, + }; + io_cfg[0].format = CAM_FORMAT_MIPI_RAW_12; // CAM_FORMAT_UBWC_TP10 for YUV + io_cfg[0].color_space = CAM_COLOR_SPACE_BASE; // CAM_COLOR_SPACE_BT601_FULL for YUV + io_cfg[0].color_pattern = 0x5; // 0x0 for YUV + io_cfg[0].bpp = 0xc; + io_cfg[0].resource_type = CAM_ISP_IFE_OUT_RES_RDI_0; // CAM_ISP_IFE_OUT_RES_FULL for YUV + io_cfg[0].fence = fence; + io_cfg[0].direction = CAM_BUF_OUTPUT; + io_cfg[0].subsample_pattern = 0x1; + io_cfg[0].framedrop_pattern = 0x1; + } + + int ret = device_config(multi_cam_state->isp_fd, session_handle, isp_dev_handle, cam_packet_handle); + assert(ret == 0); + if (ret != 0) { + LOGE("isp config failed"); + } + + mm.free(buf2); + mm.free(pkt); +} + +void CameraState::enqueue_buffer(int i, bool dp) { + int ret; + int request_id = request_ids[i]; + + if (buf_handle[i] && sync_objs[i]) { + // wait + struct cam_sync_wait sync_wait = {0}; + sync_wait.sync_obj = sync_objs[i]; + sync_wait.timeout_ms = 50; // max dt tolerance, typical should be 23 + ret = do_cam_control(multi_cam_state->cam_sync_fd, CAM_SYNC_WAIT, &sync_wait, sizeof(sync_wait)); + if (ret != 0) { + LOGE("failed to wait for sync: %d %d", ret, sync_wait.sync_obj); + // TODO: handle frame drop cleanly + } + + buf.camera_bufs_metadata[i].timestamp_eof = (uint64_t)nanos_since_boot(); // set true eof + if (dp) buf.queue(i); + + // destroy old output fence + struct cam_sync_info sync_destroy = {0}; + sync_destroy.sync_obj = sync_objs[i]; + ret = do_cam_control(multi_cam_state->cam_sync_fd, CAM_SYNC_DESTROY, &sync_destroy, sizeof(sync_destroy)); + if (ret != 0) { + LOGE("failed to destroy sync object: %d %d", ret, sync_destroy.sync_obj); + } + } + + // create output fence + struct cam_sync_info sync_create = {0}; + strcpy(sync_create.name, "NodeOutputPortFence"); + ret = do_cam_control(multi_cam_state->cam_sync_fd, CAM_SYNC_CREATE, &sync_create, sizeof(sync_create)); + if (ret != 0) { + LOGE("failed to create fence: %d %d", ret, sync_create.sync_obj) + } + sync_objs[i] = sync_create.sync_obj; + + // schedule request with camera request manager + struct cam_req_mgr_sched_request req_mgr_sched_request = {0}; + req_mgr_sched_request.session_hdl = session_handle; + req_mgr_sched_request.link_hdl = link_handle; + req_mgr_sched_request.req_id = request_id; + ret = do_cam_control(multi_cam_state->video0_fd, CAM_REQ_MGR_SCHED_REQ, &req_mgr_sched_request, sizeof(req_mgr_sched_request)); + if (ret != 0) { + LOGE("failed to schedule cam mgr request: %d %d", ret, request_id); + } + + // poke sensor, must happen after schedule + sensors_poke(request_id); + + // submit request to the ife + config_isp(buf_handle[i], sync_objs[i], request_id, buf0_handle, 65632*(i+1)); +} + +void CameraState::enqueue_req_multi(int start, int n, bool dp) { + for (int i=start;idevice_iommu; + mem_mgr_map_cmd.num_hdl = 1; + mem_mgr_map_cmd.flags = CAM_MEM_FLAG_HW_READ_WRITE; + mem_mgr_map_cmd.fd = buf.camera_bufs[i].fd; + int ret = do_cam_control(s->video0_fd, CAM_REQ_MGR_MAP_BUF, &mem_mgr_map_cmd, sizeof(mem_mgr_map_cmd)); + LOGD("map buf req: (fd: %d) 0x%x %d", buf.camera_bufs[i].fd, mem_mgr_map_cmd.out.buf_handle, ret); + buf_handle[i] = mem_mgr_map_cmd.out.buf_handle; + } + enqueue_req_multi(1, FRAME_BUF_COUNT, 0); +} + +void CameraState::camera_init(MultiCameraState *s, VisionIpcServer * v, int camera_id_, unsigned int fps, cl_device_id device_id, cl_context ctx, VisionStreamType yuv_type) { + if (!enabled) return; + camera_id = camera_id_; + + LOGD("camera init %d", camera_num); + assert(camera_id < std::size(cameras_supported)); + ci = cameras_supported[camera_id]; + assert(ci.frame_width != 0); + + request_id_last = 0; + skipped = true; + + camera_set_parameters(); + + buf.init(device_id, ctx, this, v, FRAME_BUF_COUNT, yuv_type); + camera_map_bufs(s); +} + +void CameraState::camera_open(MultiCameraState *multi_cam_state_, int camera_num_, bool enabled_) { + multi_cam_state = multi_cam_state_; + camera_num = camera_num_; + enabled = enabled_; + if (!enabled) return; + + int ret; + sensor_fd = open_v4l_by_name_and_index("cam-sensor-driver", camera_num); + assert(sensor_fd >= 0); + LOGD("opened sensor for %d", camera_num); + + // init memorymanager for this camera + mm.init(multi_cam_state->video0_fd); + + // probe the sensor + LOGD("-- Probing sensor %d", camera_num); + camera_id = CAMERA_ID_AR0231; + ret = sensors_init(); + if (ret != 0) { + // TODO: use build flag instead? + LOGD("AR0231 init failed, trying OX03C10"); + camera_id = CAMERA_ID_OX03C10; + ret = sensors_init(); + } + LOGD("-- Probing sensor %d done with %d", camera_num, ret); + if (ret != 0) { + LOGE("** sensor %d FAILED bringup, disabling", camera_num); + enabled = false; + return; + } + + // create session + struct cam_req_mgr_session_info session_info = {}; + ret = do_cam_control(multi_cam_state->video0_fd, CAM_REQ_MGR_CREATE_SESSION, &session_info, sizeof(session_info)); + LOGD("get session: %d 0x%X", ret, session_info.session_hdl); + session_handle = session_info.session_hdl; + + // access the sensor + LOGD("-- Accessing sensor"); + auto sensor_dev_handle_ = device_acquire(sensor_fd, session_handle, nullptr); + assert(sensor_dev_handle_); + sensor_dev_handle = *sensor_dev_handle_; + LOGD("acquire sensor dev"); + + LOG("-- Configuring sensor"); + uint32_t dt; + if (camera_id == CAMERA_ID_AR0231) { + sensors_i2c(init_array_ar0231, std::size(init_array_ar0231), CAM_SENSOR_PACKET_OPCODE_SENSOR_CONFIG, true); + dt = 0x12; // Changing stats to 0x2C doesn't work, so change pixels to 0x12 instead + } else if (camera_id == CAMERA_ID_OX03C10) { + sensors_i2c(init_array_ox03c10, std::size(init_array_ox03c10), CAM_SENSOR_PACKET_OPCODE_SENSOR_CONFIG, false); + // one is 0x2a, two are 0x2b + dt = 0x2c; + } else { + assert(false); + } + printf("dt is %x\n", dt); + + // NOTE: to be able to disable road and wide road, we still have to configure the sensor over i2c + // If you don't do this, the strobe GPIO is an output (even in reset it seems!) + if (!enabled) return; + + struct cam_isp_in_port_info in_port_info = { + .res_type = (uint32_t[]){CAM_ISP_IFE_IN_RES_PHY_0, CAM_ISP_IFE_IN_RES_PHY_1, CAM_ISP_IFE_IN_RES_PHY_2}[camera_num], + + .lane_type = CAM_ISP_LANE_TYPE_DPHY, + .lane_num = 4, + .lane_cfg = 0x3210, + + .vc = 0x0, + .dt = dt, + .format = CAM_FORMAT_MIPI_RAW_12, + + .test_pattern = 0x2, // 0x3? + .usage_type = 0x0, + + .left_start = 0, + .left_stop = ci.frame_width - 1, + .left_width = ci.frame_width, + + .right_start = 0, + .right_stop = ci.frame_width - 1, + .right_width = ci.frame_width, + + .line_start = 0, + .line_stop = ci.frame_height + ci.extra_height - 1, + .height = ci.frame_height + ci.extra_height, + + .pixel_clk = 0x0, + .batch_size = 0x0, + .dsp_mode = CAM_ISP_DSP_MODE_NONE, + .hbi_cnt = 0x0, + .custom_csid = 0x0, + + .num_out_res = 0x1, + .data[0] = (struct cam_isp_out_port_info){ + .res_type = CAM_ISP_IFE_OUT_RES_RDI_0, + .format = CAM_FORMAT_MIPI_RAW_12, + .width = ci.frame_width, + .height = ci.frame_height + ci.extra_height, + .comp_grp_id = 0x0, .split_point = 0x0, .secure_mode = 0x0, + }, + }; + struct cam_isp_resource isp_resource = { + .resource_id = CAM_ISP_RES_ID_PORT, + .handle_type = CAM_HANDLE_USER_POINTER, + .res_hdl = (uint64_t)&in_port_info, + .length = sizeof(in_port_info), + }; + + auto isp_dev_handle_ = device_acquire(multi_cam_state->isp_fd, session_handle, &isp_resource); + assert(isp_dev_handle_); + isp_dev_handle = *isp_dev_handle_; + LOGD("acquire isp dev"); + + csiphy_fd = open_v4l_by_name_and_index("cam-csiphy-driver", camera_num); + assert(csiphy_fd >= 0); + LOGD("opened csiphy for %d", camera_num); + + struct cam_csiphy_acquire_dev_info csiphy_acquire_dev_info = {.combo_mode = 0}; + auto csiphy_dev_handle_ = device_acquire(csiphy_fd, session_handle, &csiphy_acquire_dev_info); + assert(csiphy_dev_handle_); + csiphy_dev_handle = *csiphy_dev_handle_; + LOGD("acquire csiphy dev"); + + // config ISP + alloc_w_mmu_hdl(multi_cam_state->video0_fd, 984480, (uint32_t*)&buf0_handle, 0x20, CAM_MEM_FLAG_HW_READ_WRITE | CAM_MEM_FLAG_KMD_ACCESS | CAM_MEM_FLAG_UMD_ACCESS | CAM_MEM_FLAG_CMD_BUF_TYPE, multi_cam_state->device_iommu, multi_cam_state->cdm_iommu); + config_isp(0, 0, 1, buf0_handle, 0); + + // config csiphy + LOG("-- Config CSI PHY"); + { + uint32_t cam_packet_handle = 0; + int size = sizeof(struct cam_packet)+sizeof(struct cam_cmd_buf_desc)*1; + struct cam_packet *pkt = (struct cam_packet *)mm.alloc(size, &cam_packet_handle); + pkt->num_cmd_buf = 1; + pkt->kmd_cmd_buf_index = -1; + pkt->header.size = size; + struct cam_cmd_buf_desc *buf_desc = (struct cam_cmd_buf_desc *)&pkt->payload; + + buf_desc[0].size = buf_desc[0].length = sizeof(struct cam_csiphy_info); + buf_desc[0].type = CAM_CMD_BUF_GENERIC; + + struct cam_csiphy_info *csiphy_info = (struct cam_csiphy_info *)mm.alloc(buf_desc[0].size, (uint32_t*)&buf_desc[0].mem_handle); + csiphy_info->lane_mask = 0x1f; + csiphy_info->lane_assign = 0x3210;// skip clk. How is this 16 bit for 5 channels?? + csiphy_info->csiphy_3phase = 0x0; // no 3 phase, only 2 conductors per lane + csiphy_info->combo_mode = 0x0; + csiphy_info->lane_cnt = 0x4; + csiphy_info->secure_mode = 0x0; + csiphy_info->settle_time = MIPI_SETTLE_CNT * 200000000ULL; + csiphy_info->data_rate = 48000000; // Calculated by camera_freqs.py + + int ret_ = device_config(csiphy_fd, session_handle, csiphy_dev_handle, cam_packet_handle); + assert(ret_ == 0); + + mm.free(csiphy_info); + mm.free(pkt); + } + + // link devices + LOG("-- Link devices"); + struct cam_req_mgr_link_info req_mgr_link_info = {0}; + req_mgr_link_info.session_hdl = session_handle; + req_mgr_link_info.num_devices = 2; + req_mgr_link_info.dev_hdls[0] = isp_dev_handle; + req_mgr_link_info.dev_hdls[1] = sensor_dev_handle; + ret = do_cam_control(multi_cam_state->video0_fd, CAM_REQ_MGR_LINK, &req_mgr_link_info, sizeof(req_mgr_link_info)); + link_handle = req_mgr_link_info.link_hdl; + LOGD("link: %d session: 0x%X isp: 0x%X sensors: 0x%X link: 0x%X", ret, session_handle, isp_dev_handle, sensor_dev_handle, link_handle); + + struct cam_req_mgr_link_control req_mgr_link_control = {0}; + req_mgr_link_control.ops = CAM_REQ_MGR_LINK_ACTIVATE; + req_mgr_link_control.session_hdl = session_handle; + req_mgr_link_control.num_links = 1; + req_mgr_link_control.link_hdls[0] = link_handle; + ret = do_cam_control(multi_cam_state->video0_fd, CAM_REQ_MGR_LINK_CONTROL, &req_mgr_link_control, sizeof(req_mgr_link_control)); + LOGD("link control: %d", ret); + + ret = device_control(csiphy_fd, CAM_START_DEV, session_handle, csiphy_dev_handle); + LOGD("start csiphy: %d", ret); + ret = device_control(multi_cam_state->isp_fd, CAM_START_DEV, session_handle, isp_dev_handle); + LOGD("start isp: %d", ret); + + // TODO: this is unneeded, should we be doing the start i2c in a different way? + //ret = device_control(sensor_fd, CAM_START_DEV, session_handle, sensor_dev_handle); + //LOGD("start sensor: %d", ret); +} + +void cameras_init(VisionIpcServer *v, MultiCameraState *s, cl_device_id device_id, cl_context ctx) { + s->driver_cam.camera_init(s, v, s->driver_cam.camera_id, 20, device_id, ctx, VISION_STREAM_DRIVER); + s->road_cam.camera_init(s, v, s->road_cam.camera_id, 20, device_id, ctx, VISION_STREAM_ROAD); + s->wide_road_cam.camera_init(s, v, s->wide_road_cam.camera_id, 20, device_id, ctx, VISION_STREAM_WIDE_ROAD); + + s->pm = new PubMaster({"roadCameraState", "driverCameraState", "wideRoadCameraState", "thumbnail"}); +} + +void cameras_open(MultiCameraState *s) { + int ret; + + LOG("-- Opening devices"); + // video0 is req_mgr, the target of many ioctls + s->video0_fd = HANDLE_EINTR(open("/dev/v4l/by-path/platform-soc:qcom_cam-req-mgr-video-index0", O_RDWR | O_NONBLOCK)); + assert(s->video0_fd >= 0); + LOGD("opened video0"); + + // video1 is cam_sync, the target of some ioctls + s->cam_sync_fd = HANDLE_EINTR(open("/dev/v4l/by-path/platform-cam_sync-video-index0", O_RDWR | O_NONBLOCK)); + assert(s->cam_sync_fd >= 0); + LOGD("opened video1 (cam_sync)"); + + // looks like there's only one of these + s->isp_fd = open_v4l_by_name_and_index("cam-isp"); + assert(s->isp_fd >= 0); + LOGD("opened isp"); + + // query icp for MMU handles + LOG("-- Query ICP for MMU handles"); + struct cam_isp_query_cap_cmd isp_query_cap_cmd = {0}; + struct cam_query_cap_cmd query_cap_cmd = {0}; + query_cap_cmd.handle_type = 1; + query_cap_cmd.caps_handle = (uint64_t)&isp_query_cap_cmd; + query_cap_cmd.size = sizeof(isp_query_cap_cmd); + ret = do_cam_control(s->isp_fd, CAM_QUERY_CAP, &query_cap_cmd, sizeof(query_cap_cmd)); + assert(ret == 0); + LOGD("using MMU handle: %x", isp_query_cap_cmd.device_iommu.non_secure); + LOGD("using MMU handle: %x", isp_query_cap_cmd.cdm_iommu.non_secure); + s->device_iommu = isp_query_cap_cmd.device_iommu.non_secure; + s->cdm_iommu = isp_query_cap_cmd.cdm_iommu.non_secure; + + // subscribe + LOG("-- Subscribing"); + struct v4l2_event_subscription sub = {0}; + sub.type = V4L_EVENT_CAM_REQ_MGR_EVENT; + sub.id = V4L_EVENT_CAM_REQ_MGR_SOF_BOOT_TS; + ret = HANDLE_EINTR(ioctl(s->video0_fd, VIDIOC_SUBSCRIBE_EVENT, &sub)); + LOGD("req mgr subscribe: %d", ret); + + s->driver_cam.camera_open(s, 2, !env_disable_driver); + LOGD("driver camera opened"); + s->road_cam.camera_open(s, 1, !env_disable_road); + LOGD("road camera opened"); + s->wide_road_cam.camera_open(s, 0, !env_disable_wide_road); + LOGD("wide road camera opened"); +} + +void CameraState::camera_close() { + int ret; + + // stop devices + LOG("-- Stop devices %d", camera_num); + + if (enabled) { + // ret = device_control(sensor_fd, CAM_STOP_DEV, session_handle, sensor_dev_handle); + // LOGD("stop sensor: %d", ret); + ret = device_control(multi_cam_state->isp_fd, CAM_STOP_DEV, session_handle, isp_dev_handle); + LOGD("stop isp: %d", ret); + ret = device_control(csiphy_fd, CAM_STOP_DEV, session_handle, csiphy_dev_handle); + LOGD("stop csiphy: %d", ret); + // link control stop + LOG("-- Stop link control"); + struct cam_req_mgr_link_control req_mgr_link_control = {0}; + req_mgr_link_control.ops = CAM_REQ_MGR_LINK_DEACTIVATE; + req_mgr_link_control.session_hdl = session_handle; + req_mgr_link_control.num_links = 1; + req_mgr_link_control.link_hdls[0] = link_handle; + ret = do_cam_control(multi_cam_state->video0_fd, CAM_REQ_MGR_LINK_CONTROL, &req_mgr_link_control, sizeof(req_mgr_link_control)); + LOGD("link control stop: %d", ret); + + // unlink + LOG("-- Unlink"); + struct cam_req_mgr_unlink_info req_mgr_unlink_info = {0}; + req_mgr_unlink_info.session_hdl = session_handle; + req_mgr_unlink_info.link_hdl = link_handle; + ret = do_cam_control(multi_cam_state->video0_fd, CAM_REQ_MGR_UNLINK, &req_mgr_unlink_info, sizeof(req_mgr_unlink_info)); + LOGD("unlink: %d", ret); + + // release devices + LOGD("-- Release devices"); + ret = device_control(multi_cam_state->isp_fd, CAM_RELEASE_DEV, session_handle, isp_dev_handle); + LOGD("release isp: %d", ret); + ret = device_control(csiphy_fd, CAM_RELEASE_DEV, session_handle, csiphy_dev_handle); + LOGD("release csiphy: %d", ret); + + for (int i = 0; i < FRAME_BUF_COUNT; i++) { + release(multi_cam_state->video0_fd, buf_handle[i]); + } + LOGD("released buffers"); + } + + ret = device_control(sensor_fd, CAM_RELEASE_DEV, session_handle, sensor_dev_handle); + LOGD("release sensor: %d", ret); + + // destroyed session + struct cam_req_mgr_session_info session_info = {.session_hdl = session_handle}; + ret = do_cam_control(multi_cam_state->video0_fd, CAM_REQ_MGR_DESTROY_SESSION, &session_info, sizeof(session_info)); + LOGD("destroyed session %d: %d", camera_num, ret); +} + +void cameras_close(MultiCameraState *s) { + s->driver_cam.camera_close(); + s->road_cam.camera_close(); + s->wide_road_cam.camera_close(); + + delete s->pm; +} + +std::map> CameraState::ar0231_build_register_lut(uint8_t *data) { + // This function builds a lookup table from register address, to a pair of indices in the + // buffer where to read this address. The buffer contains padding bytes, + // as well as markers to indicate the type of the next byte. + // + // 0xAA is used to indicate the MSB of the address, 0xA5 for the LSB of the address. + // Every byte of data (MSB and LSB) is preceded by 0x5A. Specifying an address is optional + // for contiguous ranges. See page 27-29 of the AR0231 Developer guide for more information. + + int max_i[] = {1828 / 2 * 3, 1500 / 2 * 3}; + auto get_next_idx = [](int cur_idx) { + return (cur_idx % 3 == 1) ? cur_idx + 2 : cur_idx + 1; // Every third byte is padding + }; + + std::map> registers; + for (int register_row = 0; register_row < 2; register_row++) { + uint8_t *registers_raw = data + ci.frame_stride * register_row; + assert(registers_raw[0] == 0x0a); // Start of line + + int value_tag_count = 0; + int first_val_idx = 0; + uint16_t cur_addr = 0; + + for (int i = 1; i <= max_i[register_row]; i = get_next_idx(get_next_idx(i))) { + int val_idx = get_next_idx(i); + + uint8_t tag = registers_raw[i]; + uint16_t val = registers_raw[val_idx]; + + if (tag == 0xAA) { // Register MSB tag + cur_addr = val << 8; + } else if (tag == 0xA5) { // Register LSB tag + cur_addr |= val; + cur_addr -= 2; // Next value tag will increment address again + } else if (tag == 0x5A) { // Value tag + + // First tag + if (value_tag_count % 2 == 0) { + cur_addr += 2; + first_val_idx = val_idx; + } else { + registers[cur_addr] = std::make_pair(first_val_idx + ci.frame_stride * register_row, val_idx + ci.frame_stride * register_row); + } + + value_tag_count++; + } + } + } + return registers; +} + +std::map CameraState::ar0231_parse_registers(uint8_t *data, std::initializer_list addrs) { + if (ar0231_register_lut.empty()) { + ar0231_register_lut = ar0231_build_register_lut(data); + } + + std::map registers; + for (uint16_t addr : addrs) { + auto offset = ar0231_register_lut[addr]; + registers[addr] = ((uint16_t)data[offset.first] << 8) | data[offset.second]; + } + return registers; +} + +void CameraState::handle_camera_event(void *evdat) { + if (!enabled) return; + struct cam_req_mgr_message *event_data = (struct cam_req_mgr_message *)evdat; + assert(event_data->session_hdl == session_handle); + assert(event_data->u.frame_msg.link_hdl == link_handle); + + uint64_t timestamp = event_data->u.frame_msg.timestamp; + int main_id = event_data->u.frame_msg.frame_id; + int real_id = event_data->u.frame_msg.request_id; + + if (real_id != 0) { // next ready + if (real_id == 1) {idx_offset = main_id;} + int buf_idx = (real_id - 1) % FRAME_BUF_COUNT; + + // check for skipped frames + if (main_id > frame_id_last + 1 && !skipped) { + LOGE("camera %d realign", camera_num); + clear_req_queue(); + enqueue_req_multi(real_id + 1, FRAME_BUF_COUNT - 1, 0); + skipped = true; + } else if (main_id == frame_id_last + 1) { + skipped = false; + } + + // check for dropped requests + if (real_id > request_id_last + 1) { + LOGE("camera %d dropped requests %d %d", camera_num, real_id, request_id_last); + enqueue_req_multi(request_id_last + 1 + FRAME_BUF_COUNT, real_id - (request_id_last + 1), 0); + } + + // metas + frame_id_last = main_id; + request_id_last = real_id; + + auto &meta_data = buf.camera_bufs_metadata[buf_idx]; + meta_data.frame_id = main_id - idx_offset; + meta_data.timestamp_sof = timestamp; + exp_lock.lock(); + meta_data.gain = analog_gain_frac * (1 + dc_gain_weight * (dc_gain_factor-1) / dc_gain_max_weight); + meta_data.high_conversion_gain = dc_gain_enabled; + meta_data.integ_lines = exposure_time; + meta_data.measured_grey_fraction = measured_grey_fraction; + meta_data.target_grey_fraction = target_grey_fraction; + exp_lock.unlock(); + + // dispatch + enqueue_req_multi(real_id + FRAME_BUF_COUNT, 1, 1); + } else { // not ready + if (main_id > frame_id_last + 10) { + LOGE("camera %d reset after half second of no response", camera_num); + clear_req_queue(); + enqueue_req_multi(request_id_last + 1, FRAME_BUF_COUNT, 0); + frame_id_last = main_id; + skipped = true; + } + } +} + +void CameraState::set_camera_exposure(float grey_frac) { + if (!enabled) return; + const float dt = 0.05; + + const float ts_grey = 10.0; + const float ts_ev = 0.05; + + const float k_grey = (dt / ts_grey) / (1.0 + dt / ts_grey); + const float k_ev = (dt / ts_ev) / (1.0 + dt / ts_ev); + + // It takes 3 frames for the commanded exposure settings to take effect. The first frame is already started by the time + // we reach this function, the other 2 are due to the register buffering in the sensor. + // Therefore we use the target EV from 3 frames ago, the grey fraction that was just measured was the result of that control action. + // TODO: Lower latency to 2 frames, by using the histogram outputted by the sensor we can do AE before the debayering is complete + + const float cur_ev_ = cur_ev[buf.cur_frame_data.frame_id % 3]; + + // Scale target grey between 0.1 and 0.4 depending on lighting conditions + float new_target_grey = std::clamp(0.4 - 0.3 * log2(1.0 + target_grey_factor*cur_ev_) / log2(6000.0), 0.1, 0.4); + float target_grey = (1.0 - k_grey) * target_grey_fraction + k_grey * new_target_grey; + + float desired_ev = std::clamp(cur_ev_ * target_grey / grey_frac, min_ev, max_ev); + float k = (1.0 - k_ev) / 3.0; + desired_ev = (k * cur_ev[0]) + (k * cur_ev[1]) + (k * cur_ev[2]) + (k_ev * desired_ev); + + float best_ev_score = 1e6; + int new_g = 0; + int new_t = 0; + + // Hysteresis around high conversion gain + // We usually want this on since it results in lower noise, but turn off in very bright day scenes + bool enable_dc_gain = dc_gain_enabled; + if (!enable_dc_gain && target_grey < dc_gain_on_grey) { + enable_dc_gain = true; + dc_gain_weight = dc_gain_min_weight; + } else if (enable_dc_gain && target_grey > dc_gain_off_grey) { + enable_dc_gain = false; + dc_gain_weight = dc_gain_max_weight; + } + + if (enable_dc_gain && dc_gain_weight < dc_gain_max_weight) {dc_gain_weight += 1;} + if (!enable_dc_gain && dc_gain_weight > dc_gain_min_weight) {dc_gain_weight -= 1;} + + std::string gain_bytes, time_bytes; + if (env_ctrl_exp_from_params) { + gain_bytes = Params().get("CameraDebugExpGain"); + time_bytes = Params().get("CameraDebugExpTime"); + } + + if (gain_bytes.size() > 0 && time_bytes.size() > 0) { + // Override gain and exposure time + gain_idx = std::stoi(gain_bytes); + exposure_time = std::stoi(time_bytes); + + new_g = gain_idx; + new_t = exposure_time; + enable_dc_gain = false; + } else { + // Simple brute force optimizer to choose sensor parameters + // to reach desired EV + for (int g = std::max((int)analog_gain_min_idx, gain_idx - 1); g <= std::min((int)analog_gain_max_idx, gain_idx + 1); g++) { + float gain = sensor_analog_gains[g] * (1 + dc_gain_weight * (dc_gain_factor-1) / dc_gain_max_weight); + + // Compute optimal time for given gain + int t = std::clamp(int(std::round(desired_ev / gain)), exposure_time_min, exposure_time_max); + + // Only go below recommended gain when absolutely necessary to not overexpose + if (g < analog_gain_rec_idx && t > 20 && g < gain_idx) { + continue; + } + + // Compute error to desired ev + float score = std::abs(desired_ev - (t * gain)) * 10; + + // Going below recommended gain needs lower penalty to not overexpose + float m = g > analog_gain_rec_idx ? 5.0 : 0.1; + score += std::abs(g - (int)analog_gain_rec_idx) * m; + + // LOGE("cam: %d - gain: %d, t: %d (%.2f), score %.2f, score + gain %.2f, %.3f, %.3f", camera_num, g, t, desired_ev / gain, score, score + std::abs(g - gain_idx) * (score + 1.0) / 10.0, desired_ev, min_ev); + + // Small penalty on changing gain + score += ((1 - analog_gain_cost_delta) + analog_gain_cost_delta * (g - analog_gain_min_idx) / (analog_gain_max_idx - analog_gain_min_idx)) * std::abs(g - gain_idx) * (score + 1.0) / 10.0; + + if (score < best_ev_score) { + new_t = t; + new_g = g; + best_ev_score = score; + } + } + } + + exp_lock.lock(); + + measured_grey_fraction = grey_frac; + target_grey_fraction = target_grey; + + analog_gain_frac = sensor_analog_gains[new_g]; + gain_idx = new_g; + exposure_time = new_t; + dc_gain_enabled = enable_dc_gain; + + float gain = analog_gain_frac * (1 + dc_gain_weight * (dc_gain_factor-1) / dc_gain_max_weight); + cur_ev[buf.cur_frame_data.frame_id % 3] = exposure_time * gain; + + exp_lock.unlock(); + + // Processing a frame takes right about 50ms, so we need to wait a few ms + // so we don't send i2c commands around the frame start. + int ms = (nanos_since_boot() - buf.cur_frame_data.timestamp_sof) / 1000000; + if (ms < 60) { + util::sleep_for(60 - ms); + } + // LOGE("ae - camera %d, cur_t %.5f, sof %.5f, dt %.5f", camera_num, 1e-9 * nanos_since_boot(), 1e-9 * buf.cur_frame_data.timestamp_sof, 1e-9 * (nanos_since_boot() - buf.cur_frame_data.timestamp_sof)); + + if (camera_id == CAMERA_ID_AR0231) { + uint16_t analog_gain_reg = 0xFF00 | (new_g << 4) | new_g; + struct i2c_random_wr_payload exp_reg_array[] = { + {0x3366, analog_gain_reg}, + {0x3362, (uint16_t)(dc_gain_enabled ? 0x1 : 0x0)}, + {0x3012, (uint16_t)exposure_time}, + }; + sensors_i2c(exp_reg_array, sizeof(exp_reg_array)/sizeof(struct i2c_random_wr_payload), CAM_SENSOR_PACKET_OPCODE_SENSOR_CONFIG, true); + } else if (camera_id == CAMERA_ID_OX03C10) { + // t_HCG + t_LCG + t_VS on LPD, t_SPD on SPD + uint32_t hcg_time = std::max((dc_gain_weight * exposure_time / dc_gain_max_weight), 0); + uint32_t lcg_time = std::max(((dc_gain_max_weight - dc_gain_weight) * exposure_time / dc_gain_max_weight), 0); + // uint32_t spd_time = std::max(hcg_time / 16, (uint32_t)exposure_time_min); + uint32_t vs_time = std::min(std::max((uint32_t)exposure_time / 128, VS_TIME_MIN_OX03C10), VS_TIME_MAX_OX03C10); + uint32_t spd_time = vs_time; + + uint32_t real_gain = ox03c10_analog_gains_reg[new_g]; + uint32_t min_gain = ox03c10_analog_gains_reg[0]; + struct i2c_random_wr_payload exp_reg_array[] = { + {0x3501, hcg_time>>8}, {0x3502, hcg_time&0xFF}, + {0x3581, lcg_time>>8}, {0x3582, lcg_time&0xFF}, + {0x3541, spd_time>>8}, {0x3542, spd_time&0xFF}, + {0x35c1, vs_time>>8}, {0x35c2, vs_time&0xFF}, + + {0x3508, real_gain>>8}, {0x3509, real_gain&0xFF}, + {0x3588, min_gain>>8}, {0x3589, min_gain&0xFF}, + {0x3548, min_gain>>8}, {0x3549, min_gain&0xFF}, + {0x35c8, min_gain>>8}, {0x35c9, min_gain&0xFF}, + }; + sensors_i2c(exp_reg_array, sizeof(exp_reg_array)/sizeof(struct i2c_random_wr_payload), CAM_SENSOR_PACKET_OPCODE_SENSOR_CONFIG, false); + } +} + +static float ar0231_parse_temp_sensor(uint16_t calib1, uint16_t calib2, uint16_t data_reg) { + // See AR0231 Developer Guide - page 36 + float slope = (125.0 - 55.0) / ((float)calib1 - (float)calib2); + float t0 = 55.0 - slope * (float)calib2; + return t0 + slope * (float)data_reg; +} + +static void ar0231_process_registers(MultiCameraState *s, CameraState *c, cereal::FrameData::Builder &framed){ + const uint8_t expected_preamble[] = {0x0a, 0xaa, 0x55, 0x20, 0xa5, 0x55}; + uint8_t *data = (uint8_t*)c->buf.cur_camera_buf->addr + c->ci.registers_offset; + + if (memcmp(data, expected_preamble, std::size(expected_preamble)) != 0){ + LOGE("unexpected register data found"); + return; + } + + auto registers = c->ar0231_parse_registers(data, {0x2000, 0x2002, 0x20b0, 0x20b2, 0x30c6, 0x30c8, 0x30ca, 0x30cc}); + + uint32_t frame_id = ((uint32_t)registers[0x2000] << 16) | registers[0x2002]; + framed.setFrameIdSensor(frame_id); + + float temp_0 = ar0231_parse_temp_sensor(registers[0x30c6], registers[0x30c8], registers[0x20b0]); + float temp_1 = ar0231_parse_temp_sensor(registers[0x30ca], registers[0x30cc], registers[0x20b2]); + framed.setTemperaturesC({temp_0, temp_1}); +} + +static void process_driver_camera(MultiCameraState *s, CameraState *c, int cnt) { + c->set_camera_exposure(set_exposure_target(&c->buf, 96, 1832, 2, 242, 1148, 4)); + + MessageBuilder msg; + auto framed = msg.initEvent().initDriverCameraState(); + framed.setFrameType(cereal::FrameData::FrameType::FRONT); + fill_frame_data(framed, c->buf.cur_frame_data, c); + + if (c->camera_id == CAMERA_ID_AR0231) { + ar0231_process_registers(s, c, framed); + } + s->pm->send("driverCameraState", msg); +} + +void process_road_camera(MultiCameraState *s, CameraState *c, int cnt) { + const CameraBuf *b = &c->buf; + + MessageBuilder msg; + auto framed = c == &s->road_cam ? msg.initEvent().initRoadCameraState() : msg.initEvent().initWideRoadCameraState(); + fill_frame_data(framed, b->cur_frame_data, c); + if (env_log_raw_frames && c == &s->road_cam && cnt % 100 == 5) { // no overlap with qlog decimation + framed.setImage(get_raw_frame_image(b)); + } + LOGT(c->buf.cur_frame_data.frame_id, "%s: Image set", c == &s->road_cam ? "RoadCamera" : "WideRoadCamera"); + if (c == &s->road_cam) { + framed.setTransform(b->yuv_transform.v); + LOGT(c->buf.cur_frame_data.frame_id, "%s: Transformed", "RoadCamera"); + } + + if (c->camera_id == CAMERA_ID_AR0231) { + ar0231_process_registers(s, c, framed); + } + + s->pm->send(c == &s->road_cam ? "roadCameraState" : "wideRoadCameraState", msg); + + const auto [x, y, w, h] = (c == &s->wide_road_cam) ? std::tuple(96, 250, 1734, 524) : std::tuple(96, 160, 1734, 986); + const int skip = 2; + c->set_camera_exposure(set_exposure_target(b, x, x + w, skip, y, y + h, skip)); +} + +void cameras_run(MultiCameraState *s) { + LOG("-- Starting threads"); + std::vector threads; + if (s->driver_cam.enabled) threads.push_back(start_process_thread(s, &s->driver_cam, process_driver_camera)); + if (s->road_cam.enabled) threads.push_back(start_process_thread(s, &s->road_cam, process_road_camera)); + if (s->wide_road_cam.enabled) threads.push_back(start_process_thread(s, &s->wide_road_cam, process_road_camera)); + + // start devices + LOG("-- Starting devices"); + s->driver_cam.sensors_start(); + s->road_cam.sensors_start(); + s->wide_road_cam.sensors_start(); + + // poll events + LOG("-- Dequeueing Video events"); + while (!do_exit) { + struct pollfd fds[1] = {{0}}; + + fds[0].fd = s->video0_fd; + fds[0].events = POLLPRI; + + int ret = poll(fds, std::size(fds), 1000); + if (ret < 0) { + if (errno == EINTR || errno == EAGAIN) continue; + LOGE("poll failed (%d - %d)", ret, errno); + break; + } + + if (!fds[0].revents) continue; + + struct v4l2_event ev = {0}; + ret = HANDLE_EINTR(ioctl(fds[0].fd, VIDIOC_DQEVENT, &ev)); + if (ret == 0) { + if (ev.type == V4L_EVENT_CAM_REQ_MGR_EVENT) { + struct cam_req_mgr_message *event_data = (struct cam_req_mgr_message *)ev.u.data; + // LOGD("v4l2 event: sess_hdl 0x%X, link_hdl 0x%X, frame_id %d, req_id %lld, timestamp 0x%llx, sof_status %d\n", event_data->session_hdl, event_data->u.frame_msg.link_hdl, event_data->u.frame_msg.frame_id, event_data->u.frame_msg.request_id, event_data->u.frame_msg.timestamp, event_data->u.frame_msg.sof_status); + if (env_debug_frames) { + printf("sess_hdl 0x%6X, link_hdl 0x%6X, frame_id %lu, req_id %lu, timestamp %.2f ms, sof_status %d\n", event_data->session_hdl, event_data->u.frame_msg.link_hdl, event_data->u.frame_msg.frame_id, event_data->u.frame_msg.request_id, event_data->u.frame_msg.timestamp/1e6, event_data->u.frame_msg.sof_status); + } + + if (event_data->session_hdl == s->road_cam.session_handle) { + s->road_cam.handle_camera_event(event_data); + } else if (event_data->session_hdl == s->wide_road_cam.session_handle) { + s->wide_road_cam.handle_camera_event(event_data); + } else if (event_data->session_hdl == s->driver_cam.session_handle) { + s->driver_cam.handle_camera_event(event_data); + } else { + LOGE("Unknown vidioc event source"); + assert(false); + } + } + } else { + LOGE("VIDIOC_DQEVENT failed, errno=%d", errno); + } + } + + LOG(" ************** STOPPING **************"); + + for (auto &t : threads) t.join(); + + cameras_close(s); +} diff --git a/system/camerad/cameras/camera_qcom2.h b/system/camerad/cameras/camera_qcom2.h new file mode 100644 index 0000000000..150ea0a1c0 --- /dev/null +++ b/system/camerad/cameras/camera_qcom2.h @@ -0,0 +1,118 @@ +#pragma once + +#include +#include +#include + +#include + +#include "system/camerad/cameras/camera_common.h" +#include "system/camerad/cameras/camera_util.h" +#include "common/params.h" +#include "common/util.h" + +#define FRAME_BUF_COUNT 4 +#define ANALOG_GAIN_MAX_CNT 55 + +class CameraState { +public: + MultiCameraState *multi_cam_state; + CameraInfo ci; + bool enabled; + + std::mutex exp_lock; + + int exposure_time; + bool dc_gain_enabled; + int dc_gain_weight; + int gain_idx; + float analog_gain_frac; + + int exposure_time_min; + int exposure_time_max; + + float dc_gain_factor; + int dc_gain_min_weight; + int dc_gain_max_weight; + float dc_gain_on_grey; + float dc_gain_off_grey; + + float sensor_analog_gains[ANALOG_GAIN_MAX_CNT]; + int analog_gain_min_idx; + int analog_gain_max_idx; + int analog_gain_rec_idx; + int analog_gain_cost_delta; + + float cur_ev[3]; + float min_ev, max_ev; + + float measured_grey_fraction; + float target_grey_fraction; + float target_grey_factor; + + unique_fd sensor_fd; + unique_fd csiphy_fd; + + int camera_num; + + void handle_camera_event(void *evdat); + void set_camera_exposure(float grey_frac); + + void sensors_start(); + + void camera_open(MultiCameraState *multi_cam_state, int camera_num, bool enabled); + void camera_set_parameters(); + void camera_map_bufs(MultiCameraState *s); + void camera_init(MultiCameraState *s, VisionIpcServer *v, int camera_id, unsigned int fps, cl_device_id device_id, cl_context ctx, VisionStreamType yuv_type); + void camera_close(); + + std::map ar0231_parse_registers(uint8_t *data, std::initializer_list addrs); + + int32_t session_handle; + int32_t sensor_dev_handle; + int32_t isp_dev_handle; + int32_t csiphy_dev_handle; + + int32_t link_handle; + + int buf0_handle; + int buf_handle[FRAME_BUF_COUNT]; + int sync_objs[FRAME_BUF_COUNT]; + int request_ids[FRAME_BUF_COUNT]; + int request_id_last; + int frame_id_last; + int idx_offset; + bool skipped; + int camera_id; + + CameraBuf buf; + MemoryManager mm; + +private: + void config_isp(int io_mem_handle, int fence, int request_id, int buf0_mem_handle, int buf0_offset); + void enqueue_req_multi(int start, int n, bool dp); + void enqueue_buffer(int i, bool dp); + int clear_req_queue(); + + int sensors_init(); + void sensors_poke(int request_id); + void sensors_i2c(struct i2c_random_wr_payload* dat, int len, int op_code, bool data_word); + + // Register parsing + std::map> ar0231_register_lut; + std::map> ar0231_build_register_lut(uint8_t *data); +}; + +typedef struct MultiCameraState { + unique_fd video0_fd; + unique_fd cam_sync_fd; + unique_fd isp_fd; + int device_iommu; + int cdm_iommu; + + CameraState road_cam; + CameraState wide_road_cam; + CameraState driver_cam; + + PubMaster *pm; +} MultiCameraState; diff --git a/system/camerad/cameras/camera_util.cc b/system/camerad/cameras/camera_util.cc new file mode 100644 index 0000000000..6d139590e4 --- /dev/null +++ b/system/camerad/cameras/camera_util.cc @@ -0,0 +1,135 @@ +#include "system/camerad/cameras/camera_util.h" + +#include + +#include +#include + +#include "common/swaglog.h" +#include "common/util.h" + +// ************** low level camera helpers **************** +int do_cam_control(int fd, int op_code, void *handle, int size) { + struct cam_control camcontrol = {0}; + camcontrol.op_code = op_code; + camcontrol.handle = (uint64_t)handle; + if (size == 0) { + camcontrol.size = 8; + camcontrol.handle_type = CAM_HANDLE_MEM_HANDLE; + } else { + camcontrol.size = size; + camcontrol.handle_type = CAM_HANDLE_USER_POINTER; + } + + int ret = HANDLE_EINTR(ioctl(fd, VIDIOC_CAM_CONTROL, &camcontrol)); + if (ret == -1) { + LOGE("VIDIOC_CAM_CONTROL error: op_code %d - errno %d", op_code, errno); + } + return ret; +} + +std::optional device_acquire(int fd, int32_t session_handle, void *data, uint32_t num_resources) { + struct cam_acquire_dev_cmd cmd = { + .session_handle = session_handle, + .handle_type = CAM_HANDLE_USER_POINTER, + .num_resources = (uint32_t)(data ? num_resources : 0), + .resource_hdl = (uint64_t)data, + }; + int err = do_cam_control(fd, CAM_ACQUIRE_DEV, &cmd, sizeof(cmd)); + return err == 0 ? std::make_optional(cmd.dev_handle) : std::nullopt; +}; + +int device_config(int fd, int32_t session_handle, int32_t dev_handle, uint64_t packet_handle) { + struct cam_config_dev_cmd cmd = { + .session_handle = session_handle, + .dev_handle = dev_handle, + .packet_handle = packet_handle, + }; + return do_cam_control(fd, CAM_CONFIG_DEV, &cmd, sizeof(cmd)); +} + +int device_control(int fd, int op_code, int session_handle, int dev_handle) { + // start stop and release are all the same + struct cam_start_stop_dev_cmd cmd { .session_handle = session_handle, .dev_handle = dev_handle }; + return do_cam_control(fd, op_code, &cmd, sizeof(cmd)); +} + +void *alloc_w_mmu_hdl(int video0_fd, int len, uint32_t *handle, int align, int flags, int mmu_hdl, int mmu_hdl2) { + struct cam_mem_mgr_alloc_cmd mem_mgr_alloc_cmd = {0}; + mem_mgr_alloc_cmd.len = len; + mem_mgr_alloc_cmd.align = align; + mem_mgr_alloc_cmd.flags = flags; + mem_mgr_alloc_cmd.num_hdl = 0; + if (mmu_hdl != 0) { + mem_mgr_alloc_cmd.mmu_hdls[0] = mmu_hdl; + mem_mgr_alloc_cmd.num_hdl++; + } + if (mmu_hdl2 != 0) { + mem_mgr_alloc_cmd.mmu_hdls[1] = mmu_hdl2; + mem_mgr_alloc_cmd.num_hdl++; + } + + do_cam_control(video0_fd, CAM_REQ_MGR_ALLOC_BUF, &mem_mgr_alloc_cmd, sizeof(mem_mgr_alloc_cmd)); + *handle = mem_mgr_alloc_cmd.out.buf_handle; + + void *ptr = NULL; + if (mem_mgr_alloc_cmd.out.fd > 0) { + ptr = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, mem_mgr_alloc_cmd.out.fd, 0); + assert(ptr != MAP_FAILED); + } + + // LOGD("allocated: %x %d %llx mapped %p", mem_mgr_alloc_cmd.out.buf_handle, mem_mgr_alloc_cmd.out.fd, mem_mgr_alloc_cmd.out.vaddr, ptr); + + return ptr; +} + +void release(int video0_fd, uint32_t handle) { + int ret; + struct cam_mem_mgr_release_cmd mem_mgr_release_cmd = {0}; + mem_mgr_release_cmd.buf_handle = handle; + + ret = do_cam_control(video0_fd, CAM_REQ_MGR_RELEASE_BUF, &mem_mgr_release_cmd, sizeof(mem_mgr_release_cmd)); + assert(ret == 0); +} + +void release_fd(int video0_fd, uint32_t handle) { + // handle to fd + close(handle>>16); + release(video0_fd, handle); +} + +void *MemoryManager::alloc(int size, uint32_t *handle) { + lock.lock(); + void *ptr; + if (!cached_allocations[size].empty()) { + ptr = cached_allocations[size].front(); + cached_allocations[size].pop(); + *handle = handle_lookup[ptr]; + } else { + ptr = alloc_w_mmu_hdl(video0_fd, size, handle); + handle_lookup[ptr] = *handle; + size_lookup[ptr] = size; + } + lock.unlock(); + return ptr; +} + +void MemoryManager::free(void *ptr) { + lock.lock(); + cached_allocations[size_lookup[ptr]].push(ptr); + lock.unlock(); +} + +MemoryManager::~MemoryManager() { + for (auto& x : cached_allocations) { + while (!x.second.empty()) { + void *ptr = x.second.front(); + x.second.pop(); + LOGD("freeing cached allocation %p with size %d", ptr, size_lookup[ptr]); + munmap(ptr, size_lookup[ptr]); + release_fd(video0_fd, handle_lookup[ptr]); + handle_lookup.erase(ptr); + size_lookup.erase(ptr); + } + } +} diff --git a/system/camerad/cameras/camera_util.h b/system/camerad/cameras/camera_util.h new file mode 100644 index 0000000000..e408f6c0e2 --- /dev/null +++ b/system/camerad/cameras/camera_util.h @@ -0,0 +1,30 @@ +#pragma once + +#include +#include +#include +#include + +#include + +std::optional device_acquire(int fd, int32_t session_handle, void *data, uint32_t num_resources=1); +int device_config(int fd, int32_t session_handle, int32_t dev_handle, uint64_t packet_handle); +int device_control(int fd, int op_code, int session_handle, int dev_handle); +int do_cam_control(int fd, int op_code, void *handle, int size); +void *alloc_w_mmu_hdl(int video0_fd, int len, uint32_t *handle, int align = 8, int flags = CAM_MEM_FLAG_KMD_ACCESS | CAM_MEM_FLAG_UMD_ACCESS | CAM_MEM_FLAG_CMD_BUF_TYPE, + int mmu_hdl = 0, int mmu_hdl2 = 0); +void release(int video0_fd, uint32_t handle); + +class MemoryManager { + public: + void init(int _video0_fd) { video0_fd = _video0_fd; } + void *alloc(int len, uint32_t *handle); + void free(void *ptr); + ~MemoryManager(); + private: + std::mutex lock; + std::map handle_lookup; + std::map size_lookup; + std::map > cached_allocations; + int video0_fd; +}; diff --git a/system/camerad/cameras/real_debayer.cl b/system/camerad/cameras/real_debayer.cl new file mode 100644 index 0000000000..cff5ae455b --- /dev/null +++ b/system/camerad/cameras/real_debayer.cl @@ -0,0 +1,193 @@ +#define UV_WIDTH RGB_WIDTH / 2 +#define UV_HEIGHT RGB_HEIGHT / 2 + +#define RGB_TO_Y(r, g, b) ((((mul24(b, 13) + mul24(g, 65) + mul24(r, 33)) + 64) >> 7) + 16) +#define RGB_TO_U(r, g, b) ((mul24(b, 56) - mul24(g, 37) - mul24(r, 19) + 0x8080) >> 8) +#define RGB_TO_V(r, g, b) ((mul24(r, 56) - mul24(g, 47) - mul24(b, 9) + 0x8080) >> 8) +#define AVERAGE(x, y, z, w) ((convert_ushort(x) + convert_ushort(y) + convert_ushort(z) + convert_ushort(w) + 1) >> 1) + +float3 color_correct(float3 rgb) { + // color correction + #if IS_OX + float3 x = rgb.x * (float3)(1.5664815 , -0.29808738, -0.03973474); + x += rgb.y * (float3)(-0.48672447, 1.41914433, -0.40295248); + x += rgb.z * (float3)(-0.07975703, -0.12105695, 1.44268722); + #else + float3 x = rgb.x * (float3)(1.82717181, -0.31231438, 0.07307673); + x += rgb.y * (float3)(-0.5743977, 1.36858544, -0.53183455); + x += rgb.z * (float3)(-0.25277411, -0.05627105, 1.45875782); + #endif + + // tone mapping params + const float gamma_k = 0.75; + const float gamma_b = 0.125; + const float mp = 0.01; // ideally midpoint should be adaptive + const float rk = 9 - 100*mp; + + // poly approximation for s curve + return (x > mp) ? + ((rk * (x-mp) * (1-(gamma_k*mp+gamma_b)) * (1+1/(rk*(1-mp))) / (1+rk*(x-mp))) + gamma_k*mp + gamma_b) : + ((rk * (x-mp) * (gamma_k*mp+gamma_b) * (1+1/(rk*mp)) / (1-rk*(x-mp))) + gamma_k*mp + gamma_b); +} + +float get_vignetting_s(float r) { + if (r < 62500) { + return (1.0f + 0.0000008f*r); + } else if (r < 490000) { + return (0.9625f + 0.0000014f*r); + } else if (r < 1102500) { + return (1.26434f + 0.0000000000016f*r*r); + } else { + return (0.53503625f + 0.0000000000022f*r*r); + } +} + +constant float ox03c10_lut[] = { + 0.0000e+00, 5.9488e-08, 1.1898e-07, 1.7846e-07, 2.3795e-07, 2.9744e-07, 3.5693e-07, 4.1642e-07, 4.7591e-07, 5.3539e-07, 5.9488e-07, 6.5437e-07, 7.1386e-07, 7.7335e-07, 8.3284e-07, 8.9232e-07, 9.5181e-07, 1.0113e-06, 1.0708e-06, 1.1303e-06, 1.1898e-06, 1.2493e-06, 1.3087e-06, 1.3682e-06, 1.4277e-06, 1.4872e-06, 1.5467e-06, 1.6062e-06, 1.6657e-06, 1.7252e-06, 1.7846e-06, 1.8441e-06, 1.9036e-06, 1.9631e-06, 2.0226e-06, 2.0821e-06, 2.1416e-06, 2.2011e-06, 2.2606e-06, 2.3200e-06, 2.3795e-06, 2.4390e-06, 2.4985e-06, 2.5580e-06, 2.6175e-06, 2.6770e-06, 2.7365e-06, 2.7959e-06, 2.8554e-06, 2.9149e-06, 2.9744e-06, 3.0339e-06, 3.0934e-06, 3.1529e-06, 3.2124e-06, 3.2719e-06, 3.3313e-06, 3.3908e-06, 3.4503e-06, 3.5098e-06, 3.5693e-06, 3.6288e-06, 3.6883e-06, 3.7478e-06, 3.8072e-06, 3.8667e-06, 3.9262e-06, 3.9857e-06, 4.0452e-06, 4.1047e-06, 4.1642e-06, 4.2237e-06, 4.2832e-06, 4.3426e-06, 4.4021e-06, 4.4616e-06, 4.5211e-06, 4.5806e-06, 4.6401e-06, 4.6996e-06, 4.7591e-06, 4.8185e-06, 4.8780e-06, 4.9375e-06, 4.9970e-06, 5.0565e-06, 5.1160e-06, 5.1755e-06, 5.2350e-06, 5.2945e-06, 5.3539e-06, 5.4134e-06, 5.4729e-06, 5.5324e-06, 5.5919e-06, 5.6514e-06, 5.7109e-06, 5.7704e-06, 5.8298e-06, 5.8893e-06, 5.9488e-06, 6.0083e-06, 6.0678e-06, 6.1273e-06, 6.1868e-06, 6.2463e-06, 6.3058e-06, 6.3652e-06, 6.4247e-06, 6.4842e-06, 6.5437e-06, 6.6032e-06, 6.6627e-06, 6.7222e-06, 6.7817e-06, 6.8411e-06, 6.9006e-06, 6.9601e-06, 7.0196e-06, 7.0791e-06, 7.1386e-06, 7.1981e-06, 7.2576e-06, 7.3171e-06, 7.3765e-06, 7.4360e-06, 7.4955e-06, 7.5550e-06, 7.6145e-06, 7.6740e-06, 7.7335e-06, 7.7930e-06, 7.8524e-06, 7.9119e-06, 7.9714e-06, 8.0309e-06, 8.0904e-06, 8.1499e-06, 8.2094e-06, 8.2689e-06, 8.3284e-06, 8.3878e-06, 8.4473e-06, 8.5068e-06, 8.5663e-06, 8.6258e-06, 8.6853e-06, 8.7448e-06, 8.8043e-06, 8.8637e-06, 8.9232e-06, 8.9827e-06, 9.0422e-06, 9.1017e-06, 9.1612e-06, 9.2207e-06, 9.2802e-06, 9.3397e-06, 9.3991e-06, 9.4586e-06, 9.5181e-06, 9.5776e-06, 9.6371e-06, 9.6966e-06, 9.7561e-06, 9.8156e-06, 9.8750e-06, 9.9345e-06, 9.9940e-06, 1.0054e-05, 1.0113e-05, 1.0172e-05, 1.0232e-05, 1.0291e-05, 1.0351e-05, 1.0410e-05, 1.0470e-05, 1.0529e-05, 1.0589e-05, 1.0648e-05, 1.0708e-05, 1.0767e-05, 1.0827e-05, 1.0886e-05, 1.0946e-05, 1.1005e-05, 1.1065e-05, 1.1124e-05, 1.1184e-05, 1.1243e-05, 1.1303e-05, 1.1362e-05, 1.1422e-05, 1.1481e-05, 1.1541e-05, 1.1600e-05, 1.1660e-05, 1.1719e-05, 1.1779e-05, 1.1838e-05, 1.1898e-05, 1.1957e-05, 1.2017e-05, 1.2076e-05, 1.2136e-05, 1.2195e-05, 1.2255e-05, 1.2314e-05, 1.2374e-05, 1.2433e-05, 1.2493e-05, 1.2552e-05, 1.2612e-05, 1.2671e-05, 1.2730e-05, 1.2790e-05, 1.2849e-05, 1.2909e-05, 1.2968e-05, 1.3028e-05, 1.3087e-05, 1.3147e-05, 1.3206e-05, 1.3266e-05, 1.3325e-05, 1.3385e-05, 1.3444e-05, 1.3504e-05, 1.3563e-05, 1.3623e-05, 1.3682e-05, 1.3742e-05, 1.3801e-05, 1.3861e-05, 1.3920e-05, 1.3980e-05, 1.4039e-05, 1.4099e-05, 1.4158e-05, 1.4218e-05, 1.4277e-05, 1.4337e-05, 1.4396e-05, 1.4456e-05, 1.4515e-05, 1.4575e-05, 1.4634e-05, 1.4694e-05, 1.4753e-05, 1.4813e-05, 1.4872e-05, 1.4932e-05, 1.4991e-05, 1.5051e-05, 1.5110e-05, 1.5169e-05, + 1.5229e-05, 1.5288e-05, 1.5348e-05, 1.5407e-05, 1.5467e-05, 1.5526e-05, 1.5586e-05, 1.5645e-05, 1.5705e-05, 1.5764e-05, 1.5824e-05, 1.5883e-05, 1.5943e-05, 1.6002e-05, 1.6062e-05, 1.6121e-05, 1.6181e-05, 1.6240e-05, 1.6300e-05, 1.6359e-05, 1.6419e-05, 1.6478e-05, 1.6538e-05, 1.6597e-05, 1.6657e-05, 1.6716e-05, 1.6776e-05, 1.6835e-05, 1.6895e-05, 1.6954e-05, 1.7014e-05, 1.7073e-05, 1.7133e-05, 1.7192e-05, 1.7252e-05, 1.7311e-05, 1.7371e-05, 1.7430e-05, 1.7490e-05, 1.7549e-05, 1.7609e-05, 1.7668e-05, 1.7727e-05, 1.7787e-05, 1.7846e-05, 1.7906e-05, 1.7965e-05, 1.8025e-05, 1.8084e-05, 1.8144e-05, 1.8203e-05, 1.8263e-05, 1.8322e-05, 1.8382e-05, 1.8441e-05, 1.8501e-05, 1.8560e-05, 1.8620e-05, 1.8679e-05, 1.8739e-05, 1.8798e-05, 1.8858e-05, 1.8917e-05, 1.8977e-05, 1.9036e-05, 1.9096e-05, 1.9155e-05, 1.9215e-05, 1.9274e-05, 1.9334e-05, 1.9393e-05, 1.9453e-05, 1.9512e-05, 1.9572e-05, 1.9631e-05, 1.9691e-05, 1.9750e-05, 1.9810e-05, 1.9869e-05, 1.9929e-05, 1.9988e-05, 2.0048e-05, 2.0107e-05, 2.0167e-05, 2.0226e-05, 2.0285e-05, 2.0345e-05, 2.0404e-05, 2.0464e-05, 2.0523e-05, 2.0583e-05, 2.0642e-05, 2.0702e-05, 2.0761e-05, 2.0821e-05, 2.0880e-05, 2.0940e-05, 2.0999e-05, 2.1059e-05, 2.1118e-05, 2.1178e-05, 2.1237e-05, 2.1297e-05, 2.1356e-05, 2.1416e-05, 2.1475e-05, 2.1535e-05, 2.1594e-05, 2.1654e-05, 2.1713e-05, 2.1773e-05, 2.1832e-05, 2.1892e-05, 2.1951e-05, 2.2011e-05, 2.2070e-05, 2.2130e-05, 2.2189e-05, 2.2249e-05, 2.2308e-05, 2.2368e-05, 2.2427e-05, 2.2487e-05, 2.2546e-05, 2.2606e-05, 2.2665e-05, 2.2725e-05, 2.2784e-05, 2.2843e-05, 2.2903e-05, 2.2962e-05, 2.3022e-05, 2.3081e-05, 2.3141e-05, 2.3200e-05, 2.3260e-05, 2.3319e-05, 2.3379e-05, 2.3438e-05, 2.3498e-05, 2.3557e-05, 2.3617e-05, 2.3676e-05, 2.3736e-05, 2.3795e-05, 2.3855e-05, 2.3914e-05, 2.3974e-05, 2.4033e-05, 2.4093e-05, 2.4152e-05, 2.4212e-05, 2.4271e-05, 2.4331e-05, 2.4390e-05, 2.4450e-05, 2.4509e-05, 2.4569e-05, 2.4628e-05, 2.4688e-05, 2.4747e-05, 2.4807e-05, 2.4866e-05, 2.4926e-05, 2.4985e-05, 2.5045e-05, 2.5104e-05, 2.5164e-05, 2.5223e-05, 2.5282e-05, 2.5342e-05, 2.5401e-05, 2.5461e-05, 2.5520e-05, 2.5580e-05, 2.5639e-05, 2.5699e-05, 2.5758e-05, 2.5818e-05, 2.5877e-05, 2.5937e-05, 2.5996e-05, 2.6056e-05, 2.6115e-05, 2.6175e-05, 2.6234e-05, 2.6294e-05, 2.6353e-05, 2.6413e-05, 2.6472e-05, 2.6532e-05, 2.6591e-05, 2.6651e-05, 2.6710e-05, 2.6770e-05, 2.6829e-05, 2.6889e-05, 2.6948e-05, 2.7008e-05, 2.7067e-05, 2.7127e-05, 2.7186e-05, 2.7246e-05, 2.7305e-05, 2.7365e-05, 2.7424e-05, 2.7484e-05, 2.7543e-05, 2.7603e-05, 2.7662e-05, 2.7722e-05, 2.7781e-05, 2.7840e-05, 2.7900e-05, 2.7959e-05, 2.8019e-05, 2.8078e-05, 2.8138e-05, 2.8197e-05, 2.8257e-05, 2.8316e-05, 2.8376e-05, 2.8435e-05, 2.8495e-05, 2.8554e-05, 2.8614e-05, 2.8673e-05, 2.8733e-05, 2.8792e-05, 2.8852e-05, 2.8911e-05, 2.8971e-05, 2.9030e-05, 2.9090e-05, 2.9149e-05, 2.9209e-05, 2.9268e-05, 2.9328e-05, 2.9387e-05, 2.9447e-05, 2.9506e-05, 2.9566e-05, 2.9625e-05, 2.9685e-05, 2.9744e-05, 2.9804e-05, 2.9863e-05, 2.9923e-05, 2.9982e-05, 3.0042e-05, 3.0101e-05, 3.0161e-05, 3.0220e-05, 3.0280e-05, 3.0339e-05, 3.0398e-05, + 3.0458e-05, 3.0577e-05, 3.0697e-05, 3.0816e-05, 3.0936e-05, 3.1055e-05, 3.1175e-05, 3.1294e-05, 3.1414e-05, 3.1533e-05, 3.1652e-05, 3.1772e-05, 3.1891e-05, 3.2011e-05, 3.2130e-05, 3.2250e-05, 3.2369e-05, 3.2489e-05, 3.2608e-05, 3.2727e-05, 3.2847e-05, 3.2966e-05, 3.3086e-05, 3.3205e-05, 3.3325e-05, 3.3444e-05, 3.3563e-05, 3.3683e-05, 3.3802e-05, 3.3922e-05, 3.4041e-05, 3.4161e-05, 3.4280e-05, 3.4400e-05, 3.4519e-05, 3.4638e-05, 3.4758e-05, 3.4877e-05, 3.4997e-05, 3.5116e-05, 3.5236e-05, 3.5355e-05, 3.5475e-05, 3.5594e-05, 3.5713e-05, 3.5833e-05, 3.5952e-05, 3.6072e-05, 3.6191e-05, 3.6311e-05, 3.6430e-05, 3.6550e-05, 3.6669e-05, 3.6788e-05, 3.6908e-05, 3.7027e-05, 3.7147e-05, 3.7266e-05, 3.7386e-05, 3.7505e-05, 3.7625e-05, 3.7744e-05, 3.7863e-05, 3.7983e-05, 3.8102e-05, 3.8222e-05, 3.8341e-05, 3.8461e-05, 3.8580e-05, 3.8700e-05, 3.8819e-05, 3.8938e-05, 3.9058e-05, 3.9177e-05, 3.9297e-05, 3.9416e-05, 3.9536e-05, 3.9655e-05, 3.9775e-05, 3.9894e-05, 4.0013e-05, 4.0133e-05, 4.0252e-05, 4.0372e-05, 4.0491e-05, 4.0611e-05, 4.0730e-05, 4.0850e-05, 4.0969e-05, 4.1088e-05, 4.1208e-05, 4.1327e-05, 4.1447e-05, 4.1566e-05, 4.1686e-05, 4.1805e-05, 4.1925e-05, 4.2044e-05, 4.2163e-05, 4.2283e-05, 4.2402e-05, 4.2522e-05, 4.2641e-05, 4.2761e-05, 4.2880e-05, 4.2999e-05, 4.3119e-05, 4.3238e-05, 4.3358e-05, 4.3477e-05, 4.3597e-05, 4.3716e-05, 4.3836e-05, 4.3955e-05, 4.4074e-05, 4.4194e-05, 4.4313e-05, 4.4433e-05, 4.4552e-05, 4.4672e-05, 4.4791e-05, 4.4911e-05, 4.5030e-05, 4.5149e-05, 4.5269e-05, 4.5388e-05, 4.5508e-05, 4.5627e-05, 4.5747e-05, 4.5866e-05, 4.5986e-05, 4.6105e-05, 4.6224e-05, 4.6344e-05, 4.6463e-05, 4.6583e-05, 4.6702e-05, 4.6822e-05, 4.6941e-05, 4.7061e-05, 4.7180e-05, 4.7299e-05, 4.7419e-05, 4.7538e-05, 4.7658e-05, 4.7777e-05, 4.7897e-05, 4.8016e-05, 4.8136e-05, 4.8255e-05, 4.8374e-05, 4.8494e-05, 4.8613e-05, 4.8733e-05, 4.8852e-05, 4.8972e-05, 4.9091e-05, 4.9211e-05, 4.9330e-05, 4.9449e-05, 4.9569e-05, 4.9688e-05, 4.9808e-05, 4.9927e-05, 5.0047e-05, 5.0166e-05, 5.0286e-05, 5.0405e-05, 5.0524e-05, 5.0644e-05, 5.0763e-05, 5.0883e-05, 5.1002e-05, 5.1122e-05, 5.1241e-05, 5.1361e-05, 5.1480e-05, 5.1599e-05, 5.1719e-05, 5.1838e-05, 5.1958e-05, 5.2077e-05, 5.2197e-05, 5.2316e-05, 5.2435e-05, 5.2555e-05, 5.2674e-05, 5.2794e-05, 5.2913e-05, 5.3033e-05, 5.3152e-05, 5.3272e-05, 5.3391e-05, 5.3510e-05, 5.3630e-05, 5.3749e-05, 5.3869e-05, 5.3988e-05, 5.4108e-05, 5.4227e-05, 5.4347e-05, 5.4466e-05, 5.4585e-05, 5.4705e-05, 5.4824e-05, 5.4944e-05, 5.5063e-05, 5.5183e-05, 5.5302e-05, 5.5422e-05, 5.5541e-05, 5.5660e-05, 5.5780e-05, 5.5899e-05, 5.6019e-05, 5.6138e-05, 5.6258e-05, 5.6377e-05, 5.6497e-05, 5.6616e-05, 5.6735e-05, 5.6855e-05, 5.6974e-05, 5.7094e-05, 5.7213e-05, 5.7333e-05, 5.7452e-05, 5.7572e-05, 5.7691e-05, 5.7810e-05, 5.7930e-05, 5.8049e-05, 5.8169e-05, 5.8288e-05, 5.8408e-05, 5.8527e-05, 5.8647e-05, 5.8766e-05, 5.8885e-05, 5.9005e-05, 5.9124e-05, 5.9244e-05, 5.9363e-05, 5.9483e-05, 5.9602e-05, 5.9722e-05, 5.9841e-05, 5.9960e-05, 6.0080e-05, 6.0199e-05, 6.0319e-05, 6.0438e-05, 6.0558e-05, 6.0677e-05, 6.0797e-05, 6.0916e-05, + 6.1154e-05, 6.1392e-05, 6.1631e-05, 6.1869e-05, 6.2107e-05, 6.2345e-05, 6.2583e-05, 6.2821e-05, 6.3060e-05, 6.3298e-05, 6.3536e-05, 6.3774e-05, 6.4012e-05, 6.4251e-05, 6.4489e-05, 6.4727e-05, 6.4965e-05, 6.5203e-05, 6.5441e-05, 6.5680e-05, 6.5918e-05, 6.6156e-05, 6.6394e-05, 6.6632e-05, 6.6871e-05, 6.7109e-05, 6.7347e-05, 6.7585e-05, 6.7823e-05, 6.8062e-05, 6.8300e-05, 6.8538e-05, 6.8776e-05, 6.9014e-05, 6.9252e-05, 6.9491e-05, 6.9729e-05, 6.9967e-05, 7.0205e-05, 7.0443e-05, 7.0682e-05, 7.0920e-05, 7.1158e-05, 7.1396e-05, 7.1634e-05, 7.1872e-05, 7.2111e-05, 7.2349e-05, 7.2587e-05, 7.2825e-05, 7.3063e-05, 7.3302e-05, 7.3540e-05, 7.3778e-05, 7.4016e-05, 7.4254e-05, 7.4493e-05, 7.4731e-05, 7.4969e-05, 7.5207e-05, 7.5445e-05, 7.5683e-05, 7.5922e-05, 7.6160e-05, 7.6398e-05, 7.6636e-05, 7.6874e-05, 7.7113e-05, 7.7351e-05, 7.7589e-05, 7.7827e-05, 7.8065e-05, 7.8304e-05, 7.8542e-05, 7.8780e-05, 7.9018e-05, 7.9256e-05, 7.9494e-05, 7.9733e-05, 7.9971e-05, 8.0209e-05, 8.0447e-05, 8.0685e-05, 8.0924e-05, 8.1162e-05, 8.1400e-05, 8.1638e-05, 8.1876e-05, 8.2114e-05, 8.2353e-05, 8.2591e-05, 8.2829e-05, 8.3067e-05, 8.3305e-05, 8.3544e-05, 8.3782e-05, 8.4020e-05, 8.4258e-05, 8.4496e-05, 8.4735e-05, 8.4973e-05, 8.5211e-05, 8.5449e-05, 8.5687e-05, 8.5925e-05, 8.6164e-05, 8.6402e-05, 8.6640e-05, 8.6878e-05, 8.7116e-05, 8.7355e-05, 8.7593e-05, 8.7831e-05, 8.8069e-05, 8.8307e-05, 8.8545e-05, 8.8784e-05, 8.9022e-05, 8.9260e-05, 8.9498e-05, 8.9736e-05, 8.9975e-05, 9.0213e-05, 9.0451e-05, 9.0689e-05, 9.0927e-05, 9.1166e-05, 9.1404e-05, 9.1642e-05, 9.1880e-05, 9.2118e-05, 9.2356e-05, 9.2595e-05, 9.2833e-05, 9.3071e-05, 9.3309e-05, 9.3547e-05, 9.3786e-05, 9.4024e-05, 9.4262e-05, 9.4500e-05, 9.4738e-05, 9.4977e-05, 9.5215e-05, 9.5453e-05, 9.5691e-05, 9.5929e-05, 9.6167e-05, 9.6406e-05, 9.6644e-05, 9.6882e-05, 9.7120e-05, 9.7358e-05, 9.7597e-05, 9.7835e-05, 9.8073e-05, 9.8311e-05, 9.8549e-05, 9.8787e-05, 9.9026e-05, 9.9264e-05, 9.9502e-05, 9.9740e-05, 9.9978e-05, 1.0022e-04, 1.0045e-04, 1.0069e-04, 1.0093e-04, 1.0117e-04, 1.0141e-04, 1.0165e-04, 1.0188e-04, 1.0212e-04, 1.0236e-04, 1.0260e-04, 1.0284e-04, 1.0307e-04, 1.0331e-04, 1.0355e-04, 1.0379e-04, 1.0403e-04, 1.0427e-04, 1.0450e-04, 1.0474e-04, 1.0498e-04, 1.0522e-04, 1.0546e-04, 1.0569e-04, 1.0593e-04, 1.0617e-04, 1.0641e-04, 1.0665e-04, 1.0689e-04, 1.0712e-04, 1.0736e-04, 1.0760e-04, 1.0784e-04, 1.0808e-04, 1.0831e-04, 1.0855e-04, 1.0879e-04, 1.0903e-04, 1.0927e-04, 1.0951e-04, 1.0974e-04, 1.0998e-04, 1.1022e-04, 1.1046e-04, 1.1070e-04, 1.1093e-04, 1.1117e-04, 1.1141e-04, 1.1165e-04, 1.1189e-04, 1.1213e-04, 1.1236e-04, 1.1260e-04, 1.1284e-04, 1.1308e-04, 1.1332e-04, 1.1355e-04, 1.1379e-04, 1.1403e-04, 1.1427e-04, 1.1451e-04, 1.1475e-04, 1.1498e-04, 1.1522e-04, 1.1546e-04, 1.1570e-04, 1.1594e-04, 1.1618e-04, 1.1641e-04, 1.1665e-04, 1.1689e-04, 1.1713e-04, 1.1737e-04, 1.1760e-04, 1.1784e-04, 1.1808e-04, 1.1832e-04, 1.1856e-04, 1.1880e-04, 1.1903e-04, 1.1927e-04, 1.1951e-04, 1.1975e-04, 1.1999e-04, 1.2022e-04, 1.2046e-04, 1.2070e-04, 1.2094e-04, 1.2118e-04, 1.2142e-04, 1.2165e-04, 1.2189e-04, + 1.2213e-04, 1.2237e-04, 1.2261e-04, 1.2284e-04, 1.2308e-04, 1.2332e-04, 1.2356e-04, 1.2380e-04, 1.2404e-04, 1.2427e-04, 1.2451e-04, 1.2475e-04, 1.2499e-04, 1.2523e-04, 1.2546e-04, 1.2570e-04, 1.2594e-04, 1.2618e-04, 1.2642e-04, 1.2666e-04, 1.2689e-04, 1.2713e-04, 1.2737e-04, 1.2761e-04, 1.2785e-04, 1.2808e-04, 1.2832e-04, 1.2856e-04, 1.2880e-04, 1.2904e-04, 1.2928e-04, 1.2951e-04, 1.2975e-04, 1.2999e-04, 1.3023e-04, 1.3047e-04, 1.3070e-04, 1.3094e-04, 1.3118e-04, 1.3142e-04, 1.3166e-04, 1.3190e-04, 1.3213e-04, 1.3237e-04, 1.3261e-04, 1.3285e-04, 1.3309e-04, 1.3332e-04, 1.3356e-04, 1.3380e-04, 1.3404e-04, 1.3428e-04, 1.3452e-04, 1.3475e-04, 1.3499e-04, 1.3523e-04, 1.3547e-04, 1.3571e-04, 1.3594e-04, 1.3618e-04, 1.3642e-04, 1.3666e-04, 1.3690e-04, 1.3714e-04, 1.3737e-04, 1.3761e-04, 1.3785e-04, 1.3809e-04, 1.3833e-04, 1.3856e-04, 1.3880e-04, 1.3904e-04, 1.3928e-04, 1.3952e-04, 1.3976e-04, 1.3999e-04, 1.4023e-04, 1.4047e-04, 1.4071e-04, 1.4095e-04, 1.4118e-04, 1.4142e-04, 1.4166e-04, 1.4190e-04, 1.4214e-04, 1.4238e-04, 1.4261e-04, 1.4285e-04, 1.4309e-04, 1.4333e-04, 1.4357e-04, 1.4380e-04, 1.4404e-04, 1.4428e-04, 1.4452e-04, 1.4476e-04, 1.4500e-04, 1.4523e-04, 1.4547e-04, 1.4571e-04, 1.4595e-04, 1.4619e-04, 1.4642e-04, 1.4666e-04, 1.4690e-04, 1.4714e-04, 1.4738e-04, 1.4762e-04, 1.4785e-04, 1.4809e-04, 1.4833e-04, 1.4857e-04, 1.4881e-04, 1.4904e-04, 1.4928e-04, 1.4952e-04, 1.4976e-04, 1.5000e-04, 1.5024e-04, 1.5047e-04, 1.5071e-04, 1.5095e-04, 1.5119e-04, 1.5143e-04, 1.5166e-04, 1.5190e-04, 1.5214e-04, 1.5238e-04, 1.5262e-04, 1.5286e-04, 1.5309e-04, 1.5333e-04, 1.5357e-04, 1.5381e-04, 1.5405e-04, 1.5428e-04, 1.5452e-04, 1.5476e-04, 1.5500e-04, 1.5524e-04, 1.5548e-04, 1.5571e-04, 1.5595e-04, 1.5619e-04, 1.5643e-04, 1.5667e-04, 1.5690e-04, 1.5714e-04, 1.5738e-04, 1.5762e-04, 1.5786e-04, 1.5810e-04, 1.5833e-04, 1.5857e-04, 1.5881e-04, 1.5905e-04, 1.5929e-04, 1.5952e-04, 1.5976e-04, 1.6000e-04, 1.6024e-04, 1.6048e-04, 1.6072e-04, 1.6095e-04, 1.6119e-04, 1.6143e-04, 1.6167e-04, 1.6191e-04, 1.6214e-04, 1.6238e-04, 1.6262e-04, 1.6286e-04, 1.6310e-04, 1.6334e-04, 1.6357e-04, 1.6381e-04, 1.6405e-04, 1.6429e-04, 1.6453e-04, 1.6476e-04, 1.6500e-04, 1.6524e-04, 1.6548e-04, 1.6572e-04, 1.6596e-04, 1.6619e-04, 1.6643e-04, 1.6667e-04, 1.6691e-04, 1.6715e-04, 1.6738e-04, 1.6762e-04, 1.6786e-04, 1.6810e-04, 1.6834e-04, 1.6858e-04, 1.6881e-04, 1.6905e-04, 1.6929e-04, 1.6953e-04, 1.6977e-04, 1.7001e-04, 1.7024e-04, 1.7048e-04, 1.7072e-04, 1.7096e-04, 1.7120e-04, 1.7143e-04, 1.7167e-04, 1.7191e-04, 1.7215e-04, 1.7239e-04, 1.7263e-04, 1.7286e-04, 1.7310e-04, 1.7334e-04, 1.7358e-04, 1.7382e-04, 1.7405e-04, 1.7429e-04, 1.7453e-04, 1.7477e-04, 1.7501e-04, 1.7525e-04, 1.7548e-04, 1.7572e-04, 1.7596e-04, 1.7620e-04, 1.7644e-04, 1.7667e-04, 1.7691e-04, 1.7715e-04, 1.7739e-04, 1.7763e-04, 1.7787e-04, 1.7810e-04, 1.7834e-04, 1.7858e-04, 1.7882e-04, 1.7906e-04, 1.7929e-04, 1.7953e-04, 1.7977e-04, 1.8001e-04, 1.8025e-04, 1.8049e-04, 1.8072e-04, 1.8096e-04, 1.8120e-04, 1.8144e-04, 1.8168e-04, 1.8191e-04, 1.8215e-04, 1.8239e-04, 1.8263e-04, 1.8287e-04, + 1.8311e-04, 1.8334e-04, 1.8358e-04, 1.8382e-04, 1.8406e-04, 1.8430e-04, 1.8453e-04, 1.8477e-04, 1.8501e-04, 1.8525e-04, 1.8549e-04, 1.8573e-04, 1.8596e-04, 1.8620e-04, 1.8644e-04, 1.8668e-04, 1.8692e-04, 1.8715e-04, 1.8739e-04, 1.8763e-04, 1.8787e-04, 1.8811e-04, 1.8835e-04, 1.8858e-04, 1.8882e-04, 1.8906e-04, 1.8930e-04, 1.8954e-04, 1.8977e-04, 1.9001e-04, 1.9025e-04, 1.9049e-04, 1.9073e-04, 1.9097e-04, 1.9120e-04, 1.9144e-04, 1.9168e-04, 1.9192e-04, 1.9216e-04, 1.9239e-04, 1.9263e-04, 1.9287e-04, 1.9311e-04, 1.9335e-04, 1.9359e-04, 1.9382e-04, 1.9406e-04, 1.9430e-04, 1.9454e-04, 1.9478e-04, 1.9501e-04, 1.9525e-04, 1.9549e-04, 1.9573e-04, 1.9597e-04, 1.9621e-04, 1.9644e-04, 1.9668e-04, 1.9692e-04, 1.9716e-04, 1.9740e-04, 1.9763e-04, 1.9787e-04, 1.9811e-04, 1.9835e-04, 1.9859e-04, 1.9883e-04, 1.9906e-04, 1.9930e-04, 1.9954e-04, 1.9978e-04, 2.0002e-04, 2.0025e-04, 2.0049e-04, 2.0073e-04, 2.0097e-04, 2.0121e-04, 2.0145e-04, 2.0168e-04, 2.0192e-04, 2.0216e-04, 2.0240e-04, 2.0264e-04, 2.0287e-04, 2.0311e-04, 2.0335e-04, 2.0359e-04, 2.0383e-04, 2.0407e-04, 2.0430e-04, 2.0454e-04, 2.0478e-04, 2.0502e-04, 2.0526e-04, 2.0549e-04, 2.0573e-04, 2.0597e-04, 2.0621e-04, 2.0645e-04, 2.0669e-04, 2.0692e-04, 2.0716e-04, 2.0740e-04, 2.0764e-04, 2.0788e-04, 2.0811e-04, 2.0835e-04, 2.0859e-04, 2.0883e-04, 2.0907e-04, 2.0931e-04, 2.0954e-04, 2.0978e-04, 2.1002e-04, 2.1026e-04, 2.1050e-04, 2.1073e-04, 2.1097e-04, 2.1121e-04, 2.1145e-04, 2.1169e-04, 2.1193e-04, 2.1216e-04, 2.1240e-04, 2.1264e-04, 2.1288e-04, 2.1312e-04, 2.1335e-04, 2.1359e-04, 2.1383e-04, 2.1407e-04, 2.1431e-04, 2.1455e-04, 2.1478e-04, 2.1502e-04, 2.1526e-04, 2.1550e-04, 2.1574e-04, 2.1597e-04, 2.1621e-04, 2.1645e-04, 2.1669e-04, 2.1693e-04, 2.1717e-04, 2.1740e-04, 2.1764e-04, 2.1788e-04, 2.1812e-04, 2.1836e-04, 2.1859e-04, 2.1883e-04, 2.1907e-04, 2.1931e-04, 2.1955e-04, 2.1979e-04, 2.2002e-04, 2.2026e-04, 2.2050e-04, 2.2074e-04, 2.2098e-04, 2.2121e-04, 2.2145e-04, 2.2169e-04, 2.2193e-04, 2.2217e-04, 2.2241e-04, 2.2264e-04, 2.2288e-04, 2.2312e-04, 2.2336e-04, 2.2360e-04, 2.2383e-04, 2.2407e-04, 2.2431e-04, 2.2455e-04, 2.2479e-04, 2.2503e-04, 2.2526e-04, 2.2550e-04, 2.2574e-04, 2.2598e-04, 2.2622e-04, 2.2646e-04, 2.2669e-04, 2.2693e-04, 2.2717e-04, 2.2741e-04, 2.2765e-04, 2.2788e-04, 2.2812e-04, 2.2836e-04, 2.2860e-04, 2.2884e-04, 2.2908e-04, 2.2931e-04, 2.2955e-04, 2.2979e-04, 2.3003e-04, 2.3027e-04, 2.3050e-04, 2.3074e-04, 2.3098e-04, 2.3122e-04, 2.3146e-04, 2.3170e-04, 2.3193e-04, 2.3217e-04, 2.3241e-04, 2.3265e-04, 2.3289e-04, 2.3312e-04, 2.3336e-04, 2.3360e-04, 2.3384e-04, 2.3408e-04, 2.3432e-04, 2.3455e-04, 2.3479e-04, 2.3503e-04, 2.3527e-04, 2.3551e-04, 2.3574e-04, 2.3598e-04, 2.3622e-04, 2.3646e-04, 2.3670e-04, 2.3694e-04, 2.3717e-04, 2.3741e-04, 2.3765e-04, 2.3789e-04, 2.3813e-04, 2.3836e-04, 2.3860e-04, 2.3884e-04, 2.3908e-04, 2.3932e-04, 2.3956e-04, 2.3979e-04, 2.4003e-04, 2.4027e-04, 2.4051e-04, 2.4075e-04, 2.4098e-04, 2.4122e-04, 2.4146e-04, 2.4170e-04, 2.4194e-04, 2.4218e-04, 2.4241e-04, 2.4265e-04, 2.4289e-04, 2.4313e-04, 2.4337e-04, 2.4360e-04, 2.4384e-04, + 2.4480e-04, 2.4575e-04, 2.4670e-04, 2.4766e-04, 2.4861e-04, 2.4956e-04, 2.5052e-04, 2.5147e-04, 2.5242e-04, 2.5337e-04, 2.5433e-04, 2.5528e-04, 2.5623e-04, 2.5719e-04, 2.5814e-04, 2.5909e-04, 2.6005e-04, 2.6100e-04, 2.6195e-04, 2.6291e-04, 2.6386e-04, 2.6481e-04, 2.6577e-04, 2.6672e-04, 2.6767e-04, 2.6863e-04, 2.6958e-04, 2.7053e-04, 2.7149e-04, 2.7244e-04, 2.7339e-04, 2.7435e-04, 2.7530e-04, 2.7625e-04, 2.7720e-04, 2.7816e-04, 2.7911e-04, 2.8006e-04, 2.8102e-04, 2.8197e-04, 2.8292e-04, 2.8388e-04, 2.8483e-04, 2.8578e-04, 2.8674e-04, 2.8769e-04, 2.8864e-04, 2.8960e-04, 2.9055e-04, 2.9150e-04, 2.9246e-04, 2.9341e-04, 2.9436e-04, 2.9532e-04, 2.9627e-04, 2.9722e-04, 2.9818e-04, 2.9913e-04, 3.0008e-04, 3.0104e-04, 3.0199e-04, 3.0294e-04, 3.0389e-04, 3.0485e-04, 3.0580e-04, 3.0675e-04, 3.0771e-04, 3.0866e-04, 3.0961e-04, 3.1057e-04, 3.1152e-04, 3.1247e-04, 3.1343e-04, 3.1438e-04, 3.1533e-04, 3.1629e-04, 3.1724e-04, 3.1819e-04, 3.1915e-04, 3.2010e-04, 3.2105e-04, 3.2201e-04, 3.2296e-04, 3.2391e-04, 3.2487e-04, 3.2582e-04, 3.2677e-04, 3.2772e-04, 3.2868e-04, 3.2963e-04, 3.3058e-04, 3.3154e-04, 3.3249e-04, 3.3344e-04, 3.3440e-04, 3.3535e-04, 3.3630e-04, 3.3726e-04, 3.3821e-04, 3.3916e-04, 3.4012e-04, 3.4107e-04, 3.4202e-04, 3.4298e-04, 3.4393e-04, 3.4488e-04, 3.4584e-04, 3.4679e-04, 3.4774e-04, 3.4870e-04, 3.4965e-04, 3.5060e-04, 3.5156e-04, 3.5251e-04, 3.5346e-04, 3.5441e-04, 3.5537e-04, 3.5632e-04, 3.5727e-04, 3.5823e-04, 3.5918e-04, 3.6013e-04, 3.6109e-04, 3.6204e-04, 3.6299e-04, 3.6395e-04, 3.6490e-04, 3.6585e-04, 3.6681e-04, 3.6776e-04, 3.6871e-04, 3.6967e-04, 3.7062e-04, 3.7157e-04, 3.7253e-04, 3.7348e-04, 3.7443e-04, 3.7539e-04, 3.7634e-04, 3.7729e-04, 3.7825e-04, 3.7920e-04, 3.8015e-04, 3.8110e-04, 3.8206e-04, 3.8301e-04, 3.8396e-04, 3.8492e-04, 3.8587e-04, 3.8682e-04, 3.8778e-04, 3.8873e-04, 3.8968e-04, 3.9064e-04, 3.9159e-04, 3.9254e-04, 3.9350e-04, 3.9445e-04, 3.9540e-04, 3.9636e-04, 3.9731e-04, 3.9826e-04, 3.9922e-04, 4.0017e-04, 4.0112e-04, 4.0208e-04, 4.0303e-04, 4.0398e-04, 4.0493e-04, 4.0589e-04, 4.0684e-04, 4.0779e-04, 4.0875e-04, 4.0970e-04, 4.1065e-04, 4.1161e-04, 4.1256e-04, 4.1351e-04, 4.1447e-04, 4.1542e-04, 4.1637e-04, 4.1733e-04, 4.1828e-04, 4.1923e-04, 4.2019e-04, 4.2114e-04, 4.2209e-04, 4.2305e-04, 4.2400e-04, 4.2495e-04, 4.2591e-04, 4.2686e-04, 4.2781e-04, 4.2877e-04, 4.2972e-04, 4.3067e-04, 4.3162e-04, 4.3258e-04, 4.3353e-04, 4.3448e-04, 4.3544e-04, 4.3639e-04, 4.3734e-04, 4.3830e-04, 4.3925e-04, 4.4020e-04, 4.4116e-04, 4.4211e-04, 4.4306e-04, 4.4402e-04, 4.4497e-04, 4.4592e-04, 4.4688e-04, 4.4783e-04, 4.4878e-04, 4.4974e-04, 4.5069e-04, 4.5164e-04, 4.5260e-04, 4.5355e-04, 4.5450e-04, 4.5545e-04, 4.5641e-04, 4.5736e-04, 4.5831e-04, 4.5927e-04, 4.6022e-04, 4.6117e-04, 4.6213e-04, 4.6308e-04, 4.6403e-04, 4.6499e-04, 4.6594e-04, 4.6689e-04, 4.6785e-04, 4.6880e-04, 4.6975e-04, 4.7071e-04, 4.7166e-04, 4.7261e-04, 4.7357e-04, 4.7452e-04, 4.7547e-04, 4.7643e-04, 4.7738e-04, 4.7833e-04, 4.7929e-04, 4.8024e-04, 4.8119e-04, 4.8214e-04, 4.8310e-04, 4.8405e-04, 4.8500e-04, 4.8596e-04, 4.8691e-04, 4.8786e-04, + 4.8977e-04, 4.9168e-04, 4.9358e-04, 4.9549e-04, 4.9740e-04, 4.9931e-04, 5.0121e-04, 5.0312e-04, 5.0503e-04, 5.0693e-04, 5.0884e-04, 5.1075e-04, 5.1265e-04, 5.1456e-04, 5.1647e-04, 5.1837e-04, 5.2028e-04, 5.2219e-04, 5.2409e-04, 5.2600e-04, 5.2791e-04, 5.2982e-04, 5.3172e-04, 5.3363e-04, 5.3554e-04, 5.3744e-04, 5.3935e-04, 5.4126e-04, 5.4316e-04, 5.4507e-04, 5.4698e-04, 5.4888e-04, 5.5079e-04, 5.5270e-04, 5.5460e-04, 5.5651e-04, 5.5842e-04, 5.6033e-04, 5.6223e-04, 5.6414e-04, 5.6605e-04, 5.6795e-04, 5.6986e-04, 5.7177e-04, 5.7367e-04, 5.7558e-04, 5.7749e-04, 5.7939e-04, 5.8130e-04, 5.8321e-04, 5.8512e-04, 5.8702e-04, 5.8893e-04, 5.9084e-04, 5.9274e-04, 5.9465e-04, 5.9656e-04, 5.9846e-04, 6.0037e-04, 6.0228e-04, 6.0418e-04, 6.0609e-04, 6.0800e-04, 6.0990e-04, 6.1181e-04, 6.1372e-04, 6.1563e-04, 6.1753e-04, 6.1944e-04, 6.2135e-04, 6.2325e-04, 6.2516e-04, 6.2707e-04, 6.2897e-04, 6.3088e-04, 6.3279e-04, 6.3469e-04, 6.3660e-04, 6.3851e-04, 6.4041e-04, 6.4232e-04, 6.4423e-04, 6.4614e-04, 6.4804e-04, 6.4995e-04, 6.5186e-04, 6.5376e-04, 6.5567e-04, 6.5758e-04, 6.5948e-04, 6.6139e-04, 6.6330e-04, 6.6520e-04, 6.6711e-04, 6.6902e-04, 6.7092e-04, 6.7283e-04, 6.7474e-04, 6.7665e-04, 6.7855e-04, 6.8046e-04, 6.8237e-04, 6.8427e-04, 6.8618e-04, 6.8809e-04, 6.8999e-04, 6.9190e-04, 6.9381e-04, 6.9571e-04, 6.9762e-04, 6.9953e-04, 7.0143e-04, 7.0334e-04, 7.0525e-04, 7.0716e-04, 7.0906e-04, 7.1097e-04, 7.1288e-04, 7.1478e-04, 7.1669e-04, 7.1860e-04, 7.2050e-04, 7.2241e-04, 7.2432e-04, 7.2622e-04, 7.2813e-04, 7.3004e-04, 7.3195e-04, 7.3385e-04, 7.3576e-04, 7.3767e-04, 7.3957e-04, 7.4148e-04, 7.4339e-04, 7.4529e-04, 7.4720e-04, 7.4911e-04, 7.5101e-04, 7.5292e-04, 7.5483e-04, 7.5673e-04, 7.5864e-04, 7.6055e-04, 7.6246e-04, 7.6436e-04, 7.6627e-04, 7.6818e-04, 7.7008e-04, 7.7199e-04, 7.7390e-04, 7.7580e-04, 7.7771e-04, 7.7962e-04, 7.8152e-04, 7.8343e-04, 7.8534e-04, 7.8724e-04, 7.8915e-04, 7.9106e-04, 7.9297e-04, 7.9487e-04, 7.9678e-04, 7.9869e-04, 8.0059e-04, 8.0250e-04, 8.0441e-04, 8.0631e-04, 8.0822e-04, 8.1013e-04, 8.1203e-04, 8.1394e-04, 8.1585e-04, 8.1775e-04, 8.1966e-04, 8.2157e-04, 8.2348e-04, 8.2538e-04, 8.2729e-04, 8.2920e-04, 8.3110e-04, 8.3301e-04, 8.3492e-04, 8.3682e-04, 8.3873e-04, 8.4064e-04, 8.4254e-04, 8.4445e-04, 8.4636e-04, 8.4826e-04, 8.5017e-04, 8.5208e-04, 8.5399e-04, 8.5589e-04, 8.5780e-04, 8.5971e-04, 8.6161e-04, 8.6352e-04, 8.6543e-04, 8.6733e-04, 8.6924e-04, 8.7115e-04, 8.7305e-04, 8.7496e-04, 8.7687e-04, 8.7878e-04, 8.8068e-04, 8.8259e-04, 8.8450e-04, 8.8640e-04, 8.8831e-04, 8.9022e-04, 8.9212e-04, 8.9403e-04, 8.9594e-04, 8.9784e-04, 8.9975e-04, 9.0166e-04, 9.0356e-04, 9.0547e-04, 9.0738e-04, 9.0929e-04, 9.1119e-04, 9.1310e-04, 9.1501e-04, 9.1691e-04, 9.1882e-04, 9.2073e-04, 9.2263e-04, 9.2454e-04, 9.2645e-04, 9.2835e-04, 9.3026e-04, 9.3217e-04, 9.3407e-04, 9.3598e-04, 9.3789e-04, 9.3980e-04, 9.4170e-04, 9.4361e-04, 9.4552e-04, 9.4742e-04, 9.4933e-04, 9.5124e-04, 9.5314e-04, 9.5505e-04, 9.5696e-04, 9.5886e-04, 9.6077e-04, 9.6268e-04, 9.6458e-04, 9.6649e-04, 9.6840e-04, 9.7031e-04, 9.7221e-04, 9.7412e-04, 9.7603e-04, + 9.7984e-04, 9.8365e-04, 9.8747e-04, 9.9128e-04, 9.9510e-04, 9.9891e-04, 1.0027e-03, 1.0065e-03, 1.0104e-03, 1.0142e-03, 1.0180e-03, 1.0218e-03, 1.0256e-03, 1.0294e-03, 1.0332e-03, 1.0371e-03, 1.0409e-03, 1.0447e-03, 1.0485e-03, 1.0523e-03, 1.0561e-03, 1.0599e-03, 1.0638e-03, 1.0676e-03, 1.0714e-03, 1.0752e-03, 1.0790e-03, 1.0828e-03, 1.0866e-03, 1.0905e-03, 1.0943e-03, 1.0981e-03, 1.1019e-03, 1.1057e-03, 1.1095e-03, 1.1133e-03, 1.1172e-03, 1.1210e-03, 1.1248e-03, 1.1286e-03, 1.1324e-03, 1.1362e-03, 1.1400e-03, 1.1439e-03, 1.1477e-03, 1.1515e-03, 1.1553e-03, 1.1591e-03, 1.1629e-03, 1.1667e-03, 1.1706e-03, 1.1744e-03, 1.1782e-03, 1.1820e-03, 1.1858e-03, 1.1896e-03, 1.1934e-03, 1.1973e-03, 1.2011e-03, 1.2049e-03, 1.2087e-03, 1.2125e-03, 1.2163e-03, 1.2201e-03, 1.2240e-03, 1.2278e-03, 1.2316e-03, 1.2354e-03, 1.2392e-03, 1.2430e-03, 1.2468e-03, 1.2507e-03, 1.2545e-03, 1.2583e-03, 1.2621e-03, 1.2659e-03, 1.2697e-03, 1.2735e-03, 1.2774e-03, 1.2812e-03, 1.2850e-03, 1.2888e-03, 1.2926e-03, 1.2964e-03, 1.3002e-03, 1.3040e-03, 1.3079e-03, 1.3117e-03, 1.3155e-03, 1.3193e-03, 1.3231e-03, 1.3269e-03, 1.3307e-03, 1.3346e-03, 1.3384e-03, 1.3422e-03, 1.3460e-03, 1.3498e-03, 1.3536e-03, 1.3574e-03, 1.3613e-03, 1.3651e-03, 1.3689e-03, 1.3727e-03, 1.3765e-03, 1.3803e-03, 1.3841e-03, 1.3880e-03, 1.3918e-03, 1.3956e-03, 1.3994e-03, 1.4032e-03, 1.4070e-03, 1.4108e-03, 1.4147e-03, 1.4185e-03, 1.4223e-03, 1.4261e-03, 1.4299e-03, 1.4337e-03, 1.4375e-03, 1.4414e-03, 1.4452e-03, 1.4490e-03, 1.4528e-03, 1.4566e-03, 1.4604e-03, 1.4642e-03, 1.4681e-03, 1.4719e-03, 1.4757e-03, 1.4795e-03, 1.4833e-03, 1.4871e-03, 1.4909e-03, 1.4948e-03, 1.4986e-03, 1.5024e-03, 1.5062e-03, 1.5100e-03, 1.5138e-03, 1.5176e-03, 1.5215e-03, 1.5253e-03, 1.5291e-03, 1.5329e-03, 1.5367e-03, 1.5405e-03, 1.5443e-03, 1.5482e-03, 1.5520e-03, 1.5558e-03, 1.5596e-03, 1.5634e-03, 1.5672e-03, 1.5710e-03, 1.5749e-03, 1.5787e-03, 1.5825e-03, 1.5863e-03, 1.5901e-03, 1.5939e-03, 1.5977e-03, 1.6016e-03, 1.6054e-03, 1.6092e-03, 1.6130e-03, 1.6168e-03, 1.6206e-03, 1.6244e-03, 1.6283e-03, 1.6321e-03, 1.6359e-03, 1.6397e-03, 1.6435e-03, 1.6473e-03, 1.6511e-03, 1.6550e-03, 1.6588e-03, 1.6626e-03, 1.6664e-03, 1.6702e-03, 1.6740e-03, 1.6778e-03, 1.6817e-03, 1.6855e-03, 1.6893e-03, 1.6931e-03, 1.6969e-03, 1.7007e-03, 1.7045e-03, 1.7084e-03, 1.7122e-03, 1.7160e-03, 1.7198e-03, 1.7236e-03, 1.7274e-03, 1.7312e-03, 1.7351e-03, 1.7389e-03, 1.7427e-03, 1.7465e-03, 1.7503e-03, 1.7541e-03, 1.7579e-03, 1.7618e-03, 1.7656e-03, 1.7694e-03, 1.7732e-03, 1.7770e-03, 1.7808e-03, 1.7846e-03, 1.7885e-03, 1.7923e-03, 1.7961e-03, 1.7999e-03, 1.8037e-03, 1.8075e-03, 1.8113e-03, 1.8152e-03, 1.8190e-03, 1.8228e-03, 1.8266e-03, 1.8304e-03, 1.8342e-03, 1.8380e-03, 1.8419e-03, 1.8457e-03, 1.8495e-03, 1.8533e-03, 1.8571e-03, 1.8609e-03, 1.8647e-03, 1.8686e-03, 1.8724e-03, 1.8762e-03, 1.8800e-03, 1.8838e-03, 1.8876e-03, 1.8914e-03, 1.8953e-03, 1.8991e-03, 1.9029e-03, 1.9067e-03, 1.9105e-03, 1.9143e-03, 1.9181e-03, 1.9220e-03, 1.9258e-03, 1.9296e-03, 1.9334e-03, 1.9372e-03, 1.9410e-03, 1.9448e-03, 1.9487e-03, 1.9525e-03, + 1.9601e-03, 1.9677e-03, 1.9754e-03, 1.9830e-03, 1.9906e-03, 1.9982e-03, 2.0059e-03, 2.0135e-03, 2.0211e-03, 2.0288e-03, 2.0364e-03, 2.0440e-03, 2.0516e-03, 2.0593e-03, 2.0669e-03, 2.0745e-03, 2.0822e-03, 2.0898e-03, 2.0974e-03, 2.1050e-03, 2.1127e-03, 2.1203e-03, 2.1279e-03, 2.1356e-03, 2.1432e-03, 2.1508e-03, 2.1585e-03, 2.1661e-03, 2.1737e-03, 2.1813e-03, 2.1890e-03, 2.1966e-03, 2.2042e-03, 2.2119e-03, 2.2195e-03, 2.2271e-03, 2.2347e-03, 2.2424e-03, 2.2500e-03, 2.2576e-03, 2.2653e-03, 2.2729e-03, 2.2805e-03, 2.2881e-03, 2.2958e-03, 2.3034e-03, 2.3110e-03, 2.3187e-03, 2.3263e-03, 2.3339e-03, 2.3415e-03, 2.3492e-03, 2.3568e-03, 2.3644e-03, 2.3721e-03, 2.3797e-03, 2.3873e-03, 2.3949e-03, 2.4026e-03, 2.4102e-03, 2.4178e-03, 2.4255e-03, 2.4331e-03, 2.4407e-03, 2.4483e-03, 2.4560e-03, 2.4636e-03, 2.4712e-03, 2.4789e-03, 2.4865e-03, 2.4941e-03, 2.5018e-03, 2.5094e-03, 2.5170e-03, 2.5246e-03, 2.5323e-03, 2.5399e-03, 2.5475e-03, 2.5552e-03, 2.5628e-03, 2.5704e-03, 2.5780e-03, 2.5857e-03, 2.5933e-03, 2.6009e-03, 2.6086e-03, 2.6162e-03, 2.6238e-03, 2.6314e-03, 2.6391e-03, 2.6467e-03, 2.6543e-03, 2.6620e-03, 2.6696e-03, 2.6772e-03, 2.6848e-03, 2.6925e-03, 2.7001e-03, 2.7077e-03, 2.7154e-03, 2.7230e-03, 2.7306e-03, 2.7382e-03, 2.7459e-03, 2.7535e-03, 2.7611e-03, 2.7688e-03, 2.7764e-03, 2.7840e-03, 2.7917e-03, 2.7993e-03, 2.8069e-03, 2.8145e-03, 2.8222e-03, 2.8298e-03, 2.8374e-03, 2.8451e-03, 2.8527e-03, 2.8603e-03, 2.8679e-03, 2.8756e-03, 2.8832e-03, 2.8908e-03, 2.8985e-03, 2.9061e-03, 2.9137e-03, 2.9213e-03, 2.9290e-03, 2.9366e-03, 2.9442e-03, 2.9519e-03, 2.9595e-03, 2.9671e-03, 2.9747e-03, 2.9824e-03, 2.9900e-03, 2.9976e-03, 3.0053e-03, 3.0129e-03, 3.0205e-03, 3.0281e-03, 3.0358e-03, 3.0434e-03, 3.0510e-03, 3.0587e-03, 3.0663e-03, 3.0739e-03, 3.0816e-03, 3.0892e-03, 3.0968e-03, 3.1044e-03, 3.1121e-03, 3.1197e-03, 3.1273e-03, 3.1350e-03, 3.1426e-03, 3.1502e-03, 3.1578e-03, 3.1655e-03, 3.1731e-03, 3.1807e-03, 3.1884e-03, 3.1960e-03, 3.2036e-03, 3.2112e-03, 3.2189e-03, 3.2265e-03, 3.2341e-03, 3.2418e-03, 3.2494e-03, 3.2570e-03, 3.2646e-03, 3.2723e-03, 3.2799e-03, 3.2875e-03, 3.2952e-03, 3.3028e-03, 3.3104e-03, 3.3180e-03, 3.3257e-03, 3.3333e-03, 3.3409e-03, 3.3486e-03, 3.3562e-03, 3.3638e-03, 3.3715e-03, 3.3791e-03, 3.3867e-03, 3.3943e-03, 3.4020e-03, 3.4096e-03, 3.4172e-03, 3.4249e-03, 3.4325e-03, 3.4401e-03, 3.4477e-03, 3.4554e-03, 3.4630e-03, 3.4706e-03, 3.4783e-03, 3.4859e-03, 3.4935e-03, 3.5011e-03, 3.5088e-03, 3.5164e-03, 3.5240e-03, 3.5317e-03, 3.5393e-03, 3.5469e-03, 3.5545e-03, 3.5622e-03, 3.5698e-03, 3.5774e-03, 3.5851e-03, 3.5927e-03, 3.6003e-03, 3.6079e-03, 3.6156e-03, 3.6232e-03, 3.6308e-03, 3.6385e-03, 3.6461e-03, 3.6537e-03, 3.6613e-03, 3.6690e-03, 3.6766e-03, 3.6842e-03, 3.6919e-03, 3.6995e-03, 3.7071e-03, 3.7148e-03, 3.7224e-03, 3.7300e-03, 3.7376e-03, 3.7453e-03, 3.7529e-03, 3.7605e-03, 3.7682e-03, 3.7758e-03, 3.7834e-03, 3.7910e-03, 3.7987e-03, 3.8063e-03, 3.8139e-03, 3.8216e-03, 3.8292e-03, 3.8368e-03, 3.8444e-03, 3.8521e-03, 3.8597e-03, 3.8673e-03, 3.8750e-03, 3.8826e-03, 3.8902e-03, 3.8978e-03, 3.9055e-03, + 3.9207e-03, 3.9360e-03, 3.9513e-03, 3.9665e-03, 3.9818e-03, 3.9970e-03, 4.0123e-03, 4.0275e-03, 4.0428e-03, 4.0581e-03, 4.0733e-03, 4.0886e-03, 4.1038e-03, 4.1191e-03, 4.1343e-03, 4.1496e-03, 4.1649e-03, 4.1801e-03, 4.1954e-03, 4.2106e-03, 4.2259e-03, 4.2412e-03, 4.2564e-03, 4.2717e-03, 4.2869e-03, 4.3022e-03, 4.3174e-03, 4.3327e-03, 4.3480e-03, 4.3632e-03, 4.3785e-03, 4.3937e-03, 4.4090e-03, 4.4243e-03, 4.4395e-03, 4.4548e-03, 4.4700e-03, 4.4853e-03, 4.5005e-03, 4.5158e-03, 4.5311e-03, 4.5463e-03, 4.5616e-03, 4.5768e-03, 4.5921e-03, 4.6074e-03, 4.6226e-03, 4.6379e-03, 4.6531e-03, 4.6684e-03, 4.6836e-03, 4.6989e-03, 4.7142e-03, 4.7294e-03, 4.7447e-03, 4.7599e-03, 4.7752e-03, 4.7905e-03, 4.8057e-03, 4.8210e-03, 4.8362e-03, 4.8515e-03, 4.8667e-03, 4.8820e-03, 4.8973e-03, 4.9125e-03, 4.9278e-03, 4.9430e-03, 4.9583e-03, 4.9736e-03, 4.9888e-03, 5.0041e-03, 5.0193e-03, 5.0346e-03, 5.0498e-03, 5.0651e-03, 5.0804e-03, 5.0956e-03, 5.1109e-03, 5.1261e-03, 5.1414e-03, 5.1567e-03, 5.1719e-03, 5.1872e-03, 5.2024e-03, 5.2177e-03, 5.2329e-03, 5.2482e-03, 5.2635e-03, 5.2787e-03, 5.2940e-03, 5.3092e-03, 5.3245e-03, 5.3398e-03, 5.3550e-03, 5.3703e-03, 5.3855e-03, 5.4008e-03, 5.4160e-03, 5.4313e-03, 5.4466e-03, 5.4618e-03, 5.4771e-03, 5.4923e-03, 5.5076e-03, 5.5229e-03, 5.5381e-03, 5.5534e-03, 5.5686e-03, 5.5839e-03, 5.5991e-03, 5.6144e-03, 5.6297e-03, 5.6449e-03, 5.6602e-03, 5.6754e-03, 5.6907e-03, 5.7060e-03, 5.7212e-03, 5.7365e-03, 5.7517e-03, 5.7670e-03, 5.7822e-03, 5.7975e-03, 5.8128e-03, 5.8280e-03, 5.8433e-03, 5.8585e-03, 5.8738e-03, 5.8891e-03, 5.9043e-03, 5.9196e-03, 5.9348e-03, 5.9501e-03, 5.9653e-03, 5.9806e-03, 5.9959e-03, 6.0111e-03, 6.0264e-03, 6.0416e-03, 6.0569e-03, 6.0722e-03, 6.0874e-03, 6.1027e-03, 6.1179e-03, 6.1332e-03, 6.1484e-03, 6.1637e-03, 6.1790e-03, 6.1942e-03, 6.2095e-03, 6.2247e-03, 6.2400e-03, 6.2553e-03, 6.2705e-03, 6.2858e-03, 6.3010e-03, 6.3163e-03, 6.3315e-03, 6.3468e-03, 6.3621e-03, 6.3773e-03, 6.3926e-03, 6.4078e-03, 6.4231e-03, 6.4384e-03, 6.4536e-03, 6.4689e-03, 6.4841e-03, 6.4994e-03, 6.5146e-03, 6.5299e-03, 6.5452e-03, 6.5604e-03, 6.5757e-03, 6.5909e-03, 6.6062e-03, 6.6215e-03, 6.6367e-03, 6.6520e-03, 6.6672e-03, 6.6825e-03, 6.6977e-03, 6.7130e-03, 6.7283e-03, 6.7435e-03, 6.7588e-03, 6.7740e-03, 6.7893e-03, 6.8046e-03, 6.8198e-03, 6.8351e-03, 6.8503e-03, 6.8656e-03, 6.8808e-03, 6.8961e-03, 6.9114e-03, 6.9266e-03, 6.9419e-03, 6.9571e-03, 6.9724e-03, 6.9877e-03, 7.0029e-03, 7.0182e-03, 7.0334e-03, 7.0487e-03, 7.0639e-03, 7.0792e-03, 7.0945e-03, 7.1097e-03, 7.1250e-03, 7.1402e-03, 7.1555e-03, 7.1708e-03, 7.1860e-03, 7.2013e-03, 7.2165e-03, 7.2318e-03, 7.2470e-03, 7.2623e-03, 7.2776e-03, 7.2928e-03, 7.3081e-03, 7.3233e-03, 7.3386e-03, 7.3539e-03, 7.3691e-03, 7.3844e-03, 7.3996e-03, 7.4149e-03, 7.4301e-03, 7.4454e-03, 7.4607e-03, 7.4759e-03, 7.4912e-03, 7.5064e-03, 7.5217e-03, 7.5370e-03, 7.5522e-03, 7.5675e-03, 7.5827e-03, 7.5980e-03, 7.6132e-03, 7.6285e-03, 7.6438e-03, 7.6590e-03, 7.6743e-03, 7.6895e-03, 7.7048e-03, 7.7201e-03, 7.7353e-03, 7.7506e-03, 7.7658e-03, 7.7811e-03, 7.7963e-03, 7.8116e-03, + 7.8421e-03, 7.8726e-03, 7.9032e-03, 7.9337e-03, 7.9642e-03, 7.9947e-03, 8.0252e-03, 8.0557e-03, 8.0863e-03, 8.1168e-03, 8.1473e-03, 8.1778e-03, 8.2083e-03, 8.2388e-03, 8.2694e-03, 8.2999e-03, 8.3304e-03, 8.3609e-03, 8.3914e-03, 8.4219e-03, 8.4525e-03, 8.4830e-03, 8.5135e-03, 8.5440e-03, 8.5745e-03, 8.6051e-03, 8.6356e-03, 8.6661e-03, 8.6966e-03, 8.7271e-03, 8.7576e-03, 8.7882e-03, 8.8187e-03, 8.8492e-03, 8.8797e-03, 8.9102e-03, 8.9407e-03, 8.9713e-03, 9.0018e-03, 9.0323e-03, 9.0628e-03, 9.0933e-03, 9.1238e-03, 9.1544e-03, 9.1849e-03, 9.2154e-03, 9.2459e-03, 9.2764e-03, 9.3069e-03, 9.3375e-03, 9.3680e-03, 9.3985e-03, 9.4290e-03, 9.4595e-03, 9.4900e-03, 9.5206e-03, 9.5511e-03, 9.5816e-03, 9.6121e-03, 9.6426e-03, 9.6731e-03, 9.7037e-03, 9.7342e-03, 9.7647e-03, 9.7952e-03, 9.8257e-03, 9.8563e-03, 9.8868e-03, 9.9173e-03, 9.9478e-03, 9.9783e-03, 1.0009e-02, 1.0039e-02, 1.0070e-02, 1.0100e-02, 1.0131e-02, 1.0161e-02, 1.0192e-02, 1.0222e-02, 1.0253e-02, 1.0283e-02, 1.0314e-02, 1.0345e-02, 1.0375e-02, 1.0406e-02, 1.0436e-02, 1.0467e-02, 1.0497e-02, 1.0528e-02, 1.0558e-02, 1.0589e-02, 1.0619e-02, 1.0650e-02, 1.0680e-02, 1.0711e-02, 1.0741e-02, 1.0772e-02, 1.0802e-02, 1.0833e-02, 1.0863e-02, 1.0894e-02, 1.0924e-02, 1.0955e-02, 1.0985e-02, 1.1016e-02, 1.1046e-02, 1.1077e-02, 1.1107e-02, 1.1138e-02, 1.1168e-02, 1.1199e-02, 1.1230e-02, 1.1260e-02, 1.1291e-02, 1.1321e-02, 1.1352e-02, 1.1382e-02, 1.1413e-02, 1.1443e-02, 1.1474e-02, 1.1504e-02, 1.1535e-02, 1.1565e-02, 1.1596e-02, 1.1626e-02, 1.1657e-02, 1.1687e-02, 1.1718e-02, 1.1748e-02, 1.1779e-02, 1.1809e-02, 1.1840e-02, 1.1870e-02, 1.1901e-02, 1.1931e-02, 1.1962e-02, 1.1992e-02, 1.2023e-02, 1.2053e-02, 1.2084e-02, 1.2115e-02, 1.2145e-02, 1.2176e-02, 1.2206e-02, 1.2237e-02, 1.2267e-02, 1.2298e-02, 1.2328e-02, 1.2359e-02, 1.2389e-02, 1.2420e-02, 1.2450e-02, 1.2481e-02, 1.2511e-02, 1.2542e-02, 1.2572e-02, 1.2603e-02, 1.2633e-02, 1.2664e-02, 1.2694e-02, 1.2725e-02, 1.2755e-02, 1.2786e-02, 1.2816e-02, 1.2847e-02, 1.2877e-02, 1.2908e-02, 1.2938e-02, 1.2969e-02, 1.3000e-02, 1.3030e-02, 1.3061e-02, 1.3091e-02, 1.3122e-02, 1.3152e-02, 1.3183e-02, 1.3213e-02, 1.3244e-02, 1.3274e-02, 1.3305e-02, 1.3335e-02, 1.3366e-02, 1.3396e-02, 1.3427e-02, 1.3457e-02, 1.3488e-02, 1.3518e-02, 1.3549e-02, 1.3579e-02, 1.3610e-02, 1.3640e-02, 1.3671e-02, 1.3701e-02, 1.3732e-02, 1.3762e-02, 1.3793e-02, 1.3823e-02, 1.3854e-02, 1.3885e-02, 1.3915e-02, 1.3946e-02, 1.3976e-02, 1.4007e-02, 1.4037e-02, 1.4068e-02, 1.4098e-02, 1.4129e-02, 1.4159e-02, 1.4190e-02, 1.4220e-02, 1.4251e-02, 1.4281e-02, 1.4312e-02, 1.4342e-02, 1.4373e-02, 1.4403e-02, 1.4434e-02, 1.4464e-02, 1.4495e-02, 1.4525e-02, 1.4556e-02, 1.4586e-02, 1.4617e-02, 1.4647e-02, 1.4678e-02, 1.4708e-02, 1.4739e-02, 1.4770e-02, 1.4800e-02, 1.4831e-02, 1.4861e-02, 1.4892e-02, 1.4922e-02, 1.4953e-02, 1.4983e-02, 1.5014e-02, 1.5044e-02, 1.5075e-02, 1.5105e-02, 1.5136e-02, 1.5166e-02, 1.5197e-02, 1.5227e-02, 1.5258e-02, 1.5288e-02, 1.5319e-02, 1.5349e-02, 1.5380e-02, 1.5410e-02, 1.5441e-02, 1.5471e-02, 1.5502e-02, 1.5532e-02, 1.5563e-02, 1.5593e-02, 1.5624e-02, + 1.5746e-02, 1.5868e-02, 1.5990e-02, 1.6112e-02, 1.6234e-02, 1.6356e-02, 1.6478e-02, 1.6601e-02, 1.6723e-02, 1.6845e-02, 1.6967e-02, 1.7089e-02, 1.7211e-02, 1.7333e-02, 1.7455e-02, 1.7577e-02, 1.7699e-02, 1.7821e-02, 1.7943e-02, 1.8065e-02, 1.8187e-02, 1.8310e-02, 1.8432e-02, 1.8554e-02, 1.8676e-02, 1.8798e-02, 1.8920e-02, 1.9042e-02, 1.9164e-02, 1.9286e-02, 1.9408e-02, 1.9530e-02, 1.9652e-02, 1.9774e-02, 1.9896e-02, 2.0018e-02, 2.0141e-02, 2.0263e-02, 2.0385e-02, 2.0507e-02, 2.0629e-02, 2.0751e-02, 2.0873e-02, 2.0995e-02, 2.1117e-02, 2.1239e-02, 2.1361e-02, 2.1483e-02, 2.1605e-02, 2.1727e-02, 2.1850e-02, 2.1972e-02, 2.2094e-02, 2.2216e-02, 2.2338e-02, 2.2460e-02, 2.2582e-02, 2.2704e-02, 2.2826e-02, 2.2948e-02, 2.3070e-02, 2.3192e-02, 2.3314e-02, 2.3436e-02, 2.3558e-02, 2.3681e-02, 2.3803e-02, 2.3925e-02, 2.4047e-02, 2.4169e-02, 2.4291e-02, 2.4413e-02, 2.4535e-02, 2.4657e-02, 2.4779e-02, 2.4901e-02, 2.5023e-02, 2.5145e-02, 2.5267e-02, 2.5390e-02, 2.5512e-02, 2.5634e-02, 2.5756e-02, 2.5878e-02, 2.6000e-02, 2.6122e-02, 2.6244e-02, 2.6366e-02, 2.6488e-02, 2.6610e-02, 2.6732e-02, 2.6854e-02, 2.6976e-02, 2.7099e-02, 2.7221e-02, 2.7343e-02, 2.7465e-02, 2.7587e-02, 2.7709e-02, 2.7831e-02, 2.7953e-02, 2.8075e-02, 2.8197e-02, 2.8319e-02, 2.8441e-02, 2.8563e-02, 2.8685e-02, 2.8807e-02, 2.8930e-02, 2.9052e-02, 2.9174e-02, 2.9296e-02, 2.9418e-02, 2.9540e-02, 2.9662e-02, 2.9784e-02, 2.9906e-02, 3.0028e-02, 3.0150e-02, 3.0272e-02, 3.0394e-02, 3.0516e-02, 3.0639e-02, 3.0761e-02, 3.0883e-02, 3.1005e-02, 3.1127e-02, 3.1249e-02, 3.1493e-02, 3.1737e-02, 3.1981e-02, 3.2225e-02, 3.2470e-02, 3.2714e-02, 3.2958e-02, 3.3202e-02, 3.3446e-02, 3.3690e-02, 3.3934e-02, 3.4179e-02, 3.4423e-02, 3.4667e-02, 3.4911e-02, 3.5155e-02, 3.5399e-02, 3.5643e-02, 3.5888e-02, 3.6132e-02, 3.6376e-02, 3.6620e-02, 3.6864e-02, 3.7108e-02, 3.7352e-02, 3.7596e-02, 3.7841e-02, 3.8085e-02, 3.8329e-02, 3.8573e-02, 3.8817e-02, 3.9061e-02, 3.9305e-02, 3.9550e-02, 3.9794e-02, 4.0038e-02, 4.0282e-02, 4.0526e-02, 4.0770e-02, 4.1014e-02, 4.1259e-02, 4.1503e-02, 4.1747e-02, 4.1991e-02, 4.2235e-02, 4.2479e-02, 4.2723e-02, 4.2968e-02, 4.3212e-02, 4.3456e-02, 4.3700e-02, 4.3944e-02, 4.4188e-02, 4.4432e-02, 4.4677e-02, 4.4921e-02, 4.5165e-02, 4.5409e-02, 4.5653e-02, 4.5897e-02, 4.6141e-02, 4.6386e-02, 4.6630e-02, 4.6874e-02, 4.7118e-02, 4.7362e-02, 4.7606e-02, 4.7850e-02, 4.8095e-02, 4.8339e-02, 4.8583e-02, 4.8827e-02, 4.9071e-02, 4.9315e-02, 4.9559e-02, 4.9803e-02, 5.0048e-02, 5.0292e-02, 5.0536e-02, 5.0780e-02, 5.1024e-02, 5.1268e-02, 5.1512e-02, 5.1757e-02, 5.2001e-02, 5.2245e-02, 5.2489e-02, 5.2733e-02, 5.2977e-02, 5.3221e-02, 5.3466e-02, 5.3710e-02, 5.3954e-02, 5.4198e-02, 5.4442e-02, 5.4686e-02, 5.4930e-02, 5.5175e-02, 5.5419e-02, 5.5663e-02, 5.5907e-02, 5.6151e-02, 5.6395e-02, 5.6639e-02, 5.6884e-02, 5.7128e-02, 5.7372e-02, 5.7616e-02, 5.7860e-02, 5.8104e-02, 5.8348e-02, 5.8593e-02, 5.8837e-02, 5.9081e-02, 5.9325e-02, 5.9569e-02, 5.9813e-02, 6.0057e-02, 6.0301e-02, 6.0546e-02, 6.0790e-02, 6.1034e-02, 6.1278e-02, 6.1522e-02, 6.1766e-02, 6.2010e-02, 6.2255e-02, 6.2499e-02, + 6.2743e-02, 6.2987e-02, 6.3231e-02, 6.3475e-02, 6.3719e-02, 6.3964e-02, 6.4208e-02, 6.4452e-02, 6.4696e-02, 6.4940e-02, 6.5184e-02, 6.5428e-02, 6.5673e-02, 6.5917e-02, 6.6161e-02, 6.6405e-02, 6.6649e-02, 6.6893e-02, 6.7137e-02, 6.7382e-02, 6.7626e-02, 6.7870e-02, 6.8114e-02, 6.8358e-02, 6.8602e-02, 6.8846e-02, 6.9091e-02, 6.9335e-02, 6.9579e-02, 6.9823e-02, 7.0067e-02, 7.0311e-02, 7.0555e-02, 7.0799e-02, 7.1044e-02, 7.1288e-02, 7.1532e-02, 7.1776e-02, 7.2020e-02, 7.2264e-02, 7.2508e-02, 7.2753e-02, 7.2997e-02, 7.3241e-02, 7.3485e-02, 7.3729e-02, 7.3973e-02, 7.4217e-02, 7.4462e-02, 7.4706e-02, 7.4950e-02, 7.5194e-02, 7.5438e-02, 7.5682e-02, 7.5926e-02, 7.6171e-02, 7.6415e-02, 7.6659e-02, 7.6903e-02, 7.7147e-02, 7.7391e-02, 7.7635e-02, 7.7880e-02, 7.8124e-02, 7.8368e-02, 7.8612e-02, 7.8856e-02, 7.9100e-02, 7.9344e-02, 7.9589e-02, 7.9833e-02, 8.0077e-02, 8.0321e-02, 8.0565e-02, 8.0809e-02, 8.1053e-02, 8.1298e-02, 8.1542e-02, 8.1786e-02, 8.2030e-02, 8.2274e-02, 8.2518e-02, 8.2762e-02, 8.3006e-02, 8.3251e-02, 8.3495e-02, 8.3739e-02, 8.3983e-02, 8.4227e-02, 8.4471e-02, 8.4715e-02, 8.4960e-02, 8.5204e-02, 8.5448e-02, 8.5692e-02, 8.5936e-02, 8.6180e-02, 8.6424e-02, 8.6669e-02, 8.6913e-02, 8.7157e-02, 8.7401e-02, 8.7645e-02, 8.7889e-02, 8.8133e-02, 8.8378e-02, 8.8622e-02, 8.8866e-02, 8.9110e-02, 8.9354e-02, 8.9598e-02, 8.9842e-02, 9.0087e-02, 9.0331e-02, 9.0575e-02, 9.0819e-02, 9.1063e-02, 9.1307e-02, 9.1551e-02, 9.1796e-02, 9.2040e-02, 9.2284e-02, 9.2528e-02, 9.2772e-02, 9.3016e-02, 9.3260e-02, 9.3504e-02, 9.3749e-02, 9.4237e-02, 9.4725e-02, 9.5213e-02, 9.5702e-02, 9.6190e-02, 9.6678e-02, 9.7167e-02, 9.7655e-02, 9.8143e-02, 9.8631e-02, 9.9120e-02, 9.9608e-02, 1.0010e-01, 1.0058e-01, 1.0107e-01, 1.0156e-01, 1.0205e-01, 1.0254e-01, 1.0303e-01, 1.0351e-01, 1.0400e-01, 1.0449e-01, 1.0498e-01, 1.0547e-01, 1.0596e-01, 1.0644e-01, 1.0693e-01, 1.0742e-01, 1.0791e-01, 1.0840e-01, 1.0889e-01, 1.0937e-01, 1.0986e-01, 1.1035e-01, 1.1084e-01, 1.1133e-01, 1.1182e-01, 1.1230e-01, 1.1279e-01, 1.1328e-01, 1.1377e-01, 1.1426e-01, 1.1474e-01, 1.1523e-01, 1.1572e-01, 1.1621e-01, 1.1670e-01, 1.1719e-01, 1.1767e-01, 1.1816e-01, 1.1865e-01, 1.1914e-01, 1.1963e-01, 1.2012e-01, 1.2060e-01, 1.2109e-01, 1.2158e-01, 1.2207e-01, 1.2256e-01, 1.2305e-01, 1.2353e-01, 1.2402e-01, 1.2451e-01, 1.2500e-01, 1.2549e-01, 1.2598e-01, 1.2646e-01, 1.2695e-01, 1.2744e-01, 1.2793e-01, 1.2842e-01, 1.2890e-01, 1.2939e-01, 1.2988e-01, 1.3037e-01, 1.3086e-01, 1.3135e-01, 1.3183e-01, 1.3232e-01, 1.3281e-01, 1.3330e-01, 1.3379e-01, 1.3428e-01, 1.3476e-01, 1.3525e-01, 1.3574e-01, 1.3623e-01, 1.3672e-01, 1.3721e-01, 1.3769e-01, 1.3818e-01, 1.3867e-01, 1.3916e-01, 1.3965e-01, 1.4014e-01, 1.4062e-01, 1.4111e-01, 1.4160e-01, 1.4209e-01, 1.4258e-01, 1.4306e-01, 1.4355e-01, 1.4404e-01, 1.4453e-01, 1.4502e-01, 1.4551e-01, 1.4599e-01, 1.4648e-01, 1.4697e-01, 1.4746e-01, 1.4795e-01, 1.4844e-01, 1.4892e-01, 1.4941e-01, 1.4990e-01, 1.5039e-01, 1.5088e-01, 1.5137e-01, 1.5185e-01, 1.5234e-01, 1.5283e-01, 1.5332e-01, 1.5381e-01, 1.5430e-01, 1.5478e-01, 1.5527e-01, 1.5576e-01, 1.5625e-01, + 1.5674e-01, 1.5723e-01, 1.5771e-01, 1.5820e-01, 1.5869e-01, 1.5918e-01, 1.5967e-01, 1.6015e-01, 1.6064e-01, 1.6113e-01, 1.6162e-01, 1.6211e-01, 1.6260e-01, 1.6308e-01, 1.6357e-01, 1.6406e-01, 1.6455e-01, 1.6504e-01, 1.6553e-01, 1.6601e-01, 1.6650e-01, 1.6699e-01, 1.6748e-01, 1.6797e-01, 1.6846e-01, 1.6894e-01, 1.6943e-01, 1.6992e-01, 1.7041e-01, 1.7090e-01, 1.7139e-01, 1.7187e-01, 1.7236e-01, 1.7285e-01, 1.7334e-01, 1.7383e-01, 1.7431e-01, 1.7480e-01, 1.7529e-01, 1.7578e-01, 1.7627e-01, 1.7676e-01, 1.7724e-01, 1.7773e-01, 1.7822e-01, 1.7871e-01, 1.7920e-01, 1.7969e-01, 1.8017e-01, 1.8066e-01, 1.8115e-01, 1.8164e-01, 1.8213e-01, 1.8262e-01, 1.8310e-01, 1.8359e-01, 1.8408e-01, 1.8457e-01, 1.8506e-01, 1.8555e-01, 1.8603e-01, 1.8652e-01, 1.8701e-01, 1.8750e-01, 1.8848e-01, 1.8945e-01, 1.9043e-01, 1.9140e-01, 1.9238e-01, 1.9336e-01, 1.9433e-01, 1.9531e-01, 1.9629e-01, 1.9726e-01, 1.9824e-01, 1.9922e-01, 2.0019e-01, 2.0117e-01, 2.0215e-01, 2.0312e-01, 2.0410e-01, 2.0508e-01, 2.0605e-01, 2.0703e-01, 2.0801e-01, 2.0898e-01, 2.0996e-01, 2.1094e-01, 2.1191e-01, 2.1289e-01, 2.1387e-01, 2.1484e-01, 2.1582e-01, 2.1680e-01, 2.1777e-01, 2.1875e-01, 2.1972e-01, 2.2070e-01, 2.2168e-01, 2.2265e-01, 2.2363e-01, 2.2461e-01, 2.2558e-01, 2.2656e-01, 2.2754e-01, 2.2851e-01, 2.2949e-01, 2.3047e-01, 2.3144e-01, 2.3242e-01, 2.3340e-01, 2.3437e-01, 2.3535e-01, 2.3633e-01, 2.3730e-01, 2.3828e-01, 2.3926e-01, 2.4023e-01, 2.4121e-01, 2.4219e-01, 2.4316e-01, 2.4414e-01, 2.4512e-01, 2.4609e-01, 2.4707e-01, 2.4805e-01, 2.4902e-01, 2.5000e-01, 2.5097e-01, 2.5195e-01, 2.5293e-01, 2.5390e-01, 2.5488e-01, 2.5586e-01, 2.5683e-01, 2.5781e-01, 2.5879e-01, 2.5976e-01, 2.6074e-01, 2.6172e-01, 2.6269e-01, 2.6367e-01, 2.6465e-01, 2.6562e-01, 2.6660e-01, 2.6758e-01, 2.6855e-01, 2.6953e-01, 2.7051e-01, 2.7148e-01, 2.7246e-01, 2.7344e-01, 2.7441e-01, 2.7539e-01, 2.7637e-01, 2.7734e-01, 2.7832e-01, 2.7930e-01, 2.8027e-01, 2.8125e-01, 2.8222e-01, 2.8320e-01, 2.8418e-01, 2.8515e-01, 2.8613e-01, 2.8711e-01, 2.8808e-01, 2.8906e-01, 2.9004e-01, 2.9101e-01, 2.9199e-01, 2.9297e-01, 2.9394e-01, 2.9492e-01, 2.9590e-01, 2.9687e-01, 2.9785e-01, 2.9883e-01, 2.9980e-01, 3.0078e-01, 3.0176e-01, 3.0273e-01, 3.0371e-01, 3.0469e-01, 3.0566e-01, 3.0664e-01, 3.0762e-01, 3.0859e-01, 3.0957e-01, 3.1055e-01, 3.1152e-01, 3.1250e-01, 3.1347e-01, 3.1445e-01, 3.1543e-01, 3.1640e-01, 3.1738e-01, 3.1836e-01, 3.1933e-01, 3.2031e-01, 3.2129e-01, 3.2226e-01, 3.2324e-01, 3.2422e-01, 3.2519e-01, 3.2617e-01, 3.2715e-01, 3.2812e-01, 3.2910e-01, 3.3008e-01, 3.3105e-01, 3.3203e-01, 3.3301e-01, 3.3398e-01, 3.3496e-01, 3.3594e-01, 3.3691e-01, 3.3789e-01, 3.3887e-01, 3.3984e-01, 3.4082e-01, 3.4180e-01, 3.4277e-01, 3.4375e-01, 3.4472e-01, 3.4570e-01, 3.4668e-01, 3.4765e-01, 3.4863e-01, 3.4961e-01, 3.5058e-01, 3.5156e-01, 3.5254e-01, 3.5351e-01, 3.5449e-01, 3.5547e-01, 3.5644e-01, 3.5742e-01, 3.5840e-01, 3.5937e-01, 3.6035e-01, 3.6133e-01, 3.6230e-01, 3.6328e-01, 3.6426e-01, 3.6523e-01, 3.6621e-01, 3.6719e-01, 3.6816e-01, 3.6914e-01, 3.7012e-01, 3.7109e-01, 3.7207e-01, 3.7305e-01, 3.7402e-01, 3.7500e-01, + 3.7695e-01, 3.7890e-01, 3.8086e-01, 3.8281e-01, 3.8476e-01, 3.8672e-01, 3.8867e-01, 3.9062e-01, 3.9258e-01, 3.9453e-01, 3.9648e-01, 3.9844e-01, 4.0039e-01, 4.0234e-01, 4.0430e-01, 4.0625e-01, 4.0820e-01, 4.1015e-01, 4.1211e-01, 4.1406e-01, 4.1601e-01, 4.1797e-01, 4.1992e-01, 4.2187e-01, 4.2383e-01, 4.2578e-01, 4.2773e-01, 4.2969e-01, 4.3164e-01, 4.3359e-01, 4.3555e-01, 4.3750e-01, 4.3945e-01, 4.4140e-01, 4.4336e-01, 4.4531e-01, 4.4726e-01, 4.4922e-01, 4.5117e-01, 4.5312e-01, 4.5508e-01, 4.5703e-01, 4.5898e-01, 4.6094e-01, 4.6289e-01, 4.6484e-01, 4.6680e-01, 4.6875e-01, 4.7070e-01, 4.7265e-01, 4.7461e-01, 4.7656e-01, 4.7851e-01, 4.8047e-01, 4.8242e-01, 4.8437e-01, 4.8633e-01, 4.8828e-01, 4.9023e-01, 4.9219e-01, 4.9414e-01, 4.9609e-01, 4.9805e-01, 5.0000e-01, 5.0195e-01, 5.0390e-01, 5.0586e-01, 5.0781e-01, 5.0976e-01, 5.1172e-01, 5.1367e-01, 5.1562e-01, 5.1758e-01, 5.1953e-01, 5.2148e-01, 5.2344e-01, 5.2539e-01, 5.2734e-01, 5.2930e-01, 5.3125e-01, 5.3320e-01, 5.3515e-01, 5.3711e-01, 5.3906e-01, 5.4101e-01, 5.4297e-01, 5.4492e-01, 5.4687e-01, 5.4883e-01, 5.5078e-01, 5.5273e-01, 5.5469e-01, 5.5664e-01, 5.5859e-01, 5.6055e-01, 5.6250e-01, 5.6445e-01, 5.6640e-01, 5.6836e-01, 5.7031e-01, 5.7226e-01, 5.7422e-01, 5.7617e-01, 5.7812e-01, 5.8008e-01, 5.8203e-01, 5.8398e-01, 5.8594e-01, 5.8789e-01, 5.8984e-01, 5.9180e-01, 5.9375e-01, 5.9570e-01, 5.9765e-01, 5.9961e-01, 6.0156e-01, 6.0351e-01, 6.0547e-01, 6.0742e-01, 6.0937e-01, 6.1133e-01, 6.1328e-01, 6.1523e-01, 6.1719e-01, 6.1914e-01, 6.2109e-01, 6.2305e-01, 6.2500e-01, 6.2695e-01, 6.2890e-01, 6.3086e-01, 6.3281e-01, 6.3476e-01, 6.3672e-01, 6.3867e-01, 6.4062e-01, 6.4258e-01, 6.4453e-01, 6.4648e-01, 6.4844e-01, 6.5039e-01, 6.5234e-01, 6.5430e-01, 6.5625e-01, 6.5820e-01, 6.6015e-01, 6.6211e-01, 6.6406e-01, 6.6601e-01, 6.6797e-01, 6.6992e-01, 6.7187e-01, 6.7383e-01, 6.7578e-01, 6.7773e-01, 6.7969e-01, 6.8164e-01, 6.8359e-01, 6.8554e-01, 6.8750e-01, 6.8945e-01, 6.9140e-01, 6.9336e-01, 6.9531e-01, 6.9726e-01, 6.9922e-01, 7.0117e-01, 7.0312e-01, 7.0508e-01, 7.0703e-01, 7.0898e-01, 7.1094e-01, 7.1289e-01, 7.1484e-01, 7.1679e-01, 7.1875e-01, 7.2070e-01, 7.2265e-01, 7.2461e-01, 7.2656e-01, 7.2851e-01, 7.3047e-01, 7.3242e-01, 7.3437e-01, 7.3633e-01, 7.3828e-01, 7.4023e-01, 7.4219e-01, 7.4414e-01, 7.4609e-01, 7.4804e-01, 7.5000e-01, 7.5390e-01, 7.5781e-01, 7.6172e-01, 7.6562e-01, 7.6953e-01, 7.7344e-01, 7.7734e-01, 7.8125e-01, 7.8515e-01, 7.8906e-01, 7.9297e-01, 7.9687e-01, 8.0078e-01, 8.0469e-01, 8.0859e-01, 8.1250e-01, 8.1640e-01, 8.2031e-01, 8.2422e-01, 8.2812e-01, 8.3203e-01, 8.3594e-01, 8.3984e-01, 8.4375e-01, 8.4765e-01, 8.5156e-01, 8.5547e-01, 8.5937e-01, 8.6328e-01, 8.6719e-01, 8.7109e-01, 8.7500e-01, 8.7890e-01, 8.8281e-01, 8.8672e-01, 8.9062e-01, 8.9453e-01, 8.9844e-01, 9.0234e-01, 9.0625e-01, 9.1015e-01, 9.1406e-01, 9.1797e-01, 9.2187e-01, 9.2578e-01, 9.2969e-01, 9.3359e-01, 9.3750e-01, 9.4140e-01, 9.4531e-01, 9.4922e-01, 9.5312e-01, 9.5703e-01, 9.6094e-01, 9.6484e-01, 9.6875e-01, 9.7265e-01, 9.7656e-01, 9.8047e-01, 9.8437e-01, 9.8828e-01, 9.9219e-01, 9.9609e-01, 1.0000e+00 +}; + +float4 val4_from_12(uchar8 pvs, float gain) { + uint4 parsed = (uint4)(((uint)pvs.s0<<4) + (pvs.s1>>4), // is from the previous 10 bit + ((uint)pvs.s2<<4) + (pvs.s4&0xF), + ((uint)pvs.s3<<4) + (pvs.s4>>4), + ((uint)pvs.s5<<4) + (pvs.s7&0xF)); + #if IS_OX + // PWL + //float4 pv = (convert_float4(parsed) - 64.0) / (4096.0 - 64.0); + float4 pv = {ox03c10_lut[parsed.s0], ox03c10_lut[parsed.s1], ox03c10_lut[parsed.s2], ox03c10_lut[parsed.s3]}; + + // it's a 24 bit signal, center in the middle 8 bits + return clamp(pv*gain*256.0, 0.0, 1.0); + #else // AR + // normalize and scale + float4 pv = (convert_float4(parsed) - 168.0) / (4096.0 - 168.0); + return clamp(pv*gain, 0.0, 1.0); + #endif + +} + +float get_k(float a, float b, float c, float d) { + return 2.0 - (fabs(a - b) + fabs(c - d)); +} + +__kernel void debayer10(const __global uchar * in, __global uchar * out) +{ + const int gid_x = get_global_id(0); + const int gid_y = get_global_id(1); + + const int y_top_mod = (gid_y == 0) ? 2: 0; + const int y_bot_mod = (gid_y == (RGB_HEIGHT/2 - 1)) ? 1: 3; + + float3 rgb; + uchar3 rgb_out[4]; + + int start = (2 * gid_y - 1) * FRAME_STRIDE + (3 * gid_x - 2) + (FRAME_STRIDE * FRAME_OFFSET); + + // read in 8x4 chars + uchar8 dat[4]; + dat[0] = vload8(0, in + start + FRAME_STRIDE*y_top_mod); + dat[1] = vload8(0, in + start + FRAME_STRIDE*1); + dat[2] = vload8(0, in + start + FRAME_STRIDE*2); + dat[3] = vload8(0, in + start + FRAME_STRIDE*y_bot_mod); + + // correct vignetting + #if VIGNETTING + int gx = (gid_x*2 - RGB_WIDTH/2); + int gy = (gid_y*2 - RGB_HEIGHT/2); + const float gain = get_vignetting_s(gx*gx + gy*gy); + #else + const float gain = 1.0; + #endif + + // process them to floats + float4 va = val4_from_12(dat[0], gain); + float4 vb = val4_from_12(dat[1], gain); + float4 vc = val4_from_12(dat[2], gain); + float4 vd = val4_from_12(dat[3], gain); + + if (gid_x == 0) { + va.s0 = va.s2; + vb.s0 = vb.s2; + vc.s0 = vc.s2; + vd.s0 = vd.s2; + } else if (gid_x == RGB_WIDTH/2 - 1) { + va.s3 = va.s1; + vb.s3 = vb.s1; + vc.s3 = vc.s1; + vd.s3 = vd.s1; + } + + // a simplified version of https://opensignalprocessingjournal.com/contents/volumes/V6/TOSIGPJ-6-1/TOSIGPJ-6-1.pdf + const float k01 = get_k(va.s0, vb.s1, va.s2, vb.s1); + const float k02 = get_k(va.s2, vb.s1, vc.s2, vb.s1); + const float k03 = get_k(vc.s0, vb.s1, vc.s2, vb.s1); + const float k04 = get_k(va.s0, vb.s1, vc.s0, vb.s1); + rgb.x = (k02*vb.s2+k04*vb.s0)/(k02+k04); // R_G1 + rgb.y = vb.s1; // G1(R) + rgb.z = (k01*va.s1+k03*vc.s1)/(k01+k03); // B_G1 + rgb_out[0] = convert_uchar3_sat(color_correct(clamp(rgb, 0.0, 1.0)) * 255.0); + + const float k11 = get_k(va.s1, vc.s1, va.s3, vc.s3); + const float k12 = get_k(va.s2, vb.s1, vb.s3, vc.s2); + const float k13 = get_k(va.s1, va.s3, vc.s1, vc.s3); + const float k14 = get_k(va.s2, vb.s3, vc.s2, vb.s1); + rgb.x = vb.s2; // R + rgb.y = (k11*(va.s2+vc.s2)*0.5+k13*(vb.s3+vb.s1)*0.5)/(k11+k13); // G_R + rgb.z = (k12*(va.s3+vc.s1)*0.5+k14*(va.s1+vc.s3)*0.5)/(k12+k14); // B_R + rgb_out[1] = convert_uchar3_sat(color_correct(clamp(rgb, 0.0, 1.0)) * 255.0); + + const float k21 = get_k(vb.s0, vd.s0, vb.s2, vd.s2); + const float k22 = get_k(vb.s1, vc.s0, vc.s2, vd.s1); + const float k23 = get_k(vb.s0, vb.s2, vd.s0, vd.s2); + const float k24 = get_k(vb.s1, vc.s2, vd.s1, vc.s0); + rgb.x = (k22*(vb.s2+vd.s0)*0.5+k24*(vb.s0+vd.s2)*0.5)/(k22+k24); // R_B + rgb.y = (k21*(vb.s1+vd.s1)*0.5+k23*(vc.s2+vc.s0)*0.5)/(k21+k23); // G_B + rgb.z = vc.s1; // B + rgb_out[2] = convert_uchar3_sat(color_correct(clamp(rgb, 0.0, 1.0)) * 255.0); + + const float k31 = get_k(vb.s1, vc.s2, vb.s3, vc.s2); + const float k32 = get_k(vb.s3, vc.s2, vd.s3, vc.s2); + const float k33 = get_k(vd.s1, vc.s2, vd.s3, vc.s2); + const float k34 = get_k(vb.s1, vc.s2, vd.s1, vc.s2); + rgb.x = (k31*vb.s2+k33*vd.s2)/(k31+k33); // R_G2 + rgb.y = vc.s2; // G2(B) + rgb.z = (k32*vc.s3+k34*vc.s1)/(k32+k34); // B_G2 + rgb_out[3] = convert_uchar3_sat(color_correct(clamp(rgb, 0.0, 1.0)) * 255.0); + + // write ys + uchar2 yy = (uchar2)( + RGB_TO_Y(rgb_out[0].s0, rgb_out[0].s1, rgb_out[0].s2), + RGB_TO_Y(rgb_out[1].s0, rgb_out[1].s1, rgb_out[1].s2) + ); + vstore2(yy, 0, out + mad24(gid_y * 2, YUV_STRIDE, gid_x * 2)); + yy = (uchar2)( + RGB_TO_Y(rgb_out[2].s0, rgb_out[2].s1, rgb_out[2].s2), + RGB_TO_Y(rgb_out[3].s0, rgb_out[3].s1, rgb_out[3].s2) + ); + vstore2(yy, 0, out + mad24(gid_y * 2 + 1, YUV_STRIDE, gid_x * 2)); + + // write uvs + const short ar = AVERAGE(rgb_out[0].s0, rgb_out[1].s0, rgb_out[2].s0, rgb_out[3].s0); + const short ag = AVERAGE(rgb_out[0].s1, rgb_out[1].s1, rgb_out[2].s1, rgb_out[3].s1); + const short ab = AVERAGE(rgb_out[0].s2, rgb_out[1].s2, rgb_out[2].s2, rgb_out[3].s2); + uchar2 uv = (uchar2)( + RGB_TO_U(ar, ag, ab), + RGB_TO_V(ar, ag, ab) + ); + vstore2(uv, 0, out + UV_OFFSET + mad24(gid_y, YUV_STRIDE, gid_x * 2)); +} diff --git a/system/camerad/cameras/sensor2_i2c.h b/system/camerad/cameras/sensor2_i2c.h new file mode 100644 index 0000000000..ab51059d9a --- /dev/null +++ b/system/camerad/cameras/sensor2_i2c.h @@ -0,0 +1,867 @@ +struct i2c_random_wr_payload start_reg_array_ar0231[] = {{0x301A, 0x91C}}; +struct i2c_random_wr_payload stop_reg_array_ar0231[] = {{0x301A, 0x918}}; +struct i2c_random_wr_payload start_reg_array_ox03c10[] = {{0x100, 1}}; +struct i2c_random_wr_payload stop_reg_array_ox03c10[] = {{0x100, 0}}; + +struct i2c_random_wr_payload init_array_ox03c10[] = { + {0x103, 1}, + {0x107, 1}, + + // X3C_1920x1280_60fps_HDR4_LFR_PWL12_mipi1200 + + // TPM + {0x4d5a, 0x1a}, {0x4d09, 0xff}, {0x4d09, 0xdf}, + + /*) + // group 4 + {0x3208, 0x04}, + {0x4620, 0x04}, + {0x3208, 0x14}, + + // group 5 + {0x3208, 0x05}, + {0x4620, 0x04}, + {0x3208, 0x15}, + + // group 2 + {0x3208, 0x02}, + {0x3507, 0x00}, + {0x3208, 0x12}, + + // delay launch group 2 + {0x3208, 0xa2},*/ + + // PLL setup + {0x0301, 0xc8}, // pll1_divs, pll1_predivp, pll1_divpix + {0x0303, 0x01}, // pll1_prediv + {0x0304, 0x01}, {0x0305, 0x2c}, // pll1_loopdiv = 300 + {0x0306, 0x04}, // pll1_divmipi = 4 + {0x0307, 0x01}, // pll1_divm = 1 + {0x0316, 0x00}, + {0x0317, 0x00}, + {0x0318, 0x00}, + {0x0323, 0x05}, // pll2_prediv + {0x0324, 0x01}, {0x0325, 0x2c}, // pll2_divp = 300 + + // SCLK/PCLK + {0x0400, 0xe0}, {0x0401, 0x80}, + {0x0403, 0xde}, {0x0404, 0x34}, + {0x0405, 0x3b}, {0x0406, 0xde}, + {0x0407, 0x08}, + {0x0408, 0xe0}, {0x0409, 0x7f}, + {0x040a, 0xde}, {0x040b, 0x34}, + {0x040c, 0x47}, {0x040d, 0xd8}, + {0x040e, 0x08}, + + // xchk + {0x2803, 0xfe}, {0x280b, 0x00}, {0x280c, 0x79}, + + // SC ctrl + {0x3001, 0x03}, // io_pad_oen + {0x3002, 0xf8}, // io_pad_oen + {0x3005, 0x80}, // io_pad_out + {0x3007, 0x01}, // io_pad_sel + {0x3008, 0x80}, // io_pad_sel + + // FSIN first frame + /* + {0x3009, 0x2}, + {0x3015, 0x2}, + {0x3822, 0x20}, + {0x3823, 0x58}, + + {0x3826, 0x0}, {0x3827, 0x8}, + {0x3881, 0x4}, + + {0x3882, 0x8}, {0x3883, 0x0D}, + {0x3836, 0x1F}, {0x3837, 0x40}, + */ + + // FSIN with external pulses + {0x3009, 0x2}, + {0x3015, 0x2}, + {0x383E, 0x80}, + {0x3881, 0x4}, + {0x3882, 0x8}, {0x3883, 0x0D}, + {0x3836, 0x1F}, {0x3837, 0x40}, + + {0x3012, 0x41}, // SC_PHY_CTRL = 4 lane MIPI + {0x3020, 0x05}, // SC_CTRL_20 + + // this is not in the datasheet, listed as RSVD + // but the camera doesn't work without it + {0x3700, 0x28}, {0x3701, 0x15}, {0x3702, 0x19}, {0x3703, 0x23}, + {0x3704, 0x0a}, {0x3705, 0x00}, {0x3706, 0x3e}, {0x3707, 0x0d}, + {0x3708, 0x50}, {0x3709, 0x5a}, {0x370a, 0x00}, {0x370b, 0x96}, + {0x3711, 0x11}, {0x3712, 0x13}, {0x3717, 0x02}, {0x3718, 0x73}, + {0x372c, 0x40}, {0x3733, 0x01}, {0x3738, 0x36}, {0x3739, 0x36}, + {0x373a, 0x25}, {0x373b, 0x25}, {0x373f, 0x21}, {0x3740, 0x21}, + {0x3741, 0x21}, {0x3742, 0x21}, {0x3747, 0x28}, {0x3748, 0x28}, + {0x3749, 0x19}, {0x3755, 0x1a}, {0x3756, 0x0a}, {0x3757, 0x1c}, + {0x3765, 0x19}, {0x3766, 0x05}, {0x3767, 0x05}, {0x3768, 0x13}, + {0x376c, 0x07}, {0x3778, 0x20}, {0x377c, 0xc8}, {0x3781, 0x02}, + {0x3783, 0x02}, {0x379c, 0x58}, {0x379e, 0x00}, {0x379f, 0x00}, + {0x37a0, 0x00}, {0x37bc, 0x22}, {0x37c0, 0x01}, {0x37c4, 0x3e}, + {0x37c5, 0x3e}, {0x37c6, 0x2a}, {0x37c7, 0x28}, {0x37c8, 0x02}, + {0x37c9, 0x12}, {0x37cb, 0x29}, {0x37cd, 0x29}, {0x37d2, 0x00}, + {0x37d3, 0x73}, {0x37d6, 0x00}, {0x37d7, 0x6b}, {0x37dc, 0x00}, + {0x37df, 0x54}, {0x37e2, 0x00}, {0x37e3, 0x00}, {0x37f8, 0x00}, + {0x37f9, 0x01}, {0x37fa, 0x00}, {0x37fb, 0x19}, + + // also RSVD + {0x3c03, 0x01}, {0x3c04, 0x01}, {0x3c06, 0x21}, {0x3c08, 0x01}, + {0x3c09, 0x01}, {0x3c0a, 0x01}, {0x3c0b, 0x21}, {0x3c13, 0x21}, + {0x3c14, 0x82}, {0x3c16, 0x13}, {0x3c21, 0x00}, {0x3c22, 0xf3}, + {0x3c37, 0x12}, {0x3c38, 0x31}, {0x3c3c, 0x00}, {0x3c3d, 0x03}, + {0x3c44, 0x16}, {0x3c5c, 0x8a}, {0x3c5f, 0x03}, {0x3c61, 0x80}, + {0x3c6f, 0x2b}, {0x3c70, 0x5f}, {0x3c71, 0x2c}, {0x3c72, 0x2c}, + {0x3c73, 0x2c}, {0x3c76, 0x12}, + + // PEC checks + {0x3182, 0x12}, + + {0x320e, 0x00}, {0x320f, 0x00}, // RSVD + {0x3211, 0x61}, + {0x3215, 0xcd}, + {0x3219, 0x08}, + + {0x3506, 0x20}, {0x3507, 0x00}, // hcg fine exposure + {0x350a, 0x04}, {0x350b, 0x00}, {0x350c, 0x00}, // hcg digital gain + + {0x3586, 0x40}, {0x3587, 0x00}, // lcg fine exposure + {0x358a, 0x01}, {0x358b, 0x00}, {0x358c, 0x00}, // lcg digital gain + + {0x3546, 0x20}, {0x3547, 0x00}, // spd fine exposure + {0x354a, 0x01}, {0x354b, 0x00}, {0x354c, 0x00}, // spd digital gain + + {0x35c6, 0xb0}, {0x35c7, 0x00}, // vs fine exposure + {0x35ca, 0x01}, {0x35cb, 0x00}, {0x35cc, 0x00}, // vs digital gain + + // also RSVD + {0x3600, 0x8f}, {0x3605, 0x16}, {0x3609, 0xf0}, {0x360a, 0x01}, + {0x360e, 0x1d}, {0x360f, 0x10}, {0x3610, 0x70}, {0x3611, 0x3a}, + {0x3612, 0x28}, {0x361a, 0x29}, {0x361b, 0x6c}, {0x361c, 0x0b}, + {0x361d, 0x00}, {0x361e, 0xfc}, {0x362a, 0x00}, {0x364d, 0x0f}, + {0x364e, 0x18}, {0x364f, 0x12}, {0x3653, 0x1c}, {0x3654, 0x00}, + {0x3655, 0x1f}, {0x3656, 0x1f}, {0x3657, 0x0c}, {0x3658, 0x0a}, + {0x3659, 0x14}, {0x365a, 0x18}, {0x365b, 0x14}, {0x365c, 0x10}, + {0x365e, 0x12}, {0x3674, 0x08}, {0x3677, 0x3a}, {0x3678, 0x3a}, + {0x3679, 0x19}, + + // Y_ADDR_START = 4 + {0x3802, 0x00}, {0x3803, 0x04}, + // Y_ADDR_END = 0x50b + {0x3806, 0x05}, {0x3807, 0x0b}, + + // X_OUTPUT_SIZE = 0x780 = 1920 (changed to 1928) + {0x3808, 0x07}, {0x3809, 0x88}, + + // Y_OUTPUT_SIZE = 0x500 = 1280 (changed to 1208) + {0x380a, 0x04}, {0x380b, 0xb8}, + + // horizontal timing 0x447 + {0x380c, 0x04}, {0x380d, 0x47}, + + // rows per frame (was 0x2ae) + // 0x8ae = 53.65 ms + {0x380e, 0x08}, {0x380f, 0x15}, + // this should be triggered by FSIN, not free running + + {0x3810, 0x00}, {0x3811, 0x08}, // x cutoff + {0x3812, 0x00}, {0x3813, 0x04}, // y cutoff + {0x3816, 0x01}, + {0x3817, 0x01}, + {0x381c, 0x18}, + {0x381e, 0x01}, + {0x381f, 0x01}, + + // don't mirror, just flip + {0x3820, 0x04}, + + {0x3821, 0x19}, + {0x3832, 0x00}, + {0x3834, 0x00}, + {0x384c, 0x02}, + {0x384d, 0x0d}, + {0x3850, 0x00}, + {0x3851, 0x42}, + {0x3852, 0x00}, + {0x3853, 0x40}, + {0x3858, 0x04}, + {0x388c, 0x02}, + {0x388d, 0x2b}, + + // APC + {0x3b40, 0x05}, {0x3b41, 0x40}, {0x3b42, 0x00}, {0x3b43, 0x90}, + {0x3b44, 0x00}, {0x3b45, 0x20}, {0x3b46, 0x00}, {0x3b47, 0x20}, + {0x3b48, 0x19}, {0x3b49, 0x12}, {0x3b4a, 0x16}, {0x3b4b, 0x2e}, + {0x3b4c, 0x00}, {0x3b4d, 0x00}, + {0x3b86, 0x00}, {0x3b87, 0x34}, {0x3b88, 0x00}, {0x3b89, 0x08}, + {0x3b8a, 0x05}, {0x3b8b, 0x00}, {0x3b8c, 0x07}, {0x3b8d, 0x80}, + {0x3b8e, 0x00}, {0x3b8f, 0x00}, {0x3b92, 0x05}, {0x3b93, 0x00}, + {0x3b94, 0x07}, {0x3b95, 0x80}, {0x3b9e, 0x09}, + + // OTP + {0x3d82, 0x73}, + {0x3d85, 0x05}, + {0x3d8a, 0x03}, + {0x3d8b, 0xff}, + {0x3d99, 0x00}, + {0x3d9a, 0x9f}, + {0x3d9b, 0x00}, + {0x3d9c, 0xa0}, + {0x3da4, 0x00}, + {0x3da7, 0x50}, + + // DTR + {0x420e, 0x6b}, + {0x420f, 0x6e}, + {0x4210, 0x06}, + {0x4211, 0xc1}, + {0x421e, 0x02}, + {0x421f, 0x45}, + {0x4220, 0xe1}, + {0x4221, 0x01}, + {0x4301, 0xff}, + {0x4307, 0x03}, + {0x4308, 0x13}, + {0x430a, 0x13}, + {0x430d, 0x93}, + {0x430f, 0x57}, + {0x4310, 0x95}, + {0x4311, 0x16}, + {0x4316, 0x00}, + + {0x4317, 0x38}, // both embedded rows are enabled + + {0x4319, 0x03}, // spd dcg + {0x431a, 0x00}, // 8 bit mipi + {0x431b, 0x00}, + {0x431d, 0x2a}, + {0x431e, 0x11}, + + {0x431f, 0x20}, // enable PWL (pwl0_en), 12 bits + //{0x431f, 0x00}, // disable PWL + + {0x4320, 0x19}, + {0x4323, 0x80}, + {0x4324, 0x00}, + {0x4503, 0x4e}, + {0x4505, 0x00}, + {0x4509, 0x00}, + {0x450a, 0x00}, + {0x4580, 0xf8}, + {0x4583, 0x07}, + {0x4584, 0x6a}, + {0x4585, 0x08}, + {0x4586, 0x05}, + {0x4587, 0x04}, + {0x4588, 0x73}, + {0x4589, 0x05}, + {0x458a, 0x1f}, + {0x458b, 0x02}, + {0x458c, 0xdc}, + {0x458d, 0x03}, + {0x458e, 0x02}, + {0x4597, 0x07}, + {0x4598, 0x40}, + {0x4599, 0x0e}, + {0x459a, 0x0e}, + {0x459b, 0xfb}, + {0x459c, 0xf3}, + {0x4602, 0x00}, + {0x4603, 0x13}, + {0x4604, 0x00}, + {0x4609, 0x0a}, + {0x460a, 0x30}, + {0x4610, 0x00}, + {0x4611, 0x70}, + {0x4612, 0x01}, + {0x4613, 0x00}, + {0x4614, 0x00}, + {0x4615, 0x70}, + {0x4616, 0x01}, + {0x4617, 0x00}, + + {0x4800, 0x04}, // invert output PCLK + {0x480a, 0x22}, + {0x4813, 0xe4}, + + // mipi + {0x4814, 0x2a}, + {0x4837, 0x0d}, + {0x484b, 0x47}, + {0x484f, 0x00}, + {0x4887, 0x51}, + {0x4d00, 0x4a}, + {0x4d01, 0x18}, + {0x4d05, 0xff}, + {0x4d06, 0x88}, + {0x4d08, 0x63}, + {0x4d09, 0xdf}, + {0x4d15, 0x7d}, + {0x4d1a, 0x20}, + {0x4d30, 0x0a}, + {0x4d31, 0x00}, + {0x4d34, 0x7d}, + {0x4d3c, 0x7d}, + {0x4f00, 0x00}, + {0x4f01, 0x00}, + {0x4f02, 0x00}, + {0x4f03, 0x20}, + {0x4f04, 0xe0}, + {0x6a00, 0x00}, + {0x6a01, 0x20}, + {0x6a02, 0x00}, + {0x6a03, 0x20}, + {0x6a04, 0x02}, + {0x6a05, 0x80}, + {0x6a06, 0x01}, + {0x6a07, 0xe0}, + {0x6a08, 0xcf}, + {0x6a09, 0x01}, + {0x6a0a, 0x40}, + {0x6a20, 0x00}, + {0x6a21, 0x02}, + {0x6a22, 0x00}, + {0x6a23, 0x00}, + {0x6a24, 0x00}, + {0x6a25, 0x00}, + {0x6a26, 0x00}, + {0x6a27, 0x00}, + {0x6a28, 0x00}, + + // isp + {0x5000, 0x8f}, + {0x5001, 0x75}, + {0x5002, 0x7f}, // PWL0 + //{0x5002, 0x3f}, // PWL disable + {0x5003, 0x7a}, + + {0x5004, 0x3e}, + {0x5005, 0x1e}, + {0x5006, 0x1e}, + {0x5007, 0x1e}, + + {0x5008, 0x00}, + {0x500c, 0x00}, + {0x502c, 0x00}, + {0x502e, 0x00}, + {0x502f, 0x00}, + {0x504b, 0x00}, + {0x5053, 0x00}, + {0x505b, 0x00}, + {0x5063, 0x00}, + {0x5070, 0x00}, + {0x5074, 0x04}, + {0x507a, 0x04}, + {0x507b, 0x09}, + {0x5500, 0x02}, + {0x5700, 0x02}, + {0x5900, 0x02}, + {0x6007, 0x04}, + {0x6008, 0x05}, + {0x6009, 0x02}, + {0x600b, 0x08}, + {0x600c, 0x07}, + {0x600d, 0x88}, + {0x6016, 0x00}, + {0x6027, 0x04}, + {0x6028, 0x05}, + {0x6029, 0x02}, + {0x602b, 0x08}, + {0x602c, 0x07}, + {0x602d, 0x88}, + {0x6047, 0x04}, + {0x6048, 0x05}, + {0x6049, 0x02}, + {0x604b, 0x08}, + {0x604c, 0x07}, + {0x604d, 0x88}, + {0x6067, 0x04}, + {0x6068, 0x05}, + {0x6069, 0x02}, + {0x606b, 0x08}, + {0x606c, 0x07}, + {0x606d, 0x88}, + {0x6087, 0x04}, + {0x6088, 0x05}, + {0x6089, 0x02}, + {0x608b, 0x08}, + {0x608c, 0x07}, + {0x608d, 0x88}, + + // 12-bit PWL0 + {0x5e00, 0x00}, + + // m_ndX_exp[0:32] + // 9*2+0xa*3+0xb*2+0xc*2+0xd*2+0xe*2+0xf*2+0x10*2+0x11*2+0x12*4+0x13*3+0x14*3+0x15*3+0x16 = 518 + {0x5e01, 0x09}, + {0x5e02, 0x09}, + {0x5e03, 0x0a}, + {0x5e04, 0x0a}, + {0x5e05, 0x0a}, + {0x5e06, 0x0b}, + {0x5e07, 0x0b}, + {0x5e08, 0x0c}, + {0x5e09, 0x0c}, + {0x5e0a, 0x0d}, + {0x5e0b, 0x0d}, + {0x5e0c, 0x0e}, + {0x5e0d, 0x0e}, + {0x5e0e, 0x0f}, + {0x5e0f, 0x0f}, + {0x5e10, 0x10}, + {0x5e11, 0x10}, + {0x5e12, 0x11}, + {0x5e13, 0x11}, + {0x5e14, 0x12}, + {0x5e15, 0x12}, + {0x5e16, 0x12}, + {0x5e17, 0x12}, + {0x5e18, 0x13}, + {0x5e19, 0x13}, + {0x5e1a, 0x13}, + {0x5e1b, 0x14}, + {0x5e1c, 0x14}, + {0x5e1d, 0x14}, + {0x5e1e, 0x15}, + {0x5e1f, 0x15}, + {0x5e20, 0x15}, + {0x5e21, 0x16}, + + // m_ndY_val[0:32] + // 0x200+0xff+0x100*3+0x80*12+0x40*16 = 4095 + {0x5e22, 0x00}, {0x5e23, 0x02}, {0x5e24, 0x00}, + {0x5e25, 0x00}, {0x5e26, 0x00}, {0x5e27, 0xff}, + {0x5e28, 0x00}, {0x5e29, 0x01}, {0x5e2a, 0x00}, + {0x5e2b, 0x00}, {0x5e2c, 0x01}, {0x5e2d, 0x00}, + {0x5e2e, 0x00}, {0x5e2f, 0x01}, {0x5e30, 0x00}, + {0x5e31, 0x00}, {0x5e32, 0x00}, {0x5e33, 0x80}, + {0x5e34, 0x00}, {0x5e35, 0x00}, {0x5e36, 0x80}, + {0x5e37, 0x00}, {0x5e38, 0x00}, {0x5e39, 0x80}, + {0x5e3a, 0x00}, {0x5e3b, 0x00}, {0x5e3c, 0x80}, + {0x5e3d, 0x00}, {0x5e3e, 0x00}, {0x5e3f, 0x80}, + {0x5e40, 0x00}, {0x5e41, 0x00}, {0x5e42, 0x80}, + {0x5e43, 0x00}, {0x5e44, 0x00}, {0x5e45, 0x80}, + {0x5e46, 0x00}, {0x5e47, 0x00}, {0x5e48, 0x80}, + {0x5e49, 0x00}, {0x5e4a, 0x00}, {0x5e4b, 0x80}, + {0x5e4c, 0x00}, {0x5e4d, 0x00}, {0x5e4e, 0x80}, + {0x5e4f, 0x00}, {0x5e50, 0x00}, {0x5e51, 0x80}, + {0x5e52, 0x00}, {0x5e53, 0x00}, {0x5e54, 0x80}, + {0x5e55, 0x00}, {0x5e56, 0x00}, {0x5e57, 0x40}, + {0x5e58, 0x00}, {0x5e59, 0x00}, {0x5e5a, 0x40}, + {0x5e5b, 0x00}, {0x5e5c, 0x00}, {0x5e5d, 0x40}, + {0x5e5e, 0x00}, {0x5e5f, 0x00}, {0x5e60, 0x40}, + {0x5e61, 0x00}, {0x5e62, 0x00}, {0x5e63, 0x40}, + {0x5e64, 0x00}, {0x5e65, 0x00}, {0x5e66, 0x40}, + {0x5e67, 0x00}, {0x5e68, 0x00}, {0x5e69, 0x40}, + {0x5e6a, 0x00}, {0x5e6b, 0x00}, {0x5e6c, 0x40}, + {0x5e6d, 0x00}, {0x5e6e, 0x00}, {0x5e6f, 0x40}, + {0x5e70, 0x00}, {0x5e71, 0x00}, {0x5e72, 0x40}, + {0x5e73, 0x00}, {0x5e74, 0x00}, {0x5e75, 0x40}, + {0x5e76, 0x00}, {0x5e77, 0x00}, {0x5e78, 0x40}, + {0x5e79, 0x00}, {0x5e7a, 0x00}, {0x5e7b, 0x40}, + {0x5e7c, 0x00}, {0x5e7d, 0x00}, {0x5e7e, 0x40}, + {0x5e7f, 0x00}, {0x5e80, 0x00}, {0x5e81, 0x40}, + {0x5e82, 0x00}, {0x5e83, 0x00}, {0x5e84, 0x40}, + + // disable PWL + /*{0x5e01, 0x18}, {0x5e02, 0x00}, {0x5e03, 0x00}, {0x5e04, 0x00}, + {0x5e05, 0x00}, {0x5e06, 0x00}, {0x5e07, 0x00}, {0x5e08, 0x00}, + {0x5e09, 0x00}, {0x5e0a, 0x00}, {0x5e0b, 0x00}, {0x5e0c, 0x00}, + {0x5e0d, 0x00}, {0x5e0e, 0x00}, {0x5e0f, 0x00}, {0x5e10, 0x00}, + {0x5e11, 0x00}, {0x5e12, 0x00}, {0x5e13, 0x00}, {0x5e14, 0x00}, + {0x5e15, 0x00}, {0x5e16, 0x00}, {0x5e17, 0x00}, {0x5e18, 0x00}, + {0x5e19, 0x00}, {0x5e1a, 0x00}, {0x5e1b, 0x00}, {0x5e1c, 0x00}, + {0x5e1d, 0x00}, {0x5e1e, 0x00}, {0x5e1f, 0x00}, {0x5e20, 0x00}, + {0x5e21, 0x00}, + + {0x5e22, 0x00}, {0x5e23, 0x0f}, {0x5e24, 0xFF},*/ + + {0x4001, 0x2b}, // BLC_CTRL_1 + {0x4008, 0x02}, {0x4009, 0x03}, + {0x4018, 0x12}, + {0x4022, 0x40}, + {0x4023, 0x20}, + + // all black level targets are 0x40 + {0x4026, 0x00}, {0x4027, 0x40}, + {0x4028, 0x00}, {0x4029, 0x40}, + {0x402a, 0x00}, {0x402b, 0x40}, + {0x402c, 0x00}, {0x402d, 0x40}, + + {0x407e, 0xcc}, + {0x407f, 0x18}, + {0x4080, 0xff}, + {0x4081, 0xff}, + {0x4082, 0x01}, + {0x4083, 0x53}, + {0x4084, 0x01}, + {0x4085, 0x2b}, + {0x4086, 0x00}, + {0x4087, 0xb3}, + + {0x4640, 0x40}, + {0x4641, 0x11}, + {0x4642, 0x0e}, + {0x4643, 0xee}, + {0x4646, 0x0f}, + {0x4648, 0x00}, + {0x4649, 0x03}, + + {0x4f00, 0x00}, + {0x4f01, 0x00}, + {0x4f02, 0x80}, + {0x4f03, 0x2c}, + {0x4f04, 0xf8}, + + {0x4d09, 0xff}, + {0x4d09, 0xdf}, + + {0x5003, 0x7a}, + {0x5b80, 0x08}, + {0x5c00, 0x08}, + {0x5c80, 0x00}, + {0x5bbe, 0x12}, + {0x5c3e, 0x12}, + {0x5cbe, 0x12}, + {0x5b8a, 0x80}, + {0x5b8b, 0x80}, + {0x5b8c, 0x80}, + {0x5b8d, 0x80}, + {0x5b8e, 0x60}, + {0x5b8f, 0x80}, + {0x5b90, 0x80}, + {0x5b91, 0x80}, + {0x5b92, 0x80}, + {0x5b93, 0x20}, + {0x5b94, 0x80}, + {0x5b95, 0x80}, + {0x5b96, 0x80}, + {0x5b97, 0x20}, + {0x5b98, 0x00}, + {0x5b99, 0x80}, + {0x5b9a, 0x40}, + {0x5b9b, 0x20}, + {0x5b9c, 0x00}, + {0x5b9d, 0x00}, + {0x5b9e, 0x80}, + {0x5b9f, 0x00}, + {0x5ba0, 0x00}, + {0x5ba1, 0x00}, + {0x5ba2, 0x00}, + {0x5ba3, 0x00}, + {0x5ba4, 0x00}, + {0x5ba5, 0x00}, + {0x5ba6, 0x00}, + {0x5ba7, 0x00}, + {0x5ba8, 0x02}, + {0x5ba9, 0x00}, + {0x5baa, 0x02}, + {0x5bab, 0x76}, + {0x5bac, 0x03}, + {0x5bad, 0x08}, + {0x5bae, 0x00}, + {0x5baf, 0x80}, + {0x5bb0, 0x00}, + {0x5bb1, 0xc0}, + {0x5bb2, 0x01}, + {0x5bb3, 0x00}, + + // m_nNormCombineWeight + {0x5c0a, 0x80}, {0x5c0b, 0x80}, {0x5c0c, 0x80}, {0x5c0d, 0x80}, {0x5c0e, 0x60}, + {0x5c0f, 0x80}, {0x5c10, 0x80}, {0x5c11, 0x80}, {0x5c12, 0x60}, {0x5c13, 0x20}, + {0x5c14, 0x80}, {0x5c15, 0x80}, {0x5c16, 0x80}, {0x5c17, 0x20}, {0x5c18, 0x00}, + {0x5c19, 0x80}, {0x5c1a, 0x40}, {0x5c1b, 0x20}, {0x5c1c, 0x00}, {0x5c1d, 0x00}, + {0x5c1e, 0x80}, {0x5c1f, 0x00}, {0x5c20, 0x00}, {0x5c21, 0x00}, {0x5c22, 0x00}, + {0x5c23, 0x00}, {0x5c24, 0x00}, {0x5c25, 0x00}, {0x5c26, 0x00}, {0x5c27, 0x00}, + + // m_nCombinThreL + {0x5c28, 0x02}, {0x5c29, 0x00}, + {0x5c2a, 0x02}, {0x5c2b, 0x76}, + {0x5c2c, 0x03}, {0x5c2d, 0x08}, + + // m_nCombinThreS + {0x5c2e, 0x00}, {0x5c2f, 0x80}, + {0x5c30, 0x00}, {0x5c31, 0xc0}, + {0x5c32, 0x01}, {0x5c33, 0x00}, + + // m_nNormCombineWeight + {0x5c8a, 0x80}, {0x5c8b, 0x80}, {0x5c8c, 0x80}, {0x5c8d, 0x80}, {0x5c8e, 0x80}, + {0x5c8f, 0x80}, {0x5c90, 0x80}, {0x5c91, 0x80}, {0x5c92, 0x80}, {0x5c93, 0x60}, + {0x5c94, 0x80}, {0x5c95, 0x80}, {0x5c96, 0x80}, {0x5c97, 0x60}, {0x5c98, 0x40}, + {0x5c99, 0x80}, {0x5c9a, 0x80}, {0x5c9b, 0x80}, {0x5c9c, 0x40}, {0x5c9d, 0x00}, + {0x5c9e, 0x80}, {0x5c9f, 0x80}, {0x5ca0, 0x80}, {0x5ca1, 0x20}, {0x5ca2, 0x00}, + {0x5ca3, 0x80}, {0x5ca4, 0x80}, {0x5ca5, 0x00}, {0x5ca6, 0x00}, {0x5ca7, 0x00}, + + {0x5ca8, 0x01}, {0x5ca9, 0x00}, + {0x5caa, 0x02}, {0x5cab, 0x00}, + {0x5cac, 0x03}, {0x5cad, 0x08}, + + {0x5cae, 0x01}, {0x5caf, 0x00}, + {0x5cb0, 0x02}, {0x5cb1, 0x00}, + {0x5cb2, 0x03}, {0x5cb3, 0x08}, + + // combine ISP + {0x5be7, 0x80}, + {0x5bc9, 0x80}, + {0x5bca, 0x80}, + {0x5bcb, 0x80}, + {0x5bcc, 0x80}, + {0x5bcd, 0x80}, + {0x5bce, 0x80}, + {0x5bcf, 0x80}, + {0x5bd0, 0x80}, + {0x5bd1, 0x80}, + {0x5bd2, 0x20}, + {0x5bd3, 0x80}, + {0x5bd4, 0x40}, + {0x5bd5, 0x20}, + {0x5bd6, 0x00}, + {0x5bd7, 0x00}, + {0x5bd8, 0x00}, + {0x5bd9, 0x00}, + {0x5bda, 0x00}, + {0x5bdb, 0x00}, + {0x5bdc, 0x00}, + {0x5bdd, 0x00}, + {0x5bde, 0x00}, + {0x5bdf, 0x00}, + {0x5be0, 0x00}, + {0x5be1, 0x00}, + {0x5be2, 0x00}, + {0x5be3, 0x00}, + {0x5be4, 0x00}, + {0x5be5, 0x00}, + {0x5be6, 0x00}, + + // m_nSPDCombineWeight + {0x5c49, 0x80}, {0x5c4a, 0x80}, {0x5c4b, 0x80}, {0x5c4c, 0x80}, {0x5c4d, 0x40}, + {0x5c4e, 0x80}, {0x5c4f, 0x80}, {0x5c50, 0x80}, {0x5c51, 0x60}, {0x5c52, 0x20}, + {0x5c53, 0x80}, {0x5c54, 0x80}, {0x5c55, 0x80}, {0x5c56, 0x20}, {0x5c57, 0x00}, + {0x5c58, 0x80}, {0x5c59, 0x40}, {0x5c5a, 0x20}, {0x5c5b, 0x00}, {0x5c5c, 0x00}, + {0x5c5d, 0x80}, {0x5c5e, 0x00}, {0x5c5f, 0x00}, {0x5c60, 0x00}, {0x5c61, 0x00}, + {0x5c62, 0x00}, {0x5c63, 0x00}, {0x5c64, 0x00}, {0x5c65, 0x00}, {0x5c66, 0x00}, + + // m_nSPDCombineWeight + {0x5cc9, 0x80}, {0x5cca, 0x80}, {0x5ccb, 0x80}, {0x5ccc, 0x80}, {0x5ccd, 0x80}, + {0x5cce, 0x80}, {0x5ccf, 0x80}, {0x5cd0, 0x80}, {0x5cd1, 0x80}, {0x5cd2, 0x60}, + {0x5cd3, 0x80}, {0x5cd4, 0x80}, {0x5cd5, 0x80}, {0x5cd6, 0x60}, {0x5cd7, 0x40}, + {0x5cd8, 0x80}, {0x5cd9, 0x80}, {0x5cda, 0x80}, {0x5cdb, 0x40}, {0x5cdc, 0x20}, + {0x5cdd, 0x80}, {0x5cde, 0x80}, {0x5cdf, 0x80}, {0x5ce0, 0x20}, {0x5ce1, 0x00}, + {0x5ce2, 0x80}, {0x5ce3, 0x80}, {0x5ce4, 0x80}, {0x5ce5, 0x00}, {0x5ce6, 0x00}, + + {0x5d74, 0x01}, + {0x5d75, 0x00}, + + {0x5d1f, 0x81}, + {0x5d11, 0x00}, + {0x5d12, 0x10}, + {0x5d13, 0x10}, + {0x5d15, 0x05}, + {0x5d16, 0x05}, + {0x5d17, 0x05}, + {0x5d08, 0x03}, + {0x5d09, 0xb6}, + {0x5d0a, 0x03}, + {0x5d0b, 0xb6}, + {0x5d18, 0x03}, + {0x5d19, 0xb6}, + {0x5d62, 0x01}, + {0x5d40, 0x02}, + {0x5d41, 0x01}, + {0x5d63, 0x1f}, + {0x5d64, 0x00}, + {0x5d65, 0x80}, + {0x5d56, 0x00}, + {0x5d57, 0x20}, + {0x5d58, 0x00}, + {0x5d59, 0x20}, + {0x5d5a, 0x00}, + {0x5d5b, 0x0c}, + {0x5d5c, 0x02}, + {0x5d5d, 0x40}, + {0x5d5e, 0x02}, + {0x5d5f, 0x40}, + {0x5d60, 0x03}, + {0x5d61, 0x40}, + {0x5d4a, 0x02}, + {0x5d4b, 0x40}, + {0x5d4c, 0x02}, + {0x5d4d, 0x40}, + {0x5d4e, 0x02}, + {0x5d4f, 0x40}, + {0x5d50, 0x18}, + {0x5d51, 0x80}, + {0x5d52, 0x18}, + {0x5d53, 0x80}, + {0x5d54, 0x18}, + {0x5d55, 0x80}, + {0x5d46, 0x20}, + {0x5d47, 0x00}, + {0x5d48, 0x22}, + {0x5d49, 0x00}, + {0x5d42, 0x20}, + {0x5d43, 0x00}, + {0x5d44, 0x22}, + {0x5d45, 0x00}, + + {0x5004, 0x1e}, + {0x4221, 0x03}, // this is changed from 1 -> 3 + + // DCG exposure coarse + {0x3501, 0x01}, {0x3502, 0xc8}, + // SPD exposure coarse + {0x3541, 0x01}, {0x3542, 0xc8}, + // VS exposure coarse + {0x35c1, 0x00}, {0x35c2, 0x01}, + + // crc reference + {0x420e, 0x66}, {0x420f, 0x5d}, {0x4210, 0xa8}, {0x4211, 0x55}, + // crc stat check + {0x507a, 0x5f}, {0x507b, 0x46}, + + // watchdog control + {0x4f00, 0x00}, {0x4f01, 0x01}, {0x4f02, 0x80}, {0x4f04, 0x2c}, + + // color balance gains + // blue + {0x5280, 0x06}, {0x5281, 0xCB}, // hcg + {0x5480, 0x06}, {0x5481, 0xCB}, // lcg + {0x5680, 0x06}, {0x5681, 0xCB}, // spd + {0x5880, 0x06}, {0x5881, 0xCB}, // vs + + // green(blue) + {0x5282, 0x04}, {0x5283, 0x00}, + {0x5482, 0x04}, {0x5483, 0x00}, + {0x5682, 0x04}, {0x5683, 0x00}, + {0x5882, 0x04}, {0x5883, 0x00}, + + // green(red) + {0x5284, 0x04}, {0x5285, 0x00}, + {0x5484, 0x04}, {0x5485, 0x00}, + {0x5684, 0x04}, {0x5685, 0x00}, + {0x5884, 0x04}, {0x5885, 0x00}, + + // red + {0x5286, 0x08}, {0x5287, 0xDE}, + {0x5486, 0x08}, {0x5487, 0xDE}, + {0x5686, 0x08}, {0x5687, 0xDE}, + {0x5886, 0x08}, {0x5887, 0xDE}, +}; + +struct i2c_random_wr_payload init_array_ar0231[] = { + {0x301A, 0x0018}, // RESET_REGISTER + + // CLOCK Settings + // input clock is 19.2 / 2 * 0x37 = 528 MHz + // pixclk is 528 / 6 = 88 MHz + // full roll time is 1000/(PIXCLK/(LINE_LENGTH_PCK*FRAME_LENGTH_LINES)) = 39.99 ms + // img roll time is 1000/(PIXCLK/(LINE_LENGTH_PCK*Y_OUTPUT_CONTROL)) = 22.85 ms + {0x302A, 0x0006}, // VT_PIX_CLK_DIV + {0x302C, 0x0001}, // VT_SYS_CLK_DIV + {0x302E, 0x0002}, // PRE_PLL_CLK_DIV + {0x3030, 0x0037}, // PLL_MULTIPLIER + {0x3036, 0x000C}, // OP_PIX_CLK_DIV + {0x3038, 0x0001}, // OP_SYS_CLK_DIV + + // FORMAT + {0x3040, 0xC000}, // READ_MODE + {0x3004, 0x0000}, // X_ADDR_START_ + {0x3008, 0x0787}, // X_ADDR_END_ + {0x3002, 0x0000}, // Y_ADDR_START_ + {0x3006, 0x04B7}, // Y_ADDR_END_ + {0x3032, 0x0000}, // SCALING_MODE + {0x30A2, 0x0001}, // X_ODD_INC_ + {0x30A6, 0x0001}, // Y_ODD_INC_ + {0x3402, 0x0788}, // X_OUTPUT_CONTROL + {0x3404, 0x04B8}, // Y_OUTPUT_CONTROL + {0x3064, 0x1982}, // SMIA_TEST + {0x30BA, 0x11F2}, // DIGITAL_CTRL + + // Enable external trigger and disable GPIO outputs + {0x30CE, 0x0120}, // SLAVE_SH_SYNC_MODE | FRAME_START_MODE + {0x340A, 0xE0}, // GPIO3_INPUT_DISABLE | GPIO2_INPUT_DISABLE | GPIO1_INPUT_DISABLE + {0x340C, 0x802}, // GPIO_HIDRV_EN | GPIO0_ISEL=2 + + // Readout timing + {0x300C, 0x0672}, // LINE_LENGTH_PCK (valid for 3-exposure HDR) + {0x300A, 0x0855}, // FRAME_LENGTH_LINES + {0x3042, 0x0000}, // EXTRA_DELAY + + // Readout Settings + {0x31AE, 0x0204}, // SERIAL_FORMAT, 4-lane MIPI + {0x31AC, 0x0C0C}, // DATA_FORMAT_BITS, 12 -> 12 + {0x3342, 0x1212}, // MIPI_F1_PDT_EDT + {0x3346, 0x1212}, // MIPI_F2_PDT_EDT + {0x334A, 0x1212}, // MIPI_F3_PDT_EDT + {0x334E, 0x1212}, // MIPI_F4_PDT_EDT + {0x3344, 0x0011}, // MIPI_F1_VDT_VC + {0x3348, 0x0111}, // MIPI_F2_VDT_VC + {0x334C, 0x0211}, // MIPI_F3_VDT_VC + {0x3350, 0x0311}, // MIPI_F4_VDT_VC + {0x31B0, 0x0053}, // FRAME_PREAMBLE + {0x31B2, 0x003B}, // LINE_PREAMBLE + {0x301A, 0x001C}, // RESET_REGISTER + + // Noise Corrections + {0x3092, 0x0C24}, // ROW_NOISE_CONTROL + {0x337A, 0x0C80}, // DBLC_SCALE0 + {0x3370, 0x03B1}, // DBLC + {0x3044, 0x0400}, // DARK_CONTROL + + // Enable temperature sensor + {0x30B4, 0x0007}, // TEMPSENS0_CTRL_REG + {0x30B8, 0x0007}, // TEMPSENS1_CTRL_REG + + // Enable dead pixel correction using + // the 1D line correction scheme + {0x31E0, 0x0003}, + + // HDR Settings + {0x3082, 0x0004}, // OPERATION_MODE_CTRL + {0x3238, 0x0444}, // EXPOSURE_RATIO + + {0x1008, 0x0361}, // FINE_INTEGRATION_TIME_MIN + {0x100C, 0x0589}, // FINE_INTEGRATION_TIME2_MIN + {0x100E, 0x07B1}, // FINE_INTEGRATION_TIME3_MIN + {0x1010, 0x0139}, // FINE_INTEGRATION_TIME4_MIN + + // TODO: do these have to be lower than LINE_LENGTH_PCK? + {0x3014, 0x08CB}, // FINE_INTEGRATION_TIME_ + {0x321E, 0x0894}, // FINE_INTEGRATION_TIME2 + + {0x31D0, 0x0000}, // COMPANDING, no good in 10 bit? + {0x33DA, 0x0000}, // COMPANDING + {0x318E, 0x0200}, // PRE_HDR_GAIN_EN + + // DLO Settings + {0x3100, 0x4000}, // DLO_CONTROL0 + {0x3280, 0x0CCC}, // T1 G1 + {0x3282, 0x0CCC}, // T1 R + {0x3284, 0x0CCC}, // T1 B + {0x3286, 0x0CCC}, // T1 G2 + {0x3288, 0x0FA0}, // T2 G1 + {0x328A, 0x0FA0}, // T2 R + {0x328C, 0x0FA0}, // T2 B + {0x328E, 0x0FA0}, // T2 G2 + + // Initial Gains + {0x3022, 0x0001}, // GROUPED_PARAMETER_HOLD_ + {0x3366, 0xFF77}, // ANALOG_GAIN (1x) + + {0x3060, 0x3333}, // ANALOG_COLOR_GAIN + + {0x3362, 0x0000}, // DC GAIN + + {0x305A, 0x00F8}, // red gain + {0x3058, 0x0122}, // blue gain + {0x3056, 0x009A}, // g1 gain + {0x305C, 0x009A}, // g2 gain + + {0x3022, 0x0000}, // GROUPED_PARAMETER_HOLD_ + + // Initial Integration Time + {0x3012, 0x0005}, +}; diff --git a/selfdrive/camerad/imgproc/conv.cl b/system/camerad/imgproc/conv.cl similarity index 100% rename from selfdrive/camerad/imgproc/conv.cl rename to system/camerad/imgproc/conv.cl diff --git a/selfdrive/camerad/imgproc/pool.cl b/system/camerad/imgproc/pool.cl similarity index 100% rename from selfdrive/camerad/imgproc/pool.cl rename to system/camerad/imgproc/pool.cl diff --git a/selfdrive/camerad/imgproc/utils.cc b/system/camerad/imgproc/utils.cc similarity index 98% rename from selfdrive/camerad/imgproc/utils.cc rename to system/camerad/imgproc/utils.cc index a88b8f4bb1..a7bbeb9e86 100644 --- a/selfdrive/camerad/imgproc/utils.cc +++ b/system/camerad/imgproc/utils.cc @@ -1,4 +1,4 @@ -#include "selfdrive/camerad/imgproc/utils.h" +#include "system/camerad/imgproc/utils.h" #include #include diff --git a/selfdrive/camerad/imgproc/utils.h b/system/camerad/imgproc/utils.h similarity index 95% rename from selfdrive/camerad/imgproc/utils.h rename to system/camerad/imgproc/utils.h index b735975b3e..94323b15c5 100644 --- a/selfdrive/camerad/imgproc/utils.h +++ b/system/camerad/imgproc/utils.h @@ -4,7 +4,7 @@ #include #include -#include "selfdrive/common/clutil.h" +#include "common/clutil.h" #define NUM_SEGMENTS_X 8 #define NUM_SEGMENTS_Y 6 diff --git a/selfdrive/camerad/include/media/cam_cpas.h b/system/camerad/include/media/cam_cpas.h similarity index 100% rename from selfdrive/camerad/include/media/cam_cpas.h rename to system/camerad/include/media/cam_cpas.h diff --git a/selfdrive/camerad/include/media/cam_defs.h b/system/camerad/include/media/cam_defs.h similarity index 100% rename from selfdrive/camerad/include/media/cam_defs.h rename to system/camerad/include/media/cam_defs.h diff --git a/selfdrive/camerad/include/media/cam_fd.h b/system/camerad/include/media/cam_fd.h similarity index 100% rename from selfdrive/camerad/include/media/cam_fd.h rename to system/camerad/include/media/cam_fd.h diff --git a/selfdrive/camerad/include/media/cam_icp.h b/system/camerad/include/media/cam_icp.h similarity index 100% rename from selfdrive/camerad/include/media/cam_icp.h rename to system/camerad/include/media/cam_icp.h diff --git a/selfdrive/camerad/include/media/cam_isp.h b/system/camerad/include/media/cam_isp.h similarity index 100% rename from selfdrive/camerad/include/media/cam_isp.h rename to system/camerad/include/media/cam_isp.h diff --git a/selfdrive/camerad/include/media/cam_isp_ife.h b/system/camerad/include/media/cam_isp_ife.h similarity index 100% rename from selfdrive/camerad/include/media/cam_isp_ife.h rename to system/camerad/include/media/cam_isp_ife.h diff --git a/selfdrive/camerad/include/media/cam_isp_vfe.h b/system/camerad/include/media/cam_isp_vfe.h similarity index 100% rename from selfdrive/camerad/include/media/cam_isp_vfe.h rename to system/camerad/include/media/cam_isp_vfe.h diff --git a/selfdrive/camerad/include/media/cam_jpeg.h b/system/camerad/include/media/cam_jpeg.h similarity index 100% rename from selfdrive/camerad/include/media/cam_jpeg.h rename to system/camerad/include/media/cam_jpeg.h diff --git a/selfdrive/camerad/include/media/cam_lrme.h b/system/camerad/include/media/cam_lrme.h similarity index 100% rename from selfdrive/camerad/include/media/cam_lrme.h rename to system/camerad/include/media/cam_lrme.h diff --git a/selfdrive/camerad/include/media/cam_req_mgr.h b/system/camerad/include/media/cam_req_mgr.h similarity index 100% rename from selfdrive/camerad/include/media/cam_req_mgr.h rename to system/camerad/include/media/cam_req_mgr.h diff --git a/selfdrive/camerad/include/media/cam_sensor.h b/system/camerad/include/media/cam_sensor.h similarity index 100% rename from selfdrive/camerad/include/media/cam_sensor.h rename to system/camerad/include/media/cam_sensor.h diff --git a/selfdrive/camerad/include/media/cam_sensor_cmn_header.h b/system/camerad/include/media/cam_sensor_cmn_header.h similarity index 100% rename from selfdrive/camerad/include/media/cam_sensor_cmn_header.h rename to system/camerad/include/media/cam_sensor_cmn_header.h diff --git a/selfdrive/camerad/include/media/cam_sync.h b/system/camerad/include/media/cam_sync.h similarity index 100% rename from selfdrive/camerad/include/media/cam_sync.h rename to system/camerad/include/media/cam_sync.h diff --git a/selfdrive/camerad/include/msm_cam_sensor.h b/system/camerad/include/msm_cam_sensor.h similarity index 100% rename from selfdrive/camerad/include/msm_cam_sensor.h rename to system/camerad/include/msm_cam_sensor.h diff --git a/selfdrive/camerad/include/msm_camsensor_sdk.h b/system/camerad/include/msm_camsensor_sdk.h similarity index 100% rename from selfdrive/camerad/include/msm_camsensor_sdk.h rename to system/camerad/include/msm_camsensor_sdk.h diff --git a/selfdrive/camerad/include/msmb_camera.h b/system/camerad/include/msmb_camera.h similarity index 100% rename from selfdrive/camerad/include/msmb_camera.h rename to system/camerad/include/msmb_camera.h diff --git a/selfdrive/camerad/include/msmb_isp.h b/system/camerad/include/msmb_isp.h similarity index 100% rename from selfdrive/camerad/include/msmb_isp.h rename to system/camerad/include/msmb_isp.h diff --git a/selfdrive/camerad/include/msmb_ispif.h b/system/camerad/include/msmb_ispif.h similarity index 100% rename from selfdrive/camerad/include/msmb_ispif.h rename to system/camerad/include/msmb_ispif.h diff --git a/system/camerad/main.cc b/system/camerad/main.cc new file mode 100644 index 0000000000..35a3329f30 --- /dev/null +++ b/system/camerad/main.cc @@ -0,0 +1,23 @@ +#include "system/camerad/cameras/camera_common.h" + +#include + +#include "common/params.h" +#include "common/util.h" +#include "system/hardware/hw.h" + +int main(int argc, char *argv[]) { + if (Hardware::PC()) { + printf("camerad is not meant to run on PC\n"); + return 0; + } + + int ret; + ret = util::set_realtime_priority(53); + assert(ret == 0); + ret = util::set_core_affinity({6}); + assert(ret == 0 || Params().getBool("IsOffroad")); // failure ok while offroad due to offlining cores + + camerad_thread(); + return 0; +} diff --git a/system/camerad/snapshot/__init__.py b/system/camerad/snapshot/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/selfdrive/camerad/snapshot/snapshot.py b/system/camerad/snapshot/snapshot.py similarity index 62% rename from selfdrive/camerad/snapshot/snapshot.py rename to system/camerad/snapshot/snapshot.py index 506064de3d..48dfc9e02d 100755 --- a/selfdrive/camerad/snapshot/snapshot.py +++ b/system/camerad/snapshot/snapshot.py @@ -4,22 +4,21 @@ import time import numpy as np from PIL import Image -from typing import List import cereal.messaging as messaging -from cereal.visionipc.visionipc_pyx import VisionIpcClient, VisionStreamType # pylint: disable=no-name-in-module, import-error +from cereal.visionipc import VisionIpcClient, VisionStreamType from common.params import Params from common.realtime import DT_MDL -from selfdrive.hardware import TICI, PC +from system.hardware import PC from selfdrive.controls.lib.alertmanager import set_offroad_alert from selfdrive.manager.process_config import managed_processes -LM_THRESH = 120 # defined in selfdrive/camerad/imgproc/utils.h +LM_THRESH = 120 # defined in system/camerad/imgproc/utils.h VISION_STREAMS = { - "roadCameraState": VisionStreamType.VISION_STREAM_RGB_BACK, - "driverCameraState": VisionStreamType.VISION_STREAM_RGB_FRONT, - "wideRoadCameraState": VisionStreamType.VISION_STREAM_RGB_WIDE, + "roadCameraState": VisionStreamType.VISION_STREAM_ROAD, + "driverCameraState": VisionStreamType.VISION_STREAM_DRIVER, + "wideRoadCameraState": VisionStreamType.VISION_STREAM_WIDE_ROAD, } @@ -28,19 +27,31 @@ def jpeg_write(fn, dat): img.save(fn, "JPEG") -def extract_image(buf, w, h, stride): - img = np.hstack([buf[i * stride:i * stride + 3 * w] for i in range(h)]) - b = img[::3].reshape(h, w) - g = img[1::3].reshape(h, w) - r = img[2::3].reshape(h, w) - return np.dstack([r, g, b]) +def yuv_to_rgb(y, u, v): + ul = np.repeat(np.repeat(u, 2).reshape(u.shape[0], y.shape[1]), 2, axis=0).reshape(y.shape) + vl = np.repeat(np.repeat(v, 2).reshape(v.shape[0], y.shape[1]), 2, axis=0).reshape(y.shape) + yuv = np.dstack((y, ul, vl)).astype(np.int16) + yuv[:, :, 1:] -= 128 -def rois_in_focus(lapres: List[float]) -> float: - return sum(1. / len(lapres) for sharpness in lapres if sharpness >= LM_THRESH) + m = np.array([ + [1.00000, 1.00000, 1.00000], + [0.00000, -0.39465, 2.03211], + [1.13983, -0.58060, 0.00000], + ]) + rgb = np.dot(yuv, m).clip(0, 255) + return rgb.astype(np.uint8) -def get_snapshots(frame="roadCameraState", front_frame="driverCameraState", focus_perc_threshold=0.): +def extract_image(buf, w, h, stride, uv_offset): + y = np.array(buf[:uv_offset], dtype=np.uint8).reshape((-1, stride))[:h, :w] + u = np.array(buf[uv_offset::2], dtype=np.uint8).reshape((-1, stride//2))[:h//2, :w//2] + v = np.array(buf[uv_offset+1::2], dtype=np.uint8).reshape((-1, stride//2))[:h//2, :w//2] + + return yuv_to_rgb(y, u, v) + + +def get_snapshots(frame="roadCameraState", front_frame="driverCameraState"): sockets = [s for s in (frame, front_frame) if s is not None] sm = messaging.SubMaster(sockets) vipc_clients = {s: VisionIpcClient("camerad", VISION_STREAMS[s], True) for s in sockets} @@ -52,21 +63,14 @@ def get_snapshots(frame="roadCameraState", front_frame="driverCameraState", focu for client in vipc_clients.values(): client.connect(True) - # wait for focus - start_t = time.monotonic() - while time.monotonic() - start_t < 10: - sm.update(100) - if min(sm.rcv_frame.values()) > 1 and rois_in_focus(sm[frame].sharpnessScore) >= focus_perc_threshold: - break - # grab images rear, front = None, None if frame is not None: c = vipc_clients[frame] - rear = extract_image(c.recv(), c.width, c.height, c.stride) + rear = extract_image(c.recv(), c.width, c.height, c.stride, c.uv_offset) if front_frame is not None: c = vipc_clients[front_frame] - front = extract_image(c.recv(), c.width, c.height, c.stride) + front = extract_image(c.recv(), c.width, c.height, c.stride, c.uv_offset) return rear, front @@ -87,7 +91,7 @@ def snapshot(): subprocess.check_call(["pgrep", "camerad"]) print("Camerad already running") params.put_bool("IsTakingSnapshot", False) - params.delete("Offroad_IsTakingSnapshot") + params.remove("Offroad_IsTakingSnapshot") return None, None except subprocess.CalledProcessError: pass @@ -97,11 +101,9 @@ def snapshot(): if not PC: managed_processes['camerad'].start() - frame = "wideRoadCameraState" if TICI else "roadCameraState" + frame = "wideRoadCameraState" front_frame = "driverCameraState" if front_camera_allowed else None - focus_perc_threshold = 0. if TICI else 10 / 12. - - rear, front = get_snapshots(frame, front_frame, focus_perc_threshold) + rear, front = get_snapshots(frame, front_frame) finally: managed_processes['camerad'].stop() params.put_bool("IsTakingSnapshot", False) diff --git a/selfdrive/camerad/test/.gitignore b/system/camerad/test/.gitignore similarity index 100% rename from selfdrive/camerad/test/.gitignore rename to system/camerad/test/.gitignore diff --git a/selfdrive/camerad/test/ae_gray_test.cc b/system/camerad/test/ae_gray_test.cc similarity index 83% rename from selfdrive/camerad/test/ae_gray_test.cc rename to system/camerad/test/ae_gray_test.cc index 358d93d759..aabd7534ee 100644 --- a/selfdrive/camerad/test/ae_gray_test.cc +++ b/system/camerad/test/ae_gray_test.cc @@ -7,14 +7,8 @@ #include #include -#include "selfdrive/common/util.h" -#include "selfdrive/camerad/cameras/camera_common.h" - -// needed by camera_common.cc -void camera_autoexposure(CameraState *s, float grey_frac) {} -void cameras_init(VisionIpcServer *v, MultiCameraState *s, cl_device_id device_id, cl_context ctx) {} -void cameras_open(MultiCameraState *s) {} -void cameras_run(MultiCameraState *s) {} +#include "common/util.h" +#include "system/camerad/cameras/camera_common.h" int main() { // set up fake camerabuf diff --git a/selfdrive/camerad/test/ae_gray_test.h b/system/camerad/test/ae_gray_test.h similarity index 100% rename from selfdrive/camerad/test/ae_gray_test.h rename to system/camerad/test/ae_gray_test.h diff --git a/selfdrive/camerad/test/check_skips.py b/system/camerad/test/check_skips.py similarity index 100% rename from selfdrive/camerad/test/check_skips.py rename to system/camerad/test/check_skips.py diff --git a/selfdrive/camerad/test/frame_test.py b/system/camerad/test/frame_test.py similarity index 100% rename from selfdrive/camerad/test/frame_test.py rename to system/camerad/test/frame_test.py diff --git a/selfdrive/camerad/test/get_thumbnails_for_segment.py b/system/camerad/test/get_thumbnails_for_segment.py similarity index 65% rename from selfdrive/camerad/test/get_thumbnails_for_segment.py rename to system/camerad/test/get_thumbnails_for_segment.py index ab9a7b308d..898377b111 100755 --- a/selfdrive/camerad/test/get_thumbnails_for_segment.py +++ b/system/camerad/test/get_thumbnails_for_segment.py @@ -24,9 +24,9 @@ if __name__ == "__main__": lr = list(LogReader(path)) for msg in tqdm(lr): - if msg.which() == 'thumbnail': - with open(os.path.join(out_path, f"{msg.thumbnail.frameId}.jpg"), 'wb') as f: - f.write(msg.thumbnail.thumbnail) - elif msg.which() == 'navThumbnail': - with open(os.path.join(out_path, f"nav_{msg.navThumbnail.frameId}.jpg"), 'wb') as f: - f.write(msg.navThumbnail.thumbnail) + if msg.which() == 'thumbnail': + with open(os.path.join(out_path, f"{msg.thumbnail.frameId}.jpg"), 'wb') as f: + f.write(msg.thumbnail.thumbnail) + elif msg.which() == 'navThumbnail': + with open(os.path.join(out_path, f"nav_{msg.navThumbnail.frameId}.jpg"), 'wb') as f: + f.write(msg.navThumbnail.thumbnail) diff --git a/selfdrive/camerad/test/stress_restart.sh b/system/camerad/test/stress_restart.sh similarity index 100% rename from selfdrive/camerad/test/stress_restart.sh rename to system/camerad/test/stress_restart.sh diff --git a/system/camerad/test/test_camerad.py b/system/camerad/test/test_camerad.py new file mode 100755 index 0000000000..6c2ef1c7bc --- /dev/null +++ b/system/camerad/test/test_camerad.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +import time +import unittest +from collections import defaultdict + +import cereal.messaging as messaging +from cereal import log +from cereal.services import service_list +from selfdrive.manager.process_config import managed_processes +from system.hardware import TICI + +TEST_TIMESPAN = 30 +LAG_FRAME_TOLERANCE = {log.FrameData.ImageSensor.ar0321: 0.5, # ARs use synced pulses for frame starts + log.FrameData.ImageSensor.ox03c10: 1.0} # OXs react to out-of-sync at next frame + +CAMERAS = ('roadCameraState', 'driverCameraState', 'wideRoadCameraState') + + +class TestCamerad(unittest.TestCase): + @classmethod + def setUpClass(cls): + if not TICI: + raise unittest.SkipTest + + # run camerad and record logs + managed_processes['camerad'].start() + time.sleep(3) + socks = {c: messaging.sub_sock(c, conflate=False, timeout=100) for c in CAMERAS} + + cls.logs = defaultdict(list) + start_time = time.monotonic() + while time.monotonic()- start_time < TEST_TIMESPAN: + for cam, s in socks.items(): + cls.logs[cam] += messaging.drain_sock(s) + time.sleep(0.2) + managed_processes['camerad'].stop() + + cls.log_by_frame_id = defaultdict(list) + for cam, msgs in cls.logs.items(): + expected_frames = service_list[cam].frequency * TEST_TIMESPAN + assert expected_frames*0.95 < len(msgs) < expected_frames*1.05, f"unexpected frame count {cam}: {expected_frames=}, got {len(msgs)}" + + for m in msgs: + cls.log_by_frame_id[getattr(m, m.which()).frameId].append(m) + + # strip beginning and end + for _ in range(3): + mn, mx = min(cls.log_by_frame_id.keys()), max(cls.log_by_frame_id.keys()) + del cls.log_by_frame_id[mn] + del cls.log_by_frame_id[mx] + + @classmethod + def tearDownClass(cls): + managed_processes['camerad'].stop() + + def test_frame_skips(self): + skips = {} + frame_ids = self.log_by_frame_id.keys() + for frame_id in range(min(frame_ids), max(frame_ids)): + seen_cams = [msg.which() for msg in self.log_by_frame_id[frame_id]] + skip_cams = set(CAMERAS) - set(seen_cams) + if len(skip_cams): + skips[frame_id] = skip_cams + assert len(skips) == 0, f"Found frame skips, missing cameras for the following frames: {skips}" + + def test_frame_sync(self): + sensor_type = [getattr(msgs[0], msgs[0].which()).sensor for frame_id, msgs in self.log_by_frame_id.items()][0].raw + frame_times = {frame_id: [getattr(m, m.which()).timestampSof for m in msgs] for frame_id, msgs in self.log_by_frame_id.items()} + diffs = {frame_id: (max(ts) - min(ts))/1e6 for frame_id, ts in frame_times.items()} + + def get_desc(fid, diff): + cam_times = [(m.which(), getattr(m, m.which()).timestampSof/1e6) for m in self.log_by_frame_id[fid]] + return (diff, cam_times) + laggy_frames = {k: get_desc(k, v) for k, v in diffs.items() if v > LAG_FRAME_TOLERANCE[sensor_type]} + + def in_tol(diff): + return 50 - LAG_FRAME_TOLERANCE[sensor_type] < diff and diff < 50 + LAG_FRAME_TOLERANCE[sensor_type] + if len(laggy_frames) != 0 and all( in_tol(laggy_frames[lf][0]) for lf in laggy_frames): + print("TODO: handle camera out of sync") + else: + assert len(laggy_frames) == 0, f"Frames not synced properly: {laggy_frames=}" + +if __name__ == "__main__": + unittest.main() diff --git a/selfdrive/camerad/test/test_exposure.py b/system/camerad/test/test_exposure.py similarity index 92% rename from selfdrive/camerad/test/test_exposure.py rename to system/camerad/test/test_exposure.py index 6ed69627b5..8cce7e7ffa 100755 --- a/selfdrive/camerad/test/test_exposure.py +++ b/system/camerad/test/test_exposure.py @@ -4,9 +4,9 @@ import unittest import numpy as np from selfdrive.test.helpers import with_processes -from selfdrive.camerad.snapshot.snapshot import get_snapshots +from system.camerad.snapshot.snapshot import get_snapshots -from selfdrive.hardware import EON, TICI +from system.hardware import TICI TEST_TIME = 45 REPEAT = 5 @@ -14,7 +14,7 @@ REPEAT = 5 class TestCamerad(unittest.TestCase): @classmethod def setUpClass(cls): - if not (EON or TICI): + if not TICI: raise unittest.SkipTest def _numpy_rgb2gray(self, im): diff --git a/selfdrive/clocksd/.gitignore b/system/clocksd/.gitignore similarity index 100% rename from selfdrive/clocksd/.gitignore rename to system/clocksd/.gitignore diff --git a/selfdrive/clocksd/SConscript b/system/clocksd/SConscript similarity index 100% rename from selfdrive/clocksd/SConscript rename to system/clocksd/SConscript diff --git a/selfdrive/clocksd/clocksd.cc b/system/clocksd/clocksd.cc similarity index 80% rename from selfdrive/clocksd/clocksd.cc rename to system/clocksd/clocksd.cc index c24ffa41d9..a5912cf51a 100644 --- a/selfdrive/clocksd/clocksd.cc +++ b/system/clocksd/clocksd.cc @@ -16,21 +16,11 @@ #include #include "cereal/messaging/messaging.h" -#include "selfdrive/common/timing.h" -#include "selfdrive/common/util.h" +#include "common/timing.h" +#include "common/util.h" ExitHandler do_exit; -#ifdef QCOM -namespace { - int64_t arm_cntpct() { - int64_t v; - asm volatile("mrs %0, cntpct_el0" : "=r"(v)); - return v; - } -} -#endif - int main() { setpriority(PRIO_PROCESS, 0, -13); PubMaster pm({"clocks"}); @@ -65,10 +55,6 @@ int main() { uint64_t monotonic_raw = nanos_monotonic_raw(); uint64_t wall_time = nanos_since_epoch(); -#ifdef QCOM - uint64_t modem_uptime_v = arm_cntpct() / 19200ULL; // 19.2 mhz clock -#endif - MessageBuilder msg; auto clocks = msg.initEvent().initClocks(); @@ -76,9 +62,6 @@ int main() { clocks.setMonotonicNanos(monotonic); clocks.setMonotonicRawNanos(monotonic_raw); clocks.setWallTimeNanos(wall_time); -#ifdef QCOM - clocks.setModemUptimeMillis(modem_uptime_v); -#endif pm.send("clocks", msg); } diff --git a/selfdrive/hardware/.gitignore b/system/hardware/.gitignore similarity index 100% rename from selfdrive/hardware/.gitignore rename to system/hardware/.gitignore diff --git a/system/hardware/__init__.py b/system/hardware/__init__.py new file mode 100644 index 0000000000..77bb0e5e2a --- /dev/null +++ b/system/hardware/__init__.py @@ -0,0 +1,16 @@ +import os +from typing import cast + +from system.hardware.base import HardwareBase +from system.hardware.tici.hardware import Tici +from system.hardware.pc.hardware import Pc + +TICI = os.path.isfile('/TICI') +AGNOS = os.path.isfile('/AGNOS') +PC = not TICI + + +if TICI: + HARDWARE = cast(HardwareBase, Tici()) +else: + HARDWARE = cast(HardwareBase, Pc()) diff --git a/selfdrive/hardware/base.h b/system/hardware/base.h similarity index 61% rename from selfdrive/hardware/base.h rename to system/hardware/base.h index 05e55cc034..f6e0b42d73 100644 --- a/selfdrive/hardware/base.h +++ b/system/hardware/base.h @@ -2,6 +2,7 @@ #include #include +#include "cereal/messaging/messaging.h" // no-op base hw class class HardwareNone { @@ -10,16 +11,21 @@ public: static constexpr float MIN_VOLUME = 0.2; static std::string get_os_version() { return ""; } + static std::string get_name() { return ""; }; + static cereal::InitData::DeviceType get_device_type() { return cereal::InitData::DeviceType::UNKNOWN; }; + static int get_voltage() { return 0; }; + static int get_current() { return 0; }; static void reboot() {} static void poweroff() {} static void set_brightness(int percent) {} static void set_display_power(bool on) {} + static void set_volume(float volume) {} static bool get_ssh_enabled() { return false; } static void set_ssh_enabled(bool enabled) {} static bool PC() { return false; } - static bool EON() { return false; } static bool TICI() { return false; } + static bool AGNOS() { return false; } }; diff --git a/selfdrive/hardware/base.py b/system/hardware/base.py similarity index 81% rename from selfdrive/hardware/base.py rename to system/hardware/base.py index b551138ce3..31df1babe0 100644 --- a/selfdrive/hardware/base.py +++ b/system/hardware/base.py @@ -2,7 +2,11 @@ from abc import abstractmethod, ABC from collections import namedtuple from typing import Dict +from cereal import log + ThermalConfig = namedtuple('ThermalConfig', ['cpu', 'gpu', 'mem', 'bat', 'ambient', 'pmic']) +NetworkType = log.DeviceState.NetworkType + class HardwareBase(ABC): @staticmethod @@ -40,7 +44,7 @@ class HardwareBase(ABC): pass @abstractmethod - def get_imei(self, slot): + def get_imei(self, slot) -> str: pass @abstractmethod @@ -67,40 +71,19 @@ class HardwareBase(ABC): def get_network_strength(self, network_type): pass + def get_network_metered(self, network_type) -> bool: + return network_type not in (NetworkType.none, NetworkType.wifi, NetworkType.ethernet) + @staticmethod def set_bandwidth_limit(upload_speed_kbps: int, download_speed_kbps: int) -> None: pass @abstractmethod - def get_battery_capacity(self): - pass - - @abstractmethod - def get_battery_status(self): - pass - - @abstractmethod - def get_battery_current(self): - pass - - @abstractmethod - def get_battery_voltage(self): - pass - - @abstractmethod - def get_battery_charging(self): - pass - - @abstractmethod - def set_battery_charging(self, on): - pass - - @abstractmethod - def get_usb_present(self): + def get_current_power_draw(self): pass @abstractmethod - def get_current_power_draw(self): + def get_som_power_draw(self): pass @abstractmethod @@ -127,9 +110,11 @@ class HardwareBase(ABC): def get_gpu_usage_percent(self): pass - @abstractmethod def get_modem_version(self): - pass + return None + + def get_modem_nv(self): + return None @abstractmethod def get_modem_temperatures(self): @@ -143,6 +128,18 @@ class HardwareBase(ABC): def initialize_hardware(self): pass + def configure_modem(self): + pass + @abstractmethod def get_networks(self): pass + + def reset_internal_panda(self): + pass + + def recover_internal_panda(self): + pass + + def get_modem_data_usage(self): + return -1, -1 diff --git a/selfdrive/hardware/hw.h b/system/hardware/hw.h similarity index 57% rename from selfdrive/hardware/hw.h rename to system/hardware/hw.h index f18ede01ec..5599e79186 100644 --- a/selfdrive/hardware/hw.h +++ b/system/hardware/hw.h @@ -1,21 +1,13 @@ #pragma once -#include "selfdrive/hardware/base.h" -#include "selfdrive/common/util.h" +#include "system/hardware/base.h" +#include "common/util.h" -#ifdef QCOM -#include "selfdrive/hardware/eon/hardware.h" -#define Hardware HardwareEon -#elif QCOM2 -#include "selfdrive/hardware/tici/hardware.h" +#if QCOM2 +#include "system/hardware/tici/hardware.h" #define Hardware HardwareTici #else -class HardwarePC : public HardwareNone { -public: - static std::string get_os_version() { return "openpilot for PC"; } - static bool PC() { return true; } - static bool TICI() { return util::getenv("TICI", 0) == 1; } -}; +#include "system/hardware/pc/hardware.h" #define Hardware HardwarePC #endif diff --git a/system/hardware/pc/__init__.py b/system/hardware/pc/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/system/hardware/pc/hardware.h b/system/hardware/pc/hardware.h new file mode 100644 index 0000000000..529b4bfe9d --- /dev/null +++ b/system/hardware/pc/hardware.h @@ -0,0 +1,21 @@ +#pragma once + +#include "system/hardware/base.h" + +class HardwarePC : public HardwareNone { +public: + static std::string get_os_version() { return "openpilot for PC"; } + static std::string get_name() { return "pc"; }; + static cereal::InitData::DeviceType get_device_type() { return cereal::InitData::DeviceType::PC; }; + static bool PC() { return true; } + static bool TICI() { return util::getenv("TICI", 0) == 1; } + static bool AGNOS() { return util::getenv("TICI", 0) == 1; } + + static void set_volume(float volume) { + volume = util::map_val(volume, 0.f, 1.f, MIN_VOLUME, MAX_VOLUME); + + char volume_str[6]; + snprintf(volume_str, sizeof(volume_str), "%.3f", volume); + std::system(("pactl set-sink-volume @DEFAULT_SINK@ " + std::string(volume_str)).c_str()); + } +}; diff --git a/selfdrive/hardware/pc/hardware.py b/system/hardware/pc/hardware.py similarity index 78% rename from selfdrive/hardware/pc/hardware.py rename to system/hardware/pc/hardware.py index 8231bbc2f9..564f9e483a 100644 --- a/selfdrive/hardware/pc/hardware.py +++ b/system/hardware/pc/hardware.py @@ -1,7 +1,7 @@ import random from cereal import log -from selfdrive.hardware.base import HardwareBase, ThermalConfig +from system.hardware.base import HardwareBase, ThermalConfig NetworkType = log.DeviceState.NetworkType NetworkStrength = log.DeviceState.NetworkStrength @@ -50,28 +50,10 @@ class Pc(HardwareBase): def get_network_strength(self, network_type): return NetworkStrength.unknown - def get_battery_capacity(self): - return 100 - - def get_battery_status(self): - return "" - - def get_battery_current(self): - return 0 - - def get_battery_voltage(self): + def get_current_power_draw(self): return 0 - def get_battery_charging(self): - return True - - def set_battery_charging(self, on): - pass - - def get_usb_present(self): - return False - - def get_current_power_draw(self): + def get_som_power_draw(self): return 0 def shutdown(self): @@ -92,9 +74,6 @@ class Pc(HardwareBase): def get_gpu_usage_percent(self): return 0 - def get_modem_version(self): - return None - def get_modem_temperatures(self): return [] diff --git a/system/hardware/tici/__init__.py b/system/hardware/tici/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/selfdrive/hardware/tici/agnos.json b/system/hardware/tici/agnos.json similarity index 73% rename from selfdrive/hardware/tici/agnos.json rename to system/hardware/tici/agnos.json index 6674ddaa5b..7876b1af1f 100644 --- a/selfdrive/hardware/tici/agnos.json +++ b/system/hardware/tici/agnos.json @@ -1,10 +1,10 @@ [ { "name": "boot", - "url": "https://commadist.azureedge.net/agnosupdate/boot-0a86272196cb54607f8ba082f412fed4607baaf6ce3eb8dc8e950b4a1d763954.img.xz", - "hash": "0a86272196cb54607f8ba082f412fed4607baaf6ce3eb8dc8e950b4a1d763954", - "hash_raw": "0a86272196cb54607f8ba082f412fed4607baaf6ce3eb8dc8e950b4a1d763954", - "size": 14776320, + "url": "https://commadist.azureedge.net/agnosupdate/boot-72662ec5d586c7a22659a1c8b140932d5472914176020fe76ba4204edbbb214a.img.xz", + "hash": "72662ec5d586c7a22659a1c8b140932d5472914176020fe76ba4204edbbb214a", + "hash_raw": "72662ec5d586c7a22659a1c8b140932d5472914176020fe76ba4204edbbb214a", + "size": 14780416, "sparse": false, "full_check": true, "has_ab": true @@ -41,9 +41,9 @@ }, { "name": "system", - "url": "https://commadist.azureedge.net/agnosupdate/system-9b0b534ed0c35c25850dbb73d3f052611f2e2c9db32410edc25d75fbcfc6c15e.img.xz", - "hash": "b1f622f00037bbdb28c0a6016c0e42fa7f87e99591ff2417c757a67ff559b526", - "hash_raw": "9b0b534ed0c35c25850dbb73d3f052611f2e2c9db32410edc25d75fbcfc6c15e", + "url": "https://commadist.azureedge.net/agnosupdate/system-9efdc9368f05e06008a7a1dbbee21b564e89988dc94d6ddee3a3a88e42268f0e.img.xz", + "hash": "48209ce7e8cc2fff4ec024f0cd82fc2e3e097b5c0629be2b292acf64e6701449", + "hash_raw": "9efdc9368f05e06008a7a1dbbee21b564e89988dc94d6ddee3a3a88e42268f0e", "size": 10737418240, "sparse": true, "full_check": false, diff --git a/selfdrive/hardware/tici/agnos.py b/system/hardware/tici/agnos.py similarity index 67% rename from selfdrive/hardware/tici/agnos.py rename to system/hardware/tici/agnos.py index a28b13ac4a..5f446a8e90 100755 --- a/selfdrive/hardware/tici/agnos.py +++ b/system/hardware/tici/agnos.py @@ -1,22 +1,26 @@ #!/usr/bin/env python3 +import hashlib import json import lzma -import hashlib -import requests +import os import struct import subprocess import time -import os -from typing import Generator +from typing import Dict, Generator, List, Tuple, Union + +import requests + +import system.hardware.tici.casync as casync SPARSE_CHUNK_FMT = struct.Struct('H2xI4x') +CAIBX_URL = "https://commadist.azureedge.net/agnosupdate/" class StreamingDecompressor: def __init__(self, url: str) -> None: self.buf = b"" - self.req = requests.get(url, stream=True, headers={'Accept-Encoding': None}) + self.req = requests.get(url, stream=True, headers={'Accept-Encoding': None}, timeout=60) # type: ignore self.it = self.req.iter_content(chunk_size=1024 * 1024) self.decompressor = lzma.LZMADecompressor(format=lzma.FORMAT_AUTO) self.eof = False @@ -74,6 +78,7 @@ def unsparsify(f: StreamingDecompressor) -> Generator[bytes, None, None]: else: raise Exception("Unhandled sparse chunk type") + # noop wrapper with same API as unsparsify() for non sparse images def noop(f: StreamingDecompressor) -> Generator[bytes, None, None]: while not f.eof: @@ -99,26 +104,39 @@ def get_partition_path(target_slot_number: int, partition: dict) -> str: return path -def verify_partition(target_slot_number: int, partition: dict) -> bool: - full_check = partition['full_check'] - path = get_partition_path(target_slot_number, partition) - partition_size = partition['size'] +def get_raw_hash(path: str, partition_size: int) -> str: + raw_hash = hashlib.sha256() + pos, chunk_size = 0, 1024 * 1024 with open(path, 'rb+') as out: - if full_check: - raw_hash = hashlib.sha256() + while pos < partition_size: + n = min(chunk_size, partition_size - pos) + raw_hash.update(out.read(n)) + pos += n - pos = 0 - chunk_size = 1024 * 1024 - while pos < partition_size: - n = min(chunk_size, partition_size - pos) - raw_hash.update(out.read(n)) - pos += n + return raw_hash.hexdigest().lower() - return raw_hash.hexdigest().lower() == partition['hash_raw'].lower() - else: + +def verify_partition(target_slot_number: int, partition: Dict[str, Union[str, int]], force_full_check: bool = False) -> bool: + full_check = partition['full_check'] or force_full_check + path = get_partition_path(target_slot_number, partition) + + if not isinstance(partition['size'], int): + return False + + partition_size: int = partition['size'] + + if not isinstance(partition['hash_raw'], str): + return False + + partition_hash: str = partition['hash_raw'] + + if full_check: + return get_raw_hash(path, partition_size) == partition_hash.lower() + else: + with open(path, 'rb+') as out: out.seek(partition_size) - return out.read(64) == partition['hash_raw'].lower().encode() + return out.read(64) == partition_hash.lower().encode() def clear_partition_hash(target_slot_number: int, partition: dict) -> None: @@ -131,21 +149,10 @@ def clear_partition_hash(target_slot_number: int, partition: dict) -> None: os.sync() -def flash_partition(target_slot_number: int, partition: dict, cloudlog): - cloudlog.info(f"Downloading and writing {partition['name']}") - - if verify_partition(target_slot_number, partition): - cloudlog.info(f"Already flashed {partition['name']}") - return - +def extract_compressed_image(target_slot_number: int, partition: dict, cloudlog): + path = get_partition_path(target_slot_number, partition) downloader = StreamingDecompressor(partition['url']) - # Clear hash before flashing in case we get interrupted - full_check = partition['full_check'] - if not full_check: - clear_partition_hash(target_slot_number, partition) - - path = get_partition_path(target_slot_number, partition) with open(path, 'wb+') as out: # Flash partition last_p = 0 @@ -168,9 +175,76 @@ def flash_partition(target_slot_number: int, partition: dict, cloudlog): if out.tell() != partition['size']: raise Exception("Uncompressed size mismatch") - # Write hash after successfull flash os.sync() - if not full_check: + + +def extract_casync_image(target_slot_number: int, partition: dict, cloudlog): + path = get_partition_path(target_slot_number, partition) + seed_path = path[:-1] + ('b' if path[-1] == 'a' else 'a') + + target = casync.parse_caibx(partition['casync_caibx']) + + sources: List[Tuple[str, casync.ChunkReader, casync.ChunkDict]] = [] + + # First source is the current partition. + try: + raw_hash = get_raw_hash(seed_path, partition['size']) + caibx_url = f"{CAIBX_URL}{partition['name']}-{raw_hash}.caibx" + + try: + cloudlog.info(f"casync fetching {caibx_url}") + sources += [('seed', casync.FileChunkReader(seed_path), casync.build_chunk_dict(casync.parse_caibx(caibx_url)))] + except requests.RequestException: + cloudlog.error(f"casync failed to load {caibx_url}") + except Exception: + cloudlog.exception("casync failed to hash seed partition") + + # Second source is the target partition, this allows for resuming + sources += [('target', casync.FileChunkReader(path), casync.build_chunk_dict(target))] + + # Finally we add the remote source to download any missing chunks + sources += [('remote', casync.RemoteChunkReader(partition['casync_store']), casync.build_chunk_dict(target))] + + last_p = 0 + + def progress(cur): + nonlocal last_p + p = int(cur / partition['size'] * 100) + if p != last_p: + last_p = p + print(f"Installing {partition['name']}: {p}", flush=True) + + stats = casync.extract(target, sources, path, progress) + cloudlog.error(f'casync done {json.dumps(stats)}') + + os.sync() + if not verify_partition(target_slot_number, partition, force_full_check=True): + raise Exception(f"Raw hash mismatch '{partition['hash_raw'].lower()}'") + + +def flash_partition(target_slot_number: int, partition: dict, cloudlog, standalone=False): + cloudlog.info(f"Downloading and writing {partition['name']}") + + if verify_partition(target_slot_number, partition): + cloudlog.info(f"Already flashed {partition['name']}") + return + + # Clear hash before flashing in case we get interrupted + full_check = partition['full_check'] + if not full_check: + clear_partition_hash(target_slot_number, partition) + + path = get_partition_path(target_slot_number, partition) + + if ('casync_caibx' in partition) and not standalone: + extract_casync_image(target_slot_number, partition, cloudlog) + else: + extract_compressed_image(target_slot_number, partition, cloudlog) + + # Write hash after successful flash + if not full_check: + with open(path, 'wb+') as out: + out.seek(partition['size']) out.write(partition['hash_raw'].lower().encode()) @@ -183,13 +257,13 @@ def swap(manifest_path: str, target_slot_number: int, cloudlog) -> None: while True: out = subprocess.check_output(f"abctl --set_active {target_slot_number}", shell=True, stderr=subprocess.STDOUT, encoding='utf8') if ("No such file or directory" not in out) and ("lun as boot lun" in out): - cloudlog.info(f"Swap successfull {out}") + cloudlog.info(f"Swap successful {out}") break else: cloudlog.error(f"Swap failed {out}") -def flash_agnos_update(manifest_path: str, target_slot_number: int, cloudlog) -> None: +def flash_agnos_update(manifest_path: str, target_slot_number: int, cloudlog, standalone=False) -> None: update = json.load(open(manifest_path)) cloudlog.info(f"Target slot {target_slot_number}") @@ -202,7 +276,7 @@ def flash_agnos_update(manifest_path: str, target_slot_number: int, cloudlog) -> for retries in range(10): try: - flash_partition(target_slot_number, partition, cloudlog) + flash_partition(target_slot_number, partition, cloudlog, standalone) success = True break @@ -224,8 +298,8 @@ def verify_agnos_update(manifest_path: str, target_slot_number: int) -> bool: if __name__ == "__main__": - import logging import argparse + import logging parser = argparse.ArgumentParser(description="Flash and verify AGNOS update", formatter_class=argparse.ArgumentDefaultsHelpFormatter) @@ -246,9 +320,9 @@ if __name__ == "__main__": elif args.swap: while not verify_agnos_update(args.manifest, target_slot_number): logging.error("Verification failed. Flashing AGNOS") - flash_agnos_update(args.manifest, target_slot_number, logging) + flash_agnos_update(args.manifest, target_slot_number, logging, standalone=True) logging.warning(f"Verification succeeded. Swapping to slot {target_slot_number}") swap(args.manifest, target_slot_number, logging) else: - flash_agnos_update(args.manifest, target_slot_number, logging) + flash_agnos_update(args.manifest, target_slot_number, logging, standalone=True) diff --git a/selfdrive/hardware/tici/amplifier.py b/system/hardware/tici/amplifier.py similarity index 100% rename from selfdrive/hardware/tici/amplifier.py rename to system/hardware/tici/amplifier.py diff --git a/system/hardware/tici/casync.py b/system/hardware/tici/casync.py new file mode 100755 index 0000000000..993336616d --- /dev/null +++ b/system/hardware/tici/casync.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python3 +import io +import lzma +import os +import struct +import sys +import time +from abc import ABC, abstractmethod +from collections import defaultdict, namedtuple +from typing import Callable, Dict, List, Optional, Tuple + +import requests +from Crypto.Hash import SHA512 + +CA_FORMAT_INDEX = 0x96824d9c7b129ff9 +CA_FORMAT_TABLE = 0xe75b9e112f17417d +CA_FORMAT_TABLE_TAIL_MARKER = 0xe75b9e112f17417 +FLAGS = 0xb000000000000000 + +CA_HEADER_LEN = 48 +CA_TABLE_HEADER_LEN = 16 +CA_TABLE_ENTRY_LEN = 40 +CA_TABLE_MIN_LEN = CA_TABLE_HEADER_LEN + CA_TABLE_ENTRY_LEN + +CHUNK_DOWNLOAD_TIMEOUT = 60 +CHUNK_DOWNLOAD_RETRIES = 3 + +CAIBX_DOWNLOAD_TIMEOUT = 120 + +Chunk = namedtuple('Chunk', ['sha', 'offset', 'length']) +ChunkDict = Dict[bytes, Chunk] + + +class ChunkReader(ABC): + @abstractmethod + def read(self, chunk: Chunk) -> bytes: + ... + + +class FileChunkReader(ChunkReader): + """Reads chunks from a local file""" + def __init__(self, fn: str) -> None: + super().__init__() + self.f = open(fn, 'rb') + + def __del__(self): + self.f.close() + + def read(self, chunk: Chunk) -> bytes: + self.f.seek(chunk.offset) + return self.f.read(chunk.length) + + +class RemoteChunkReader(ChunkReader): + """Reads lzma compressed chunks from a remote store""" + + def __init__(self, url: str) -> None: + super().__init__() + self.url = url + self.session = requests.Session() + + def read(self, chunk: Chunk) -> bytes: + sha_hex = chunk.sha.hex() + url = os.path.join(self.url, sha_hex[:4], sha_hex + ".cacnk") + + if os.path.isfile(url): + with open(url, 'rb') as f: + contents = f.read() + else: + for i in range(CHUNK_DOWNLOAD_RETRIES): + try: + resp = self.session.get(url, timeout=CHUNK_DOWNLOAD_TIMEOUT) + break + except Exception: + if i == CHUNK_DOWNLOAD_RETRIES - 1: + raise + time.sleep(CHUNK_DOWNLOAD_TIMEOUT) + + resp.raise_for_status() + contents = resp.content + + decompressor = lzma.LZMADecompressor(format=lzma.FORMAT_AUTO) + return decompressor.decompress(contents) + + +def parse_caibx(caibx_path: str) -> List[Chunk]: + """Parses the chunks from a caibx file. Can handle both local and remote files. + Returns a list of chunks with hash, offset and length""" + caibx: io.BufferedIOBase + if os.path.isfile(caibx_path): + caibx = open(caibx_path, 'rb') + else: + resp = requests.get(caibx_path, timeout=CAIBX_DOWNLOAD_TIMEOUT) + resp.raise_for_status() + caibx = io.BytesIO(resp.content) + + caibx.seek(0, os.SEEK_END) + caibx_len = caibx.tell() + caibx.seek(0, os.SEEK_SET) + + # Parse header + length, magic, flags, min_size, _, max_size = struct.unpack("= min_size + + chunks.append(Chunk(sha, offset, length)) + offset = new_offset + + caibx.close() + return chunks + + +def build_chunk_dict(chunks: List[Chunk]) -> ChunkDict: + """Turn a list of chunks into a dict for faster lookups based on hash. + Keep first chunk since it's more likely to be already downloaded.""" + r = {} + for c in chunks: + if c.sha not in r: + r[c.sha] = c + return r + + +def extract(target: List[Chunk], + sources: List[Tuple[str, ChunkReader, ChunkDict]], + out_path: str, + progress: Optional[Callable[[int], None]] = None): + stats: Dict[str, int] = defaultdict(int) + + mode = 'rb+' if os.path.exists(out_path) else 'wb' + with open(out_path, mode) as out: + for cur_chunk in target: + + # Find source for desired chunk + for name, chunk_reader, store_chunks in sources: + if cur_chunk.sha in store_chunks: + bts = chunk_reader.read(store_chunks[cur_chunk.sha]) + + # Check length + if len(bts) != cur_chunk.length: + continue + + # Check hash + if SHA512.new(bts, truncate="256").digest() != cur_chunk.sha: + continue + + # Write to output + out.seek(cur_chunk.offset) + out.write(bts) + + stats[name] += cur_chunk.length + + if progress is not None: + progress(sum(stats.values())) + + break + else: + raise RuntimeError("Desired chunk not found in provided stores") + + return stats + + +def print_stats(stats: Dict[str, int]): + total_bytes = sum(stats.values()) + print(f"Total size: {total_bytes / 1024 / 1024:.2f} MB") + for name, total in stats.items(): + print(f" {name}: {total / 1024 / 1024:.2f} MB ({total / total_bytes * 100:.1f}%)") + + +def extract_simple(caibx_path, out_path, store_path): + # (name, callback, chunks) + target = parse_caibx(caibx_path) + sources = [ + # (store_path, RemoteChunkReader(store_path), build_chunk_dict(target)), + (store_path, FileChunkReader(store_path), build_chunk_dict(target)), + ] + + return extract(target, sources, out_path) + + +if __name__ == "__main__": + caibx = sys.argv[1] + out = sys.argv[2] + store = sys.argv[3] + + stats = extract_simple(caibx, out, store) + print_stats(stats) diff --git a/selfdrive/hardware/tici/hardware.h b/system/hardware/tici/hardware.h similarity index 56% rename from selfdrive/hardware/tici/hardware.h rename to system/hardware/tici/hardware.h index c37dbb0a36..d388f9c48a 100644 --- a/selfdrive/hardware/tici/hardware.h +++ b/system/hardware/tici/hardware.h @@ -3,18 +3,24 @@ #include #include -#include "selfdrive/common/params.h" -#include "selfdrive/common/util.h" -#include "selfdrive/hardware/base.h" +#include "common/params.h" +#include "common/util.h" +#include "system/hardware/base.h" class HardwareTici : public HardwareNone { public: static constexpr float MAX_VOLUME = 0.9; - static constexpr float MIN_VOLUME = 0.2; + static constexpr float MIN_VOLUME = 0.1; static bool TICI() { return true; } + static bool AGNOS() { return true; } static std::string get_os_version() { return "AGNOS " + util::read_file("/VERSION"); }; + static std::string get_name() { return "tici"; }; + static cereal::InitData::DeviceType get_device_type() { return cereal::InitData::DeviceType::TICI; }; + static int get_voltage() { return std::atoi(util::read_file("/sys/class/hwmon/hwmon1/in1_input").c_str()); }; + static int get_current() { return std::atoi(util::read_file("/sys/class/hwmon/hwmon1/curr1_input").c_str()); }; + static void reboot() { std::system("sudo reboot"); }; static void poweroff() { std::system("sudo poweroff"); }; @@ -32,6 +38,13 @@ public: bl_power_control.close(); } }; + static void set_volume(float volume) { + volume = util::map_val(volume, 0.f, 1.f, MIN_VOLUME, MAX_VOLUME); + + char volume_str[6]; + snprintf(volume_str, sizeof(volume_str), "%.3f", volume); + std::system(("pactl set-sink-volume @DEFAULT_SINK@ " + std::string(volume_str)).c_str()); + } static bool get_ssh_enabled() { return Params().getBool("SshEnabled"); }; static void set_ssh_enabled(bool enabled) { Params().putBool("SshEnabled", enabled); }; diff --git a/selfdrive/hardware/tici/hardware.py b/system/hardware/tici/hardware.py similarity index 62% rename from selfdrive/hardware/tici/hardware.py rename to system/hardware/tici/hardware.py index 41ae316d3c..b5f5e00410 100644 --- a/selfdrive/hardware/tici/hardware.py +++ b/system/hardware/tici/hardware.py @@ -2,18 +2,23 @@ import json import math import os import subprocess +import time from enum import IntEnum from functools import cached_property from pathlib import Path from cereal import log -from selfdrive.hardware.base import HardwareBase, ThermalConfig -from selfdrive.hardware.tici import iwlist -from selfdrive.hardware.tici.amplifier import Amplifier +from common.gpio import gpio_set, gpio_init +from system.hardware.base import HardwareBase, ThermalConfig +from system.hardware.tici import iwlist +from system.hardware.tici.pins import GPIO +from system.hardware.tici.amplifier import Amplifier NM = 'org.freedesktop.NetworkManager' NM_CON_ACT = NM + '.Connection.Active' +NM_DEV = NM + '.Device' NM_DEV_WL = NM + '.Device.Wireless' +NM_DEV_STATS = NM + '.Device.Statistics' NM_AP = NM + '.AccessPoint' DBUS_PROPS = 'org.freedesktop.DBus.Properties' @@ -23,21 +28,29 @@ MM_MODEM_SIMPLE = MM + ".Modem.Simple" MM_SIM = MM + ".Sim" class MM_MODEM_STATE(IntEnum): - FAILED = -1 - UNKNOWN = 0 - INITIALIZING = 1 - LOCKED = 2 - DISABLED = 3 - DISABLING = 4 - ENABLING = 5 - ENABLED = 6 - SEARCHING = 7 - REGISTERED = 8 - DISCONNECTING = 9 - CONNECTING = 10 - CONNECTED = 11 + FAILED = -1 + UNKNOWN = 0 + INITIALIZING = 1 + LOCKED = 2 + DISABLED = 3 + DISABLING = 4 + ENABLING = 5 + ENABLED = 6 + SEARCHING = 7 + REGISTERED = 8 + DISCONNECTING = 9 + CONNECTING = 10 + CONNECTED = 11 + +class NMMetered(IntEnum): + NM_METERED_UNKNOWN = 0 + NM_METERED_YES = 1 + NM_METERED_NO = 2 + NM_METERED_GUESS_YES = 3 + NM_METERED_GUESS_NO = 4 TIMEOUT = 0.1 +REFRESH_RATE_MS = 1000 NetworkType = log.DeviceState.NetworkType NetworkStrength = log.DeviceState.NetworkStrength @@ -46,6 +59,14 @@ NetworkStrength = log.DeviceState.NetworkStrength MM_MODEM_ACCESS_TECHNOLOGY_UMTS = 1 << 5 MM_MODEM_ACCESS_TECHNOLOGY_LTE = 1 << 14 + +def sudo_write(val, path): + os.system(f"sudo su -c 'echo {val} > {path}'") + +def affine_irq(val, irq): + sudo_write(str(val), f"/proc/irq/{irq}/smp_affinity_list") + + class Tici(HardwareBase): @cached_property def bus(self): @@ -91,11 +112,10 @@ class Tici(HardwareBase): primary_connection = self.nm.Get(NM, 'PrimaryConnection', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) primary_connection = self.bus.get_object(NM, primary_connection) primary_type = primary_connection.Get(NM_CON_ACT, 'Type', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - primary_id = primary_connection.Get(NM_CON_ACT, 'Id', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) if primary_type == '802-3-ethernet': return NetworkType.ethernet - elif primary_type == '802-11-wireless' and primary_id != 'Hotspot': + elif primary_type == '802-11-wireless': return NetworkType.wifi else: active_connections = self.nm.Get(NM, 'ActiveConnections', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) @@ -125,6 +145,10 @@ class Tici(HardwareBase): wlan_path = self.nm.GetDeviceByIpIface('wlan0', dbus_interface=NM, timeout=TIMEOUT) return self.bus.get_object(NM, wlan_path) + def get_wwan(self): + wwan_path = self.nm.GetDeviceByIpIface('wwan0', dbus_interface=NM, timeout=TIMEOUT) + return self.bus.get_object(NM, wwan_path) + def get_sim_info(self): modem = self.get_modem() sim_path = modem.Get(MM_MODEM, 'Sim', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) @@ -187,14 +211,14 @@ class Tici(HardwareBase): return None def parse_strength(self, percentage): - if percentage < 25: - return NetworkStrength.poor - elif percentage < 50: - return NetworkStrength.moderate - elif percentage < 75: - return NetworkStrength.good - else: - return NetworkStrength.great + if percentage < 25: + return NetworkStrength.poor + elif percentage < 50: + return NetworkStrength.moderate + elif percentage < 75: + return NetworkStrength.good + else: + return NetworkStrength.great def get_network_strength(self, network_type): network_strength = NetworkStrength.unknown @@ -218,6 +242,27 @@ class Tici(HardwareBase): return network_strength + def get_network_metered(self, network_type) -> bool: + try: + primary_connection = self.nm.Get(NM, 'PrimaryConnection', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) + primary_connection = self.bus.get_object(NM, primary_connection) + primary_devices = primary_connection.Get(NM_CON_ACT, 'Devices', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) + + for dev in primary_devices: + dev_obj = self.bus.get_object(NM, str(dev)) + metered_prop = dev_obj.Get(NM_DEV, 'Metered', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) + + if network_type == NetworkType.wifi: + if metered_prop in [NMMetered.NM_METERED_YES, NMMetered.NM_METERED_GUESS_YES]: + return True + elif network_type in [NetworkType.cell2G, NetworkType.cell3G, NetworkType.cell4G, NetworkType.cell5G]: + if metered_prop == NMMetered.NM_METERED_NO: + return False + except Exception: + pass + + return super().get_network_metered(network_type) + @staticmethod def set_bandwidth_limit(upload_speed_kbps: int, download_speed_kbps: int) -> None: upload_speed_kbps = int(upload_speed_kbps) # Ensure integer value @@ -242,7 +287,7 @@ class Tici(HardwareBase): ] upload = [ - # Create root Hierarchy Token Bucket that sends all trafic to 1:20 + # Create root Hierarchy Token Bucket that sends all traffic to 1:20 (True, tc + ["qdisc", "add", "dev", adapter, "root", "handle", "1:", "htb", "default", "20"]), # Create class 1:20 with specified rate limit @@ -284,6 +329,19 @@ class Tici(HardwareBase): except Exception: return None + def get_modem_nv(self): + timeout = 0.2 # Default timeout is too short + files = ( + '/nv/item_files/modem/mmode/ue_usage_setting', + '/nv/item_files/ims/IMS_enable', + '/nv/item_files/modem/mmode/sms_only', + ) + try: + modem = self.get_modem() + return { fn: str(modem.Command(f'AT+QNVFR="{fn}"', math.ceil(timeout), dbus_interface=MM_MODEM, timeout=timeout)) for fn in files} + except Exception: + return None + def get_modem_temperatures(self): timeout = 0.2 # Default timeout is too short try: @@ -303,25 +361,6 @@ class Tici(HardwareBase): pass return ret - # We don't have a battery, so let's use some sane constants - def get_battery_capacity(self): - return 100 - - def get_battery_status(self): - return "" - - def get_battery_current(self): - return 0 - - def get_battery_voltage(self): - return 0 - - def get_battery_charging(self): - return True - - def set_battery_charging(self, on): - pass - def get_usb_present(self): # Not sure if relevant on tici, but the file exists return self.read_param_file("/sys/class/power_supply/usb/present", lambda x: bool(int(x)), False) @@ -329,12 +368,20 @@ class Tici(HardwareBase): def get_current_power_draw(self): return (self.read_param_file("/sys/class/hwmon/hwmon1/power1_input", int) / 1e6) + def get_som_power_draw(self): + return (self.read_param_file("/sys/class/power_supply/bms/voltage_now", int) * self.read_param_file("/sys/class/power_supply/bms/current_now", int) / 1e12) + def shutdown(self): - # Note that for this to work and have the device stay powered off, the panda needs to be in UsbPowerMode::CLIENT! os.system("sudo poweroff") def get_thermal_config(self): - return ThermalConfig(cpu=((1, 2, 3, 4, 5, 6, 7, 8), 1000), gpu=((48,49), 1000), mem=(15, 1000), bat=(None, 1), ambient=(65, 1000), pmic=((35, 36), 1000)) + return ThermalConfig(cpu=(["cpu%d-silver-usr" % i for i in range(4)] + + ["cpu%d-gold-usr" % i for i in range(4)], 1000), + gpu=(("gpu0-usr", "gpu1-usr"), 1000), + mem=("ddr-usr", 1000), + bat=(None, 1), + ambient=("xo-therm-adc", 1000), + pmic=(("pm8998_tz", "pm8005_tz"), 1000)) def set_screen_brightness(self, percentage): try: @@ -356,18 +403,24 @@ class Tici(HardwareBase): if not powersave_enabled: self.amplifier.initialize_configuration() + # *** CPU config *** + # offline big cluster, leave core 4 online for boardd for i in range(5, 8): - # TODO: fix permissions with udev - val = "0" if powersave_enabled else "1" - os.system(f"sudo su -c 'echo {val} > /sys/devices/system/cpu/cpu{i}/online'") + val = '0' if powersave_enabled else '1' + sudo_write(val, f'/sys/devices/system/cpu/cpu{i}/online') for n in ('0', '4'): - gov = 'userspace' if powersave_enabled else 'performance' - os.system(f"sudo su -c 'echo {gov} > /sys/devices/system/cpu/cpufreq/policy{n}/scaling_governor'") + gov = 'ondemand' if powersave_enabled else 'performance' + sudo_write(gov, f'/sys/devices/system/cpu/cpufreq/policy{n}/scaling_governor') - if powersave_enabled: - os.system(f"sudo su -c 'echo 979200 > /sys/devices/system/cpu/cpufreq/policy{n}/scaling_setspeed'") + # *** IRQ config *** + affine_irq(5, 565) # kgsl-3d0 + affine_irq(4, 126) # SPI goes on boardd core + affine_irq(4, 740) # xhci-hcd:usb1 goes on the boardd core + affine_irq(4, 1069) # xhci-hcd:usb3 goes on the boardd core + for irq in range(237, 246): + affine_irq(5, irq) # camerad def get_gpu_usage_percent(self): try: @@ -382,6 +435,54 @@ class Tici(HardwareBase): # Allow thermald to write engagement status to kmsg os.system("sudo chmod a+w /dev/kmsg") + # *** IRQ config *** + + # move these off the default core + affine_irq(1, 7) # msm_drm + affine_irq(1, 250) # msm_vidc + affine_irq(1, 8) # i2c_geni (sensord) + sudo_write("f", "/proc/irq/default_smp_affinity") + + # *** GPU config *** + # https://github.com/commaai/agnos-kernel-sdm845/blob/master/arch/arm64/boot/dts/qcom/sdm845-gpu.dtsi#L216 + sudo_write("1", "/sys/class/kgsl/kgsl-3d0/min_pwrlevel") + sudo_write("1", "/sys/class/kgsl/kgsl-3d0/max_pwrlevel") + sudo_write("1", "/sys/class/kgsl/kgsl-3d0/force_bus_on") + sudo_write("1", "/sys/class/kgsl/kgsl-3d0/force_clk_on") + sudo_write("1", "/sys/class/kgsl/kgsl-3d0/force_rail_on") + sudo_write("1000000", "/sys/class/kgsl/kgsl-3d0/idle_timer") + sudo_write("performance", "/sys/class/kgsl/kgsl-3d0/devfreq/governor") + sudo_write("596", "/sys/class/kgsl/kgsl-3d0/max_clock_mhz") + + # setup governors + sudo_write("performance", "/sys/class/devfreq/soc:qcom,cpubw/governor") + sudo_write("performance", "/sys/class/devfreq/soc:qcom,memlat-cpu0/governor") + sudo_write("performance", "/sys/class/devfreq/soc:qcom,memlat-cpu4/governor") + + # *** VIDC (encoder) config *** + sudo_write("N", "/sys/kernel/debug/msm_vidc/clock_scaling") + sudo_write("Y", "/sys/kernel/debug/msm_vidc/disable_thermal_mitigation") + + def configure_modem(self): + sim_id = self.get_sim_info().get('sim_id', '') + + # configure modem as data-centric + cmds = [ + 'AT+QNVW=5280,0,"0102000000000000"', + 'AT+QNVFW="/nv/item_files/ims/IMS_enable",00', + 'AT+QNVFW="/nv/item_files/modem/mmode/ue_usage_setting",01', + ] + modem = self.get_modem() + for cmd in cmds: + try: + modem.Command(cmd, math.ceil(TIMEOUT), dbus_interface=MM_MODEM, timeout=TIMEOUT) + except Exception: + pass + + # blue prime config + if sim_id.startswith('8901410'): + os.system('mmcli -m any --3gpp-set-initial-eps-bearer-settings="apn=Broadband"') + def get_networks(self): r = {} @@ -408,3 +509,42 @@ class Tici(HardwareBase): pass return r + + def get_modem_data_usage(self): + try: + wwan = self.get_wwan() + + # Ensure refresh rate is set so values don't go stale + refresh_rate = wwan.Get(NM_DEV_STATS, 'RefreshRateMs', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) + if refresh_rate != REFRESH_RATE_MS: + u = type(refresh_rate) + wwan.Set(NM_DEV_STATS, 'RefreshRateMs', u(REFRESH_RATE_MS), dbus_interface=DBUS_PROPS, timeout=TIMEOUT) + + tx = wwan.Get(NM_DEV_STATS, 'TxBytes', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) + rx = wwan.Get(NM_DEV_STATS, 'RxBytes', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) + return int(tx), int(rx) + except Exception: + return -1, -1 + + def reset_internal_panda(self): + gpio_init(GPIO.STM_RST_N, True) + + gpio_set(GPIO.STM_RST_N, 1) + time.sleep(2) + gpio_set(GPIO.STM_RST_N, 0) + + def recover_internal_panda(self): + gpio_init(GPIO.STM_RST_N, True) + gpio_init(GPIO.STM_BOOT0, True) + + gpio_set(GPIO.STM_RST_N, 1) + gpio_set(GPIO.STM_BOOT0, 1) + time.sleep(2) + gpio_set(GPIO.STM_RST_N, 0) + gpio_set(GPIO.STM_BOOT0, 0) + + +if __name__ == "__main__": + t = Tici() + t.initialize_hardware() + t.set_power_save(False) diff --git a/selfdrive/hardware/tici/iwlist.py b/system/hardware/tici/iwlist.py similarity index 100% rename from selfdrive/hardware/tici/iwlist.py rename to system/hardware/tici/iwlist.py diff --git a/system/hardware/tici/pins.py b/system/hardware/tici/pins.py new file mode 100644 index 0000000000..fe31b9311d --- /dev/null +++ b/system/hardware/tici/pins.py @@ -0,0 +1,27 @@ +# TODO: these are also defined in a header + +# GPIO pin definitions +class GPIO: + # both GPIO_STM_RST_N and GPIO_LTE_RST_N are misnamed, they are high to reset + HUB_RST_N = 30 + UBLOX_RST_N = 32 + UBLOX_SAFEBOOT_N = 33 + UBLOX_PWR_EN = 34 + STM_RST_N = 124 + STM_BOOT0 = 134 + + LTE_RST_N = 50 + LTE_PWRKEY = 116 + LTE_BOOT = 52 + + # GPIO_CAM0_DVDD_EN = /sys/kernel/debug/regulator/camera_rear_ldo + CAM0_AVDD_EN = 8 + CAM0_RSTN = 9 + CAM1_RSTN = 7 + CAM2_RSTN = 12 + + # Sensor interrupts + BMX055_ACCEL_INT = 21 + BMX055_GYRO_INT = 23 + BMX055_MAGN_INT = 87 + LSM_INT = 84 diff --git a/system/hardware/tici/power_draw_test.py b/system/hardware/tici/power_draw_test.py new file mode 100755 index 0000000000..bde92ae4a5 --- /dev/null +++ b/system/hardware/tici/power_draw_test.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +import os +import time +import numpy as np +from system.hardware.tici.hardware import Tici +from system.hardware.tici.pins import GPIO +from common.gpio import gpio_init, gpio_set + +def read_power(): + with open("/sys/bus/i2c/devices/0-0040/hwmon/hwmon1/in1_input") as f: + voltage_total = int(f.read()) / 1000. + + with open("/sys/bus/i2c/devices/0-0040/hwmon/hwmon1/curr1_input") as f: + current_total = int(f.read()) + + with open("/sys/class/power_supply/bms/voltage_now") as f: + voltage = int(f.read()) / 1e6 # volts + + with open("/sys/class/power_supply/bms/current_now") as f: + current = int(f.read()) / 1e3 # ma + + power_som = voltage*current + power_total = voltage_total*current_total + + return power_total, power_som + +def read_power_avg(): + pwrs = [] + for _ in range(100): + pwrs.append(read_power()) + time.sleep(0.01) + power_total, power_som = np.mean([x[0] for x in pwrs]), np.mean([x[1] for x in pwrs]) + return "total %7.2f mW SOM %7.2f mW" % (power_total, power_som) + + +def gpio_export(pin): + try: + with open("/sys/class/gpio/export", 'w') as f: + f.write(str(pin)) + except Exception: + print(f"Failed to export gpio {pin}") + +if __name__ == "__main__": + gpio_export(GPIO.CAM0_AVDD_EN) + gpio_export(GPIO.CAM0_RSTN) + gpio_export(GPIO.CAM1_RSTN) + gpio_export(GPIO.CAM2_RSTN) + print("hello") + os.system('kill $(pgrep -f "manager.py")') + os.system('kill $(pgrep -f "python -m selfdrive.athena.manage_athenad")') + os.system('kill $(pgrep -f "selfdrive.athena.athenad")') + # stopping weston turns off lcd3v3 + os.system("sudo service weston stop") + os.system("sudo service ModemManager stop") + print("services stopped") + + t = Tici() + t.initialize_hardware() + t.set_power_save(True) + t.set_screen_brightness(0) + gpio_init(GPIO.STM_RST_N, True) + gpio_init(GPIO.HUB_RST_N, True) + gpio_init(GPIO.UBLOX_PWR_EN, True) + gpio_init(GPIO.LTE_RST_N, True) + gpio_init(GPIO.LTE_PWRKEY, True) + gpio_init(GPIO.CAM0_AVDD_EN, True) + gpio_init(GPIO.CAM0_RSTN, True) + gpio_init(GPIO.CAM1_RSTN, True) + gpio_init(GPIO.CAM2_RSTN, True) + + + os.system("sudo su -c 'echo 0 > /sys/kernel/debug/regulator/camera_rear_ldo/enable'") # cam 1v2 off + gpio_set(GPIO.CAM0_AVDD_EN, False) # cam 2v8 off + gpio_set(GPIO.LTE_RST_N, True) # quectel off + gpio_set(GPIO.UBLOX_PWR_EN, False) # gps off + gpio_set(GPIO.STM_RST_N, True) # panda off + gpio_set(GPIO.HUB_RST_N, False) # hub off + # cameras in reset + gpio_set(GPIO.CAM0_RSTN, False) + gpio_set(GPIO.CAM1_RSTN, False) + gpio_set(GPIO.CAM2_RSTN, False) + time.sleep(8) + + print("baseline: ", read_power_avg()) + gpio_set(GPIO.CAM0_AVDD_EN, True) + time.sleep(2) + print("cam avdd: ", read_power_avg()) + os.system("sudo su -c 'echo 1 > /sys/kernel/debug/regulator/camera_rear_ldo/enable'") + time.sleep(2) + print("cam dvdd: ", read_power_avg()) + gpio_set(GPIO.CAM0_RSTN, True) + gpio_set(GPIO.CAM1_RSTN, True) + gpio_set(GPIO.CAM2_RSTN, True) + time.sleep(2) + print("cams up: ", read_power_avg()) + gpio_set(GPIO.HUB_RST_N, True) + time.sleep(2) + print("usb hub: ", read_power_avg()) + gpio_set(GPIO.STM_RST_N, False) + time.sleep(5) + print("panda: ", read_power_avg()) + gpio_set(GPIO.UBLOX_PWR_EN, True) + time.sleep(5) + print("gps: ", read_power_avg()) + gpio_set(GPIO.LTE_RST_N, False) + time.sleep(1) + gpio_set(GPIO.LTE_PWRKEY, True) + time.sleep(1) + gpio_set(GPIO.LTE_PWRKEY, False) + time.sleep(5) + print("quectel: ", read_power_avg()) + diff --git a/system/hardware/tici/power_monitor.py b/system/hardware/tici/power_monitor.py new file mode 100755 index 0000000000..f9d1e3cc41 --- /dev/null +++ b/system/hardware/tici/power_monitor.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +import sys +import time +import datetime +import numpy as np +from typing import List + +from common.realtime import Ratekeeper +from common.filter_simple import FirstOrderFilter + + +def read_power(): + with open("/sys/bus/i2c/devices/0-0040/hwmon/hwmon1/power1_input") as f: + return int(f.read()) / 1e6 + +def sample_power(seconds=5) -> List[float]: + rate = 123 + rk = Ratekeeper(rate, print_delay_threshold=None) + + pwrs = [] + for _ in range(rate*seconds): + pwrs.append(read_power()) + rk.keep_time() + return pwrs + +def get_power(seconds=5): + pwrs = sample_power(seconds) + return np.mean(pwrs) + + +if __name__ == "__main__": + duration = None + if len(sys.argv) > 1: + duration = int(sys.argv[1]) + + rate = 23 + rk = Ratekeeper(rate, print_delay_threshold=None) + fltr = FirstOrderFilter(0, 5, 1. / rate, initialized=False) + + measurements = [] + start_time = time.monotonic() + + try: + while duration is None or time.monotonic() - start_time < duration: + fltr.update(read_power()) + if rk.frame % rate == 0: + measurements.append(fltr.x) + t = datetime.timedelta(seconds=time.monotonic() - start_time) + avg = sum(measurements) / len(measurements) + print(f"Now: {fltr.x:.2f} W, Avg: {avg:.2f} W over {t}") + rk.keep_time() + except KeyboardInterrupt: + pass + + t = datetime.timedelta(seconds=time.monotonic() - start_time) + avg = sum(measurements) / len(measurements) + print(f"\nAverage power: {avg:.2f}W over {t}") diff --git a/system/hardware/tici/precise_power_measure.py b/system/hardware/tici/precise_power_measure.py new file mode 100755 index 0000000000..5d68851367 --- /dev/null +++ b/system/hardware/tici/precise_power_measure.py @@ -0,0 +1,9 @@ +#!/usr/bin/env python3 +import numpy as np +from system.hardware.tici.power_monitor import sample_power + +if __name__ == '__main__': + print("measuring for 5 seconds") + for _ in range(3): + pwrs = sample_power() + print("mean %.2f std %.2f" % (np.mean(pwrs), np.std(pwrs))) diff --git a/system/hardware/tici/restart_modem.sh b/system/hardware/tici/restart_modem.sh new file mode 100755 index 0000000000..26c04e4fba --- /dev/null +++ b/system/hardware/tici/restart_modem.sh @@ -0,0 +1,18 @@ +#!/usr/bin/bash + +#nmcli connection modify --temporary lte gsm.home-only yes +#nmcli connection modify --temporary lte gsm.auto-config yes +#nmcli connection modify --temporary lte connection.autoconnect-retries 20 +sudo nmcli connection reload + +sudo systemctl stop ModemManager +nmcli con down lte +nmcli con down magenta-prime + +# power cycle modem +/usr/comma/lte/lte.sh stop_blocking +/usr/comma/lte/lte.sh start + +sudo systemctl restart NetworkManager +#sudo systemctl restart ModemManager +sudo ModemManager --debug diff --git a/selfdrive/hardware/tici/test_agnos_updater.py b/system/hardware/tici/test_agnos_updater.py similarity index 92% rename from selfdrive/hardware/tici/test_agnos_updater.py rename to system/hardware/tici/test_agnos_updater.py index 9f188b83dc..e0d6ed8814 100755 --- a/selfdrive/hardware/tici/test_agnos_updater.py +++ b/system/hardware/tici/test_agnos_updater.py @@ -15,7 +15,7 @@ class TestAgnosUpdater(unittest.TestCase): m = json.load(f) for img in m: - r = requests.head(img['url']) + r = requests.head(img['url'], timeout=10) r.raise_for_status() self.assertEqual(r.headers['Content-Type'], "application/x-xz") if not img['sparse']: diff --git a/system/hardware/tici/test_power_draw.py b/system/hardware/tici/test_power_draw.py new file mode 100755 index 0000000000..2460152998 --- /dev/null +++ b/system/hardware/tici/test_power_draw.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +import unittest +import time +import math +from dataclasses import dataclass + +from system.hardware import HARDWARE, TICI +from system.hardware.tici.power_monitor import get_power +from selfdrive.manager.process_config import managed_processes +from selfdrive.manager.manager import manager_cleanup + + +@dataclass +class Proc: + name: str + power: float + rtol: float = 0.05 + atol: float = 0.1 + warmup: float = 6. + +PROCS = [ + Proc('camerad', 2.15), + Proc('modeld', 1.15, atol=0.2), + Proc('dmonitoringmodeld', 0.4), + Proc('encoderd', 0.23), +] + + +class TestPowerDraw(unittest.TestCase): + + @classmethod + def setUpClass(cls): + if not TICI: + raise unittest.SkipTest + + def setUp(self): + HARDWARE.initialize_hardware() + HARDWARE.set_power_save(False) + + # wait a bit for power save to disable + time.sleep(5) + + def tearDown(self): + manager_cleanup() + + def test_camera_procs(self): + baseline = get_power() + + prev = baseline + used = {} + for proc in PROCS: + managed_processes[proc.name].start() + time.sleep(proc.warmup) + + now = get_power(8) + used[proc.name] = now - prev + prev = now + + manager_cleanup() + + print("-"*35) + print(f"Baseline {baseline:.2f}W\n") + for proc in PROCS: + cur = used[proc.name] + expected = proc.power + print(f"{proc.name.ljust(20)} {expected:.2f}W {cur:.2f}W") + with self.subTest(proc=proc.name): + self.assertTrue(math.isclose(cur, expected, rel_tol=proc.rtol, abs_tol=proc.atol)) + print("-"*35) + + +if __name__ == "__main__": + unittest.main() diff --git a/system/hardware/tici/tests/__init__.py b/system/hardware/tici/tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/system/hardware/tici/tests/compare_casync_manifest.py b/system/hardware/tici/tests/compare_casync_manifest.py new file mode 100755 index 0000000000..b462e93ebc --- /dev/null +++ b/system/hardware/tici/tests/compare_casync_manifest.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +import argparse +import collections +import multiprocessing +import os +from typing import Dict, List + +import requests +from tqdm import tqdm + +import system.hardware.tici.casync as casync + + +def get_chunk_download_size(chunk): + sha = chunk.sha.hex() + path = os.path.join(remote_url, sha[:4], sha + ".cacnk") + if os.path.isfile(path): + return os.path.getsize(path) + else: + r = requests.head(path, timeout=10) + r.raise_for_status() + return int(r.headers['content-length']) + + +if __name__ == "__main__": + + parser = argparse.ArgumentParser(description='Compute overlap between two casync manifests') + parser.add_argument('frm') + parser.add_argument('to') + args = parser.parse_args() + + frm = casync.parse_caibx(args.frm) + to = casync.parse_caibx(args.to) + remote_url = args.to.replace('.caibx', '') + + most_common = collections.Counter(t.sha for t in to).most_common(1)[0][0] + + frm_dict = casync.build_chunk_dict(frm) + + # Get content-length for each chunk + with multiprocessing.Pool() as pool: + szs = list(tqdm(pool.imap(get_chunk_download_size, to), total=len(to))) + chunk_sizes = {t.sha: sz for (t, sz) in zip(to, szs)} + + sources: Dict[str, List[int]] = { + 'seed': [], + 'remote_uncompressed': [], + 'remote_compressed': [], + } + + for chunk in to: + # Assume most common chunk is the zero chunk + if chunk.sha == most_common: + continue + + if chunk.sha in frm_dict: + sources['seed'].append(chunk.length) + else: + sources['remote_uncompressed'].append(chunk.length) + sources['remote_compressed'].append(chunk_sizes[chunk.sha]) + + print() + print("Update statistics (excluding zeros)") + print() + print("Download only with no seed:") + print(f" Remote (uncompressed)\t\t{sum(sources['seed'] + sources['remote_uncompressed']) / 1000 / 1000:.2f} MB\tn = {len(to)}") + print(f" Remote (compressed download)\t{sum(chunk_sizes.values()) / 1000 / 1000:.2f} MB\tn = {len(to)}") + print() + print("Upgrade with seed partition:") + print(f" Seed (uncompressed)\t\t{sum(sources['seed']) / 1000 / 1000:.2f} MB\t\t\t\tn = {len(sources['seed'])}") + sz, n = sum(sources['remote_uncompressed']), len(sources['remote_uncompressed']) + print(f" Remote (uncompressed)\t\t{sz / 1000 / 1000:.2f} MB\t(avg {sz / 1000 / 1000 / n:4f} MB)\tn = {n}") + sz, n = sum(sources['remote_compressed']), len(sources['remote_compressed']) + print(f" Remote (compressed download)\t{sz / 1000 / 1000:.2f} MB\t(avg {sz / 1000 / 1000 / n:4f} MB)\tn = {n}") diff --git a/system/hardware/tici/tests/test_casync.py b/system/hardware/tici/tests/test_casync.py new file mode 100755 index 0000000000..8724575ad6 --- /dev/null +++ b/system/hardware/tici/tests/test_casync.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python3 +import os +import unittest +import tempfile +import subprocess + +import system.hardware.tici.casync as casync + +# dd if=/dev/zero of=/tmp/img.raw bs=1M count=2 +# sudo losetup -f /tmp/img.raw +# losetup -a | grep img.raw +LOOPBACK = os.environ.get('LOOPBACK', None) + + +class TestCasync(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tmpdir = tempfile.TemporaryDirectory() + + # Build example contents + chunk_a = [i % 256 for i in range(1024)] * 512 + chunk_b = [(256 - i) % 256 for i in range(1024)] * 512 + zeroes = [0] * (1024 * 128) + contents = chunk_a + chunk_b + zeroes + chunk_a + + cls.contents = bytes(contents) + + # Write to file + cls.orig_fn = os.path.join(cls.tmpdir.name, 'orig.bin') + with open(cls.orig_fn, 'wb') as f: + f.write(cls.contents) + + # Create casync files + cls.manifest_fn = os.path.join(cls.tmpdir.name, 'orig.caibx') + cls.store_fn = os.path.join(cls.tmpdir.name, 'store') + subprocess.check_output(["casync", "make", "--compression=xz", "--store", cls.store_fn, cls.manifest_fn, cls.orig_fn]) + + target = casync.parse_caibx(cls.manifest_fn) + hashes = [c.sha.hex() for c in target] + + # Ensure we have chunk reuse + assert len(hashes) > len(set(hashes)) + + def setUp(self): + # Clear target_lo + if LOOPBACK is not None: + self.target_lo = LOOPBACK + with open(self.target_lo, 'wb') as f: + f.write(b"0" * len(self.contents)) + + self.target_fn = os.path.join(self.tmpdir.name, next(tempfile._get_candidate_names())) + self.seed_fn = os.path.join(self.tmpdir.name, next(tempfile._get_candidate_names())) + + def tearDown(self): + for fn in [self.target_fn, self.seed_fn]: + try: + os.unlink(fn) + except FileNotFoundError: + pass + + def test_simple_extract(self): + target = casync.parse_caibx(self.manifest_fn) + + sources = [('remote', casync.RemoteChunkReader(self.store_fn), casync.build_chunk_dict(target))] + stats = casync.extract(target, sources, self.target_fn) + + with open(self.target_fn, 'rb') as target_f: + self.assertEqual(target_f.read(), self.contents) + + self.assertEqual(stats['remote'], len(self.contents)) + + def test_seed(self): + target = casync.parse_caibx(self.manifest_fn) + + # Populate seed with half of the target contents + with open(self.seed_fn, 'wb') as seed_f: + seed_f.write(self.contents[:len(self.contents) // 2]) + + sources = [('seed', casync.FileChunkReader(self.seed_fn), casync.build_chunk_dict(target))] + sources += [('remote', casync.RemoteChunkReader(self.store_fn), casync.build_chunk_dict(target))] + stats = casync.extract(target, sources, self.target_fn) + + with open(self.target_fn, 'rb') as target_f: + self.assertEqual(target_f.read(), self.contents) + + self.assertGreater(stats['seed'], 0) + self.assertLess(stats['remote'], len(self.contents)) + + def test_already_done(self): + """Test that an already flashed target doesn't download any chunks""" + target = casync.parse_caibx(self.manifest_fn) + + with open(self.target_fn, 'wb') as f: + f.write(self.contents) + + sources = [('target', casync.FileChunkReader(self.target_fn), casync.build_chunk_dict(target))] + sources += [('remote', casync.RemoteChunkReader(self.store_fn), casync.build_chunk_dict(target))] + + stats = casync.extract(target, sources, self.target_fn) + + with open(self.target_fn, 'rb') as f: + self.assertEqual(f.read(), self.contents) + + self.assertEqual(stats['target'], len(self.contents)) + + def test_chunk_reuse(self): + """Test that chunks that are reused are only downloaded once""" + target = casync.parse_caibx(self.manifest_fn) + + # Ensure target exists + with open(self.target_fn, 'wb'): + pass + + sources = [('target', casync.FileChunkReader(self.target_fn), casync.build_chunk_dict(target))] + sources += [('remote', casync.RemoteChunkReader(self.store_fn), casync.build_chunk_dict(target))] + + stats = casync.extract(target, sources, self.target_fn) + + with open(self.target_fn, 'rb') as f: + self.assertEqual(f.read(), self.contents) + + self.assertLess(stats['remote'], len(self.contents)) + + @unittest.skipUnless(LOOPBACK, "requires loopback device") + def test_lo_simple_extract(self): + target = casync.parse_caibx(self.manifest_fn) + sources = [('remote', casync.RemoteChunkReader(self.store_fn), casync.build_chunk_dict(target))] + + stats = casync.extract(target, sources, self.target_lo) + + with open(self.target_lo, 'rb') as target_f: + self.assertEqual(target_f.read(len(self.contents)), self.contents) + + self.assertEqual(stats['remote'], len(self.contents)) + + @unittest.skipUnless(LOOPBACK, "requires loopback device") + def test_lo_chunk_reuse(self): + """Test that chunks that are reused are only downloaded once""" + target = casync.parse_caibx(self.manifest_fn) + + sources = [('target', casync.FileChunkReader(self.target_lo), casync.build_chunk_dict(target))] + sources += [('remote', casync.RemoteChunkReader(self.store_fn), casync.build_chunk_dict(target))] + + stats = casync.extract(target, sources, self.target_lo) + + with open(self.target_lo, 'rb') as f: + self.assertEqual(f.read(len(self.contents)), self.contents) + + self.assertLess(stats['remote'], len(self.contents)) + + +if __name__ == "__main__": + unittest.main() diff --git a/selfdrive/hardware/tici/updater b/system/hardware/tici/updater similarity index 100% rename from selfdrive/hardware/tici/updater rename to system/hardware/tici/updater diff --git a/selfdrive/logcatd/.gitignore b/system/logcatd/.gitignore similarity index 100% rename from selfdrive/logcatd/.gitignore rename to system/logcatd/.gitignore diff --git a/system/logcatd/SConscript b/system/logcatd/SConscript new file mode 100644 index 0000000000..6bd7c6ff3e --- /dev/null +++ b/system/logcatd/SConscript @@ -0,0 +1,3 @@ +Import('env', 'cereal', 'messaging', 'common') + +env.Program('logcatd', 'logcatd_systemd.cc', LIBS=[cereal, messaging, common, 'zmq', 'capnp', 'kj', 'systemd', 'json11']) diff --git a/selfdrive/logcatd/logcatd_systemd.cc b/system/logcatd/logcatd_systemd.cc similarity index 96% rename from selfdrive/logcatd/logcatd_systemd.cc rename to system/logcatd/logcatd_systemd.cc index dabb11adcb..70467a9c15 100644 --- a/selfdrive/logcatd/logcatd_systemd.cc +++ b/system/logcatd/logcatd_systemd.cc @@ -8,8 +8,8 @@ #include "json11.hpp" #include "cereal/messaging/messaging.h" -#include "selfdrive/common/timing.h" -#include "selfdrive/common/util.h" +#include "common/timing.h" +#include "common/util.h" ExitHandler do_exit; int main(int argc, char *argv[]) { diff --git a/selfdrive/logmessaged.py b/system/logmessaged.py similarity index 95% rename from selfdrive/logmessaged.py rename to system/logmessaged.py index 1d1fab5162..280a23cf1d 100755 --- a/selfdrive/logmessaged.py +++ b/system/logmessaged.py @@ -4,7 +4,7 @@ from typing import NoReturn import cereal.messaging as messaging from common.logging_extra import SwagLogFileFormatter -from selfdrive.swaglog import get_file_handler +from system.swaglog import get_file_handler def main() -> NoReturn: diff --git a/system/micd.py b/system/micd.py new file mode 100755 index 0000000000..a56140e3b9 --- /dev/null +++ b/system/micd.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +import sounddevice as sd +import numpy as np + +from cereal import messaging +from common.filter_simple import FirstOrderFilter +from common.realtime import Ratekeeper +from system.swaglog import cloudlog + +RATE = 10 +FFT_SAMPLES = 4096 +REFERENCE_SPL = 2e-5 # newtons/m^2 +SAMPLE_RATE = 44100 +FILTER_DT = 1. / (SAMPLE_RATE / FFT_SAMPLES) + + +def calculate_spl(measurements): + # https://www.engineeringtoolbox.com/sound-pressure-d_711.html + sound_pressure = np.sqrt(np.mean(measurements ** 2)) # RMS of amplitudes + if sound_pressure > 0: + sound_pressure_level = 20 * np.log10(sound_pressure / REFERENCE_SPL) # dB + else: + sound_pressure_level = 0 + return sound_pressure, sound_pressure_level + + +def apply_a_weighting(measurements: np.ndarray) -> np.ndarray: + # Generate a Hanning window of the same length as the audio measurements + measurements_windowed = measurements * np.hanning(len(measurements)) + + # Calculate the frequency axis for the signal + freqs = np.fft.fftfreq(measurements_windowed.size, d=1 / SAMPLE_RATE) + + # Calculate the A-weighting filter + # https://en.wikipedia.org/wiki/A-weighting + A = 12194 ** 2 * freqs ** 4 / ((freqs ** 2 + 20.6 ** 2) * (freqs ** 2 + 12194 ** 2) * np.sqrt((freqs ** 2 + 107.7 ** 2) * (freqs ** 2 + 737.9 ** 2))) + A /= np.max(A) # Normalize the filter + + # Apply the A-weighting filter to the signal + return np.abs(np.fft.ifft(np.fft.fft(measurements_windowed) * A)) + + +class Mic: + def __init__(self, pm): + self.pm = pm + self.rk = Ratekeeper(RATE) + + self.measurements = np.empty(0) + + self.sound_pressure = 0 + self.sound_pressure_weighted = 0 + self.sound_pressure_level_weighted = 0 + + self.spl_filter_weighted = FirstOrderFilter(0, 2.5, FILTER_DT, initialized=False) + + def update(self): + msg = messaging.new_message('microphone') + msg.microphone.soundPressure = float(self.sound_pressure) + msg.microphone.soundPressureWeighted = float(self.sound_pressure_weighted) + + msg.microphone.soundPressureWeightedDb = float(self.sound_pressure_level_weighted) + msg.microphone.filteredSoundPressureWeightedDb = float(self.spl_filter_weighted.x) + + self.pm.send('microphone', msg) + self.rk.keep_time() + + def callback(self, indata, frames, time, status): + """ + Using amplitude measurements, calculate an uncalibrated sound pressure and sound pressure level. + Then apply A-weighting to the raw amplitudes and run the same calculations again. + + Logged A-weighted equivalents are rough approximations of the human-perceived loudness. + """ + + self.measurements = np.concatenate((self.measurements, indata[:, 0])) + + while self.measurements.size >= FFT_SAMPLES: + measurements = self.measurements[:FFT_SAMPLES] + + self.sound_pressure, _ = calculate_spl(measurements) + measurements_weighted = apply_a_weighting(measurements) + self.sound_pressure_weighted, self.sound_pressure_level_weighted = calculate_spl(measurements_weighted) + self.spl_filter_weighted.update(self.sound_pressure_level_weighted) + + self.measurements = self.measurements[FFT_SAMPLES:] + + def micd_thread(self, device=None): + if device is None: + device = "sysdefault" + + with sd.InputStream(device=device, channels=1, samplerate=SAMPLE_RATE, callback=self.callback) as stream: + cloudlog.info(f"micd stream started: {stream.samplerate=} {stream.channels=} {stream.dtype=} {stream.device=}") + while True: + self.update() + + +def main(pm=None): + if pm is None: + pm = messaging.PubMaster(['microphone']) + + mic = Mic(pm) + mic.micd_thread() + + +if __name__ == "__main__": + main() diff --git a/selfdrive/proclogd/SConscript b/system/proclogd/SConscript similarity index 100% rename from selfdrive/proclogd/SConscript rename to system/proclogd/SConscript diff --git a/selfdrive/proclogd/main.cc b/system/proclogd/main.cc similarity index 81% rename from selfdrive/proclogd/main.cc rename to system/proclogd/main.cc index 4e31597c2b..c4faa916d9 100644 --- a/selfdrive/proclogd/main.cc +++ b/system/proclogd/main.cc @@ -1,8 +1,8 @@ #include -#include "selfdrive/common/util.h" -#include "selfdrive/proclogd/proclog.h" +#include "common/util.h" +#include "system/proclogd/proclog.h" ExitHandler do_exit; diff --git a/selfdrive/proclogd/proclog.cc b/system/proclogd/proclog.cc similarity index 97% rename from selfdrive/proclogd/proclog.cc rename to system/proclogd/proclog.cc index 26fc1d94d0..09ab4f559e 100644 --- a/selfdrive/proclogd/proclog.cc +++ b/system/proclogd/proclog.cc @@ -1,4 +1,4 @@ -#include "selfdrive/proclogd/proclog.h" +#include "system/proclogd/proclog.h" #include @@ -7,8 +7,8 @@ #include #include -#include "selfdrive/common/swaglog.h" -#include "selfdrive/common/util.h" +#include "common/swaglog.h" +#include "common/util.h" namespace Parser { @@ -72,7 +72,7 @@ std::optional procStat(std::string stat) { } std::string name = stat.substr(open_paren + 1, close_paren - open_paren - 1); - // repace space in name with _ + // replace space in name with _ std::replace(&stat[open_paren], &stat[close_paren], ' ', '_'); std::istringstream iss(stat); std::vector v{std::istream_iterator(iss), @@ -95,7 +95,7 @@ std::optional procStat(std::string stat) { .num_threads = stol(v[StatPos::num_threads - 1]), .starttime = stoull(v[StatPos::starttime - 1]), .vms = stoul(v[StatPos::vsize - 1]), - .rss = stoul(v[StatPos::rss - 1]), + .rss = stol(v[StatPos::rss - 1]), .processor = stoi(v[StatPos::processor - 1]), }; return p; diff --git a/selfdrive/proclogd/proclog.h b/system/proclogd/proclog.h similarity index 90% rename from selfdrive/proclogd/proclog.h rename to system/proclogd/proclog.h index 9ed53d1bac..49f97cdd36 100644 --- a/selfdrive/proclogd/proclog.h +++ b/system/proclogd/proclog.h @@ -20,8 +20,8 @@ struct ProcCache { struct ProcStat { int pid, ppid, processor; char state; - long cutime, cstime, priority, nice, num_threads; - unsigned long utime, stime, vms, rss; + long cutime, cstime, priority, nice, num_threads, rss; + unsigned long utime, stime, vms; unsigned long long starttime; std::string name; }; diff --git a/selfdrive/proclogd/tests/.gitignore b/system/proclogd/tests/.gitignore similarity index 100% rename from selfdrive/proclogd/tests/.gitignore rename to system/proclogd/tests/.gitignore diff --git a/selfdrive/proclogd/tests/test_proclog.cc b/system/proclogd/tests/test_proclog.cc similarity index 89% rename from selfdrive/proclogd/tests/test_proclog.cc rename to system/proclogd/tests/test_proclog.cc index 88a09dd03b..affde2f320 100644 --- a/selfdrive/proclogd/tests/test_proclog.cc +++ b/system/proclogd/tests/test_proclog.cc @@ -1,7 +1,7 @@ #define CATCH_CONFIG_MAIN #include "catch2/catch.hpp" -#include "selfdrive/common/util.h" -#include "selfdrive/proclogd/proclog.h" +#include "common/util.h" +#include "system/proclogd/proclog.h" const std::string allowed_states = "RSDTZtWXxKWPI"; @@ -140,6 +140,18 @@ TEST_CASE("buildProcLogerMessage") { REQUIRE(p.getName() == "test_proclog"); REQUIRE(p.getState() == 'R'); REQUIRE_THAT(p.getExe().cStr(), Catch::Matchers::Contains("test_proclog")); + REQUIRE(p.getCmdline().size() == 1); + REQUIRE_THAT(p.getCmdline()[0], Catch::Matchers::Contains("test_proclog")); + } else { + std::string cmd_path = "/proc/" + std::to_string(p.getPid()) + "/cmdline"; + if (util::file_exists(cmd_path)) { + std::ifstream stream(cmd_path); + auto cmdline = Parser::cmdline(stream); + REQUIRE(cmdline.size() == p.getCmdline().size()); + for (int i = 0; i < p.getCmdline().size(); ++i) { + REQUIRE(cmdline[i] == p.getCmdline()[i].cStr()); + } + } } } } diff --git a/selfdrive/swaglog.py b/system/swaglog.py similarity index 99% rename from selfdrive/swaglog.py rename to system/swaglog.py index a987bfe72c..68664330a5 100644 --- a/selfdrive/swaglog.py +++ b/system/swaglog.py @@ -7,7 +7,7 @@ from logging.handlers import BaseRotatingHandler import zmq from common.logging_extra import SwagLogger, SwagFormatter, SwagLogFileFormatter -from selfdrive.hardware import PC +from system.hardware import PC if PC: SWAGLOG_DIR = os.path.join(str(Path.home()), ".comma", "log") diff --git a/selfdrive/timezoned.py b/system/timezoned.py similarity index 96% rename from selfdrive/timezoned.py rename to system/timezoned.py index 6a7e9122c1..884a5c3812 100755 --- a/selfdrive/timezoned.py +++ b/system/timezoned.py @@ -9,8 +9,8 @@ import requests from timezonefinder import TimezoneFinder from common.params import Params -from selfdrive.hardware import TICI -from selfdrive.swaglog import cloudlog +from system.hardware import AGNOS +from system.swaglog import cloudlog def set_timezone(valid_timezones, timezone): @@ -20,7 +20,7 @@ def set_timezone(valid_timezones, timezone): cloudlog.debug(f"Setting timezone to {timezone}") try: - if TICI: + if AGNOS: tzpath = os.path.join("/usr/share/zoneinfo/", timezone) subprocess.check_call(f'sudo su -c "ln -snf {tzpath} /data/etc/tmptime && \ mv /data/etc/tmptime /data/etc/localtime"', shell=True) diff --git a/selfdrive/version.py b/system/version.py similarity index 88% rename from selfdrive/version.py rename to system/version.py index 9b18edc432..6031531556 100644 --- a/selfdrive/version.py +++ b/system/version.py @@ -5,9 +5,10 @@ from typing import List, Optional from functools import lru_cache from common.basedir import BASEDIR -from selfdrive.swaglog import cloudlog +from system.swaglog import cloudlog -TESTED_BRANCHES = ['devel', 'release2-staging', 'release3-staging', 'dashcam-staging', 'release2', 'release3', 'dashcam'] +RELEASE_BRANCHES = ['release3-staging', 'dashcam3-staging', 'release3', 'dashcam3'] +TESTED_BRANCHES = RELEASE_BRANCHES + ['devel', 'devel-staging'] training_version: bytes = b"0.2.0" terms_version: bytes = b"2" @@ -55,7 +56,7 @@ def get_origin(default: Optional[str] = None) -> Optional[str]: @cache def get_normalized_origin(default: Optional[str] = None) -> Optional[str]: - origin = get_origin() + origin: Optional[str] = get_origin() if origin is None: return default @@ -68,13 +69,13 @@ def get_normalized_origin(default: Optional[str] = None) -> Optional[str]: @cache def get_version() -> str: - with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "common", "version.h")) as _versionf: + with open(os.path.join(BASEDIR, "common", "version.h")) as _versionf: version = _versionf.read().split('"')[1] return version @cache def get_short_version() -> str: - return get_version().split('-')[0] + return get_version().split('-')[0] # type: ignore @cache def is_prebuilt() -> bool: @@ -85,7 +86,7 @@ def is_prebuilt() -> bool: def is_comma_remote() -> bool: # note to fork maintainers, this is used for release metrics. please do not # touch this to get rid of the orange startup alert. there's better ways to do that - origin = get_origin() + origin: Optional[str] = get_origin() if origin is None: return False @@ -96,6 +97,9 @@ def is_comma_remote() -> bool: def is_tested_branch() -> bool: return get_short_branch() in TESTED_BRANCHES +@cache +def is_release_branch() -> bool: + return get_short_branch() in RELEASE_BRANCHES @cache def is_dirty() -> bool: diff --git a/third_party/SConscript b/third_party/SConscript index 5a7a62ae5a..e5bbfaa07a 100644 --- a/third_party/SConscript +++ b/third_party/SConscript @@ -1,6 +1,6 @@ Import('env') -env.Library('json11', ['json11/json11.cpp']) +env.Library('json11', ['json11/json11.cpp'], CCFLAGS=env['CCFLAGS'] + ['-Wno-unqualified-std-cast-call']) env.Append(CPPPATH=[Dir('json11')]) env.Library('kaitai', ['kaitai/kaitaistream.cpp'], CPPDEFINES=['KS_STR_ENCODING_NONE']) diff --git a/third_party/acados/Darwin/lib/libacados.dylib b/third_party/acados/Darwin/lib/libacados.dylib index 056074e168..6d133f693d 100755 Binary files a/third_party/acados/Darwin/lib/libacados.dylib and b/third_party/acados/Darwin/lib/libacados.dylib differ diff --git a/third_party/acados/Darwin/lib/libblasfeo.dylib b/third_party/acados/Darwin/lib/libblasfeo.dylib index e984307a2c..7ba6a8b32d 100755 Binary files a/third_party/acados/Darwin/lib/libblasfeo.dylib and b/third_party/acados/Darwin/lib/libblasfeo.dylib differ diff --git a/third_party/acados/Darwin/lib/libhpipm.dylib b/third_party/acados/Darwin/lib/libhpipm.dylib index a600c765bb..69141c8178 100755 Binary files a/third_party/acados/Darwin/lib/libhpipm.dylib and b/third_party/acados/Darwin/lib/libhpipm.dylib differ diff --git a/third_party/acados/Darwin/lib/libqpOASES_e.3.1.dylib b/third_party/acados/Darwin/lib/libqpOASES_e.3.1.dylib index 185100d2cd..b0cf93b060 100755 Binary files a/third_party/acados/Darwin/lib/libqpOASES_e.3.1.dylib and b/third_party/acados/Darwin/lib/libqpOASES_e.3.1.dylib differ diff --git a/third_party/acados/Darwin/t_renderer b/third_party/acados/Darwin/t_renderer index 7ee3eda293..1afbd81519 100755 Binary files a/third_party/acados/Darwin/t_renderer and b/third_party/acados/Darwin/t_renderer differ diff --git a/third_party/acados/aarch64/lib/libacados.so b/third_party/acados/aarch64/lib/libacados.so deleted file mode 100755 index fe961d8c50..0000000000 Binary files a/third_party/acados/aarch64/lib/libacados.so and /dev/null differ diff --git a/third_party/acados/aarch64/lib/libblasfeo.so b/third_party/acados/aarch64/lib/libblasfeo.so deleted file mode 100755 index a59f3f79f8..0000000000 Binary files a/third_party/acados/aarch64/lib/libblasfeo.so and /dev/null differ diff --git a/third_party/acados/aarch64/lib/libhpipm.so b/third_party/acados/aarch64/lib/libhpipm.so deleted file mode 100755 index 6916c9c713..0000000000 Binary files a/third_party/acados/aarch64/lib/libhpipm.so and /dev/null differ diff --git a/third_party/acados/aarch64/lib/libqpOASES_e.so b/third_party/acados/aarch64/lib/libqpOASES_e.so deleted file mode 120000 index 14048625a1..0000000000 --- a/third_party/acados/aarch64/lib/libqpOASES_e.so +++ /dev/null @@ -1 +0,0 @@ -libqpOASES_e.so.3.1 \ No newline at end of file diff --git a/third_party/acados/aarch64/lib/libqpOASES_e.so.3.1 b/third_party/acados/aarch64/lib/libqpOASES_e.so.3.1 deleted file mode 100755 index 98d8dbfcd1..0000000000 Binary files a/third_party/acados/aarch64/lib/libqpOASES_e.so.3.1 and /dev/null differ diff --git a/third_party/acados/aarch64/t_renderer b/third_party/acados/aarch64/t_renderer deleted file mode 100755 index dc3cdf554f..0000000000 Binary files a/third_party/acados/aarch64/t_renderer and /dev/null differ diff --git a/third_party/acados/build.sh b/third_party/acados/build.sh index 9216032e98..0481e8159b 100755 --- a/third_party/acados/build.sh +++ b/third_party/acados/build.sh @@ -1,4 +1,5 @@ -#!/usr/bin/bash -e +#!/usr/bin/env bash +set -e DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" @@ -7,25 +8,34 @@ BLAS_TARGET="X64_AUTOMATIC" if [ -f /TICI ]; then ARCHNAME="larch64" BLAS_TARGET="ARMV8A_ARM_CORTEX_A57" -elif [ -f /EON ]; then - ARCHNAME="aarch64" - BLAS_TARGET="ARMV8A_ARM_CORTEX_A57" +fi + +ACADOS_FLAGS="-DACADOS_WITH_QPOASES=ON -UBLASFEO_TARGET -DBLASFEO_TARGET=$BLAS_TARGET" + +if [[ "$OSTYPE" == "darwin"* ]]; then + if [[ $(uname -m) == "x86_64" ]]; then + ACADOS_FLAGS="$ACADOS_FLAGS -DCMAKE_OSX_ARCHITECTURES=x86_64" + ARCHNAME="Darwin_x86_64" + else + ACADOS_FLAGS="$ACADOS_FLAGS -DCMAKE_OSX_ARCHITECTURES=arm64;x86_64" + ARCHNAME="Darwin" + fi fi if [ ! -d acados_repo/ ]; then - #git clone https://github.com/acados/acados.git $DIR/acados - git clone https://github.com/commaai/acados.git $DIR/acados_repo + git clone https://github.com/acados/acados.git $DIR/acados_repo + # git clone https://github.com/commaai/acados.git $DIR/acados_repo fi cd acados_repo -git fetch -git checkout 79e9e3e76f2751198858adf382c97837833ad31f +git fetch --all +git checkout 8ea8827fafb1b23b4c7da1c4cf650de1cbd73584 git submodule update --recursive --init # build mkdir -p build cd build -cmake -DACADOS_WITH_QPOASES=ON -UBLASFEO_TARGET -DBLASFEO_TARGET=$BLAS_TARGET .. -make -j4 install +cmake $ACADOS_FLAGS .. +make -j20 install INSTALL_DIR="$DIR/$ARCHNAME" rm -rf $INSTALL_DIR @@ -33,43 +43,14 @@ mkdir -p $INSTALL_DIR rm $DIR/acados_repo/lib/*.json +rm -rf $DIR/include cp -r $DIR/acados_repo/include $DIR cp -r $DIR/acados_repo/lib $INSTALL_DIR +rm -rf $DIR/../../pyextra/acados_template cp -r $DIR/acados_repo/interfaces/acados_template/acados_template $DIR/../../pyextra #pip3 install -e $DIR/acados/interfaces/acados_template -# hack to workaround no rpath on android -if [ -f /EON ]; then - pushd $INSTALL_DIR/lib - for lib in $(ls .); do - if ! readlink $lib; then - patchelf --set-soname $PWD/$lib $lib - - if [ "$lib" = "libacados.so" ]; then - for nlib in "libhpipm.so" "libblasfeo.so" "libqpOASES_e.so.3.1"; do - patchelf --replace-needed $nlib $PWD/$nlib $lib - done - fi - - if [ "$lib" = "libhpipm.so" ]; then - patchelf --replace-needed libblasfeo.so $PWD/libblasfeo.so $lib - fi - - # pad extra byte to workaround bionic linker bug - # https://android.googlesource.com/platform/bionic/+/93ce35434ca5af43a7449e289959543f0a2426fa%5E%21/#F0 - dd if=/dev/zero bs=1 count=1 >> $lib - fi - done - popd - - cd $DIR - git checkout $INSTALL_DIR/t_renderer -fi - # build tera -# build with commaai/termux-packages for NEOS -if [ ! -f /EON ]; then - cd $DIR/acados_repo/interfaces/acados_template/tera_renderer/ - cargo build --verbose --release - cp target/release/t_renderer $INSTALL_DIR/ -fi +cd $DIR/acados_repo/interfaces/acados_template/tera_renderer/ +cargo build --verbose --release +cp target/release/t_renderer $INSTALL_DIR/ diff --git a/third_party/acados/include/acados/dense_qp/dense_qp_qpoases.h b/third_party/acados/include/acados/dense_qp/dense_qp_qpoases.h index 8fca17dd17..9f0bb1af68 100644 --- a/third_party/acados/include/acados/dense_qp/dense_qp_qpoases.h +++ b/third_party/acados/include/acados/dense_qp/dense_qp_qpoases.h @@ -118,6 +118,8 @@ int dense_qp_qpoases(void *config, dense_qp_in *qp_in, dense_qp_out *qp_out, voi // void dense_qp_qpoases_eval_sens(void *config_, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); // +void dense_qp_qpoases_memory_reset(void *config_, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); +// void dense_qp_qpoases_config_initialize_default(void *config_); #ifdef __cplusplus diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_common.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_common.h index 64939b9ed1..60d835fc58 100644 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_common.h +++ b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_common.h @@ -93,6 +93,7 @@ typedef struct ocp_nlp_config char *field, int stage, int index, void *sens_nlp_out); // prepare memory int (*precompute)(void *config, void *dims, void *nlp_in, void *nlp_out, void *opts_, void *mem, void *work); + void (*memory_reset_qp_solver)(void *config, void *dims, void *nlp_in, void *nlp_out, void *opts_, void *mem, void *work); // initalize this struct with default values void (*config_initialize_default)(void *config); // general getter @@ -234,11 +235,7 @@ typedef struct ocp_nlp_out // NOTE: the inequalities are internally organized in the following order: // [ lbu lbx lg lh lphi ubu ubx ug uh uphi; lsbu lsbx lsg lsh lsphi usbu usbx usg ush usphi] - - int sqp_iter; - int qp_iter; double inf_norm_res; - double total_time; void *raw_memory; // Pointer to allocated memory, to be used for freeing @@ -274,11 +271,16 @@ typedef struct ocp_nlp_opts double levenberg_marquardt; // LM factor to be added to the hessian before regularization int reuse_workspace; int num_threads; + int print_level; // TODO: move to separate struct? ocp_nlp_globalization_t globalization; + int full_step_dual; + int line_search_use_sufficient_descent; + int globalization_use_SOC; double alpha_min; double alpha_reduction; + double eps_sufficient_descent; } ocp_nlp_opts; // @@ -305,6 +307,7 @@ typedef struct ocp_nlp_res struct blasfeo_dvec *res_eq; // dynamics struct blasfeo_dvec *res_ineq; // inequality constraints struct blasfeo_dvec *res_comp; // complementarity + struct blasfeo_dvec tmp; // tmp double inf_norm_res_stat; double inf_norm_res_eq; double inf_norm_res_ineq; @@ -316,6 +319,8 @@ typedef struct ocp_nlp_res acados_size_t ocp_nlp_res_calculate_size(ocp_nlp_dims *dims); // ocp_nlp_res *ocp_nlp_res_assign(ocp_nlp_dims *dims, void *raw_memory); +// +void ocp_nlp_res_get_inf_norm(ocp_nlp_res *res, double *out); /************************************************ * memory @@ -351,7 +356,7 @@ typedef struct ocp_nlp_memory bool *set_sim_guess; // indicate if there is new explicitly provided guess for integration variables struct blasfeo_dvec *sim_guess; - int *sqp_iter; // pointer to iteration number + int *sqp_iter; // pointer to iteration number } ocp_nlp_memory; @@ -375,8 +380,12 @@ typedef struct ocp_nlp_workspace void **cost; // cost_workspace void **constraints; // constraints_workspace - ocp_nlp_out *tmp_nlp_out; - ocp_nlp_out *weight_merit_fun; + // for globalization: -> move to module?! + ocp_nlp_out *tmp_nlp_out; + ocp_nlp_out *weight_merit_fun; + struct blasfeo_dvec tmp_nxu; + struct blasfeo_dvec tmp_ni; + struct blasfeo_dvec dxnext_dy; } ocp_nlp_workspace; @@ -392,8 +401,10 @@ ocp_nlp_workspace *ocp_nlp_workspace_assign(ocp_nlp_config *config, ocp_nlp_dims * function ************************************************/ +void ocp_nlp_alias_memory_to_submodules(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, + ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work); // -void ocp_nlp_initialize_qp(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, +void ocp_nlp_initialize_submodules(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work); // void ocp_nlp_approximate_qp_matrices(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, @@ -409,7 +420,8 @@ void ocp_nlp_update_variables_sqp(ocp_nlp_config *config, ocp_nlp_dims *dims, oc ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work, double alpha); // double ocp_nlp_line_search(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work); + ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work, + int check_early_termination); // double ocp_nlp_evaluate_merit_fun(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work); diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_dynamics_common.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_dynamics_common.h index 45dac20a25..f2128a8574 100644 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_dynamics_common.h +++ b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_dynamics_common.h @@ -84,6 +84,7 @@ typedef struct /* memory */ acados_size_t (*memory_calculate_size)(void *config, void *dims, void *opts); void *(*memory_assign)(void *config, void *dims, void *opts, void *raw_memory); + // get shooting node gap x_next(x_n, u_n) - x_{n+1} struct blasfeo_dvec *(*memory_get_fun_ptr)(void *memory_); struct blasfeo_dvec *(*memory_get_adj_ptr)(void *memory_); void (*memory_set_ux_ptr)(struct blasfeo_dvec *ux, void *memory_); diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_noreg.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_noreg.h index 8d2b6ecc13..c085e00d5d 100644 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_noreg.h +++ b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_noreg.h @@ -65,11 +65,6 @@ extern "C" { * options ************************************************/ -typedef struct -{ - int dummy; -} ocp_nlp_reg_noreg_opts; - // acados_size_t ocp_nlp_reg_noreg_opts_calculate_size(void); // @@ -84,12 +79,6 @@ void ocp_nlp_reg_noreg_opts_set(void *config_, ocp_nlp_reg_dims *dims, void *opt /************************************************ * memory ************************************************/ - -typedef struct -{ - int dummy; -} ocp_nlp_reg_noreg_memory; - // acados_size_t ocp_nlp_reg_noreg_memory_calculate_size(void *config, ocp_nlp_reg_dims *dims, void *opts); // diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_sqp.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_sqp.h index 81a4afd030..74cfb042e3 100644 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_sqp.h +++ b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_sqp.h @@ -68,7 +68,6 @@ typedef struct int qp_warm_start; // qp_warm_start in all but the first sqp iterations bool warm_start_first_qp; // to set qp_warm_start in first iteration int rti_phase; // only phase 0 at the moment - int print_level; // verbosity int initialize_t_slacks; // 0-false or 1-true } ocp_nlp_sqp_opts; @@ -107,6 +106,7 @@ typedef struct double time_sim; double time_sim_la; double time_sim_ad; + double time_solution_sensitivities; // statistics double *stat; @@ -122,7 +122,9 @@ typedef struct acados_size_t ocp_nlp_sqp_memory_calculate_size(void *config, void *dims, void *opts_); // void *ocp_nlp_sqp_memory_assign(void *config, void *dims, void *opts_, void *raw_memory); - +// +void ocp_nlp_sqp_memory_reset_qp_solver(void *config_, void *dims_, void *nlp_in_, void *nlp_out_, + void *opts_, void *mem_, void *work_); /************************************************ diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_sqp_rti.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_sqp_rti.h index 6f16594d2b..af22c06a17 100644 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_sqp_rti.h +++ b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_sqp_rti.h @@ -64,7 +64,6 @@ typedef struct int qp_warm_start; // NOTE: this is not actually setting the warm_start! Just for compatibility with sqp. bool warm_start_first_qp; // to set qp_warm_start in first iteration int rti_phase; // phase of RTI. Possible values 1 (preparation), 2 (feedback) 0 (both) - int print_level; // verbosity } ocp_nlp_sqp_rti_opts; @@ -100,6 +99,7 @@ typedef struct double time_reg; double time_tot; double time_glob; + double time_solution_sensitivities; // statistics double *stat; diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_common.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_common.h index bba55f8f75..caf6caf2f0 100644 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_common.h +++ b/third_party/acados/include/acados/ocp_qp/ocp_qp_common.h @@ -72,6 +72,7 @@ typedef struct void (*memory_get)(void *config_, void *mem_, const char *field, void* value); acados_size_t (*workspace_calculate_size)(void *config, void *dims, void *opts); int (*evaluate)(void *config, void *qp_in, void *qp_out, void *opts, void *mem, void *work); + void (*memory_reset)(void *config, void *qp_in, void *qp_out, void *opts, void *mem, void *work); void (*eval_sens)(void *config, void *qp_in, void *qp_out, void *opts, void *mem, void *work); } qp_solver_config; #endif diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_hpipm.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_hpipm.h index 84e874863f..91690e458d 100644 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_hpipm.h +++ b/third_party/acados/include/acados/ocp_qp/ocp_qp_hpipm.h @@ -63,6 +63,7 @@ typedef struct ocp_qp_hpipm_memory_ struct d_ocp_qp_ipm_ws *hpipm_workspace; double time_qp_solver_call; int iter; + int status; } ocp_qp_hpipm_memory; @@ -87,6 +88,8 @@ acados_size_t ocp_qp_hpipm_workspace_calculate_size(void *config, void *dims, vo // int ocp_qp_hpipm(void *config, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); // +void ocp_qp_hpipm_memory_reset(void *config_, void *qp_in_, void *qp_out_, void *opts_, void *mem_, void *work_); +// void ocp_qp_hpipm_eval_sens(void *config, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); // void ocp_qp_hpipm_config_initialize_default(void *config); diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_hpmpc.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_hpmpc.h index 37d1c0a337..de6ce501b1 100644 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_hpmpc.h +++ b/third_party/acados/include/acados/ocp_qp/ocp_qp_hpmpc.h @@ -99,6 +99,7 @@ typedef struct ocp_qp_hpmpc_memory_ double time_qp_solver_call; int iter; + int status; } ocp_qp_hpmpc_memory; diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_ooqp.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_ooqp.h index e1b789b96a..1a3b7b2fa2 100644 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_ooqp.h +++ b/third_party/acados/include/acados/ocp_qp/ocp_qp_ooqp.h @@ -112,6 +112,7 @@ typedef struct ocp_qp_ooqp_memory_ int nnz; // max(nnzQ, nnzA, nnzC) double time_qp_solver_call; int iter; + int status; } ocp_qp_ooqp_memory; diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_osqp.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_osqp.h index 55321a46b2..4ae391a9ff 100644 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_osqp.h +++ b/third_party/acados/include/acados/ocp_qp/ocp_qp_osqp.h @@ -75,6 +75,7 @@ typedef struct ocp_qp_osqp_memory_ double time_qp_solver_call; int iter; + int status; } ocp_qp_osqp_memory; diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_qpdunes.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_qpdunes.h index 348627c676..ad4d094516 100644 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_qpdunes.h +++ b/third_party/acados/include/acados/ocp_qp/ocp_qp_qpdunes.h @@ -71,6 +71,7 @@ typedef struct ocp_qp_qpdunes_memory_ qpData_t qpData; double time_qp_solver_call; int iter; + int status; } ocp_qp_qpdunes_memory; diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_xcond_solver.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_xcond_solver.h index 9d4f309bd9..d4b30e007b 100644 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_xcond_solver.h +++ b/third_party/acados/include/acados/ocp_qp/ocp_qp_xcond_solver.h @@ -92,6 +92,7 @@ typedef struct acados_size_t (*memory_calculate_size)(void *config, ocp_qp_xcond_solver_dims *dims, void *opts); void *(*memory_assign)(void *config, ocp_qp_xcond_solver_dims *dims, void *opts, void *raw_memory); void (*memory_get)(void *config_, void *mem_, const char *field, void* value); + void (*memory_reset)(void *config, ocp_qp_xcond_solver_dims *dims, ocp_qp_in *qp_in, ocp_qp_out *qp_out, void *opts, void *mem, void *work); acados_size_t (*workspace_calculate_size)(void *config, ocp_qp_xcond_solver_dims *dims, void *opts); int (*evaluate)(void *config, ocp_qp_xcond_solver_dims *dims, ocp_qp_in *qp_in, ocp_qp_out *qp_out, void *opts, void *mem, void *work); void (*eval_sens)(void *config, ocp_qp_xcond_solver_dims *dims, ocp_qp_in *param_qp_in, ocp_qp_out *sens_qp_out, void *opts, void *mem, void *work); diff --git a/third_party/acados/include/acados/sim/sim_lifted_irk_integrator.h b/third_party/acados/include/acados/sim/sim_lifted_irk_integrator.h index 8e476b0e27..9ec2d97bed 100644 --- a/third_party/acados/include/acados/sim/sim_lifted_irk_integrator.h +++ b/third_party/acados/include/acados/sim/sim_lifted_irk_integrator.h @@ -96,6 +96,7 @@ typedef struct struct blasfeo_dvec *u; // controls (nu) -- for expansion step int update_sens; + // int init_K; double time_sim; double time_ad; diff --git a/third_party/acados/include/acados/utils/print.h b/third_party/acados/include/acados/utils/print.h index 2993447dbd..f8568afb26 100644 --- a/third_party/acados/include/acados/utils/print.h +++ b/third_party/acados/include/acados/utils/print.h @@ -69,28 +69,32 @@ void ocp_nlp_out_print(ocp_nlp_dims *dims, ocp_nlp_out *nlp_out); void ocp_nlp_res_print(ocp_nlp_dims *dims, ocp_nlp_res *nlp_res); // ocp qp +// TODO: move printing routines below that print qp structures to HPIPM! void print_ocp_qp_dims(ocp_qp_dims *dims); // void print_dense_qp_dims(dense_qp_dims *dims); void print_ocp_qp_in(ocp_qp_in *qp_in); +void print_ocp_qp_in_to_file(FILE *file, ocp_qp_in *qp_in); + void print_ocp_qp_out(ocp_qp_out *qp_out); +void print_ocp_qp_out_to_file(FILE *file, ocp_qp_out *qp_out); + +void print_ocp_qp_res(ocp_qp_res *qp_res); + +void print_dense_qp_in(dense_qp_in *qp_in); // void print_ocp_qp_in_to_string(char string_out[], ocp_qp_in *qp_in); // void print_ocp_qp_out_to_string(char string_out[], ocp_qp_out *qp_out); -void print_ocp_qp_res(ocp_qp_res *qp_res); - // void print_colmaj_ocp_qp_in(colmaj_ocp_qp_in *qp); // void print_colmaj_ocp_qp_in_to_file(colmaj_ocp_qp_in *qp); // void print_colmaj_ocp_qp_out(char *filename, colmaj_ocp_qp_in *qp, colmaj_ocp_qp_out *out); -void print_dense_qp_in(dense_qp_in *qp_in); - void print_qp_info(qp_info *info); // void acados_warning(char warning_string[]); diff --git a/third_party/acados/include/acados/utils/types.h b/third_party/acados/include/acados/utils/types.h index 99ad375fea..d3da0a86b7 100644 --- a/third_party/acados/include/acados/utils/types.h +++ b/third_party/acados/include/acados/utils/types.h @@ -35,6 +35,21 @@ #ifndef ACADOS_UTILS_TYPES_H_ #define ACADOS_UTILS_TYPES_H_ +/* Symbol visibility in DLLs */ +#ifndef ACADOS_SYMBOL_EXPORT + #if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) + #if defined(STATIC_LINKED) + #define ACADOS_SYMBOL_EXPORT + #else + #define ACADOS_SYMBOL_EXPORT __declspec(dllexport) + #endif + #elif defined(__GNUC__) && ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) + #define ACADOS_SYMBOL_EXPORT __attribute__ ((visibility ("default"))) + #else + #define ACADOS_SYMBOL_EXPORT + #endif +#endif + #ifdef __cplusplus extern "C" { #endif diff --git a/third_party/acados/include/acados_c/ocp_nlp_interface.h b/third_party/acados/include/acados_c/ocp_nlp_interface.h index b6b893024b..50bc0cf1af 100644 --- a/third_party/acados/include/acados_c/ocp_nlp_interface.h +++ b/third_party/acados/include/acados_c/ocp_nlp_interface.h @@ -46,6 +46,7 @@ extern "C" { #include "acados/sim/sim_irk_integrator.h" #include "acados/sim/sim_lifted_irk_integrator.h" #include "acados/sim/sim_gnsf.h" +#include "acados/utils/types.h" // acados_c #include "acados_c/ocp_qp_interface.h" #include "acados_c/sim_interface.h" @@ -107,13 +108,13 @@ typedef enum /// Structure to store the configuration of a non-linear program -typedef struct ocp_nlp_plan +typedef struct ocp_nlp_plan_t { /// QP solver configuration. - ocp_qp_solver_plan ocp_qp_solver_plan; + ocp_qp_solver_plan_t ocp_qp_solver_plan; /// Simulation solver configuration for each stage. - sim_solver_plan *sim_solver_plan; + sim_solver_plan_t *sim_solver_plan; /// Nlp solver type. ocp_nlp_solver_t nlp_solver; @@ -133,7 +134,7 @@ typedef struct ocp_nlp_plan /// Horizon length. int N; -} ocp_nlp_plan; +} ocp_nlp_plan_t; /// Structure to store the state/configuration for the non-linear programming solver @@ -151,46 +152,46 @@ typedef struct ocp_nlp_solver /// default/invalid state. /// /// \param N Horizon length -ocp_nlp_plan *ocp_nlp_plan_create(int N); +ACADOS_SYMBOL_EXPORT ocp_nlp_plan_t *ocp_nlp_plan_create(int N); /// Destructor for plan struct, frees memory. /// /// \param plan_ The plan struct to destroy. -void ocp_nlp_plan_destroy(void* plan_); +ACADOS_SYMBOL_EXPORT void ocp_nlp_plan_destroy(void* plan_); /// Constructs an nlp configuration struct from a plan. /// /// \param plan The plan (user nlp configuration). -ocp_nlp_config *ocp_nlp_config_create(ocp_nlp_plan plan); +ACADOS_SYMBOL_EXPORT ocp_nlp_config *ocp_nlp_config_create(ocp_nlp_plan_t plan); /// Desctructor of the nlp configuration. /// /// \param config_ The configuration struct. -void ocp_nlp_config_destroy(void *config_); +ACADOS_SYMBOL_EXPORT void ocp_nlp_config_destroy(void *config_); /// Constructs an struct that contains the dimensions of the variables. /// /// \param config_ The configuration struct. -ocp_nlp_dims *ocp_nlp_dims_create(void *config_); +ACADOS_SYMBOL_EXPORT ocp_nlp_dims *ocp_nlp_dims_create(void *config_); /// Destructor of The dimension struct. /// /// \param dims_ The dimension struct. -void ocp_nlp_dims_destroy(void *dims_); +ACADOS_SYMBOL_EXPORT void ocp_nlp_dims_destroy(void *dims_); /// Constructs an input struct for a non-linear programs. /// /// \param config The configuration struct. /// \param dims The dimension struct. -ocp_nlp_in *ocp_nlp_in_create(ocp_nlp_config *config, ocp_nlp_dims *dims); +ACADOS_SYMBOL_EXPORT ocp_nlp_in *ocp_nlp_in_create(ocp_nlp_config *config, ocp_nlp_dims *dims); /// Destructor of the inputs struct. /// /// \param in The inputs struct. -void ocp_nlp_in_destroy(void *in); +ACADOS_SYMBOL_EXPORT void ocp_nlp_in_destroy(void *in); /// Sets the sampling times for the given stage. @@ -201,9 +202,12 @@ void ocp_nlp_in_destroy(void *in); /// \param stage Stage number. /// \param field Has to be "Ts" (TBC other options). /// \param value The sampling times (floating point). -void ocp_nlp_in_set(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, int stage, +ACADOS_SYMBOL_EXPORT void ocp_nlp_in_set(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, int stage, const char *field, void *value); +/// +// void ocp_nlp_in_get(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, int stage, +// const char *field, void *value); /// Sets the function pointers to the dynamics functions for the given stage. /// @@ -214,7 +218,7 @@ void ocp_nlp_in_set(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, /// \param fun_type The name of the function type, either impl_ode_fun, /// impl_ode_fun_jac_x_xdot, impl_ode_jac_x_xdot_u (TBC) /// \param fun_ptr Function pointer to the dynamics function. -int ocp_nlp_dynamics_model_set(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, +ACADOS_SYMBOL_EXPORT int ocp_nlp_dynamics_model_set(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, int stage, const char *fun_type, void *fun_ptr); @@ -227,7 +231,7 @@ int ocp_nlp_dynamics_model_set(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_n /// \param field The name of the field, either nls_res_jac, /// y_ref, W (others TBC) /// \param value Cost values. -int ocp_nlp_cost_model_set(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, +ACADOS_SYMBOL_EXPORT int ocp_nlp_cost_model_set(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, int stage, const char *field, void *value); @@ -239,7 +243,7 @@ int ocp_nlp_cost_model_set(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_i /// \param stage Stage number. /// \param field The name of the field, either lb, ub (others TBC) /// \param value Constraints function or values. -int ocp_nlp_constraints_model_set(ocp_nlp_config *config, ocp_nlp_dims *dims, +ACADOS_SYMBOL_EXPORT int ocp_nlp_constraints_model_set(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, int stage, const char *field, void *value); /* out */ @@ -248,12 +252,12 @@ int ocp_nlp_constraints_model_set(ocp_nlp_config *config, ocp_nlp_dims *dims, /// /// \param config The configuration struct. /// \param dims The dimension struct. -ocp_nlp_out *ocp_nlp_out_create(ocp_nlp_config *config, ocp_nlp_dims *dims); +ACADOS_SYMBOL_EXPORT ocp_nlp_out *ocp_nlp_out_create(ocp_nlp_config *config, ocp_nlp_dims *dims); /// Destructor of the output struct. /// /// \param out The output struct. -void ocp_nlp_out_destroy(void *out); +ACADOS_SYMBOL_EXPORT void ocp_nlp_out_destroy(void *out); /// Sets fields in the output struct of an nlp solver, used to initialize the solver. @@ -264,7 +268,7 @@ void ocp_nlp_out_destroy(void *out); /// \param stage Stage number. /// \param field The name of the field, either x, u, pi. /// \param value Initialization values. -void ocp_nlp_out_set(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, +ACADOS_SYMBOL_EXPORT void ocp_nlp_out_set(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, int stage, const char *field, void *value); @@ -276,21 +280,21 @@ void ocp_nlp_out_set(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *ou /// \param stage Stage number. /// \param field The name of the field, either x, u, z, pi. /// \param value Pointer to the output memory. -void ocp_nlp_out_get(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, +ACADOS_SYMBOL_EXPORT void ocp_nlp_out_get(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, int stage, const char *field, void *value); // -void ocp_nlp_get_at_stage(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_solver *solver, +ACADOS_SYMBOL_EXPORT void ocp_nlp_get_at_stage(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_solver *solver, int stage, const char *field, void *value); // TODO(andrea): remove this once/if the MATLAB interface uses the new setters below? -int ocp_nlp_dims_get_from_attr(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, +ACADOS_SYMBOL_EXPORT int ocp_nlp_dims_get_from_attr(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, int stage, const char *field); -void ocp_nlp_constraint_dims_get_from_attr(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, +ACADOS_SYMBOL_EXPORT void ocp_nlp_constraint_dims_get_from_attr(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, int stage, const char *field, int *dims_out); -void ocp_nlp_cost_dims_get_from_attr(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, +ACADOS_SYMBOL_EXPORT void ocp_nlp_cost_dims_get_from_attr(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, int stage, const char *field, int *dims_out); void ocp_nlp_dynamics_dims_get_from_attr(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, @@ -302,12 +306,12 @@ void ocp_nlp_dynamics_dims_get_from_attr(ocp_nlp_config *config, ocp_nlp_dims *d /// /// \param config The configuration struct. /// \param dims The dimension struct. -void *ocp_nlp_solver_opts_create(ocp_nlp_config *config, ocp_nlp_dims *dims); +ACADOS_SYMBOL_EXPORT void *ocp_nlp_solver_opts_create(ocp_nlp_config *config, ocp_nlp_dims *dims); /// Destructor of the options. /// /// \param opts The options struct. -void ocp_nlp_solver_opts_destroy(void *opts); +ACADOS_SYMBOL_EXPORT void ocp_nlp_solver_opts_destroy(void *opts); /// Sets an option. /// @@ -315,10 +319,13 @@ void ocp_nlp_solver_opts_destroy(void *opts); /// \param opts_ The options struct. /// \param field Name of the option. /// \param value Value of the option. -void ocp_nlp_solver_opts_set(ocp_nlp_config *config, void *opts_, const char *field, void* value); +ACADOS_SYMBOL_EXPORT void ocp_nlp_solver_opts_set(ocp_nlp_config *config, void *opts_, const char *field, void* value); + + +// ACADOS_SYMBOL_EXPORT void ocp_nlp_solver_opts_get(ocp_nlp_config *config, void *opts_, const char *field, void* value); -void ocp_nlp_solver_opts_set_at_stage(ocp_nlp_config *config, void *opts_, int stage, const char *field, void* value); +ACADOS_SYMBOL_EXPORT void ocp_nlp_solver_opts_set_at_stage(ocp_nlp_config *config, void *opts_, int stage, const char *field, void* value); /// TBC @@ -327,7 +334,7 @@ void ocp_nlp_solver_opts_set_at_stage(ocp_nlp_config *config, void *opts_, int s /// \param config The configuration struct. /// \param dims The dimension struct. /// \param opts_ The options struct. -void ocp_nlp_solver_opts_update(ocp_nlp_config *config, ocp_nlp_dims *dims, void *opts_); +ACADOS_SYMBOL_EXPORT void ocp_nlp_solver_opts_update(ocp_nlp_config *config, ocp_nlp_dims *dims, void *opts_); /* solver */ @@ -338,12 +345,12 @@ void ocp_nlp_solver_opts_update(ocp_nlp_config *config, ocp_nlp_dims *dims, void /// \param dims The dimension struct. /// \param opts_ The options struct. /// \return The solver. -ocp_nlp_solver *ocp_nlp_solver_create(ocp_nlp_config *config, ocp_nlp_dims *dims, void *opts_); +ACADOS_SYMBOL_EXPORT ocp_nlp_solver *ocp_nlp_solver_create(ocp_nlp_config *config, ocp_nlp_dims *dims, void *opts_); /// Destructor of the solver. /// /// \param solver The solver struct. -void ocp_nlp_solver_destroy(void *solver); +ACADOS_SYMBOL_EXPORT void ocp_nlp_solver_destroy(void *solver); /// Solves the optimal control problem. Call ocp_nlp_precompute before /// calling this functions (TBC). @@ -351,7 +358,17 @@ void ocp_nlp_solver_destroy(void *solver); /// \param solver The solver struct. /// \param nlp_in The inputs struct. /// \param nlp_out The output struct. -int ocp_nlp_solve(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in, ocp_nlp_out *nlp_out); +ACADOS_SYMBOL_EXPORT int ocp_nlp_solve(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in, ocp_nlp_out *nlp_out); + + + +/// Resets the memory of the QP solver +/// +/// \param solver The solver struct. +/// \param nlp_in The inputs struct. +/// \param nlp_out The output struct. +ACADOS_SYMBOL_EXPORT void ocp_nlp_solver_reset_qp_memory(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in, ocp_nlp_out *nlp_out); + /// Performs precomputations for the solver. Needs to be called before /// ocl_nlp_solve (TBC). @@ -359,7 +376,7 @@ int ocp_nlp_solve(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in, ocp_nlp_out *nlp_o /// \param solver The solver struct. /// \param nlp_in The inputs struct. /// \param nlp_out The output struct. -int ocp_nlp_precompute(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in, ocp_nlp_out *nlp_out); +ACADOS_SYMBOL_EXPORT int ocp_nlp_precompute(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in, ocp_nlp_out *nlp_out); /// Computes cost function value. @@ -367,20 +384,28 @@ int ocp_nlp_precompute(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in, ocp_nlp_out * /// \param solver The solver struct. /// \param nlp_in The inputs struct. /// \param nlp_out The output struct. -void ocp_nlp_eval_cost(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in, ocp_nlp_out *nlp_out); +ACADOS_SYMBOL_EXPORT void ocp_nlp_eval_cost(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in, ocp_nlp_out *nlp_out); // void ocp_nlp_eval_residuals(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in, ocp_nlp_out *nlp_out); +/// Computes the residuals. +/// +/// \param solver The solver struct. +/// \param nlp_in The inputs struct. +/// \param nlp_out The output struct. +ACADOS_SYMBOL_EXPORT void ocp_nlp_eval_residuals(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in, ocp_nlp_out *nlp_out); + + // -void ocp_nlp_eval_param_sens(ocp_nlp_solver *solver, char *field, int stage, int index, ocp_nlp_out *sens_nlp_out); +ACADOS_SYMBOL_EXPORT void ocp_nlp_eval_param_sens(ocp_nlp_solver *solver, char *field, int stage, int index, ocp_nlp_out *sens_nlp_out); /* get */ /// \param config The configuration struct. /// \param solver The solver struct. /// \param field Supports "sqp_iter", "status", "nlp_res", "time_tot", ... /// \param return_value_ Pointer to the output memory. -void ocp_nlp_get(ocp_nlp_config *config, ocp_nlp_solver *solver, +ACADOS_SYMBOL_EXPORT void ocp_nlp_get(ocp_nlp_config *config, ocp_nlp_solver *solver, const char *field, void *return_value_); /* set */ @@ -391,7 +416,7 @@ void ocp_nlp_get(ocp_nlp_config *config, ocp_nlp_solver *solver, /// \param stage Stage number. /// \param field Supports "z_guess", "xdot_guess" (IRK), "phi_guess" (GNSF-IRK) /// \param value The initial guess for the algebraic variables in the integrator (if continuous model is used). -void ocp_nlp_set(ocp_nlp_config *config, ocp_nlp_solver *solver, +ACADOS_SYMBOL_EXPORT void ocp_nlp_set(ocp_nlp_config *config, ocp_nlp_solver *solver, int stage, const char *field, void *value); diff --git a/third_party/acados/include/acados_c/ocp_qp_interface.h b/third_party/acados/include/acados_c/ocp_qp_interface.h index a567ebeb35..2582f142da 100644 --- a/third_party/acados/include/acados_c/ocp_qp_interface.h +++ b/third_party/acados/include/acados_c/ocp_qp_interface.h @@ -105,7 +105,7 @@ typedef enum { typedef struct { ocp_qp_solver_t qp_solver; -} ocp_qp_solver_plan; +} ocp_qp_solver_plan_t; /// Linear ocp configuration. @@ -127,7 +127,7 @@ void ocp_qp_xcond_solver_config_initialize_from_plan( /// Constructs a qp solver config and Initializes with default values. /// /// \param plan The qp solver plan struct. -ocp_qp_xcond_solver_config *ocp_qp_xcond_solver_config_create(ocp_qp_solver_plan plan); +ocp_qp_xcond_solver_config *ocp_qp_xcond_solver_config_create(ocp_qp_solver_plan_t plan); /// Destructor for config struct, frees memory. /// diff --git a/third_party/acados/include/acados_c/sim_interface.h b/third_party/acados/include/acados_c/sim_interface.h index cc47b62ed4..5dce6f153a 100644 --- a/third_party/acados/include/acados_c/sim_interface.h +++ b/third_party/acados/include/acados_c/sim_interface.h @@ -57,7 +57,7 @@ typedef enum typedef struct { sim_solver_t sim_solver; -} sim_solver_plan; +} sim_solver_plan_t; @@ -74,64 +74,64 @@ typedef struct /* config */ // -sim_config *sim_config_create(sim_solver_plan plan); +ACADOS_SYMBOL_EXPORT sim_config *sim_config_create(sim_solver_plan_t plan); // -void sim_config_destroy(void *config); +ACADOS_SYMBOL_EXPORT void sim_config_destroy(void *config); /* dims */ // -void *sim_dims_create(void *config_); +ACADOS_SYMBOL_EXPORT void *sim_dims_create(void *config_); // -void sim_dims_destroy(void *dims); +ACADOS_SYMBOL_EXPORT void sim_dims_destroy(void *dims); // -void sim_dims_set(sim_config *config, void *dims, const char *field, const int* value); +ACADOS_SYMBOL_EXPORT void sim_dims_set(sim_config *config, void *dims, const char *field, const int* value); // -void sim_dims_get(sim_config *config, void *dims, const char *field, int* value); +ACADOS_SYMBOL_EXPORT void sim_dims_get(sim_config *config, void *dims, const char *field, int* value); // -void sim_dims_get_from_attr(sim_config *config, void *dims, const char *field, int *dims_out); +ACADOS_SYMBOL_EXPORT void sim_dims_get_from_attr(sim_config *config, void *dims, const char *field, int *dims_out); /* in */ // -sim_in *sim_in_create(sim_config *config, void *dims); +ACADOS_SYMBOL_EXPORT sim_in *sim_in_create(sim_config *config, void *dims); // -void sim_in_destroy(void *out); +ACADOS_SYMBOL_EXPORT void sim_in_destroy(void *out); // -int sim_in_set(void *config_, void *dims_, sim_in *in, const char *field, void *value); +ACADOS_SYMBOL_EXPORT int sim_in_set(void *config_, void *dims_, sim_in *in, const char *field, void *value); /* out */ // -sim_out *sim_out_create(sim_config *config, void *dims); +ACADOS_SYMBOL_EXPORT sim_out *sim_out_create(sim_config *config, void *dims); // -void sim_out_destroy(void *out); +ACADOS_SYMBOL_EXPORT void sim_out_destroy(void *out); // -int sim_out_get(void *config, void *dims, sim_out *out, const char *field, void *value); +ACADOS_SYMBOL_EXPORT int sim_out_get(void *config, void *dims, sim_out *out, const char *field, void *value); /* opts */ // -void *sim_opts_create(sim_config *config, void *dims); +ACADOS_SYMBOL_EXPORT void *sim_opts_create(sim_config *config, void *dims); // -void sim_opts_destroy(void *opts); +ACADOS_SYMBOL_EXPORT void sim_opts_destroy(void *opts); // -void sim_opts_set(sim_config *config, void *opts, const char *field, void *value); +ACADOS_SYMBOL_EXPORT void sim_opts_set(sim_config *config, void *opts, const char *field, void *value); // -void sim_opts_get(sim_config *config, void *opts, const char *field, void *value); +ACADOS_SYMBOL_EXPORT void sim_opts_get(sim_config *config, void *opts, const char *field, void *value); /* solver */ // -acados_size_t sim_calculate_size(sim_config *config, void *dims, void *opts_); +ACADOS_SYMBOL_EXPORT acados_size_t sim_calculate_size(sim_config *config, void *dims, void *opts_); // -sim_solver *sim_assign(sim_config *config, void *dims, void *opts_, void *raw_memory); +ACADOS_SYMBOL_EXPORT sim_solver *sim_assign(sim_config *config, void *dims, void *opts_, void *raw_memory); // -sim_solver *sim_solver_create(sim_config *config, void *dims, void *opts_); +ACADOS_SYMBOL_EXPORT sim_solver *sim_solver_create(sim_config *config, void *dims, void *opts_); // -void sim_solver_destroy(void *solver); +ACADOS_SYMBOL_EXPORT void sim_solver_destroy(void *solver); // -int sim_solve(sim_solver *solver, sim_in *in, sim_out *out); +ACADOS_SYMBOL_EXPORT int sim_solve(sim_solver *solver, sim_in *in, sim_out *out); // -int sim_precompute(sim_solver *solver, sim_in *in, sim_out *out); +ACADOS_SYMBOL_EXPORT int sim_precompute(sim_solver *solver, sim_in *in, sim_out *out); // -int sim_solver_set(sim_solver *solver, const char *field, void *value); +ACADOS_SYMBOL_EXPORT int sim_solver_set(sim_solver *solver, const char *field, void *value); #ifdef __cplusplus } /* extern "C" */ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_block_size.h b/third_party/acados/include/blasfeo/include/blasfeo_block_size.h index 0ccd4f1bba..5d0907a61c 100644 --- a/third_party/acados/include/blasfeo/include/blasfeo_block_size.h +++ b/third_party/acados/include/blasfeo/include/blasfeo_block_size.h @@ -53,6 +53,7 @@ #define D_PS 8 // panel size #define D_PLD 8 // 4 // GCD of panel length #define D_M_KERNEL 24 // max kernel size +#define D_N_KERNEL 8 // max kernel size #define D_KC 128 //256 // 192 #define D_NC 144 //72 //96 //72 // 120 // 512 #define D_MC 2400 // 6000 @@ -60,6 +61,7 @@ #define S_PS 16 // panel size #define S_PLD 4 // GCD of panel length TODO probably 16 when writing assebly #define S_M_KERNEL 32 // max kernel size +#define S_N_KERNEL 8 // max kernel size #define S_KC 128 //256 #define S_NC 128 //144 #define S_MC 3000 @@ -74,13 +76,15 @@ #define D_PS 4 // panel size #define D_PLD 4 // 2 // GCD of panel length #define D_M_KERNEL 12 // max kernel size +#define D_N_KERNEL 8 // max kernel size #define D_KC 256 // 192 -#define D_NC 72 //96 //72 // 120 // 512 -#define D_MC 1500 // 6000 +#define D_NC 64 //96 //72 // 120 // 512 +#define D_MC 1500 // single #define S_PS 8 // panel size #define S_PLD 4 // 2 // GCD of panel length #define S_M_KERNEL 24 // max kernel size +#define S_N_KERNEL 8 // max kernel size #define S_KC 256 #define S_NC 144 #define S_MC 3000 @@ -95,6 +99,7 @@ #define D_PS 4 // panel size #define D_PLD 4 // 2 // GCD of panel length #define D_M_KERNEL 8 // max kernel size +#define D_N_KERNEL 4 // max kernel size #define D_KC 256 //320 //256 //320 #define D_NC 72 //64 //72 //60 // 120 #define D_MC 1000 // 800 @@ -102,6 +107,7 @@ #define S_PS 8 // panel size #define S_PLD 4 // 2 // GCD of panel length #define S_M_KERNEL 16 // max kernel size +#define S_N_KERNEL 8 // max kernel size #define S_KC 256 #define S_NC 144 #define S_MC 2000 @@ -114,6 +120,7 @@ #define D_PS 4 // panel size #define D_PLD 4 // 2 // GCD of panel length #define D_M_KERNEL 4 // max kernel size +#define D_N_KERNEL 4 // max kernel size #define D_KC 256 #define D_NC 128 // TODO these are just dummy #define D_MC 3000 // TODO these are just dummy @@ -121,6 +128,7 @@ #define S_PS 4 #define S_PLD 4 //2 #define S_M_KERNEL 4 // max kernel size +#define S_N_KERNEL 4 // max kernel size #define S_KC 256 #define S_NC 128 // TODO these are just dummy #define S_MC 3000 // TODO these are just dummy @@ -133,6 +141,7 @@ #define D_PS 4 // panel size #define D_PLD 4 // 2 // GCD of panel length #define D_M_KERNEL 4 // max kernel size +#define D_N_KERNEL 4 // max kernel size #define D_KC 256 #define D_NC 128 // TODO these are just dummy #define D_MC 3000 // TODO these are just dummy @@ -140,6 +149,7 @@ #define S_PS 4 #define S_PLD 4 //2 #define S_M_KERNEL 4 // max kernel size +#define S_N_KERNEL 4 // max kernel size #define S_KC 256 #define S_NC 128 // TODO these are just dummy #define S_MC 3000 // TODO these are just dummy @@ -153,6 +163,7 @@ #define D_PS 4 // panel size #define D_PLD 4 // 2 // GCD of panel length #define D_M_KERNEL 4 // max kernel size +#define D_N_KERNEL 4 // max kernel size #define D_KC 256 #define D_NC 128 // TODO these are just dummy #define D_MC 3000 // TODO these are just dummy @@ -160,6 +171,7 @@ #define S_PS 4 #define S_PLD 4 //2 #define S_M_KERNEL 4 // max kernel size +#define S_N_KERNEL 4 // max kernel size #define S_KC 256 #define S_NC 128 // TODO these are just dummy #define S_MC 3000 // TODO these are just dummy @@ -173,6 +185,7 @@ #define D_PS 4 // panel size #define D_PLD 4 // 2 // GCD of panel length #define D_M_KERNEL 4 // max kernel size +#define D_N_KERNEL 4 // max kernel size #define D_KC 256 #define D_NC 128 // TODO these are just dummy #define D_MC 3000 // TODO these are just dummy @@ -180,11 +193,35 @@ #define S_PS 4 #define S_PLD 4 //2 #define S_M_KERNEL 4 // max kernel size +#define S_N_KERNEL 4 // max kernel size #define S_KC 256 #define S_NC 128 // TODO these are just dummy #define S_MC 3000 // TODO these are just dummy +#elif defined(TARGET_ARMV8A_APPLE_M1) +// common +#define CACHE_LINE_SIZE 64 +#define L1_CACHE_SIZE (128*1024) // L1 data cache size (big cores): 64 kB, ?-way ; DTLB1 ? +#define LLC_CACHE_SIZE (12*1024*1024) // LLC (L2) cache size (big cores): 12 MB +// double +#define D_PS 4 // panel size +#define D_PLD 4 // 2 // GCD of panel length +#define D_M_KERNEL 8 // max kernel size +#define D_N_KERNEL 4 // max kernel size +#define D_KC 512 //256 +#define D_NC 128 //256 +#define D_MC 6000 +// single +#define S_PS 4 +#define S_PLD 4 //2 +#define S_M_KERNEL 8 // max kernel size +#define S_N_KERNEL 8 // max kernel size +#define S_KC 512 +#define S_NC 256 +#define S_MC 6000 + + #elif defined(TARGET_ARMV8A_ARM_CORTEX_A76) // common #define CACHE_LINE_SIZE 64 @@ -194,6 +231,7 @@ #define D_PS 4 // panel size #define D_PLD 4 // 2 // GCD of panel length #define D_M_KERNEL 8 // max kernel size +#define D_N_KERNEL 4 // max kernel size #define D_KC 512 //256 #define D_NC 128 //256 #define D_MC 6000 @@ -201,6 +239,7 @@ #define S_PS 4 #define S_PLD 4 //2 #define S_M_KERNEL 8 // max kernel size +#define S_N_KERNEL 8 // max kernel size #define S_KC 512 #define S_NC 256 #define S_MC 6000 @@ -215,6 +254,7 @@ #define D_PS 4 // panel size #define D_PLD 4 // 2 // GCD of panel length #define D_M_KERNEL 8 // max kernel size +#define D_N_KERNEL 4 // max kernel size #define D_KC 320 #define D_NC 256 #define D_MC 6000 @@ -222,6 +262,7 @@ #define S_PS 4 #define S_PLD 4 //2 #define S_M_KERNEL 8 // max kernel size +#define S_N_KERNEL 8 // max kernel size #define S_KC 256 #define S_NC 128 // TODO these are just dummy #define S_MC 3000 // TODO these are just dummy @@ -236,13 +277,15 @@ #define D_PS 4 // panel size #define D_PLD 4 // 2 // GCD of panel length #define D_M_KERNEL 8 // max kernel size -#define D_KC 224 //256 //192 -#define D_NC 40 //36 //48 -#define D_MC 512 //488 //600 +#define D_N_KERNEL 4 // max kernel size +#define D_KC 128 //224 //256 //192 +#define D_NC 72 //40 //36 //48 +#define D_MC (4*192) //512 //488 //600 // single #define S_PS 4 #define S_PLD 4 //2 #define S_M_KERNEL 8 // max kernel size +#define S_N_KERNEL 8 // max kernel size #define S_KC 256 #define S_NC 128 // TODO these are just dummy #define S_MC 3000 // TODO these are just dummy @@ -257,6 +300,7 @@ #define D_PS 4 // panel size #define D_PLD 4 // 2 // GCD of panel length #define D_M_KERNEL 12 // max kernel size +#define D_N_KERNEL 4 // max kernel size #define D_KC 224 #define D_NC 160 #define D_MC 6000 @@ -264,6 +308,7 @@ #define S_PS 4 #define S_PLD 4 //2 #define S_M_KERNEL 8 // max kernel size +#define S_N_KERNEL 8 // max kernel size #define S_KC 256 #define S_NC 128 // TODO these are just dummy #define S_MC 3000 // TODO these are just dummy @@ -278,6 +323,7 @@ #define D_PS 4 // panel size #define D_PLD 4 // 2 // GCD of panel length #define D_M_KERNEL 12 // max kernel size +#define D_N_KERNEL 4 // max kernel size #define D_KC 160 #define D_NC 128 #define D_MC 6000 @@ -285,6 +331,7 @@ #define S_PS 4 #define S_PLD 4 //2 #define S_M_KERNEL 8 // max kernel size +#define S_N_KERNEL 8 // max kernel size #define S_KC 256 #define S_NC 128 // TODO these are just dummy #define S_MC 3000 // TODO these are just dummy @@ -298,6 +345,7 @@ #define D_PS 4 // panel size #define D_PLD 4 // 2 // GCD of panel length #define D_M_KERNEL 4 // max kernel size +#define D_N_KERNEL 4 // max kernel size #define D_KC 256 #define D_NC 128 // TODO these are just dummy #define D_MC 3000 // TODO these are just dummy @@ -305,6 +353,7 @@ #define S_PS 4 #define S_PLD 4 //2 #define S_M_KERNEL 4 // max kernel size +#define S_N_KERNEL 4 // max kernel size #define S_KC 256 #define S_NC 128 // TODO these are just dummy #define S_MC 3000 // TODO these are just dummy @@ -318,6 +367,7 @@ #define D_PS 4 // panel size #define D_PLD 4 // 2 // GCD of panel length #define D_M_KERNEL 4 // max kernel size +#define D_N_KERNEL 4 // max kernel size #define D_KC 256 #define D_NC 128 // TODO these are just dummy #define D_MC 3000 // TODO these are just dummy @@ -325,6 +375,7 @@ #define S_PS 4 #define S_PLD 4 //2 #define S_M_KERNEL 4 // max kernel size +#define S_N_KERNEL 4 // max kernel size #define S_KC 256 #define S_NC 128 // TODO these are just dummy #define S_MC 3000 // TODO these are just dummy @@ -338,6 +389,7 @@ #define D_PS 4 // panel size #define D_PLD 4 // 2 // GCD of panel length #define D_M_KERNEL 4 // max kernel size +#define D_N_KERNEL 4 // max kernel size #define D_KC 256 #define D_NC 128 // TODO these are just dummy #define D_MC 3000 // TODO these are just dummy @@ -345,6 +397,7 @@ #define S_PS 4 #define S_PLD 4 //2 #define S_M_KERNEL 4 // max kernel size +#define S_N_KERNEL 4 // max kernel size #define S_KC 256 #define S_NC 128 // TODO these are just dummy #define S_MC 3000 // TODO these are just dummy @@ -358,6 +411,7 @@ #define D_PS 4 // panel size #define D_PLD 4 // 2 // GCD of panel length #define D_M_KERNEL 4 // max kernel size +#define D_N_KERNEL 4 // max kernel size #define D_KC 256 #define D_NC 128 // TODO these are just dummy #define D_MC 3000 // TODO these are just dummy @@ -366,6 +420,7 @@ #define S_PS 4 #define S_PLD 4 //2 #define S_M_KERNEL 4 // max kernel size +#define S_N_KERNEL 4 // max kernel size #define S_KC 256 #define S_NC 128 // TODO these are just dummy #define S_MC 3000 // TODO these are just dummy diff --git a/third_party/acados/include/blasfeo/include/blasfeo_common.h b/third_party/acados/include/blasfeo/include/blasfeo_common.h index a648142ba0..03b6c36d84 100644 --- a/third_party/acados/include/blasfeo/include/blasfeo_common.h +++ b/third_party/acados/include/blasfeo/include/blasfeo_common.h @@ -198,6 +198,24 @@ struct blasfeo_pm_smat int memsize; // size of needed memory }; +struct blasfeo_pm_dvec + { + double *mem; // pointer to passed chunk of memory + double *pa; // pointer to a pm array of doubles, the first is aligned to cache line size + int m; // size + int pm; // packed size + int memsize; // size of needed memory + }; + +struct blasfeo_pm_svec + { + float *mem; // pointer to passed chunk of memory + float *pa; // pointer to a pm array of floats, the first is aligned to cache line size + int m; // size + int pm; // packed size + int memsize; // size of needed memory + }; + // Explicitly column-major matrix structure struct blasfeo_cm_dmat { @@ -221,11 +239,31 @@ struct blasfeo_cm_smat int memsize; // size of needed memory }; +struct blasfeo_cm_dvec + { + double *mem; // pointer to passed chunk of memory + double *pa; // pointer to a m array of doubles, the first is aligned to cache line size + int m; // size + int memsize; // size of needed memory + }; + +struct blasfeo_cm_svec + { + float *mem; // pointer to passed chunk of memory + float *pa; // pointer to a m array of floats, the first is aligned to cache line size + int m; // size + int memsize; // size of needed memory + }; + #define BLASFEO_PM_DMATEL(sA,ai,aj) ((sA)->pA[((ai)-((ai)&((sA)->ps-1)))*(sA)->cn+(aj)*((sA)->ps)+((ai)&((sA)->ps-1))]) #define BLASFEO_PM_SMATEL(sA,ai,aj) ((sA)->pA[((ai)-((ai)&((sA)->ps-1)))*(sA)->cn+(aj)*((sA)->ps)+((ai)&((sA)->ps-1))]) +#define BLASFEO_PM_DVECEL(sa,ai) ((sa)->pa[ai]) +#define BLASFEO_PM_SVECEL(sa,ai) ((sa)->pa[ai]) #define BLASFEO_CM_DMATEL(sA,ai,aj) ((sA)->pA[(ai)+(aj)*(sA)->m]) #define BLASFEO_CM_SMATEL(sA,ai,aj) ((sA)->pA[(ai)+(aj)*(sA)->m]) +#define BLASFEO_CM_DVECEL(sa,ai) ((sa)->pa[ai]) +#define BLASFEO_CM_SVECEL(sa,ai) ((sa)->pa[ai]) diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_aux.h b/third_party/acados/include/blasfeo/include/blasfeo_d_aux.h index 7a9415a59d..a6d6119c6c 100644 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_aux.h +++ b/third_party/acados/include/blasfeo/include/blasfeo_d_aux.h @@ -185,9 +185,14 @@ void blasfeo_dveccp(int m, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec void blasfeo_dvecsc(int m, double alpha, struct blasfeo_dvec *sx, int xi); // y <= alpha*x void blasfeo_dveccpsc(int m, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi); +// z[idx] += alpha * x void blasfeo_dvecad_sp(int m, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dvec *sz, int zi); +// z[idx] <= alpha * x void blasfeo_dvecin_sp(int m, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dvec *sz, int zi); -void blasfeo_dvecex_sp(int m, double alpha, int *idx, struct blasfeo_dvec *sx, int x, struct blasfeo_dvec *sz, int zi); +// z <= alpha * x[idx] +void blasfeo_dvecex_sp(int m, double alpha, int *idx, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); +// z += alpha * x[idx] +void blasfeo_dvecexad_sp(int m, double alpha, int *idx, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); void blasfeo_dveccl(int m, struct blasfeo_dvec *sxm, int xim, struct blasfeo_dvec *sx, int xi, @@ -232,6 +237,17 @@ void blasfeo_cm_create_dmat(int m, int n, struct blasfeo_pm_dmat *sA, void *memo +// +// BLAS API helper functions +// + +#if ( defined(BLAS_API) & defined(MF_PANELMAJ) ) +// aux +void blasfeo_cm_dgetr(int m, int n, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj); +#endif + + + #ifdef __cplusplus } #endif diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_aux_ref.h b/third_party/acados/include/blasfeo/include/blasfeo_d_aux_ref.h index 448234044a..1e007fa89e 100644 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_aux_ref.h +++ b/third_party/acados/include/blasfeo/include/blasfeo_d_aux_ref.h @@ -182,6 +182,8 @@ void blasfeo_ref_dveccpsc(int m, double alpha, struct blasfeo_dvec *sx, int xi, void blasfeo_ref_dvecad_sp(int m, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dvec *sz, int zi); void blasfeo_ref_dvecin_sp(int m, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dvec *sz, int zi); void blasfeo_ref_dvecex_sp(int m, double alpha, int *idx, struct blasfeo_dvec *sx, int x, struct blasfeo_dvec *sz, int zi); +// z += alpha * x[idx] +void blasfeo_ref_dvecexad_sp(int m, double alpha, int *idx, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); void blasfeo_ref_dveccl(int m, struct blasfeo_dvec *sxm, int xim, struct blasfeo_dvec *sx, int xi, diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_blas_api.h b/third_party/acados/include/blasfeo/include/blasfeo_d_blas_api.h index 64dd43f677..ff9e9d4c16 100644 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_blas_api.h +++ b/third_party/acados/include/blasfeo/include/blasfeo_d_blas_api.h @@ -44,6 +44,30 @@ +#ifdef BLAS_API +#ifdef CBLAS_API +#ifndef BLASFEO_CBLAS_ENUM +#define BLASFEO_CBLAS_ENUM +#ifdef FORTRAN_BLAS_API +#ifndef CBLAS_H +enum CBLAS_ORDER {CblasRowMajor=101, CblasColMajor=102}; +enum CBLAS_TRANSPOSE {CblasNoTrans=111, CblasTrans=112, CblasConjTrans=113}; +enum CBLAS_UPLO {CblasUpper=121, CblasLower=122}; +enum CBLAS_DIAG {CblasNonUnit=131, CblasUnit=132}; +enum CBLAS_SIDE {CblasLeft=141, CblasRight=142}; +#endif // CBLAS_H +#else // FORTRAN_BLAS_API +enum BLASFEO_CBLAS_ORDER {BlasfeoCblasRowMajor=101, BlasfeoCblasColMajor=102}; +enum BLASFEO_CBLAS_TRANSPOSE {BlasfeoCblasNoTrans=111, BlasfeoCblasTrans=112, BlasfeoCblasConjTrans=113}; +enum BLASFEO_CBLAS_UPLO {BlasfeoCblasUpper=121, BlasfeoCblasLower=122}; +enum BLASFEO_CBLAS_DIAG {BlasfeoCblasNonUnit=131, BlasfeoCblasUnit=132}; +enum BLASFEO_CBLAS_SIDE {BlasfeoCblasLeft=141, BlasfeoCblasRight=142}; +#endif // FORTRAN_BLAS_API +#endif // BLASFEO_CBLAS_ENUM +#endif // CBLAS_API +#endif // BLAS_API + + #ifdef __cplusplus extern "C" { #endif @@ -66,6 +90,14 @@ void dcopy_(int *n, double *x, int *incx, double *y, int *incy); // double ddot_(int *n, double *x, int *incx, double *y, int *incy); +// BLAS 2 +// +void dgemv_(char *tran, int *m, int *n, double *alpha, double *A, int *lda, double *x, int *incx, double *beta, double *y, int *incy); +// +void dsymv_(char *uplo, int *n, double *alpha, double *A, int *lda, double *x, int *incx, double *beta, double *y, int *incy); +// +void dger_(int *m, int *n, double *alpha, double *x, int *incx, double *y, int *incy, double *A, int *lda); + // BLAS 3 // void dgemm_(char *ta, char *tb, int *m, int *n, int *k, double *alpha, double *A, int *lda, double *B, int *ldb, double *beta, double *C, int *ldc); @@ -75,6 +107,8 @@ void dsyrk_(char *uplo, char *ta, int *m, int *k, double *alpha, double *A, int void dtrmm_(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *A, int *lda, double *B, int *ldb); // void dtrsm_(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *A, int *lda, double *B, int *ldb); +// +void dsyr2k_(char *uplo, char *ta, int *m, int *k, double *alpha, double *A, int *lda, double *B, int *ldb, double *beta, double *C, int *ldc); @@ -100,49 +134,125 @@ void dtrtrs_(char *uplo, char *trans, char *diag, int *m, int *n, double *A, int +// aux +void dgetr_(int *m, int *n, double *A, int *lda, double *B, int *ldb); + + + +#ifdef CBLAS_API + + + +// CBLAS 1 +// +void cblas_daxpy(const int N, const double alpha, const double *X, const int incX, double *Y, const int incY); +// +void cblas_dswap(const int N, double *X, const int incX, double *Y, const int incY); +// +void cblas_dcopy(const int N, const double *X, const int incX, double *Y, const int incY); + +// CBLAS 3 +// +void cblas_dgemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const double alpha, const double *A, const int lda, const double *B, const int ldb, const double beta, double *C, const int ldc); +// +void cblas_dsyrk(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE Trans, const int N, const int K, const double alpha, const double *A, const int lda, const double beta, double *C, const int ldc); +// +void cblas_dtrmm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int M, const int N, const double alpha, const double *A, const int lda, double *B, const int ldb); +// +void cblas_dtrsm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int M, const int N, const double alpha, const double *A, const int lda, double *B, const int ldb); + + + +#endif // CBLAS_API + + + #else // BLASFEO_API // BLAS 1 // -void blas_daxpy(int *n, double *alpha, double *x, int *incx, double *y, int *incy); +void blasfeo_blas_daxpy(int *n, double *alpha, double *x, int *incx, double *y, int *incy); // -double blas_ddot(int *n, double *x, int *incx, double *y, int *incy); +double blasfeo_blas_ddot(int *n, double *x, int *incx, double *y, int *incy); // -void blas_dcopy(int *n, double *x, int *incx, double *y, int *incy); +void blasfeo_blas_dcopy(int *n, double *x, int *incx, double *y, int *incy); + +// BLAS 2 +// +void blasfeo_blas_dgemv(char *trans, int *m, int *n, double *alpha, double *A, int *lda, double *x, int *incx, double *beta, double *y, int *incy); +// +void blasfeo_blas_dsymv(char *uplo, int *n, double *alpha, double *A, int *lda, double *x, int *incx, double *beta, double *y, int *incy); +// +void blasfeo_blas_dger(int *m, int *n, double *alpha, double *x, int *incx, double *y, int *incy, double *A, int *lda); // BLAS 3 // -void blas_dgemm(char *ta, char *tb, int *m, int *n, int *k, double *alpha, double *A, int *lda, double *B, int *ldb, double *beta, double *C, int *ldc); +void blasfeo_blas_dgemm(char *ta, char *tb, int *m, int *n, int *k, double *alpha, double *A, int *lda, double *B, int *ldb, double *beta, double *C, int *ldc); +// +void blasfeo_blas_dsyrk(char *uplo, char *ta, int *m, int *k, double *alpha, double *A, int *lda, double *beta, double *C, int *ldc); // -void blas_dsyrk(char *uplo, char *ta, int *m, int *k, double *alpha, double *A, int *lda, double *beta, double *C, int *ldc); +void blasfeo_blas_dtrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *A, int *lda, double *B, int *ldb); // -void blas_dtrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *A, int *lda, double *B, int *ldb); +void blasfeo_blas_dtrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *A, int *lda, double *B, int *ldb); // -void blas_dtrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *A, int *lda, double *B, int *ldb); +void blasfeo_blas_dsyr2k(char *uplo, char *ta, int *m, int *k, double *alpha, double *A, int *lda, double *B, int *ldb, double *beta, double *C, int *ldc); // LAPACK // -void blas_dgesv(int *m, int *n, double *A, int *lda, int *ipiv, double *B, int *ldb, int *info); +void blasfeo_lapack_dgesv(int *m, int *n, double *A, int *lda, int *ipiv, double *B, int *ldb, int *info); // -void blas_dgetrf(int *m, int *n, double *A, int *lda, int *ipiv, int *info); +void blasfeo_lapack_dgetrf(int *m, int *n, double *A, int *lda, int *ipiv, int *info); // -void blas_dgetrf_np(int *m, int *n, double *A, int *lda, int *info); +void blasfeo_lapack_dgetrf_np(int *m, int *n, double *A, int *lda, int *info); // -void blas_dgetrs(char *trans, int *m, int *n, double *A, int *lda, int *ipiv, double *B, int *ldb, int *info); +void blasfeo_lapack_dgetrs(char *trans, int *m, int *n, double *A, int *lda, int *ipiv, double *B, int *ldb, int *info); // -void blas_dlaswp(int *n, double *A, int *lda, int *k1, int *k2, int *ipiv, int *incx); +void blasfeo_lapack_dlaswp(int *n, double *A, int *lda, int *k1, int *k2, int *ipiv, int *incx); // -void blas_dposv(char *uplo, int *m, int *n, double *A, int *lda, double *B, int *ldb, int *info); +void blasfeo_lapack_dposv(char *uplo, int *m, int *n, double *A, int *lda, double *B, int *ldb, int *info); // -void blas_dpotrf(char *uplo, int *m, double *A, int *lda, int *info); +void blasfeo_lapack_dpotrf(char *uplo, int *m, double *A, int *lda, int *info); // -void blas_dpotrs(char *uplo, int *m, int *n, double *A, int *lda, double *B, int *ldb, int *info); +void blasfeo_lapack_dpotrs(char *uplo, int *m, int *n, double *A, int *lda, double *B, int *ldb, int *info); // -void blas_dtrtrs(char *uplo, char *trans, char *diag, int *m, int *n, double *A, int *lda, double *B, int *ldb, int *info); +void blasfeo_lapack_dtrtrs(char *uplo, char *trans, char *diag, int *m, int *n, double *A, int *lda, double *B, int *ldb, int *info); + + + +// aux +void blasfeo_blas_dgetr(int *m, int *n, double *A, int *lda, double *B, int *ldb); + + + +#ifdef CBLAS_API + + + +// CBLAS 1 +// +void blasfeo_cblas_daxpy(const int N, const double alpha, const double *X, const int incX, double *Y, const int incY); +// +void blasfeo_cblas_dswap(const int N, double *X, const int incX, double *Y, const int incY); +// +void blasfeo_cblas_dcopy(const int N, const double *X, const int incX, double *Y, const int incY); + +// CBLAS 3 +// +void blasfeo_cblas_dgemm(const enum BLASFEO_CBLAS_ORDER Order, const enum BLASFEO_CBLAS_TRANSPOSE TransA, const enum BLASFEO_CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const double alpha, const double *A, const int lda, const double *B, const int ldb, const double beta, double *C, const int ldc); +// +void blasfeo_cblas_dsyrk(const enum BLASFEO_CBLAS_ORDER Order, const enum BLASFEO_CBLAS_UPLO Uplo, const enum BLASFEO_CBLAS_TRANSPOSE Trans, const int N, const int K, const double alpha, const double *A, const int lda, const double beta, double *C, const int ldc); +// +void blasfeo_cblas_dtrmm(const enum BLASFEO_CBLAS_ORDER Order, const enum BLASFEO_CBLAS_SIDE Side, const enum BLASFEO_CBLAS_UPLO Uplo, const enum BLASFEO_CBLAS_TRANSPOSE TransA, const enum BLASFEO_CBLAS_DIAG Diag, const int M, const int N, const double alpha, const double *A, const int lda, double *B, const int ldb); +// +void blasfeo_cblas_dtrsm(const enum BLASFEO_CBLAS_ORDER Order, const enum BLASFEO_CBLAS_SIDE Side, const enum BLASFEO_CBLAS_UPLO Uplo, const enum BLASFEO_CBLAS_TRANSPOSE TransA, const enum BLASFEO_CBLAS_DIAG Diag, const int M, const int N, const double alpha, const double *A, const int lda, double *B, const int ldb); + + + +#endif // CBLAS_API diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_api.h b/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_api.h index 15915f436f..88bb3fce22 100644 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_api.h +++ b/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_api.h @@ -119,6 +119,10 @@ void blasfeo_dgemv_nt(int m, int n, double alpha_n, double alpha_t, struct blasf // z <= beta * y + alpha * A * x, where A is symmetric and only the lower triangular patr of A is accessed void blasfeo_dsymv_l(int m, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); void blasfeo_dsymv_l_mn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); +// z <= beta * y + alpha * A * x, where A is symmetric and only the upper triangular patr of A is accessed +void blasfeo_dsymv_u(int m, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); +// D = C + alpha * x * y^T +void blasfeo_dger(int m, int n, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); // diagonal @@ -227,6 +231,14 @@ void blasfeo_dtrsm_runu(int m, int n, double alpha, struct blasfeo_dmat *sA, int void blasfeo_dtrsm_rutn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); // D <= alpha * B * A^{-T} , with A upper triangular with unit diagonal void blasfeo_dtrsm_rutu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); +// D <= beta * C + alpha * A * B^T + alpha * B * A^T; C, D lower triangular +void blasfeo_dsyr2k_ln(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); +// D <= beta * C + alpha * A^T * B + alpha * B^T * A; C, D lower triangular +void blasfeo_dsyr2k_lt(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); +// D <= beta * C + alpha * A * B^T + alpha * B * A^T; C, D upper triangular +void blasfeo_dsyr2k_un(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); +// D <= beta * C + alpha * A^T * B + alpha * B^T * A; C, D upper triangular +void blasfeo_dsyr2k_ut(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); // diagonal @@ -327,6 +339,16 @@ void blasfeo_cm_dtrmm_runn(int m, int n, double alpha, struct blasfeo_cm_dmat *s void blasfeo_cm_dtrmm_runu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); void blasfeo_cm_dtrmm_rutn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); void blasfeo_cm_dtrmm_rutu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); +void blasfeo_cm_dsyr2k_ln(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); +void blasfeo_cm_dsyr2k_lt(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); +void blasfeo_cm_dsyr2k_un(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); +void blasfeo_cm_dsyr2k_ut(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); +// BLAS 2 +void blasfeo_cm_dgemv_n(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dvec *sx, int xi, double beta, struct blasfeo_cm_dvec *sy, int yi, struct blasfeo_cm_dvec *sz, int zi); +void blasfeo_cm_dgemv_t(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dvec *sx, int xi, double beta, struct blasfeo_cm_dvec *sy, int yi, struct blasfeo_cm_dvec *sz, int zi); +void blasfeo_cm_dsymv_l(int m, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dvec *sx, int xi, double beta, struct blasfeo_cm_dvec *sy, int yi, struct blasfeo_cm_dvec *sz, int zi); +void blasfeo_cm_dsymv_u(int m, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dvec *sx, int xi, double beta, struct blasfeo_cm_dvec *sy, int yi, struct blasfeo_cm_dvec *sz, int zi); +void blasfeo_cm_dger(int m, int n, double alpha, struct blasfeo_cm_dvec *sx, int xi, struct blasfeo_cm_dvec *sy, int yi, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); // LAPACK void blasfeo_cm_dpotrf_l(int m, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); void blasfeo_cm_dpotrf_u(int m, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_hp_api.h b/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_hp_api.h new file mode 100644 index 0000000000..405733f13e --- /dev/null +++ b/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_hp_api.h @@ -0,0 +1,84 @@ +/************************************************************************************************** +* * +* This file is part of BLASFEO. * +* * +* BLASFEO -- BLAS For Embedded Optimization. * +* Copyright (C) 2019 by Gianluca Frison. * +* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * +* All rights reserved. * +* * +* The 2-Clause BSD License * +* * +* Redistribution and use in source and binary forms, with or without * +* modification, are permitted provided that the following conditions are met: * +* * +* 1. Redistributions of source code must retain the above copyright notice, this * +* list of conditions and the following disclaimer. * +* 2. 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. * +* * +* 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 AND FITNESS FOR A PARTICULAR PURPOSE 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. * +* * +* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * +* * +**************************************************************************************************/ + +#ifndef BLASFEO_D_BLASFEO_HP_API_H_ +#define BLASFEO_D_BLASFEO_HP_API_H_ + + + +#include "blasfeo_common.h" + + + +#ifdef __cplusplus +extern "C" { +#endif + + + +// +// level 3 BLAS +// + +// dense + + +// D <= beta * C + alpha * A^T * B +void blasfeo_hp_dgemm_tn(int m, int n, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); +// D <= beta * C + alpha * A * B^T; C, D lower triangular +void blasfeo_hp_dsyrk_ln(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); +// D <= beta * C + alpha * A * A^T ; C, D lower triangular +void blasfeo_hp_dsyrk3_ln(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); +// D <= alpha * B * A^{-T} , with A lower triangular +void blasfeo_hp_dtrsm_rltn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); + + +// +// level 2 BLAS +// + +// dense + +// z <= beta * y + alpha * A * x +void blasfeo_hp_dgemv_n(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); + + + +#ifdef __cplusplus +} +#endif + +#endif // BLASFEO_D_BLASFEO_HP_API_H_ + diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_ref_api.h b/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_ref_api.h index 5773715cfa..1a8b22c67e 100644 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_ref_api.h +++ b/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_ref_api.h @@ -119,6 +119,10 @@ void blasfeo_ref_dgemv_nt(int m, int n, double alpha_n, double alpha_t, struct b // z <= beta * y + alpha * A * x, where A is symmetric and only the lower triangular patr of A is accessed void blasfeo_ref_dsymv_l(int m, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); void blasfeo_ref_dsymv_l_mn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); +// z <= beta * y + alpha * A * x, where A is symmetric and only the upper triangular patr of A is accessed +void blasfeo_ref_dsymv_u(int m, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); +// D = C + alpha * x * y^T +void blasfeo_ref_dger(int m, int n, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); // diagonal @@ -214,6 +218,14 @@ void blasfeo_ref_dtrsm_runu(int m, int n, double alpha, struct blasfeo_dmat *sA, void blasfeo_ref_dtrsm_rutn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); // D <= alpha * B * A^{-T} , with A upper triangular with unit diagonal void blasfeo_ref_dtrsm_rutu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); +// D <= beta * C + alpha * A * B^T + alpha * B * A^T ; C, D lower triangular +void blasfeo_ref_dsyr2k_ln(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); +// D <= beta * C + alpha * A^T * B + alpha * B^T * A ; C, D lower triangular +void blasfeo_ref_dsyr2k_lt(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); +// D <= beta * C + alpha * A * B^T + alpha * B * A^T ; C, D upper triangular +void blasfeo_ref_dsyr2k_un(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); +// D <= beta * C + alpha * A^T * B + alpha * B^T * A ; C, D upper triangular +void blasfeo_ref_dsyr2k_ut(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); // diagonal diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_kernel.h b/third_party/acados/include/blasfeo/include/blasfeo_d_kernel.h index 7094857697..d20ac38bbd 100644 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_kernel.h +++ b/third_party/acados/include/blasfeo/include/blasfeo_d_kernel.h @@ -728,14 +728,22 @@ void kernel_dsyrk_nt_l_12x4_lib44cc(int kmax, double *alpha, double *A, int sda, void kernel_dsyrk_nt_l_12x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dsyrk_nt_u_12x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); void kernel_dsyrk_nt_u_12x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); +void kernel_dger2k_nt_12x4_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, double *A1, int sda1, double *B1, double *beta, double *C, int ldc, double *D, int ldd); +void kernel_dger2k_nt_12x4_vs_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, double *A1, int sda1, double *B1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); +void kernel_dsyr2k_nt_l_12x4_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, double *A1, int sda1, double *B1, double *beta, double *C, int ldc, double *D, int ldd); +void kernel_dsyr2k_nt_l_12x4_vs_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, double *A1, int sda1, double *B1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dtrmm_nt_rl_12x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); void kernel_dtrmm_nt_rl_12x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dtrmm_nt_rl_one_12x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); void kernel_dtrmm_nt_rl_one_12x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); +void kernel_dtrmm_nt_ru_12x4_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd); +void kernel_dtrmm_nt_ru_12x4_vs_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); void kernel_dtrmm_nt_ru_12x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); void kernel_dtrmm_nt_ru_12x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dtrmm_nt_ru_one_12x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); void kernel_dtrmm_nt_ru_one_12x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); +void kernel_dtrsm_nt_ll_inv_12x4_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int sde, double *inv_diag_E); +void kernel_dtrsm_nt_ll_inv_12x4_vs_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int sde, double *inv_diag_E, int km, int kn); void kernel_dtrsm_nt_rl_inv_12x4_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE); void kernel_dtrsm_nt_rl_inv_12x4_vs_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE, int m1, int n1); void kernel_dtrsm_nt_rl_inv_12x4_lib44ccc(int kmax, double *A, int sda, double *B, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); @@ -751,6 +759,7 @@ void kernel_dpotrf_nt_l_12x4_vs_lib44cc(int kmax, double *A, int sda, double *B, // 4x12 void kernel_dgemm_nt_4x12_lib44cc(int kmax, double *alpha, double *A, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd); void kernel_dgemm_nt_4x12_vs_lib44cc(int kmax, double *alpha, double *A, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); +void kernel_dgemm_nt_4x12_p0_vs_lib44cc(int kmax, double *alpha, double *A, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1, double *A_p, double *B_p); void kernel_dtrmm_nt_rl_4x12_tran_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd); void kernel_dtrmm_nt_rl_4x12_tran_vs_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); void kernel_dtrmm_nt_rl_one_4x12_tran_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd); @@ -764,6 +773,10 @@ void kernel_dsyrk_nt_l_8x8_lib44cc(int kmax, double *alpha, double *A, int sda, void kernel_dsyrk_nt_l_8x8_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dsyrk_nt_u_8x8_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd); void kernel_dsyrk_nt_u_8x8_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); +void kernel_dger2k_nt_8x8_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, int sdb0, double *A1, int sda1, double *B1, int sdb1, double *beta, double *C, int ldc, double *D, int ldd); +void kernel_dger2k_nt_8x8_vs_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, int sdb0, double *A1, int sda1, double *B1, int sdb1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); +void kernel_dsyr2k_nt_l_8x8_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, int sdb0, double *A1, int sda1, double *B1, int sdb1, double *beta, double *C, int ldc, double *D, int ldd); +void kernel_dsyr2k_nt_l_8x8_vs_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, int sdb0, double *A1, int sda1, double *B1, int sdb1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dpotrf_nt_l_8x8_lib44cc(int kmax, double *A, int sda, double *B, int sdb, double *C, int ldc, double *D, int ldd, double *dD); void kernel_dpotrf_nt_l_8x8_vs_lib44cc(int kmax, double *A, int sda, double *B, int sdb, double *C, int ldc, double *D, int ldd, double *dD, int m1, int n1); // 8x4 @@ -775,14 +788,22 @@ void kernel_dsyrk_nt_l_8x4_lib44cc(int kmax, double *alpha, double *A, int sda, void kernel_dsyrk_nt_l_8x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dsyrk_nt_u_8x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); void kernel_dsyrk_nt_u_8x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); +void kernel_dger2k_nt_8x4_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, double *A1, int sda1, double *B1, double *beta, double *C, int ldc, double *D, int ldd); +void kernel_dger2k_nt_8x4_vs_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, double *A1, int sda1, double *B1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); +void kernel_dsyr2k_nt_l_8x4_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, double *A1, int sda1, double *B1, double *beta, double *C, int ldc, double *D, int ldd); +void kernel_dsyr2k_nt_l_8x4_vs_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, double *A1, int sda1, double *B1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dtrmm_nt_rl_8x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); void kernel_dtrmm_nt_rl_8x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dtrmm_nt_rl_one_8x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); void kernel_dtrmm_nt_rl_one_8x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); +void kernel_dtrmm_nt_ru_8x4_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd); +void kernel_dtrmm_nt_ru_8x4_vs_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); void kernel_dtrmm_nt_ru_8x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); void kernel_dtrmm_nt_ru_8x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dtrmm_nt_ru_one_8x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); void kernel_dtrmm_nt_ru_one_8x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); +void kernel_dtrsm_nt_ll_inv_8x4_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int sde, double *inv_diag_E); +void kernel_dtrsm_nt_ll_inv_8x4_vs_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int sde, double *inv_diag_E, int km, int kn); void kernel_dtrsm_nt_rl_inv_8x4_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE); void kernel_dtrsm_nt_rl_inv_8x4_vs_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE, int m1, int n1); void kernel_dtrsm_nt_rl_inv_8x4_lib44ccc(int kmax, double *A, int sda, double *B, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); @@ -813,6 +834,10 @@ void kernel_dsyrk_nt_l_4x4_lib44cc(int kmax, double *alpha, double *A, double *B void kernel_dsyrk_nt_l_4x4_vs_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dsyrk_nt_u_4x4_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd); void kernel_dsyrk_nt_u_4x4_vs_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); +void kernel_dger2k_nt_4x4_lib44cc(int kmax, double *alpha, double *A0, double *B0, double *A1, double *B1, double *beta, double *C, int ldc, double *D, int ldd); +void kernel_dger2k_nt_4x4_vs_lib44cc(int kmax, double *alpha, double *A0, double *B0, double *A1, double *B1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); +void kernel_dsyr2k_nt_l_4x4_lib44cc(int kmax, double *alpha, double *A0, double *B0, double *A1, double *B1, double *beta, double *C, int ldc, double *D, int ldd); +void kernel_dsyr2k_nt_l_4x4_vs_lib44cc(int kmax, double *alpha, double *A0, double *B0, double *A1, double *B1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dtrmm_nt_rl_4x4_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd); void kernel_dtrmm_nt_rl_4x4_vs_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dtrmm_nt_rl_4x4_tran_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd); @@ -821,6 +846,8 @@ void kernel_dtrmm_nt_rl_one_4x4_lib44cc(int kmax, double *alpha, double *A, doub void kernel_dtrmm_nt_rl_one_4x4_vs_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dtrmm_nt_rl_one_4x4_tran_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd); void kernel_dtrmm_nt_rl_one_4x4_tran_vs_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd, int m1, int n1); +void kernel_dtrmm_nt_ru_4x4_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd); +void kernel_dtrmm_nt_ru_4x4_vs_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd, int m1, int n1); void kernel_dtrmm_nt_ru_4x4_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd); void kernel_dtrmm_nt_ru_4x4_vs_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dtrmm_nt_ru_4x4_tran_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd); @@ -829,6 +856,8 @@ void kernel_dtrmm_nt_ru_one_4x4_lib44cc(int kmax, double *alpha, double *A, doub void kernel_dtrmm_nt_ru_one_4x4_vs_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dtrmm_nt_ru_one_4x4_tran_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd); void kernel_dtrmm_nt_ru_one_4x4_tran_vs_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd, int m1, int n1); +void kernel_dtrsm_nt_ll_inv_4x4_lib44cc4(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *inv_diag_E); +void kernel_dtrsm_nt_ll_inv_4x4_vs_lib44cc4(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *inv_diag_E, int km, int kn); void kernel_dtrsm_nt_rl_inv_4x4_lib44cc4(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE); void kernel_dtrsm_nt_rl_inv_4x4_vs_lib44cc4(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE, int m1, int n1); void kernel_dtrsm_nt_rl_inv_4x4_lib44ccc(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); @@ -852,6 +881,8 @@ void kernel_dgemm_nt_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, d void kernel_dgemm_nt_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dsyrk_nt_l_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); void kernel_dsyrk_nt_l_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); +void kernel_dger2k_nt_12x4_lib4ccc(int kmax, double *alpha, double *A0, int sda0, double *B0, int ldb0, double *A1, int sda1, double *B1, int ldb1, double *beta, double *C, int ldc, double *D, int ldd); +void kernel_dger2k_nt_12x4_vs_lib4ccc(int kmax, double *alpha, double *A0, int sda0, double *B0, int ldb0, double *A1, int sda1, double *B1, int ldb1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dtrmm_nn_rl_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); void kernel_dtrmm_nn_rl_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dtrmm_nn_rl_one_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); @@ -868,6 +899,8 @@ void kernel_dtrmm_nt_ru_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda void kernel_dtrmm_nt_ru_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dtrmm_nt_ru_one_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); void kernel_dtrmm_nt_ru_one_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); +void kernel_dtrsm_nn_ll_inv_12x4_lib4ccc4(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int sde, double *inv_diag_E); +void kernel_dtrsm_nn_ll_inv_12x4_vs_lib4ccc4(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int sde, double *inv_diag_E, int km, int kn); void kernel_dtrsm_nn_ll_one_12x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); void kernel_dtrsm_nn_ll_one_12x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); void kernel_dtrsm_nn_rl_inv_12x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); @@ -920,6 +953,8 @@ void kernel_dgemm_nt_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, do void kernel_dgemm_nt_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dsyrk_nt_l_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); void kernel_dsyrk_nt_l_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); +void kernel_dger2k_nt_8x4_lib4ccc(int kmax, double *alpha, double *A0, int sda0, double *B0, int ldb0, double *A1, int sda1, double *B1, int ldb1, double *beta, double *C, int ldc, double *D, int ldd); +void kernel_dger2k_nt_8x4_vs_lib4ccc(int kmax, double *alpha, double *A0, int sda0, double *B0, int ldb0, double *A1, int sda1, double *B1, int ldb1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dtrmm_nn_rl_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); void kernel_dtrmm_nn_rl_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dtrmm_nn_rl_one_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); @@ -936,6 +971,8 @@ void kernel_dtrmm_nt_ru_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, void kernel_dtrmm_nt_ru_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dtrmm_nt_ru_one_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); void kernel_dtrmm_nt_ru_one_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); +void kernel_dtrsm_nn_ll_inv_8x4_lib4ccc4(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int sde, double *inv_diag_E); +void kernel_dtrsm_nn_ll_inv_8x4_vs_lib4ccc4(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int sde, double *inv_diag_E, int km, int kn); void kernel_dtrsm_nn_ll_one_8x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); void kernel_dtrsm_nn_ll_one_8x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); void kernel_dtrsm_nn_rl_inv_8x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); @@ -986,6 +1023,8 @@ void kernel_dgemm_nt_4x4_lib4ccc(int kmax, double *alpha, double *A, double *B, void kernel_dgemm_nt_4x4_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dsyrk_nt_l_4x4_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); void kernel_dsyrk_nt_l_4x4_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); +void kernel_dger2k_nt_4x4_lib4ccc(int kmax, double *alpha, double *A0, double *B0, int ldb0, double *A1, double *B1, int ldb1, double *beta, double *C, int ldc, double *D, int ldd); +void kernel_dger2k_nt_4x4_vs_lib4ccc(int kmax, double *alpha, double *A0, double *B0, int ldb0, double *A1, double *B1, int ldb1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dtrmm_nn_rl_4x4_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); void kernel_dtrmm_nn_rl_4x4_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dtrmm_nn_rl_4x4_tran_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd); @@ -1018,6 +1057,8 @@ void kernel_dtrmm_nt_ru_one_4x4_lib4ccc(int kmax, double *alpha, double *A, doub void kernel_dtrmm_nt_ru_one_4x4_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); void kernel_dtrmm_nt_ru_one_4x4_tran_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd); void kernel_dtrmm_nt_ru_one_4x4_tran_vs_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd, int m1, int n1); +void kernel_dtrsm_nn_ll_inv_4x4_lib4ccc4(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *inv_diag_E); +void kernel_dtrsm_nn_ll_inv_4x4_vs_lib4ccc4(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *inv_diag_E, int km, int kn); void kernel_dtrsm_nn_ll_one_4x4_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); void kernel_dtrsm_nn_ll_one_4x4_vs_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); void kernel_dtrsm_nn_rl_inv_4x4_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); @@ -1181,6 +1222,7 @@ void kernel_drowsw_lib(int kmax, double *pA, int lda, double *pC, int ldc); // 12 void kernel_dgemm_nt_12xn_p0_lib44cc(int n, int k, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, double *A_p, double *B_p); void kernel_dgemm_nt_12xn_pl_lib44cc(int n, int k, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, double *A_p, double *B_p); +void kernel_dgemm_nt_mx12_p0_lib44cc(int m, int k, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, double *A_p, double *B_p); // 8 void kernel_dgemm_nt_8xn_p0_lib44cc(int n, int k, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, double *A_p, double *B_p); @@ -1232,11 +1274,43 @@ void kernel_dgemm_tt_8x8_libc8cc(int kmax, double *alpha, double *A, int lda, do void kernel_dgemm_tt_8x8_vs_libc8cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); +// level 2 BLAS +void kernel_dgemv_n_4_libc(int kmax, double *alpha, double *A, int lda, double *x, double *z); +void kernel_dgemv_n_4_vs_libc(int kmax, double *alpha, double *A, int lda, double *x, double *z, int km); +void kernel_dgemv_t_4_libc(int kmax, double *alpha, double *A, int lda, double *x, double *beta, double *y, double *z); +void kernel_dgemv_t_4_vs_libc(int kmax, double *alpha, double *A, int lda, double *x, double *beta, double *y, double *z, int km); +void kernel_dsymv_l_4_libc(int kmax, double *alpha, double *A, int lda, double *x, double *z); +void kernel_dsymv_l_4_vs_libc(int kmax, double *alpha, double *A, int lda, double *x, double *z, int km); +void kernel_dsymv_u_4_libc(int kmax, double *alpha, double *A, int lda, double *x, double *z); +void kernel_dsymv_u_4_vs_libc(int kmax, double *alpha, double *A, int lda, double *x, double *z, int km); +void kernel_dger_4_libc(int kmax, double *alpha, double *x, double *y, double *C, int ldc, double *D, int ldd); +void kernel_dger_4_vs_libc(int kmax, double *alpha, double *x, double *y, double *C, int ldc, double *D, int ldd, int km); + + // aux void kernel_dvecld_inc1(int kmax, double *x); void kernel_dveccp_inc1(int kmax, double *x, double *y); +//void kernel_dgetr_nt_8_p0_lib(int kmax, double *A, int lda, double *C, int ldc, double *Ap, double *Bp); +//void kernel_dgetr_nt_8_lib(int kmax, double *A, int lda, double *C, int ldc); +//void kernel_dgetr_nt_4_lib(int kmax, double *A, int lda, double *C, int ldc); +void kernel_dgetr_tn_8_p0_lib(int kmax, double *A, int lda, double *C, int ldc, double *Ap, double *Bp); +void kernel_dgetr_tn_8_lib(int kmax, double *A, int lda, double *C, int ldc); +void kernel_dgetr_tn_4_lib(int kmax, double *A, int lda, double *C, int ldc); +void kernel_dgetr_tn_4_vs_lib(int kmax, double *A, int lda, double *C, int ldc, int m1); + + +// building blocks for blocked algorithms +// +void blasfeo_hp_dgemm_nt_m2(int m, int n, int k, double alpha, double *pA, int sda, double *pB, int sdb, double beta, double *C, int ldc, double *D, int ldd); +void blasfeo_hp_dgemm_nt_n2(int m, int n, int k, double alpha, double *pA, int sda, double *pB, int sdb, double beta, double *C, int ldc, double *D, int ldd); +// +void kernel_dpack_buffer_fn(int m, int n, double *A, int lda, double *pA, int sda); +void kernel_dpack_buffer_ft(int m, int n, double *A, int lda, double *pA, int sda); +void kernel_dpack_buffer_ln(int m, double *A, int lda, double *pA, int sda); +void kernel_dpack_buffer_lt(int m, double *A, int lda, double *pA, int sda); +void kernel_dpack_buffer_ut(int m, double *A, int lda, double *pA, int sda); diff --git a/third_party/acados/include/blasfeo/include/blasfeo_processor_features.h b/third_party/acados/include/blasfeo/include/blasfeo_processor_features.h index 65a0c7e80a..67a0a4da04 100644 --- a/third_party/acados/include/blasfeo/include/blasfeo_processor_features.h +++ b/third_party/acados/include/blasfeo/include/blasfeo_processor_features.h @@ -39,20 +39,20 @@ /** * Flags to indicate the different processor features */ -enum -{ - // x86-64 CPU features - BLASFEO_PROCESSOR_FEATURE_AVX = 0x0001, /// AVX instruction set - BLASFEO_PROCESSOR_FEATURE_AVX2 = 0x0002, /// AVX2 instruction set - BLASFEO_PROCESSOR_FEATURE_FMA = 0x0004, /// FMA instruction set - BLASFEO_PROCESSOR_FEATURE_SSE3 = 0x0008, /// SSE3 instruction set - - // ARM CPU features - BLASFEO_PROCESSOR_FEATURE_VFPv3 = 0x0100, /// VFPv3 instruction set - BLASFEO_PROCESSOR_FEATURE_NEON = 0x0100, /// NEON instruction set - BLASFEO_PROCESSOR_FEATURE_VFPv4 = 0x0100, /// VFPv4 instruction set - BLASFEO_PROCESSOR_FEATURE_NEONv2 = 0x0100, /// NEONv2 instruction set -} BLASFEO_PROCESSOR_FEATURES; +//enum +//{ +// // x86-64 CPU features +// BLASFEO_PROCESSOR_FEATURE_AVX = 0x0001, /// AVX instruction set +// BLASFEO_PROCESSOR_FEATURE_AVX2 = 0x0002, /// AVX2 instruction set +// BLASFEO_PROCESSOR_FEATURE_FMA = 0x0004, /// FMA instruction set +// BLASFEO_PROCESSOR_FEATURE_SSE3 = 0x0008, /// SSE3 instruction set +// +// // ARM CPU features +// BLASFEO_PROCESSOR_FEATURE_VFPv3 = 0x0100, /// VFPv3 instruction set +// BLASFEO_PROCESSOR_FEATURE_NEON = 0x0100, /// NEON instruction set +// BLASFEO_PROCESSOR_FEATURE_VFPv4 = 0x0100, /// VFPv4 instruction set +// BLASFEO_PROCESSOR_FEATURE_NEONv2 = 0x0100, /// NEONv2 instruction set +//} BLASFEO_PROCESSOR_FEATURES; /** * Test the features that this processor provides against what the library was compiled with. diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_aux.h b/third_party/acados/include/blasfeo/include/blasfeo_s_aux.h index 539268849c..f43f5e83ce 100644 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_aux.h +++ b/third_party/acados/include/blasfeo/include/blasfeo_s_aux.h @@ -127,6 +127,8 @@ float blasfeo_svecex1(struct blasfeo_svec *sx, int xi); void blasfeo_svecad_sp(int m, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_svec *sz, int zi); void blasfeo_svecin_sp(int m, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_svec *sz, int zi); void blasfeo_svecex_sp(int m, float alpha, int *idx, struct blasfeo_svec *sx, int x, struct blasfeo_svec *sz, int zi); +// z += alpha * x[idx] +void blasfeo_svecexad_sp(int m, double alpha, int *idx, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); void blasfeo_sveccl(int m, struct blasfeo_svec *sxm, int xim, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sxp, int xip, struct blasfeo_svec *sz, int zi); void blasfeo_sveccl_mask(int m, struct blasfeo_svec *sxm, int xim, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sxp, int xip, struct blasfeo_svec *sz, int zi, struct blasfeo_svec *sm, int mi); void blasfeo_svecze(int m, struct blasfeo_svec *sm, int mi, struct blasfeo_svec *sv, int vi, struct blasfeo_svec *se, int ei); diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_aux_ref.h b/third_party/acados/include/blasfeo/include/blasfeo_s_aux_ref.h index f6e16a9577..998e1d8999 100644 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_aux_ref.h +++ b/third_party/acados/include/blasfeo/include/blasfeo_s_aux_ref.h @@ -128,6 +128,8 @@ float blasfeo_ref_svecex1(struct blasfeo_svec *sx, int xi); void blasfeo_ref_svecad_sp(int m, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_svec *sz, int zi); void blasfeo_ref_svecin_sp(int m, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_svec *sz, int zi); void blasfeo_ref_svecex_sp(int m, float alpha, int *idx, struct blasfeo_svec *sx, int x, struct blasfeo_svec *sz, int zi); +// z += alpha * x[idx] +void blasfeo_ref_svecexad_sp(int m, double alpha, int *idx, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); void blasfeo_ref_sveccl(int m, struct blasfeo_svec *sxm, int xim, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sxp, int xip, struct blasfeo_svec *sz, int zi); void blasfeo_ref_sveccl_mask(int m, struct blasfeo_svec *sxm, int xim, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sxp, int xip, struct blasfeo_svec *sz, int zi, struct blasfeo_svec *sm, int mi); void blasfeo_ref_svecze(int m, struct blasfeo_svec *sm, int mi, struct blasfeo_svec *sv, int vi, struct blasfeo_svec *se, int ei); diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_blas_api.h b/third_party/acados/include/blasfeo/include/blasfeo_s_blas_api.h index d0fa2245c5..cf2b3e0a2d 100644 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_blas_api.h +++ b/third_party/acados/include/blasfeo/include/blasfeo_s_blas_api.h @@ -44,6 +44,31 @@ +#ifdef BLAS_API +#ifdef CBLAS_API +#ifndef BLASFEO_CBLAS_ENUM +#define BLASFEO_CBLAS_ENUM +#ifdef FORTRAN_BLAS_API +#ifndef CBLAS_H +enum CBLAS_ORDER {CblasRowMajor=101, CblasColMajor=102}; +enum CBLAS_TRANSPOSE {CblasNoTrans=111, CblasTrans=112, CblasConjTrans=113}; +enum CBLAS_UPLO {CblasUpper=121, CblasLower=122}; +enum CBLAS_DIAG {CblasNonUnit=131, CblasUnit=132}; +enum CBLAS_SIDE {CblasLeft=141, CblasRight=142}; +#endif // CBLAS_H +#else // FORTRAN_BLAS_API +enum BLASFEO_CBLAS_ORDER {CblasRowMajor=101, CblasColMajor=102}; +enum BLASFEO_CBLAS_TRANSPOSE {CblasNoTrans=111, CblasTrans=112, CblasConjTrans=113}; +enum BLASFEO_CBLAS_UPLO {CblasUpper=121, CblasLower=122}; +enum BLASFEO_CBLAS_DIAG {CblasNonUnit=131, CblasUnit=132}; +enum BLASFEO_CBLAS_SIDE {CblasLeft=141, CblasRight=142}; +#endif // FORTRAN_BLAS_API +#endif // BLASFEO_CBLAS_ENUM +#endif // CBLAS_API +#endif // BLAS_API + + + #ifdef __cplusplus extern "C" { #endif @@ -78,27 +103,67 @@ void spotrf_(char *uplo, int *m, float *A, int *lda, int *info); +#ifdef CBLAS_API + + + +// CBLAS 1 +// +void cblas_saxpy(const int N, const float alpha, const float *X, const int incX, float *Y, const int incY); + +// CBLAS 3 +// +void cblas_sgemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const float alpha, const float *A, const int lda, const float *B, const int ldb, const float beta, float *C, const int ldc); +// +void cblas_strsm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int M, const int N, const float alpha, const float *A, const int lda, float *B, const int ldb); + + + +#endif // CBLAS_API + + + #else // BLASFEO_API // BLAS 1 // -void blas_saxpy(int *n, float *alpha, float *x, int *incx, float *y, int *incy); +void blasfeo_blas_saxpy(int *n, float *alpha, float *x, int *incx, float *y, int *incy); // -float blas_sdot(int *n, float *x, int *incx, float *y, int *incy); +float blasfeo_blas_sdot(int *n, float *x, int *incx, float *y, int *incy); // BLAS 3 // -void blas_sgemm(char *ta, char *tb, int *m, int *n, int *k, float *alpha, float *A, int *lda, float *B, int *ldb, float *beta, float *C, int *ldc); +void blasfeo_blas_sgemm(char *ta, char *tb, int *m, int *n, int *k, float *alpha, float *A, int *lda, float *B, int *ldb, float *beta, float *C, int *ldc); // -void blas_strsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, float *alpha, float *A, int *lda, float *B, int *ldb); +void blasfeo_blas_strsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, float *alpha, float *A, int *lda, float *B, int *ldb); // LAPACK // -void blas_spotrf(char *uplo, int *m, float *A, int *lda, int *info); +void blasfeo_lapack_spotrf(char *uplo, int *m, float *A, int *lda, int *info); + + + +#ifdef CBLAS_API + + + +// CBLAS 1 +// +void blasfeo_cblas_saxpy(const int N, const float alpha, const float *X, const int incX, float *Y, const int incY); + +// CBLAS 3 +// +void blasfeo_cblas_sgemm(const enum BLASFEO_CBLAS_ORDER Order, const enum BLASFEO_CBLAS_TRANSPOSE TransA, const enum BLASFEO_CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const float alpha, const float *A, const int lda, const float *B, const int ldb, const float beta, float *C, const int ldc); +// +void blasfeo_cblas_strsm(const enum BLASFEO_CBLAS_ORDER Order, const enum BLASFEO_CBLAS_SIDE Side, const enum BLASFEO_CBLAS_UPLO Uplo, const enum BLASFEO_CBLAS_TRANSPOSE TransA, const enum BLASFEO_CBLAS_DIAG Diag, const int M, const int N, const float alpha, const float *A, const int lda, float *B, const int ldb); + + + +#endif // CBLAS_API diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_blasfeo_api.h b/third_party/acados/include/blasfeo/include/blasfeo_s_blasfeo_api.h index 24b21ead25..8b98104735 100644 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_blasfeo_api.h +++ b/third_party/acados/include/blasfeo/include/blasfeo_s_blasfeo_api.h @@ -115,6 +115,10 @@ void blasfeo_sgemv_nt(int m, int n, float alpha_n, float alpha_t, struct blasfeo // z <= beta * y + alpha * A * x, where A is symmetric and only the lower triangular patr of A is accessed void blasfeo_ssymv_l(int m, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); void blasfeo_ssymv_l_mn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); +// z <= beta * y + alpha * A * x, where A is symmetric and only the upper triangular patr of A is accessed +void blasfeo_ssymv_u(int m, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); +// D = C + alpha * x * y^T +void blasfeo_sger(int m, int n, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); // diagonal @@ -182,6 +186,14 @@ void blasfeo_strsm_runu(int m, int n, float alpha, struct blasfeo_smat *sA, int void blasfeo_strsm_rutn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); // D <= alpha * B * A^{-T} , with A upper triangular with unit diagonal void blasfeo_strsm_rutu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); +// D <= beta * C + alpha * A * B^T + alpha * B * A^T; C, D lower triangular +void blasfeo_ssyr2k_ln(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); +// D <= beta * C + alpha * A^T * B + alpha * B^T * A; C, D lower triangular +void blasfeo_ssyr2k_lt(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); +// D <= beta * C + alpha * A * B^T + alpha * B * A^T; C, D upper triangular +void blasfeo_ssyr2k_un(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); +// D <= beta * C + alpha * A^T * B + alpha * B^T * A; C, D upper triangular +void blasfeo_ssyr2k_ut(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); // diagonal diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_blasfeo_ref_api.h b/third_party/acados/include/blasfeo/include/blasfeo_s_blasfeo_ref_api.h index 805914cc05..17cb179695 100644 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_blasfeo_ref_api.h +++ b/third_party/acados/include/blasfeo/include/blasfeo_s_blasfeo_ref_api.h @@ -115,6 +115,10 @@ void blasfeo_ref_sgemv_nt(int m, int n, float alpha_n, float alpha_t, struct bla // z <= beta * y + alpha * A * x, where A is symmetric and only the lower triangular patr of A is accessed void blasfeo_ref_ssymv_l(int m, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); void blasfeo_ref_ssymv_l_mn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); +// z <= beta * y + alpha * A * x, where A is symmetric and only the upper triangular patr of A is accessed +void blasfeo_ref_ssymv_u(int m, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); +// D = C + alpha * x * y^T +void blasfeo_ref_sger(int m, int n, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); // diagonal @@ -182,6 +186,14 @@ void blasfeo_ref_strsm_runu(int m, int n, float alpha, struct blasfeo_smat *sA, void blasfeo_ref_strsm_rutn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); // D <= alpha * B * A^{-T} , with A upper triangular with unit diagonal void blasfeo_ref_strsm_rutu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); +// D <= beta * C + alpha * A * B^T + alpha * B * A^T ; C, D lower triangular +void blasfeo_ref_ssyr2k_ln(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); +// D <= beta * C + alpha * A^T * B + alpha * B^T * A ; C, D lower triangular +void blasfeo_ref_ssyr2k_lt(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); +// D <= beta * C + alpha * A * B^T + alpha * B * A^T ; C, D upper triangular +void blasfeo_ref_ssyr2k_un(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); +// D <= beta * C + alpha * A^T * B + alpha * B^T * A ; C, D upper triangular +void blasfeo_ref_ssyr2k_ut(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); // diagonal diff --git a/third_party/acados/include/blasfeo/include/blasfeo_target.h b/third_party/acados/include/blasfeo/include/blasfeo_target.h index 51f617a649..4ff4f307b3 100644 --- a/third_party/acados/include/blasfeo/include/blasfeo_target.h +++ b/third_party/acados/include/blasfeo/include/blasfeo_target.h @@ -1,13 +1,13 @@ -#ifndef TARGET_X64_INTEL_HASWELL -#define TARGET_X64_INTEL_HASWELL +#ifndef TARGET_ARMV8A_ARM_CORTEX_A57 +#define TARGET_ARMV8A_ARM_CORTEX_A57 #endif #ifndef TARGET_NEED_FEATURE_AVX2 -#define TARGET_NEED_FEATURE_AVX2 1 +/* #undef TARGET_NEED_FEATURE_AVX2 */ #endif #ifndef TARGET_NEED_FEATURE_FMA -#define TARGET_NEED_FEATURE_FMA 1 +/* #undef TARGET_NEED_FEATURE_FMA */ #endif #ifndef TARGET_NEED_FEATURE_SSE3 @@ -27,11 +27,11 @@ #endif #ifndef TARGET_NEED_FEATURE_VFPv4 -/* #undef TARGET_NEED_FEATURE_VFPv4 */ +#define TARGET_NEED_FEATURE_VFPv4 1 #endif #ifndef TARGET_NEED_FEATURE_NEONv2 -/* #undef TARGET_NEED_FEATURE_NEONv2 */ +#define TARGET_NEED_FEATURE_NEONv2 1 #endif #ifndef LA_HIGH_PERFORMANCE diff --git a/third_party/acados/include/blasfeo/include/d_blas.h b/third_party/acados/include/blasfeo/include/d_blas.h index d6f8786721..ffd2578da3 100644 --- a/third_party/acados/include/blasfeo/include/d_blas.h +++ b/third_party/acados/include/blasfeo/include/d_blas.h @@ -61,6 +61,7 @@ void dgemm_(char *ta, char *tb, int *m, int *n, int *k, double *alpha, double *A void dsyrk_(char *uplo, char *trans, int *n, int *k, double *alpha, double *A, int *lda, double *beta, double *C, int *ldc); void dtrmm_(char *side, char *uplo, char *trans, char *diag, int *m, int *n, double *alpha, double *A, int *lda, double *B, int *ldb); void dtrsm_(char *side, char *uplo, char *trans, char *diag, int *m, int *n, double *alpha, double *A, int *lda, double *B, int *ldb); +void dsyr2k_(char *uplo, char *trans, int *n, int *k, double *alpha, double *A, int *lda, double *B, int *ldb, double *beta, double *C, int *ldc); // lapack void dpotrf_(char *uplo, int *m, double *A, int *lda, int *info); diff --git a/third_party/acados/include/blasfeo/include/s_blas.h b/third_party/acados/include/blasfeo/include/s_blas.h index 58b2bb0a1a..3b299ce64c 100644 --- a/third_party/acados/include/blasfeo/include/s_blas.h +++ b/third_party/acados/include/blasfeo/include/s_blas.h @@ -61,6 +61,7 @@ void sgemm_(char *ta, char *tb, int *m, int *n, int *k, float *alpha, float *A, void ssyrk_(char *uplo, char *trans, int *n, int *k, float *alpha, float *A, int *lda, float *beta, float *C, int *ldc); void strmm_(char *side, char *uplo, char *transa, char *diag, int *m, int *n, float *alpha, float *A, int *lda, float *B, int *ldb); void strsm_(char *side, char *uplo, char *transa, char *diag, int *m, int *n, float *alpha, float *A, int *lda, float *B, int *ldb); +void ssyr2k_(char *uplo, char *trans, int *n, int *k, float *alpha, float *A, int *lda, float *B, int *ldb, float *beta, float *C, int *ldc); // lapack void spotrf_(char *uplo, int *m, float *A, int *lda, int *info); diff --git a/third_party/acados/larch64/lib/libacados.so b/third_party/acados/larch64/lib/libacados.so index 1f2b1f5c0b..35f83d4159 100644 Binary files a/third_party/acados/larch64/lib/libacados.so and b/third_party/acados/larch64/lib/libacados.so differ diff --git a/third_party/acados/larch64/lib/libblasfeo.so b/third_party/acados/larch64/lib/libblasfeo.so index 790282fa19..6b0e26de79 100644 Binary files a/third_party/acados/larch64/lib/libblasfeo.so and b/third_party/acados/larch64/lib/libblasfeo.so differ diff --git a/third_party/acados/x86_64/lib/libacados.so b/third_party/acados/x86_64/lib/libacados.so index 00a5e2371a..b8a6280d68 100644 Binary files a/third_party/acados/x86_64/lib/libacados.so and b/third_party/acados/x86_64/lib/libacados.so differ diff --git a/third_party/acados/x86_64/lib/libblasfeo.so b/third_party/acados/x86_64/lib/libblasfeo.so index 5a8399287a..e4a19caf13 100644 Binary files a/third_party/acados/x86_64/lib/libblasfeo.so and b/third_party/acados/x86_64/lib/libblasfeo.so differ diff --git a/third_party/acados/x86_64/lib/libhpipm.so b/third_party/acados/x86_64/lib/libhpipm.so index f52091d931..428c76a117 100644 Binary files a/third_party/acados/x86_64/lib/libhpipm.so and b/third_party/acados/x86_64/lib/libhpipm.so differ diff --git a/third_party/acados/x86_64/lib/libqpOASES_e.so.3.1 b/third_party/acados/x86_64/lib/libqpOASES_e.so.3.1 index 6b553554fd..cf3604688c 100644 Binary files a/third_party/acados/x86_64/lib/libqpOASES_e.so.3.1 and b/third_party/acados/x86_64/lib/libqpOASES_e.so.3.1 differ diff --git a/third_party/acados/x86_64/t_renderer b/third_party/acados/x86_64/t_renderer index 181ef9c3d2..5ced89c28d 100755 Binary files a/third_party/acados/x86_64/t_renderer and b/third_party/acados/x86_64/t_renderer differ diff --git a/third_party/android_frameworks_native/get.txt b/third_party/android_frameworks_native/get.txt deleted file mode 100644 index 277bdcb6a8..0000000000 --- a/third_party/android_frameworks_native/get.txt +++ /dev/null @@ -1,3 +0,0 @@ -git clone https://github.com/CyanogenMod/android_frameworks_native.git && cd android_frameworks_native -git reset --hard b22bca465e55618a949d9cbdea665a1a3a831241 -cp -r include ~/one/third_party/android_frameworks_native/ diff --git a/third_party/android_frameworks_native/include/android/asset_manager.h b/third_party/android_frameworks_native/include/android/asset_manager.h deleted file mode 100644 index d65483968e..0000000000 --- a/third_party/android_frameworks_native/include/android/asset_manager.h +++ /dev/null @@ -1,215 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/android/asset_manager_jni.h b/third_party/android_frameworks_native/include/android/asset_manager_jni.h deleted file mode 100644 index dcee17e10f..0000000000 --- a/third_party/android_frameworks_native/include/android/asset_manager_jni.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/android/bitmap.h b/third_party/android_frameworks_native/include/android/bitmap.h deleted file mode 100644 index 261e64fac9..0000000000 --- a/third_party/android_frameworks_native/include/android/bitmap.h +++ /dev/null @@ -1,112 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/android/configuration.h b/third_party/android_frameworks_native/include/android/configuration.h deleted file mode 100644 index 81f71a92cb..0000000000 --- a/third_party/android_frameworks_native/include/android/configuration.h +++ /dev/null @@ -1,708 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/android/input.h b/third_party/android_frameworks_native/include/android/input.h deleted file mode 100644 index 46cf89c7e1..0000000000 --- a/third_party/android_frameworks_native/include/android/input.h +++ /dev/null @@ -1,1317 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/android/keycodes.h b/third_party/android_frameworks_native/include/android/keycodes.h deleted file mode 100644 index 421abe5477..0000000000 --- a/third_party/android_frameworks_native/include/android/keycodes.h +++ /dev/null @@ -1,752 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/android/looper.h b/third_party/android_frameworks_native/include/android/looper.h deleted file mode 100644 index 718f703048..0000000000 --- a/third_party/android_frameworks_native/include/android/looper.h +++ /dev/null @@ -1,269 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/android/multinetwork.h b/third_party/android_frameworks_native/include/android/multinetwork.h deleted file mode 100644 index 6c718c9037..0000000000 --- a/third_party/android_frameworks_native/include/android/multinetwork.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/android/native_activity.h b/third_party/android_frameworks_native/include/android/native_activity.h deleted file mode 100644 index d3d99cf7a9..0000000000 --- a/third_party/android_frameworks_native/include/android/native_activity.h +++ /dev/null @@ -1,340 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/android/native_window.h b/third_party/android_frameworks_native/include/android/native_window.h deleted file mode 100644 index cf07f1afad..0000000000 --- a/third_party/android_frameworks_native/include/android/native_window.h +++ /dev/null @@ -1,150 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/android/native_window_jni.h b/third_party/android_frameworks_native/include/android/native_window_jni.h deleted file mode 100644 index 60a36c3f27..0000000000 --- a/third_party/android_frameworks_native/include/android/native_window_jni.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/android/obb.h b/third_party/android_frameworks_native/include/android/obb.h deleted file mode 100644 index 4c6d9d7bad..0000000000 --- a/third_party/android_frameworks_native/include/android/obb.h +++ /dev/null @@ -1,76 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/android/rect.h b/third_party/android_frameworks_native/include/android/rect.h deleted file mode 100644 index 80741c0442..0000000000 --- a/third_party/android_frameworks_native/include/android/rect.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/android/sensor.h b/third_party/android_frameworks_native/include/android/sensor.h deleted file mode 100644 index 73928ea76f..0000000000 --- a/third_party/android_frameworks_native/include/android/sensor.h +++ /dev/null @@ -1,475 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/android/storage_manager.h b/third_party/android_frameworks_native/include/android/storage_manager.h deleted file mode 100644 index 7f2ee08d62..0000000000 --- a/third_party/android_frameworks_native/include/android/storage_manager.h +++ /dev/null @@ -1,154 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/android/trace.h b/third_party/android_frameworks_native/include/android/trace.h deleted file mode 100644 index e42e334102..0000000000 --- a/third_party/android_frameworks_native/include/android/trace.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/android/window.h b/third_party/android_frameworks_native/include/android/window.h deleted file mode 100644 index 436bf3a830..0000000000 --- a/third_party/android_frameworks_native/include/android/window.h +++ /dev/null @@ -1,224 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/binder/AppOpsManager.h b/third_party/android_frameworks_native/include/binder/AppOpsManager.h deleted file mode 100644 index 1d0e968c4a..0000000000 --- a/third_party/android_frameworks_native/include/binder/AppOpsManager.h +++ /dev/null @@ -1,130 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/binder/Binder.h b/third_party/android_frameworks_native/include/binder/Binder.h deleted file mode 100644 index 86628a03d3..0000000000 --- a/third_party/android_frameworks_native/include/binder/Binder.h +++ /dev/null @@ -1,105 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/binder/BinderService.h b/third_party/android_frameworks_native/include/binder/BinderService.h deleted file mode 100644 index ef703bda90..0000000000 --- a/third_party/android_frameworks_native/include/binder/BinderService.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/binder/BpBinder.h b/third_party/android_frameworks_native/include/binder/BpBinder.h deleted file mode 100644 index 7ef93aa390..0000000000 --- a/third_party/android_frameworks_native/include/binder/BpBinder.h +++ /dev/null @@ -1,124 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/binder/BufferedTextOutput.h b/third_party/android_frameworks_native/include/binder/BufferedTextOutput.h deleted file mode 100644 index 9a7c43bb13..0000000000 --- a/third_party/android_frameworks_native/include/binder/BufferedTextOutput.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/binder/Debug.h b/third_party/android_frameworks_native/include/binder/Debug.h deleted file mode 100644 index f6a335502f..0000000000 --- a/third_party/android_frameworks_native/include/binder/Debug.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/binder/IAppOpsCallback.h b/third_party/android_frameworks_native/include/binder/IAppOpsCallback.h deleted file mode 100644 index 7f8eb0168b..0000000000 --- a/third_party/android_frameworks_native/include/binder/IAppOpsCallback.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/binder/IAppOpsService.h b/third_party/android_frameworks_native/include/binder/IAppOpsService.h deleted file mode 100644 index cd81efa363..0000000000 --- a/third_party/android_frameworks_native/include/binder/IAppOpsService.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/binder/IBatteryStats.h b/third_party/android_frameworks_native/include/binder/IBatteryStats.h deleted file mode 100644 index 5f3818652b..0000000000 --- a/third_party/android_frameworks_native/include/binder/IBatteryStats.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/binder/IBinder.h b/third_party/android_frameworks_native/include/binder/IBinder.h deleted file mode 100644 index 43b654334b..0000000000 --- a/third_party/android_frameworks_native/include/binder/IBinder.h +++ /dev/null @@ -1,152 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/binder/IInterface.h b/third_party/android_frameworks_native/include/binder/IInterface.h deleted file mode 100644 index 4ce361380d..0000000000 --- a/third_party/android_frameworks_native/include/binder/IInterface.h +++ /dev/null @@ -1,150 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/binder/IMemory.h b/third_party/android_frameworks_native/include/binder/IMemory.h deleted file mode 100644 index 178ef85937..0000000000 --- a/third_party/android_frameworks_native/include/binder/IMemory.h +++ /dev/null @@ -1,107 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/binder/IPCThreadState.h b/third_party/android_frameworks_native/include/binder/IPCThreadState.h deleted file mode 100644 index 1853cff235..0000000000 --- a/third_party/android_frameworks_native/include/binder/IPCThreadState.h +++ /dev/null @@ -1,135 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/binder/IPermissionController.h b/third_party/android_frameworks_native/include/binder/IPermissionController.h deleted file mode 100644 index 4e5fb34838..0000000000 --- a/third_party/android_frameworks_native/include/binder/IPermissionController.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/binder/IProcessInfoService.h b/third_party/android_frameworks_native/include/binder/IProcessInfoService.h deleted file mode 100644 index dc62f457c7..0000000000 --- a/third_party/android_frameworks_native/include/binder/IProcessInfoService.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/binder/IServiceManager.h b/third_party/android_frameworks_native/include/binder/IServiceManager.h deleted file mode 100644 index 2c297d64fb..0000000000 --- a/third_party/android_frameworks_native/include/binder/IServiceManager.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/binder/MemoryBase.h b/third_party/android_frameworks_native/include/binder/MemoryBase.h deleted file mode 100644 index 463e26d977..0000000000 --- a/third_party/android_frameworks_native/include/binder/MemoryBase.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/binder/MemoryDealer.h b/third_party/android_frameworks_native/include/binder/MemoryDealer.h deleted file mode 100644 index aa415d5ac8..0000000000 --- a/third_party/android_frameworks_native/include/binder/MemoryDealer.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/binder/MemoryHeapBase.h b/third_party/android_frameworks_native/include/binder/MemoryHeapBase.h deleted file mode 100644 index ea9b66c497..0000000000 --- a/third_party/android_frameworks_native/include/binder/MemoryHeapBase.h +++ /dev/null @@ -1,103 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/binder/MemoryHeapIon.h b/third_party/android_frameworks_native/include/binder/MemoryHeapIon.h deleted file mode 100644 index 7e059f4eac..0000000000 --- a/third_party/android_frameworks_native/include/binder/MemoryHeapIon.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/binder/Parcel.h b/third_party/android_frameworks_native/include/binder/Parcel.h deleted file mode 100644 index 91ffae0ba3..0000000000 --- a/third_party/android_frameworks_native/include/binder/Parcel.h +++ /dev/null @@ -1,436 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/binder/PermissionCache.h b/third_party/android_frameworks_native/include/binder/PermissionCache.h deleted file mode 100644 index bcdf0c2914..0000000000 --- a/third_party/android_frameworks_native/include/binder/PermissionCache.h +++ /dev/null @@ -1,80 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/binder/ProcessInfoService.h b/third_party/android_frameworks_native/include/binder/ProcessInfoService.h deleted file mode 100644 index c5ead20676..0000000000 --- a/third_party/android_frameworks_native/include/binder/ProcessInfoService.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/binder/ProcessState.h b/third_party/android_frameworks_native/include/binder/ProcessState.h deleted file mode 100644 index f9edc2a691..0000000000 --- a/third_party/android_frameworks_native/include/binder/ProcessState.h +++ /dev/null @@ -1,116 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/binder/TextOutput.h b/third_party/android_frameworks_native/include/binder/TextOutput.h deleted file mode 100644 index 974a194d8c..0000000000 --- a/third_party/android_frameworks_native/include/binder/TextOutput.h +++ /dev/null @@ -1,195 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/BitTube.h b/third_party/android_frameworks_native/include/gui/BitTube.h deleted file mode 100644 index 3ecac52ad7..0000000000 --- a/third_party/android_frameworks_native/include/gui/BitTube.h +++ /dev/null @@ -1,95 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/BufferItem.h b/third_party/android_frameworks_native/include/gui/BufferItem.h deleted file mode 100644 index 145efe6f60..0000000000 --- a/third_party/android_frameworks_native/include/gui/BufferItem.h +++ /dev/null @@ -1,130 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/BufferItemConsumer.h b/third_party/android_frameworks_native/include/gui/BufferItemConsumer.h deleted file mode 100644 index 56c7a3f463..0000000000 --- a/third_party/android_frameworks_native/include/gui/BufferItemConsumer.h +++ /dev/null @@ -1,93 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/BufferQueue.h b/third_party/android_frameworks_native/include/gui/BufferQueue.h deleted file mode 100644 index 09300a20c9..0000000000 --- a/third_party/android_frameworks_native/include/gui/BufferQueue.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/BufferQueueConsumer.h b/third_party/android_frameworks_native/include/gui/BufferQueueConsumer.h deleted file mode 100644 index cde302f8a6..0000000000 --- a/third_party/android_frameworks_native/include/gui/BufferQueueConsumer.h +++ /dev/null @@ -1,187 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/BufferQueueCore.h b/third_party/android_frameworks_native/include/gui/BufferQueueCore.h deleted file mode 100644 index 99134ea501..0000000000 --- a/third_party/android_frameworks_native/include/gui/BufferQueueCore.h +++ /dev/null @@ -1,287 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/BufferQueueDefs.h b/third_party/android_frameworks_native/include/gui/BufferQueueDefs.h deleted file mode 100644 index 83e9580037..0000000000 --- a/third_party/android_frameworks_native/include/gui/BufferQueueDefs.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/BufferQueueProducer.h b/third_party/android_frameworks_native/include/gui/BufferQueueProducer.h deleted file mode 100644 index 9754a89eac..0000000000 --- a/third_party/android_frameworks_native/include/gui/BufferQueueProducer.h +++ /dev/null @@ -1,228 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/BufferSlot.h b/third_party/android_frameworks_native/include/gui/BufferSlot.h deleted file mode 100644 index 6085e116a3..0000000000 --- a/third_party/android_frameworks_native/include/gui/BufferSlot.h +++ /dev/null @@ -1,142 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/ConsumerBase.h b/third_party/android_frameworks_native/include/gui/ConsumerBase.h deleted file mode 100644 index 9307a26fb3..0000000000 --- a/third_party/android_frameworks_native/include/gui/ConsumerBase.h +++ /dev/null @@ -1,252 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/CpuConsumer.h b/third_party/android_frameworks_native/include/gui/CpuConsumer.h deleted file mode 100644 index 3b07a31750..0000000000 --- a/third_party/android_frameworks_native/include/gui/CpuConsumer.h +++ /dev/null @@ -1,131 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/DisplayEventReceiver.h b/third_party/android_frameworks_native/include/gui/DisplayEventReceiver.h deleted file mode 100644 index a4718b91c6..0000000000 --- a/third_party/android_frameworks_native/include/gui/DisplayEventReceiver.h +++ /dev/null @@ -1,137 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/GLConsumer.h b/third_party/android_frameworks_native/include/gui/GLConsumer.h deleted file mode 100644 index c35c7be064..0000000000 --- a/third_party/android_frameworks_native/include/gui/GLConsumer.h +++ /dev/null @@ -1,488 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/GraphicBufferAlloc.h b/third_party/android_frameworks_native/include/gui/GraphicBufferAlloc.h deleted file mode 100644 index 69fe51ef93..0000000000 --- a/third_party/android_frameworks_native/include/gui/GraphicBufferAlloc.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/GuiConfig.h b/third_party/android_frameworks_native/include/gui/GuiConfig.h deleted file mode 100644 index b020ed9b6a..0000000000 --- a/third_party/android_frameworks_native/include/gui/GuiConfig.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/IConsumerListener.h b/third_party/android_frameworks_native/include/gui/IConsumerListener.h deleted file mode 100644 index 3f39799564..0000000000 --- a/third_party/android_frameworks_native/include/gui/IConsumerListener.h +++ /dev/null @@ -1,104 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/IDisplayEventConnection.h b/third_party/android_frameworks_native/include/gui/IDisplayEventConnection.h deleted file mode 100644 index 86247de62b..0000000000 --- a/third_party/android_frameworks_native/include/gui/IDisplayEventConnection.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/IGraphicBufferAlloc.h b/third_party/android_frameworks_native/include/gui/IGraphicBufferAlloc.h deleted file mode 100644 index f3c46ec2ed..0000000000 --- a/third_party/android_frameworks_native/include/gui/IGraphicBufferAlloc.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/IGraphicBufferConsumer.h b/third_party/android_frameworks_native/include/gui/IGraphicBufferConsumer.h deleted file mode 100644 index 60ec9cc0e9..0000000000 --- a/third_party/android_frameworks_native/include/gui/IGraphicBufferConsumer.h +++ /dev/null @@ -1,280 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/IGraphicBufferProducer.h b/third_party/android_frameworks_native/include/gui/IGraphicBufferProducer.h deleted file mode 100644 index 9530de1aa8..0000000000 --- a/third_party/android_frameworks_native/include/gui/IGraphicBufferProducer.h +++ /dev/null @@ -1,502 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/IProducerListener.h b/third_party/android_frameworks_native/include/gui/IProducerListener.h deleted file mode 100644 index 3848a6c850..0000000000 --- a/third_party/android_frameworks_native/include/gui/IProducerListener.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/ISensorEventConnection.h b/third_party/android_frameworks_native/include/gui/ISensorEventConnection.h deleted file mode 100644 index f64c6b8604..0000000000 --- a/third_party/android_frameworks_native/include/gui/ISensorEventConnection.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/ISensorServer.h b/third_party/android_frameworks_native/include/gui/ISensorServer.h deleted file mode 100644 index 3dca2a3739..0000000000 --- a/third_party/android_frameworks_native/include/gui/ISensorServer.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/ISurfaceComposer.h b/third_party/android_frameworks_native/include/gui/ISurfaceComposer.h deleted file mode 100644 index 6e3fc5a6de..0000000000 --- a/third_party/android_frameworks_native/include/gui/ISurfaceComposer.h +++ /dev/null @@ -1,201 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/ISurfaceComposerClient.h b/third_party/android_frameworks_native/include/gui/ISurfaceComposerClient.h deleted file mode 100644 index d3e8b8ba13..0000000000 --- a/third_party/android_frameworks_native/include/gui/ISurfaceComposerClient.h +++ /dev/null @@ -1,95 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/Sensor.h b/third_party/android_frameworks_native/include/gui/Sensor.h deleted file mode 100644 index 8142be6352..0000000000 --- a/third_party/android_frameworks_native/include/gui/Sensor.h +++ /dev/null @@ -1,113 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/SensorEventQueue.h b/third_party/android_frameworks_native/include/gui/SensorEventQueue.h deleted file mode 100644 index e5b9fc5984..0000000000 --- a/third_party/android_frameworks_native/include/gui/SensorEventQueue.h +++ /dev/null @@ -1,98 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/SensorManager.h b/third_party/android_frameworks_native/include/gui/SensorManager.h deleted file mode 100644 index 0cff46c076..0000000000 --- a/third_party/android_frameworks_native/include/gui/SensorManager.h +++ /dev/null @@ -1,84 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/StreamSplitter.h b/third_party/android_frameworks_native/include/gui/StreamSplitter.h deleted file mode 100644 index 8f47eb47ac..0000000000 --- a/third_party/android_frameworks_native/include/gui/StreamSplitter.h +++ /dev/null @@ -1,184 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/Surface.h b/third_party/android_frameworks_native/include/gui/Surface.h deleted file mode 100644 index 72f1067076..0000000000 --- a/third_party/android_frameworks_native/include/gui/Surface.h +++ /dev/null @@ -1,324 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/SurfaceComposerClient.h b/third_party/android_frameworks_native/include/gui/SurfaceComposerClient.h deleted file mode 100644 index 9ec3f23491..0000000000 --- a/third_party/android_frameworks_native/include/gui/SurfaceComposerClient.h +++ /dev/null @@ -1,242 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/gui/SurfaceControl.h b/third_party/android_frameworks_native/include/gui/SurfaceControl.h deleted file mode 100644 index 5fa45d1668..0000000000 --- a/third_party/android_frameworks_native/include/gui/SurfaceControl.h +++ /dev/null @@ -1,112 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/ui/ANativeObjectBase.h b/third_party/android_frameworks_native/include/ui/ANativeObjectBase.h deleted file mode 100644 index 76e850fa27..0000000000 --- a/third_party/android_frameworks_native/include/ui/ANativeObjectBase.h +++ /dev/null @@ -1,102 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/ui/DisplayInfo.h b/third_party/android_frameworks_native/include/ui/DisplayInfo.h deleted file mode 100644 index ad73ee72f9..0000000000 --- a/third_party/android_frameworks_native/include/ui/DisplayInfo.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/ui/DisplayStatInfo.h b/third_party/android_frameworks_native/include/ui/DisplayStatInfo.h deleted file mode 100644 index 0549a832b5..0000000000 --- a/third_party/android_frameworks_native/include/ui/DisplayStatInfo.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/ui/Fence.h b/third_party/android_frameworks_native/include/ui/Fence.h deleted file mode 100644 index b431bd52aa..0000000000 --- a/third_party/android_frameworks_native/include/ui/Fence.h +++ /dev/null @@ -1,117 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/ui/FrameStats.h b/third_party/android_frameworks_native/include/ui/FrameStats.h deleted file mode 100644 index 6bfe635c72..0000000000 --- a/third_party/android_frameworks_native/include/ui/FrameStats.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/ui/FramebufferNativeWindow.h b/third_party/android_frameworks_native/include/ui/FramebufferNativeWindow.h deleted file mode 100644 index 6b66d5f66b..0000000000 --- a/third_party/android_frameworks_native/include/ui/FramebufferNativeWindow.h +++ /dev/null @@ -1,102 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/ui/GraphicBuffer.h b/third_party/android_frameworks_native/include/ui/GraphicBuffer.h deleted file mode 100644 index 3da720ff37..0000000000 --- a/third_party/android_frameworks_native/include/ui/GraphicBuffer.h +++ /dev/null @@ -1,183 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/ui/GraphicBufferAllocator.h b/third_party/android_frameworks_native/include/ui/GraphicBufferAllocator.h deleted file mode 100644 index 5443f09a10..0000000000 --- a/third_party/android_frameworks_native/include/ui/GraphicBufferAllocator.h +++ /dev/null @@ -1,95 +0,0 @@ -/* -** -** 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/third_party/android_frameworks_native/include/ui/GraphicBufferMapper.h b/third_party/android_frameworks_native/include/ui/GraphicBufferMapper.h deleted file mode 100644 index 9900624827..0000000000 --- a/third_party/android_frameworks_native/include/ui/GraphicBufferMapper.h +++ /dev/null @@ -1,80 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/ui/PixelFormat.h b/third_party/android_frameworks_native/include/ui/PixelFormat.h deleted file mode 100644 index f26fecb8b1..0000000000 --- a/third_party/android_frameworks_native/include/ui/PixelFormat.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/ui/Point.h b/third_party/android_frameworks_native/include/ui/Point.h deleted file mode 100644 index 1d7f64d307..0000000000 --- a/third_party/android_frameworks_native/include/ui/Point.h +++ /dev/null @@ -1,88 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/ui/Region.h b/third_party/android_frameworks_native/include/ui/Region.h deleted file mode 100644 index 2a1491837d..0000000000 --- a/third_party/android_frameworks_native/include/ui/Region.h +++ /dev/null @@ -1,223 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/ui/TMatHelpers.h b/third_party/android_frameworks_native/include/ui/TMatHelpers.h deleted file mode 100644 index a6aadcad40..0000000000 --- a/third_party/android_frameworks_native/include/ui/TMatHelpers.h +++ /dev/null @@ -1,257 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/ui/TVecHelpers.h b/third_party/android_frameworks_native/include/ui/TVecHelpers.h deleted file mode 100644 index bb7dbfc2b8..0000000000 --- a/third_party/android_frameworks_native/include/ui/TVecHelpers.h +++ /dev/null @@ -1,381 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/ui/UiConfig.h b/third_party/android_frameworks_native/include/ui/UiConfig.h deleted file mode 100644 index fcf8ed5d6b..0000000000 --- a/third_party/android_frameworks_native/include/ui/UiConfig.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/ui/mat4.h b/third_party/android_frameworks_native/include/ui/mat4.h deleted file mode 100644 index 4fd1effd71..0000000000 --- a/third_party/android_frameworks_native/include/ui/mat4.h +++ /dev/null @@ -1,395 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/ui/vec2.h b/third_party/android_frameworks_native/include/ui/vec2.h deleted file mode 100644 index c31d0e43e3..0000000000 --- a/third_party/android_frameworks_native/include/ui/vec2.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/ui/vec3.h b/third_party/android_frameworks_native/include/ui/vec3.h deleted file mode 100644 index dde59a96fb..0000000000 --- a/third_party/android_frameworks_native/include/ui/vec3.h +++ /dev/null @@ -1,113 +0,0 @@ -/* - * 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/third_party/android_frameworks_native/include/ui/vec4.h b/third_party/android_frameworks_native/include/ui/vec4.h deleted file mode 100644 index e03d331fb3..0000000000 --- a/third_party/android_frameworks_native/include/ui/vec4.h +++ /dev/null @@ -1,118 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/activity_recognition.h b/third_party/android_hardware_libhardware/include/hardware/activity_recognition.h deleted file mode 100644 index 8f9945982d..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/activity_recognition.h +++ /dev/null @@ -1,223 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/audio.h b/third_party/android_hardware_libhardware/include/hardware/audio.h deleted file mode 100644 index 22e7419769..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/audio.h +++ /dev/null @@ -1,700 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/audio_alsaops.h b/third_party/android_hardware_libhardware/include/hardware/audio_alsaops.h deleted file mode 100644 index 0d266ff554..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/audio_alsaops.h +++ /dev/null @@ -1,102 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/audio_amplifier.h b/third_party/android_hardware_libhardware/include/hardware/audio_amplifier.h deleted file mode 100644 index e3477d52ad..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/audio_amplifier.h +++ /dev/null @@ -1,144 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/audio_effect.h b/third_party/android_hardware_libhardware/include/hardware/audio_effect.h deleted file mode 100644 index 41cd2e6146..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/audio_effect.h +++ /dev/null @@ -1,1014 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/audio_policy.h b/third_party/android_hardware_libhardware/include/hardware/audio_policy.h deleted file mode 100644 index 99cb0449fb..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/audio_policy.h +++ /dev/null @@ -1,457 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/bluetooth.h b/third_party/android_hardware_libhardware/include/hardware/bluetooth.h deleted file mode 100644 index 5e8b468d64..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/bluetooth.h +++ /dev/null @@ -1,595 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/bt_av.h b/third_party/android_hardware_libhardware/include/hardware/bt_av.h deleted file mode 100644 index be82fbeffd..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/bt_av.h +++ /dev/null @@ -1,133 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/bt_common_types.h b/third_party/android_hardware_libhardware/include/hardware/bt_common_types.h deleted file mode 100644 index e30ac24e3c..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/bt_common_types.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/bt_gatt.h b/third_party/android_hardware_libhardware/include/hardware/bt_gatt.h deleted file mode 100644 index 42e14c2f15..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/bt_gatt.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/bt_gatt_client.h b/third_party/android_hardware_libhardware/include/hardware/bt_gatt_client.h deleted file mode 100644 index e7e8e82bb9..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/bt_gatt_client.h +++ /dev/null @@ -1,455 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/bt_gatt_server.h b/third_party/android_hardware_libhardware/include/hardware/bt_gatt_server.h deleted file mode 100644 index 0d6cc1e8d6..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/bt_gatt_server.h +++ /dev/null @@ -1,196 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/bt_gatt_types.h b/third_party/android_hardware_libhardware/include/hardware/bt_gatt_types.h deleted file mode 100644 index e037ddcdbb..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/bt_gatt_types.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/bt_hd.h b/third_party/android_hardware_libhardware/include/hardware/bt_hd.h deleted file mode 100644 index 6ba5b097d0..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/bt_hd.h +++ /dev/null @@ -1,129 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/bt_hf.h b/third_party/android_hardware_libhardware/include/hardware/bt_hf.h deleted file mode 100644 index dbac061308..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/bt_hf.h +++ /dev/null @@ -1,348 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/bt_hf_client.h b/third_party/android_hardware_libhardware/include/hardware/bt_hf_client.h deleted file mode 100644 index 0577e97d4b..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/bt_hf_client.h +++ /dev/null @@ -1,375 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/bt_hh.h b/third_party/android_hardware_libhardware/include/hardware/bt_hh.h deleted file mode 100644 index ece3c11428..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/bt_hh.h +++ /dev/null @@ -1,191 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/bt_hl.h b/third_party/android_hardware_libhardware/include/hardware/bt_hl.h deleted file mode 100644 index bd29e3abf5..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/bt_hl.h +++ /dev/null @@ -1,123 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/bt_mce.h b/third_party/android_hardware_libhardware/include/hardware/bt_mce.h deleted file mode 100644 index 5d159b336d..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/bt_mce.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/bt_pan.h b/third_party/android_hardware_libhardware/include/hardware/bt_pan.h deleted file mode 100644 index 83e7949b21..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/bt_pan.h +++ /dev/null @@ -1,87 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/bt_rc.h b/third_party/android_hardware_libhardware/include/hardware/bt_rc.h deleted file mode 100644 index 6e1109d381..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/bt_rc.h +++ /dev/null @@ -1,527 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/bt_sdp.h b/third_party/android_hardware_libhardware/include/hardware/bt_sdp.h deleted file mode 100644 index 8f39bc5bdc..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/bt_sdp.h +++ /dev/null @@ -1,150 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/bt_sock.h b/third_party/android_hardware_libhardware/include/hardware/bt_sock.h deleted file mode 100644 index 9dd83bb1c9..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/bt_sock.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/camera.h b/third_party/android_hardware_libhardware/include/hardware/camera.h deleted file mode 100644 index b1f18fffce..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/camera.h +++ /dev/null @@ -1,298 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/camera2.h b/third_party/android_hardware_libhardware/include/hardware/camera2.h deleted file mode 100644 index d920d4b65c..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/camera2.h +++ /dev/null @@ -1,839 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/camera3.h b/third_party/android_hardware_libhardware/include/hardware/camera3.h deleted file mode 100644 index 3ef6d6fada..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/camera3.h +++ /dev/null @@ -1,3077 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/camera_common.h b/third_party/android_hardware_libhardware/include/hardware/camera_common.h deleted file mode 100644 index 7658dd4062..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/camera_common.h +++ /dev/null @@ -1,916 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/consumerir.h b/third_party/android_hardware_libhardware/include/hardware/consumerir.h deleted file mode 100644 index 15334c1111..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/consumerir.h +++ /dev/null @@ -1,92 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/display_defs.h b/third_party/android_hardware_libhardware/include/hardware/display_defs.h deleted file mode 100644 index 669ef78c4e..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/display_defs.h +++ /dev/null @@ -1,67 +0,0 @@ -/* 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/third_party/android_hardware_libhardware/include/hardware/fb.h b/third_party/android_hardware_libhardware/include/hardware/fb.h deleted file mode 100644 index 9df94165b9..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/fb.h +++ /dev/null @@ -1,173 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/fingerprint.h b/third_party/android_hardware_libhardware/include/hardware/fingerprint.h deleted file mode 100644 index ac88c10322..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/fingerprint.h +++ /dev/null @@ -1,266 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/fused_location.h b/third_party/android_hardware_libhardware/include/hardware/fused_location.h deleted file mode 100644 index 73360a12a1..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/fused_location.h +++ /dev/null @@ -1,825 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/gatekeeper.h b/third_party/android_hardware_libhardware/include/hardware/gatekeeper.h deleted file mode 100644 index 2bb2b08c39..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/gatekeeper.h +++ /dev/null @@ -1,190 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/gps.h b/third_party/android_hardware_libhardware/include/hardware/gps.h deleted file mode 100644 index 76b6cb7aed..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/gps.h +++ /dev/null @@ -1,1871 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/gralloc.h b/third_party/android_hardware_libhardware/include/hardware/gralloc.h deleted file mode 100644 index 07ac0290b4..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/gralloc.h +++ /dev/null @@ -1,401 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/hardware.h b/third_party/android_hardware_libhardware/include/hardware/hardware.h deleted file mode 100644 index 74f57aa4c2..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/hardware.h +++ /dev/null @@ -1,238 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/hdmi_cec.h b/third_party/android_hardware_libhardware/include/hardware/hdmi_cec.h deleted file mode 100644 index ab70f92e2b..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/hdmi_cec.h +++ /dev/null @@ -1,429 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/hw_auth_token.h b/third_party/android_hardware_libhardware/include/hardware/hw_auth_token.h deleted file mode 100644 index f471d1ab7d..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/hw_auth_token.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/hwcomposer.h b/third_party/android_hardware_libhardware/include/hardware/hwcomposer.h deleted file mode 100644 index aa466b300a..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/hwcomposer.h +++ /dev/null @@ -1,833 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/hwcomposer_defs.h b/third_party/android_hardware_libhardware/include/hardware/hwcomposer_defs.h deleted file mode 100644 index a90822a4b8..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/hwcomposer_defs.h +++ /dev/null @@ -1,263 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/input.h b/third_party/android_hardware_libhardware/include/hardware/input.h deleted file mode 100644 index 969b8ce570..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/input.h +++ /dev/null @@ -1,549 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/keymaster0.h b/third_party/android_hardware_libhardware/include/hardware/keymaster0.h deleted file mode 100644 index f020e5b188..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/keymaster0.h +++ /dev/null @@ -1,149 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/keymaster1.h b/third_party/android_hardware_libhardware/include/hardware/keymaster1.h deleted file mode 100644 index ac2cc2b408..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/keymaster1.h +++ /dev/null @@ -1,597 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/keymaster_common.h b/third_party/android_hardware_libhardware/include/hardware/keymaster_common.h deleted file mode 100644 index 772d7e4d23..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/keymaster_common.h +++ /dev/null @@ -1,185 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/keymaster_defs.h b/third_party/android_hardware_libhardware/include/hardware/keymaster_defs.h deleted file mode 100644 index 1a723c94a8..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/keymaster_defs.h +++ /dev/null @@ -1,539 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/lights.h b/third_party/android_hardware_libhardware/include/hardware/lights.h deleted file mode 100644 index 777c91593f..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/lights.h +++ /dev/null @@ -1,157 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/local_time_hal.h b/third_party/android_hardware_libhardware/include/hardware/local_time_hal.h deleted file mode 100644 index 946e799783..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/local_time_hal.h +++ /dev/null @@ -1,123 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/memtrack.h b/third_party/android_hardware_libhardware/include/hardware/memtrack.h deleted file mode 100644 index 57ba4ad796..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/memtrack.h +++ /dev/null @@ -1,160 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/nfc.h b/third_party/android_hardware_libhardware/include/hardware/nfc.h deleted file mode 100644 index 6002e34e83..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/nfc.h +++ /dev/null @@ -1,302 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/nfc_tag.h b/third_party/android_hardware_libhardware/include/hardware/nfc_tag.h deleted file mode 100644 index 040a07d8cb..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/nfc_tag.h +++ /dev/null @@ -1,95 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/power.h b/third_party/android_hardware_libhardware/include/hardware/power.h deleted file mode 100644 index 2eb98fe966..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/power.h +++ /dev/null @@ -1,184 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/qemu_pipe.h b/third_party/android_hardware_libhardware/include/hardware/qemu_pipe.h deleted file mode 100644 index 53aec97a08..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/qemu_pipe.h +++ /dev/null @@ -1,94 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/qemud.h b/third_party/android_hardware_libhardware/include/hardware/qemud.h deleted file mode 100644 index 5c39f9c939..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/qemud.h +++ /dev/null @@ -1,153 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/radio.h b/third_party/android_hardware_libhardware/include/hardware/radio.h deleted file mode 100644 index 145deb5737..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/radio.h +++ /dev/null @@ -1,298 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/sensors.h b/third_party/android_hardware_libhardware/include/hardware/sensors.h deleted file mode 100644 index 51bffe1196..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/sensors.h +++ /dev/null @@ -1,1096 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/sound_trigger.h b/third_party/android_hardware_libhardware/include/hardware/sound_trigger.h deleted file mode 100644 index 2a8db87caa..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/sound_trigger.h +++ /dev/null @@ -1,130 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/tv_input.h b/third_party/android_hardware_libhardware/include/hardware/tv_input.h deleted file mode 100644 index 456b06e1fd..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/tv_input.h +++ /dev/null @@ -1,408 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/vibrator.h b/third_party/android_hardware_libhardware/include/hardware/vibrator.h deleted file mode 100644 index 92b1fd0051..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/vibrator.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * 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/third_party/android_hardware_libhardware/include/hardware/wipower.h b/third_party/android_hardware_libhardware/include/hardware/wipower.h deleted file mode 100644 index eb3a0ee0d5..0000000000 --- a/third_party/android_hardware_libhardware/include/hardware/wipower.h +++ /dev/null @@ -1,119 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/android_reboot.h b/third_party/android_system_core/include/cutils/android_reboot.h deleted file mode 100644 index a3861a02dc..0000000000 --- a/third_party/android_system_core/include/cutils/android_reboot.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/aref.h b/third_party/android_system_core/include/cutils/aref.h deleted file mode 100644 index 3bd36ea04c..0000000000 --- a/third_party/android_system_core/include/cutils/aref.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/ashmem.h b/third_party/android_system_core/include/cutils/ashmem.h deleted file mode 100644 index 25b233e6a1..0000000000 --- a/third_party/android_system_core/include/cutils/ashmem.h +++ /dev/null @@ -1,45 +0,0 @@ -/* 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/third_party/android_system_core/include/cutils/atomic.h b/third_party/android_system_core/include/cutils/atomic.h deleted file mode 100644 index ded972acb2..0000000000 --- a/third_party/android_system_core/include/cutils/atomic.h +++ /dev/null @@ -1,237 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/bitops.h b/third_party/android_system_core/include/cutils/bitops.h deleted file mode 100644 index 045830d90b..0000000000 --- a/third_party/android_system_core/include/cutils/bitops.h +++ /dev/null @@ -1,120 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/compiler.h b/third_party/android_system_core/include/cutils/compiler.h deleted file mode 100644 index 70f884a1e7..0000000000 --- a/third_party/android_system_core/include/cutils/compiler.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/config_utils.h b/third_party/android_system_core/include/cutils/config_utils.h deleted file mode 100644 index 2dea6f19fa..0000000000 --- a/third_party/android_system_core/include/cutils/config_utils.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/debugger.h b/third_party/android_system_core/include/cutils/debugger.h deleted file mode 100644 index 285e1afcd7..0000000000 --- a/third_party/android_system_core/include/cutils/debugger.h +++ /dev/null @@ -1,77 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/fs.h b/third_party/android_system_core/include/cutils/fs.h deleted file mode 100644 index 70f0b92919..0000000000 --- a/third_party/android_system_core/include/cutils/fs.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/hashmap.h b/third_party/android_system_core/include/cutils/hashmap.h deleted file mode 100644 index 5cb344c152..0000000000 --- a/third_party/android_system_core/include/cutils/hashmap.h +++ /dev/null @@ -1,150 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/iosched_policy.h b/third_party/android_system_core/include/cutils/iosched_policy.h deleted file mode 100644 index 25b87bac0a..0000000000 --- a/third_party/android_system_core/include/cutils/iosched_policy.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/jstring.h b/third_party/android_system_core/include/cutils/jstring.h deleted file mode 100644 index a3426081a0..0000000000 --- a/third_party/android_system_core/include/cutils/jstring.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/klog.h b/third_party/android_system_core/include/cutils/klog.h deleted file mode 100644 index 295d62be37..0000000000 --- a/third_party/android_system_core/include/cutils/klog.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/list.h b/third_party/android_system_core/include/cutils/list.h deleted file mode 100644 index 4ba2cfd499..0000000000 --- a/third_party/android_system_core/include/cutils/list.h +++ /dev/null @@ -1,88 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/log.h b/third_party/android_system_core/include/cutils/log.h deleted file mode 100644 index 0e0248e50f..0000000000 --- a/third_party/android_system_core/include/cutils/log.h +++ /dev/null @@ -1 +0,0 @@ -#include diff --git a/third_party/android_system_core/include/cutils/memory.h b/third_party/android_system_core/include/cutils/memory.h deleted file mode 100644 index 4d26882556..0000000000 --- a/third_party/android_system_core/include/cutils/memory.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/misc.h b/third_party/android_system_core/include/cutils/misc.h deleted file mode 100644 index 0de505f277..0000000000 --- a/third_party/android_system_core/include/cutils/misc.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/multiuser.h b/third_party/android_system_core/include/cutils/multiuser.h deleted file mode 100644 index 635ddb1358..0000000000 --- a/third_party/android_system_core/include/cutils/multiuser.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/native_handle.h b/third_party/android_system_core/include/cutils/native_handle.h deleted file mode 100644 index 268c5d3f51..0000000000 --- a/third_party/android_system_core/include/cutils/native_handle.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/open_memstream.h b/third_party/android_system_core/include/cutils/open_memstream.h deleted file mode 100644 index c1a81ebbcb..0000000000 --- a/third_party/android_system_core/include/cutils/open_memstream.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/partition_utils.h b/third_party/android_system_core/include/cutils/partition_utils.h deleted file mode 100644 index 72ca80d350..0000000000 --- a/third_party/android_system_core/include/cutils/partition_utils.h +++ /dev/null @@ -1,26 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/process_name.h b/third_party/android_system_core/include/cutils/process_name.h deleted file mode 100644 index 1e72e5c3ad..0000000000 --- a/third_party/android_system_core/include/cutils/process_name.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/properties.h b/third_party/android_system_core/include/cutils/properties.h deleted file mode 100644 index 24aa224f64..0000000000 --- a/third_party/android_system_core/include/cutils/properties.h +++ /dev/null @@ -1,133 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/qtaguid.h b/third_party/android_system_core/include/cutils/qtaguid.h deleted file mode 100644 index f8550fda83..0000000000 --- a/third_party/android_system_core/include/cutils/qtaguid.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/record_stream.h b/third_party/android_system_core/include/cutils/record_stream.h deleted file mode 100644 index bfac87a53c..0000000000 --- a/third_party/android_system_core/include/cutils/record_stream.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/sched_policy.h b/third_party/android_system_core/include/cutils/sched_policy.h deleted file mode 100644 index 6a8d570b2c..0000000000 --- a/third_party/android_system_core/include/cutils/sched_policy.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/sockets.h b/third_party/android_system_core/include/cutils/sockets.h deleted file mode 100644 index f8076ca452..0000000000 --- a/third_party/android_system_core/include/cutils/sockets.h +++ /dev/null @@ -1,104 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/str_parms.h b/third_party/android_system_core/include/cutils/str_parms.h deleted file mode 100644 index aa1435a080..0000000000 --- a/third_party/android_system_core/include/cutils/str_parms.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/threads.h b/third_party/android_system_core/include/cutils/threads.h deleted file mode 100644 index 5727494079..0000000000 --- a/third_party/android_system_core/include/cutils/threads.h +++ /dev/null @@ -1,148 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/trace.h b/third_party/android_system_core/include/cutils/trace.h deleted file mode 100644 index e4ed17983d..0000000000 --- a/third_party/android_system_core/include/cutils/trace.h +++ /dev/null @@ -1,252 +0,0 @@ -/* - * 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/third_party/android_system_core/include/cutils/uevent.h b/third_party/android_system_core/include/cutils/uevent.h deleted file mode 100644 index da1c2aae6b..0000000000 --- a/third_party/android_system_core/include/cutils/uevent.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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/third_party/android_system_core/include/log/event_tag_map.h b/third_party/android_system_core/include/log/event_tag_map.h deleted file mode 100644 index 1653c61e9a..0000000000 --- a/third_party/android_system_core/include/log/event_tag_map.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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/third_party/android_system_core/include/log/log.h b/third_party/android_system_core/include/log/log.h deleted file mode 100644 index 63a441a689..0000000000 --- a/third_party/android_system_core/include/log/log.h +++ /dev/null @@ -1,642 +0,0 @@ -/* - * 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/third_party/android_system_core/include/log/log_read.h b/third_party/android_system_core/include/log/log_read.h deleted file mode 100644 index 1b70affc35..0000000000 --- a/third_party/android_system_core/include/log/log_read.h +++ /dev/null @@ -1,170 +0,0 @@ -/* - * 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/third_party/android_system_core/include/log/logd.h b/third_party/android_system_core/include/log/logd.h deleted file mode 100644 index 0fe515f2ab..0000000000 --- a/third_party/android_system_core/include/log/logd.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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/third_party/android_system_core/include/log/logger.h b/third_party/android_system_core/include/log/logger.h deleted file mode 100644 index f030dab5a9..0000000000 --- a/third_party/android_system_core/include/log/logger.h +++ /dev/null @@ -1,196 +0,0 @@ -/* -** -** 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/third_party/android_system_core/include/log/logprint.h b/third_party/android_system_core/include/log/logprint.h deleted file mode 100644 index 4b812cc941..0000000000 --- a/third_party/android_system_core/include/log/logprint.h +++ /dev/null @@ -1,161 +0,0 @@ -/* - * 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/third_party/android_system_core/include/log/uio.h b/third_party/android_system_core/include/log/uio.h deleted file mode 100644 index 7059da5f76..0000000000 --- a/third_party/android_system_core/include/log/uio.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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/third_party/android_system_core/include/system/camera.h b/third_party/android_system_core/include/system/camera.h deleted file mode 100644 index 0570ca04c6..0000000000 --- a/third_party/android_system_core/include/system/camera.h +++ /dev/null @@ -1,365 +0,0 @@ -/* - * 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/third_party/android_system_core/include/system/graphics.h b/third_party/android_system_core/include/system/graphics.h deleted file mode 100644 index afd9f7bdb3..0000000000 --- a/third_party/android_system_core/include/system/graphics.h +++ /dev/null @@ -1,763 +0,0 @@ -/* - * 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/third_party/android_system_core/include/system/radio.h b/third_party/android_system_core/include/system/radio.h deleted file mode 100644 index a088526046..0000000000 --- a/third_party/android_system_core/include/system/radio.h +++ /dev/null @@ -1,247 +0,0 @@ -/* - * 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/third_party/android_system_core/include/system/thread_defs.h b/third_party/android_system_core/include/system/thread_defs.h deleted file mode 100644 index 377a48ce92..0000000000 --- a/third_party/android_system_core/include/system/thread_defs.h +++ /dev/null @@ -1,77 +0,0 @@ -/* - * 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/third_party/android_system_core/include/system/window.h b/third_party/android_system_core/include/system/window.h deleted file mode 100644 index 508ce00bac..0000000000 --- a/third_party/android_system_core/include/system/window.h +++ /dev/null @@ -1,954 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/AndroidThreads.h b/third_party/android_system_core/include/utils/AndroidThreads.h deleted file mode 100644 index aad1e82cb7..0000000000 --- a/third_party/android_system_core/include/utils/AndroidThreads.h +++ /dev/null @@ -1,125 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/Atomic.h b/third_party/android_system_core/include/utils/Atomic.h deleted file mode 100644 index 7eb476c94e..0000000000 --- a/third_party/android_system_core/include/utils/Atomic.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/BasicHashtable.h b/third_party/android_system_core/include/utils/BasicHashtable.h deleted file mode 100644 index c235d62526..0000000000 --- a/third_party/android_system_core/include/utils/BasicHashtable.h +++ /dev/null @@ -1,402 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/BitSet.h b/third_party/android_system_core/include/utils/BitSet.h deleted file mode 100644 index 8c612931de..0000000000 --- a/third_party/android_system_core/include/utils/BitSet.h +++ /dev/null @@ -1,294 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/BlobCache.h b/third_party/android_system_core/include/utils/BlobCache.h deleted file mode 100644 index 65dca9fb45..0000000000 --- a/third_party/android_system_core/include/utils/BlobCache.h +++ /dev/null @@ -1,249 +0,0 @@ -/* - ** 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/third_party/android_system_core/include/utils/ByteOrder.h b/third_party/android_system_core/include/utils/ByteOrder.h deleted file mode 100644 index baa3a83ddd..0000000000 --- a/third_party/android_system_core/include/utils/ByteOrder.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/CallStack.h b/third_party/android_system_core/include/utils/CallStack.h deleted file mode 100644 index 27e89f4622..0000000000 --- a/third_party/android_system_core/include/utils/CallStack.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/Compat.h b/third_party/android_system_core/include/utils/Compat.h deleted file mode 100644 index 7d96310272..0000000000 --- a/third_party/android_system_core/include/utils/Compat.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/Condition.h b/third_party/android_system_core/include/utils/Condition.h deleted file mode 100644 index 5a7251982a..0000000000 --- a/third_party/android_system_core/include/utils/Condition.h +++ /dev/null @@ -1,158 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/Debug.h b/third_party/android_system_core/include/utils/Debug.h deleted file mode 100644 index 08893bdaaf..0000000000 --- a/third_party/android_system_core/include/utils/Debug.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/Endian.h b/third_party/android_system_core/include/utils/Endian.h deleted file mode 100644 index 591cae0d34..0000000000 --- a/third_party/android_system_core/include/utils/Endian.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/Errors.h b/third_party/android_system_core/include/utils/Errors.h deleted file mode 100644 index 46173db4a3..0000000000 --- a/third_party/android_system_core/include/utils/Errors.h +++ /dev/null @@ -1,88 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/FileMap.h b/third_party/android_system_core/include/utils/FileMap.h deleted file mode 100644 index f70fc927e4..0000000000 --- a/third_party/android_system_core/include/utils/FileMap.h +++ /dev/null @@ -1,126 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/Flattenable.h b/third_party/android_system_core/include/utils/Flattenable.h deleted file mode 100644 index 882a8b2499..0000000000 --- a/third_party/android_system_core/include/utils/Flattenable.h +++ /dev/null @@ -1,198 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/Functor.h b/third_party/android_system_core/include/utils/Functor.h deleted file mode 100644 index 09ea614b61..0000000000 --- a/third_party/android_system_core/include/utils/Functor.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/JenkinsHash.h b/third_party/android_system_core/include/utils/JenkinsHash.h deleted file mode 100644 index 7da5dbd6a9..0000000000 --- a/third_party/android_system_core/include/utils/JenkinsHash.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/KeyedVector.h b/third_party/android_system_core/include/utils/KeyedVector.h deleted file mode 100644 index c4faae0b76..0000000000 --- a/third_party/android_system_core/include/utils/KeyedVector.h +++ /dev/null @@ -1,224 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/LinearTransform.h b/third_party/android_system_core/include/utils/LinearTransform.h deleted file mode 100644 index 04cb355c7f..0000000000 --- a/third_party/android_system_core/include/utils/LinearTransform.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/List.h b/third_party/android_system_core/include/utils/List.h deleted file mode 100644 index 403cd7f1e5..0000000000 --- a/third_party/android_system_core/include/utils/List.h +++ /dev/null @@ -1,332 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/Log.h b/third_party/android_system_core/include/utils/Log.h deleted file mode 100644 index 4259c86d1a..0000000000 --- a/third_party/android_system_core/include/utils/Log.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/Looper.h b/third_party/android_system_core/include/utils/Looper.h deleted file mode 100644 index da2d5f2b5b..0000000000 --- a/third_party/android_system_core/include/utils/Looper.h +++ /dev/null @@ -1,487 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/LruCache.h b/third_party/android_system_core/include/utils/LruCache.h deleted file mode 100644 index cd9d7f94a0..0000000000 --- a/third_party/android_system_core/include/utils/LruCache.h +++ /dev/null @@ -1,250 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/Mutex.h b/third_party/android_system_core/include/utils/Mutex.h deleted file mode 100644 index 757519b086..0000000000 --- a/third_party/android_system_core/include/utils/Mutex.h +++ /dev/null @@ -1,157 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/NativeHandle.h b/third_party/android_system_core/include/utils/NativeHandle.h deleted file mode 100644 index b82516879a..0000000000 --- a/third_party/android_system_core/include/utils/NativeHandle.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/Printer.h b/third_party/android_system_core/include/utils/Printer.h deleted file mode 100644 index bb6628767c..0000000000 --- a/third_party/android_system_core/include/utils/Printer.h +++ /dev/null @@ -1,119 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/ProcessCallStack.h b/third_party/android_system_core/include/utils/ProcessCallStack.h deleted file mode 100644 index 32458b8b14..0000000000 --- a/third_party/android_system_core/include/utils/ProcessCallStack.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/PropertyMap.h b/third_party/android_system_core/include/utils/PropertyMap.h deleted file mode 100644 index a9e674f9af..0000000000 --- a/third_party/android_system_core/include/utils/PropertyMap.h +++ /dev/null @@ -1,106 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/RWLock.h b/third_party/android_system_core/include/utils/RWLock.h deleted file mode 100644 index e743b1c8ce..0000000000 --- a/third_party/android_system_core/include/utils/RWLock.h +++ /dev/null @@ -1,126 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/RefBase.h b/third_party/android_system_core/include/utils/RefBase.h deleted file mode 100644 index eac6a78402..0000000000 --- a/third_party/android_system_core/include/utils/RefBase.h +++ /dev/null @@ -1,555 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/SharedBuffer.h b/third_party/android_system_core/include/utils/SharedBuffer.h deleted file mode 100644 index b6709537e6..0000000000 --- a/third_party/android_system_core/include/utils/SharedBuffer.h +++ /dev/null @@ -1,137 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/Singleton.h b/third_party/android_system_core/include/utils/Singleton.h deleted file mode 100644 index ffc03cb5d6..0000000000 --- a/third_party/android_system_core/include/utils/Singleton.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/SortedVector.h b/third_party/android_system_core/include/utils/SortedVector.h deleted file mode 100644 index 2d3e82a7c0..0000000000 --- a/third_party/android_system_core/include/utils/SortedVector.h +++ /dev/null @@ -1,282 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/StopWatch.h b/third_party/android_system_core/include/utils/StopWatch.h deleted file mode 100644 index 693dd3ccfc..0000000000 --- a/third_party/android_system_core/include/utils/StopWatch.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/String16.h b/third_party/android_system_core/include/utils/String16.h deleted file mode 100644 index d131bfc6a7..0000000000 --- a/third_party/android_system_core/include/utils/String16.h +++ /dev/null @@ -1,250 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/String8.h b/third_party/android_system_core/include/utils/String8.h deleted file mode 100644 index ecfcf10be7..0000000000 --- a/third_party/android_system_core/include/utils/String8.h +++ /dev/null @@ -1,408 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/StrongPointer.h b/third_party/android_system_core/include/utils/StrongPointer.h deleted file mode 100644 index aba9577da4..0000000000 --- a/third_party/android_system_core/include/utils/StrongPointer.h +++ /dev/null @@ -1,211 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/SystemClock.h b/third_party/android_system_core/include/utils/SystemClock.h deleted file mode 100644 index 01db340780..0000000000 --- a/third_party/android_system_core/include/utils/SystemClock.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/Thread.h b/third_party/android_system_core/include/utils/Thread.h deleted file mode 100644 index 28839fdedc..0000000000 --- a/third_party/android_system_core/include/utils/Thread.h +++ /dev/null @@ -1,116 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/ThreadDefs.h b/third_party/android_system_core/include/utils/ThreadDefs.h deleted file mode 100644 index 9711c13792..0000000000 --- a/third_party/android_system_core/include/utils/ThreadDefs.h +++ /dev/null @@ -1,70 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/Timers.h b/third_party/android_system_core/include/utils/Timers.h deleted file mode 100644 index 54ec47489f..0000000000 --- a/third_party/android_system_core/include/utils/Timers.h +++ /dev/null @@ -1,108 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/Tokenizer.h b/third_party/android_system_core/include/utils/Tokenizer.h deleted file mode 100644 index bb25f374cb..0000000000 --- a/third_party/android_system_core/include/utils/Tokenizer.h +++ /dev/null @@ -1,136 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/Trace.h b/third_party/android_system_core/include/utils/Trace.h deleted file mode 100644 index 6ee343d79a..0000000000 --- a/third_party/android_system_core/include/utils/Trace.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/TypeHelpers.h b/third_party/android_system_core/include/utils/TypeHelpers.h deleted file mode 100644 index 13c9081599..0000000000 --- a/third_party/android_system_core/include/utils/TypeHelpers.h +++ /dev/null @@ -1,302 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/Unicode.h b/third_party/android_system_core/include/utils/Unicode.h deleted file mode 100644 index 4e17cc3d9c..0000000000 --- a/third_party/android_system_core/include/utils/Unicode.h +++ /dev/null @@ -1,172 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/Vector.h b/third_party/android_system_core/include/utils/Vector.h deleted file mode 100644 index ed7b725213..0000000000 --- a/third_party/android_system_core/include/utils/Vector.h +++ /dev/null @@ -1,423 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/VectorImpl.h b/third_party/android_system_core/include/utils/VectorImpl.h deleted file mode 100644 index 21ad71ce60..0000000000 --- a/third_party/android_system_core/include/utils/VectorImpl.h +++ /dev/null @@ -1,183 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/ashmem.h b/third_party/android_system_core/include/utils/ashmem.h deleted file mode 100644 index 0854775780..0000000000 --- a/third_party/android_system_core/include/utils/ashmem.h +++ /dev/null @@ -1,41 +0,0 @@ -/* 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/third_party/android_system_core/include/utils/misc.h b/third_party/android_system_core/include/utils/misc.h deleted file mode 100644 index 6cccec387d..0000000000 --- a/third_party/android_system_core/include/utils/misc.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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/third_party/android_system_core/include/utils/threads.h b/third_party/android_system_core/include/utils/threads.h deleted file mode 100644 index 9de3382118..0000000000 --- a/third_party/android_system_core/include/utils/threads.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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/third_party/boringssl/LICENSE b/third_party/boringssl/LICENSE deleted file mode 100644 index 2f4dfcdb04..0000000000 --- a/third_party/boringssl/LICENSE +++ /dev/null @@ -1,274 +0,0 @@ -BoringSSL is a fork of OpenSSL. As such, large parts of it fall under OpenSSL -licensing. Files that are completely new have a Google copyright and an ISC -license. This license is reproduced at the bottom of this file. - -Contributors to BoringSSL are required to follow the CLA rules for Chromium: -https://cla.developers.google.com/clas - -Files in third_party/ have their own licenses, as described therein. The MIT -license, for third_party/fiat, which, unlike other third_party directories, is -compiled into non-test libraries, is included below. - -The OpenSSL toolkit stays under a dual license, i.e. both the conditions of the -OpenSSL License and the original SSLeay license apply to the toolkit. See below -for the actual license texts. Actually both licenses are BSD-style Open Source -licenses. In case of any license issues related to OpenSSL please contact -openssl-core@openssl.org. - -The following are Google-internal bug numbers where explicit permission from -some authors is recorded for use of their work. (This is purely for our own -record keeping.) - 27287199 - 27287880 - 27287883 - - OpenSSL License - --------------- - -/* ==================================================================== - * Copyright (c) 1998-2011 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * openssl-core@openssl.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.openssl.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS 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. - * ==================================================================== - * - * This product includes cryptographic software written by Eric Young - * (eay@cryptsoft.com). This product includes software written by Tim - * Hudson (tjh@cryptsoft.com). - * - */ - - Original SSLeay License - ----------------------- - -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] - */ - - -ISC license used for completely new code in BoringSSL: - -/* Copyright (c) 2015, Google Inc. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - - -The code in third_party/fiat carries the MIT license: - -Copyright (c) 2015-2016 the fiat-crypto authors (see -https://github.com/mit-plv/fiat-crypto/blob/master/AUTHORS). - -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. - - -The code in third_party/sike also carries the MIT license: - -Copyright (c) Microsoft Corporation. All rights reserved. - -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 - - -Licenses for support code -------------------------- - -Parts of the TLS test suite are under the Go license. This code is not included -in BoringSSL (i.e. libcrypto and libssl) when compiled, however, so -distributing code linked against BoringSSL does not trigger this license: - -Copyright (c) 2009 The Go Authors. 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 Google Inc. 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 AND FITNESS FOR -A PARTICULAR PURPOSE 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. - - -BoringSSL uses the Chromium test infrastructure to run a continuous build, -trybots etc. The scripts which manage this, and the script for generating build -metadata, are under the Chromium license. Distributing code linked against -BoringSSL does not trigger this license. - -Copyright 2015 The Chromium Authors. 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 Google Inc. 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 AND FITNESS FOR -A PARTICULAR PURPOSE 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. diff --git a/third_party/boringssl/LICENSE.boringssl b/third_party/boringssl/LICENSE.boringssl deleted file mode 100644 index 0b0b9b3292..0000000000 --- a/third_party/boringssl/LICENSE.boringssl +++ /dev/null @@ -1,192 +0,0 @@ -BoringSSL is a fork of OpenSSL. As such, large parts of it fall under OpenSSL -licensing. Files that are completely new have a Google copyright and an ISC -license. This license is reproduced at the bottom of this file. - -Contributors to BoringSSL are required to follow the CLA rules for Chromium: -https://cla.developers.google.com/clas - -Some files from Intel are under yet another license, which is also included -underneath. - -The OpenSSL toolkit stays under a dual license, i.e. both the conditions of the -OpenSSL License and the original SSLeay license apply to the toolkit. See below -for the actual license texts. Actually both licenses are BSD-style Open Source -licenses. In case of any license issues related to OpenSSL please contact -openssl-core@openssl.org. - -The following are Google-internal bug numbers where explicit permission from -some authors is recorded for use of their work. (This is purely for our own -record keeping.) - 27287199 - 27287880 - 27287883 - - OpenSSL License - --------------- - -/* ==================================================================== - * Copyright (c) 1998-2011 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * openssl-core@openssl.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.openssl.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS 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. - * ==================================================================== - * - * This product includes cryptographic software written by Eric Young - * (eay@cryptsoft.com). This product includes software written by Tim - * Hudson (tjh@cryptsoft.com). - * - */ - - Original SSLeay License - ----------------------- - -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] - */ - - -ISC license used for completely new code in BoringSSL: - -/* Copyright (c) 2015, Google Inc. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - - -Some files from Intel carry the following license: - -# Copyright (c) 2012, Intel Corporation -# -# 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 Intel Corporation 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 INTEL CORPORATION ""AS IS"" AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION 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. diff --git a/third_party/boringssl/build.txt b/third_party/boringssl/build.txt deleted file mode 100644 index 0c9cd0d31d..0000000000 --- a/third_party/boringssl/build.txt +++ /dev/null @@ -1,7 +0,0 @@ -# with neos tree -cd ~/android/system -mka libcrypt_static libssl_static - -cp ~/android/system/out/target/product/oneplus3/obj/STATIC_LIBRARIES/libcrypto_static_intermediates/libcrypto_static.a lib/ -cp ~/android/system/out/target/product/oneplus3/obj/STATIC_LIBRARIES/libssl_static_intermediates/libssl_static.a lib/ - diff --git a/third_party/boringssl/include/openssl/aead.h b/third_party/boringssl/include/openssl/aead.h deleted file mode 100644 index dc453e342d..0000000000 --- a/third_party/boringssl/include/openssl/aead.h +++ /dev/null @@ -1,315 +0,0 @@ -/* Copyright (c) 2014, Google Inc. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -#ifndef OPENSSL_HEADER_AEAD_H -#define OPENSSL_HEADER_AEAD_H - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* Authenticated Encryption with Additional Data. - * - * AEAD couples confidentiality and integrity in a single primtive. AEAD - * algorithms take a key and then can seal and open individual messages. Each - * message has a unique, per-message nonce and, optionally, additional data - * which is authenticated but not included in the ciphertext. - * - * The |EVP_AEAD_CTX_init| function initialises an |EVP_AEAD_CTX| structure and - * performs any precomputation needed to use |aead| with |key|. The length of - * the key, |key_len|, is given in bytes. - * - * The |tag_len| argument contains the length of the tags, in bytes, and allows - * for the processing of truncated authenticators. A zero value indicates that - * the default tag length should be used and this is defined as - * |EVP_AEAD_DEFAULT_TAG_LENGTH| in order to make the code clear. Using - * truncated tags increases an attacker's chance of creating a valid forgery. - * Be aware that the attacker's chance may increase more than exponentially as - * would naively be expected. - * - * When no longer needed, the initialised |EVP_AEAD_CTX| structure must be - * passed to |EVP_AEAD_CTX_cleanup|, which will deallocate any memory used. - * - * With an |EVP_AEAD_CTX| in hand, one can seal and open messages. These - * operations are intended to meet the standard notions of privacy and - * authenticity for authenticated encryption. For formal definitions see - * Bellare and Namprempre, "Authenticated encryption: relations among notions - * and analysis of the generic composition paradigm," Lecture Notes in Computer - * Science B<1976> (2000), 531–545, - * http://www-cse.ucsd.edu/~mihir/papers/oem.html. - * - * When sealing messages, a nonce must be given. The length of the nonce is - * fixed by the AEAD in use and is returned by |EVP_AEAD_nonce_length|. *The - * nonce must be unique for all messages with the same key*. This is critically - * important - nonce reuse may completely undermine the security of the AEAD. - * Nonces may be predictable and public, so long as they are unique. Uniqueness - * may be achieved with a simple counter or, if large enough, may be generated - * randomly. The nonce must be passed into the "open" operation by the receiver - * so must either be implicit (e.g. a counter), or must be transmitted along - * with the sealed message. - * - * The "seal" and "open" operations are atomic - an entire message must be - * encrypted or decrypted in a single call. Large messages may have to be split - * up in order to accomodate this. When doing so, be mindful of the need not to - * repeat nonces and the possibility that an attacker could duplicate, reorder - * or drop message chunks. For example, using a single key for a given (large) - * message and sealing chunks with nonces counting from zero would be secure as - * long as the number of chunks was securely transmitted. (Otherwise an - * attacker could truncate the message by dropping chunks from the end.) - * - * The number of chunks could be transmitted by prefixing it to the plaintext, - * for example. This also assumes that no other message would ever use the same - * key otherwise the rule that nonces must be unique for a given key would be - * violated. - * - * The "seal" and "open" operations also permit additional data to be - * authenticated via the |ad| parameter. This data is not included in the - * ciphertext and must be identical for both the "seal" and "open" call. This - * permits implicit context to be authenticated but may be empty if not needed. - * - * The "seal" and "open" operations may work in-place if the |out| and |in| - * arguments are equal. They may also be used to shift the data left inside the - * same buffer if |out| is less than |in|. However, |out| may not point inside - * the input data otherwise the input may be overwritten before it has been - * read. This situation will cause an error. - * - * The "seal" and "open" operations return one on success and zero on error. */ - - -/* AEAD algorithms. */ - -/* EVP_aead_aes_128_gcm is AES-128 in Galois Counter Mode. */ -OPENSSL_EXPORT const EVP_AEAD *EVP_aead_aes_128_gcm(void); - -/* EVP_aead_aes_256_gcm is AES-256 in Galois Counter Mode. */ -OPENSSL_EXPORT const EVP_AEAD *EVP_aead_aes_256_gcm(void); - -/* EVP_aead_chacha20_poly1305 is an AEAD built from ChaCha20 and Poly1305. */ -OPENSSL_EXPORT const EVP_AEAD *EVP_aead_chacha20_poly1305(void); - -/* EVP_aead_aes_128_key_wrap is AES-128 Key Wrap mode. This should never be - * used except to interoperate with existing systems that use this mode. - * - * If the nonce is empty then the default nonce will be used, otherwise it must - * be eight bytes long. The input must be a multiple of eight bytes long. No - * additional data can be given to this mode. */ -OPENSSL_EXPORT const EVP_AEAD *EVP_aead_aes_128_key_wrap(void); - -/* EVP_aead_aes_256_key_wrap is AES-256 in Key Wrap mode. This should never be - * used except to interoperate with existing systems that use this mode. - * - * See |EVP_aead_aes_128_key_wrap| for details. */ -OPENSSL_EXPORT const EVP_AEAD *EVP_aead_aes_256_key_wrap(void); - -/* EVP_aead_aes_128_ctr_hmac_sha256 is AES-128 in CTR mode with HMAC-SHA256 for - * authentication. The nonce is 12 bytes; the bottom 32-bits are used as the - * block counter, thus the maximum plaintext size is 64GB. */ -OPENSSL_EXPORT const EVP_AEAD *EVP_aead_aes_128_ctr_hmac_sha256(void); - -/* EVP_aead_aes_128_ctr_hmac_sha256 is AES-256 in CTR mode with HMAC-SHA256 for - * authentication. See |EVP_aead_aes_128_ctr_hmac_sha256| for details. */ -OPENSSL_EXPORT const EVP_AEAD *EVP_aead_aes_256_ctr_hmac_sha256(void); - -/* EVP_has_aes_hardware returns one if we enable hardware support for fast and - * constant-time AES-GCM. */ -OPENSSL_EXPORT int EVP_has_aes_hardware(void); - - -/* TLS-specific AEAD algorithms. - * - * These AEAD primitives do not meet the definition of generic AEADs. They are - * all specific to TLS and should not be used outside of that context. They must - * be initialized with |EVP_AEAD_CTX_init_with_direction|, are stateful, and may - * not be used concurrently. Any nonces are used as IVs, so they must be - * unpredictable. They only accept an |ad| parameter of length 11 (the standard - * TLS one with length omitted). */ - -OPENSSL_EXPORT const EVP_AEAD *EVP_aead_rc4_md5_tls(void); -OPENSSL_EXPORT const EVP_AEAD *EVP_aead_rc4_sha1_tls(void); - -OPENSSL_EXPORT const EVP_AEAD *EVP_aead_aes_128_cbc_sha1_tls(void); -OPENSSL_EXPORT const EVP_AEAD *EVP_aead_aes_128_cbc_sha1_tls_implicit_iv(void); -OPENSSL_EXPORT const EVP_AEAD *EVP_aead_aes_128_cbc_sha256_tls(void); - -OPENSSL_EXPORT const EVP_AEAD *EVP_aead_aes_256_cbc_sha1_tls(void); -OPENSSL_EXPORT const EVP_AEAD *EVP_aead_aes_256_cbc_sha1_tls_implicit_iv(void); -OPENSSL_EXPORT const EVP_AEAD *EVP_aead_aes_256_cbc_sha256_tls(void); -OPENSSL_EXPORT const EVP_AEAD *EVP_aead_aes_256_cbc_sha384_tls(void); - -OPENSSL_EXPORT const EVP_AEAD *EVP_aead_des_ede3_cbc_sha1_tls(void); -OPENSSL_EXPORT const EVP_AEAD *EVP_aead_des_ede3_cbc_sha1_tls_implicit_iv(void); - - -/* SSLv3-specific AEAD algorithms. - * - * These AEAD primitives do not meet the definition of generic AEADs. They are - * all specific to SSLv3 and should not be used outside of that context. They - * must be initialized with |EVP_AEAD_CTX_init_with_direction|, are stateful, - * and may not be used concurrently. They only accept an |ad| parameter of - * length 9 (the standard TLS one with length and version omitted). */ - -OPENSSL_EXPORT const EVP_AEAD *EVP_aead_rc4_md5_ssl3(void); -OPENSSL_EXPORT const EVP_AEAD *EVP_aead_rc4_sha1_ssl3(void); -OPENSSL_EXPORT const EVP_AEAD *EVP_aead_aes_128_cbc_sha1_ssl3(void); -OPENSSL_EXPORT const EVP_AEAD *EVP_aead_aes_256_cbc_sha1_ssl3(void); -OPENSSL_EXPORT const EVP_AEAD *EVP_aead_des_ede3_cbc_sha1_ssl3(void); - - -/* Utility functions. */ - -/* EVP_AEAD_key_length returns the length, in bytes, of the keys used by - * |aead|. */ -OPENSSL_EXPORT size_t EVP_AEAD_key_length(const EVP_AEAD *aead); - -/* EVP_AEAD_nonce_length returns the length, in bytes, of the per-message nonce - * for |aead|. */ -OPENSSL_EXPORT size_t EVP_AEAD_nonce_length(const EVP_AEAD *aead); - -/* EVP_AEAD_max_overhead returns the maximum number of additional bytes added - * by the act of sealing data with |aead|. */ -OPENSSL_EXPORT size_t EVP_AEAD_max_overhead(const EVP_AEAD *aead); - -/* EVP_AEAD_max_tag_len returns the maximum tag length when using |aead|. This - * is the largest value that can be passed as |tag_len| to - * |EVP_AEAD_CTX_init|. */ -OPENSSL_EXPORT size_t EVP_AEAD_max_tag_len(const EVP_AEAD *aead); - - -/* AEAD operations. */ - -/* An EVP_AEAD_CTX represents an AEAD algorithm configured with a specific key - * and message-independent IV. */ -typedef struct evp_aead_ctx_st { - const EVP_AEAD *aead; - /* aead_state is an opaque pointer to whatever state the AEAD needs to - * maintain. */ - void *aead_state; -} EVP_AEAD_CTX; - -/* EVP_AEAD_MAX_KEY_LENGTH contains the maximum key length used by - * any AEAD defined in this header. */ -#define EVP_AEAD_MAX_KEY_LENGTH 80 - -/* EVP_AEAD_MAX_NONCE_LENGTH contains the maximum nonce length used by - * any AEAD defined in this header. */ -#define EVP_AEAD_MAX_NONCE_LENGTH 16 - -/* EVP_AEAD_MAX_OVERHEAD contains the maximum overhead used by any AEAD - * defined in this header. */ -#define EVP_AEAD_MAX_OVERHEAD 64 - -/* EVP_AEAD_DEFAULT_TAG_LENGTH is a magic value that can be passed to - * EVP_AEAD_CTX_init to indicate that the default tag length for an AEAD should - * be used. */ -#define EVP_AEAD_DEFAULT_TAG_LENGTH 0 - -/* evp_aead_direction_t denotes the direction of an AEAD operation. */ -enum evp_aead_direction_t { - evp_aead_open, - evp_aead_seal, -}; - -/* EVP_AEAD_CTX_init initializes |ctx| for the given AEAD algorithm from |impl|. - * The |impl| argument may be NULL to choose the default implementation. - * Authentication tags may be truncated by passing a size as |tag_len|. A - * |tag_len| of zero indicates the default tag length and this is defined as - * EVP_AEAD_DEFAULT_TAG_LENGTH for readability. - * - * Returns 1 on success. Otherwise returns 0 and pushes to the error stack. In - * the error case, you do not need to call |EVP_AEAD_CTX_cleanup|, but it's - * harmless to do so. */ -OPENSSL_EXPORT int EVP_AEAD_CTX_init(EVP_AEAD_CTX *ctx, const EVP_AEAD *aead, - const uint8_t *key, size_t key_len, - size_t tag_len, ENGINE *impl); - -/* EVP_AEAD_CTX_init_with_direction calls |EVP_AEAD_CTX_init| for normal - * AEADs. For TLS-specific and SSL3-specific AEADs, it initializes |ctx| for a - * given direction. */ -OPENSSL_EXPORT int EVP_AEAD_CTX_init_with_direction( - EVP_AEAD_CTX *ctx, const EVP_AEAD *aead, const uint8_t *key, size_t key_len, - size_t tag_len, enum evp_aead_direction_t dir); - -/* EVP_AEAD_CTX_cleanup frees any data allocated by |ctx|. It is a no-op to - * call |EVP_AEAD_CTX_cleanup| on a |EVP_AEAD_CTX| that has been |memset| to - * all zeros. */ -OPENSSL_EXPORT void EVP_AEAD_CTX_cleanup(EVP_AEAD_CTX *ctx); - -/* EVP_AEAD_CTX_seal encrypts and authenticates |in_len| bytes from |in| and - * authenticates |ad_len| bytes from |ad| and writes the result to |out|. It - * returns one on success and zero otherwise. - * - * This function may be called (with the same |EVP_AEAD_CTX|) concurrently with - * itself or |EVP_AEAD_CTX_open|. - * - * At most |max_out_len| bytes are written to |out| and, in order to ensure - * success, |max_out_len| should be |in_len| plus the result of - * |EVP_AEAD_max_overhead|. On successful return, |*out_len| is set to the - * actual number of bytes written. - * - * The length of |nonce|, |nonce_len|, must be equal to the result of - * |EVP_AEAD_nonce_length| for this AEAD. - * - * |EVP_AEAD_CTX_seal| never results in a partial output. If |max_out_len| is - * insufficient, zero will be returned. (In this case, |*out_len| is set to - * zero.) - * - * If |in| and |out| alias then |out| must be <= |in|. */ -OPENSSL_EXPORT int EVP_AEAD_CTX_seal(const EVP_AEAD_CTX *ctx, uint8_t *out, - size_t *out_len, size_t max_out_len, - const uint8_t *nonce, size_t nonce_len, - const uint8_t *in, size_t in_len, - const uint8_t *ad, size_t ad_len); - -/* EVP_AEAD_CTX_open authenticates |in_len| bytes from |in| and |ad_len| bytes - * from |ad| and decrypts at most |in_len| bytes into |out|. It returns one on - * success and zero otherwise. - * - * This function may be called (with the same |EVP_AEAD_CTX|) concurrently with - * itself or |EVP_AEAD_CTX_seal|. - * - * At most |in_len| bytes are written to |out|. In order to ensure success, - * |max_out_len| should be at least |in_len|. On successful return, |*out_len| - * is set to the the actual number of bytes written. - * - * The length of |nonce|, |nonce_len|, must be equal to the result of - * |EVP_AEAD_nonce_length| for this AEAD. - * - * |EVP_AEAD_CTX_open| never results in a partial output. If |max_out_len| is - * insufficient, zero will be returned. (In this case, |*out_len| is set to - * zero.) - * - * If |in| and |out| alias then |out| must be <= |in|. */ -OPENSSL_EXPORT int EVP_AEAD_CTX_open(const EVP_AEAD_CTX *ctx, uint8_t *out, - size_t *out_len, size_t max_out_len, - const uint8_t *nonce, size_t nonce_len, - const uint8_t *in, size_t in_len, - const uint8_t *ad, size_t ad_len); - - -/* Obscure functions. */ - -/* EVP_AEAD_CTX_get_rc4_state sets |*out_key| to point to an RC4 key structure. - * It returns one on success or zero if |ctx| doesn't have an RC4 key. */ -OPENSSL_EXPORT int EVP_AEAD_CTX_get_rc4_state(const EVP_AEAD_CTX *ctx, - const RC4_KEY **out_key); - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_AEAD_H */ diff --git a/third_party/boringssl/include/openssl/aes.h b/third_party/boringssl/include/openssl/aes.h deleted file mode 100644 index 84cde416e6..0000000000 --- a/third_party/boringssl/include/openssl/aes.h +++ /dev/null @@ -1,158 +0,0 @@ -/* ==================================================================== - * Copyright (c) 2002-2006 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * openssl-core@openssl.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.openssl.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS 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 OPENSSL_HEADER_AES_H -#define OPENSSL_HEADER_AES_H - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* Raw AES functions. */ - - -#define AES_ENCRYPT 1 -#define AES_DECRYPT 0 - -/* AES_MAXNR is the maximum number of AES rounds. */ -#define AES_MAXNR 14 - -#define AES_BLOCK_SIZE 16 - -/* aes_key_st should be an opaque type, but EVP requires that the size be - * known. */ -struct aes_key_st { - uint32_t rd_key[4 * (AES_MAXNR + 1)]; - unsigned rounds; -}; -typedef struct aes_key_st AES_KEY; - -/* AES_set_encrypt_key configures |aeskey| to encrypt with the |bits|-bit key, - * |key|. - * - * WARNING: unlike other OpenSSL functions, this returns zero on success and a - * negative number on error. */ -OPENSSL_EXPORT int AES_set_encrypt_key(const uint8_t *key, unsigned bits, - AES_KEY *aeskey); - -/* AES_set_decrypt_key configures |aeskey| to decrypt with the |bits|-bit key, - * |key|. - * - * WARNING: unlike other OpenSSL functions, this returns zero on success and a - * negative number on error. */ -OPENSSL_EXPORT int AES_set_decrypt_key(const uint8_t *key, unsigned bits, - AES_KEY *aeskey); - -/* AES_encrypt encrypts a single block from |in| to |out| with |key|. The |in| - * and |out| pointers may overlap. */ -OPENSSL_EXPORT void AES_encrypt(const uint8_t *in, uint8_t *out, - const AES_KEY *key); - -/* AES_decrypt decrypts a single block from |in| to |out| with |key|. The |in| - * and |out| pointers may overlap. */ -OPENSSL_EXPORT void AES_decrypt(const uint8_t *in, uint8_t *out, - const AES_KEY *key); - - -/* Block cipher modes. */ - -/* AES_ctr128_encrypt encrypts (or decrypts, it's the same in CTR mode) |len| - * bytes from |in| to |out|. The |num| parameter must be set to zero on the - * first call and |ivec| will be incremented. */ -OPENSSL_EXPORT void AES_ctr128_encrypt(const uint8_t *in, uint8_t *out, - size_t len, const AES_KEY *key, - uint8_t ivec[AES_BLOCK_SIZE], - uint8_t ecount_buf[AES_BLOCK_SIZE], - unsigned int *num); - -/* AES_ecb_encrypt encrypts (or decrypts, if |enc| == |AES_DECRYPT|) a single, - * 16 byte block from |in| to |out|. */ -OPENSSL_EXPORT void AES_ecb_encrypt(const uint8_t *in, uint8_t *out, - const AES_KEY *key, const int enc); - -/* AES_cbc_encrypt encrypts (or decrypts, if |enc| == |AES_DECRYPT|) |len| - * bytes from |in| to |out|. The length must be a multiple of the block size. */ -OPENSSL_EXPORT void AES_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t len, - const AES_KEY *key, uint8_t *ivec, - const int enc); - -/* AES_ofb128_encrypt encrypts (or decrypts, it's the same in CTR mode) |len| - * bytes from |in| to |out|. The |num| parameter must be set to zero on the - * first call. */ -OPENSSL_EXPORT void AES_ofb128_encrypt(const uint8_t *in, uint8_t *out, - size_t len, const AES_KEY *key, - uint8_t *ivec, int *num); - -/* AES_cfb128_encrypt encrypts (or decrypts, if |enc| == |AES_DECRYPT|) |len| - * bytes from |in| to |out|. The |num| parameter must be set to zero on the - * first call. */ -OPENSSL_EXPORT void AES_cfb128_encrypt(const uint8_t *in, uint8_t *out, - size_t len, const AES_KEY *key, - uint8_t *ivec, int *num, int enc); - - -/* Android compatibility section. - * - * These functions are declared, temporarily, for Android because - * wpa_supplicant will take a little time to sync with upstream. Outside of - * Android they'll have no definition. */ - -OPENSSL_EXPORT int AES_wrap_key(AES_KEY *key, const uint8_t *iv, uint8_t *out, - const uint8_t *in, unsigned in_len); -OPENSSL_EXPORT int AES_unwrap_key(AES_KEY *key, const uint8_t *iv, uint8_t *out, - const uint8_t *in, unsigned in_len); - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_AES_H */ diff --git a/third_party/boringssl/include/openssl/asn1.h b/third_party/boringssl/include/openssl/asn1.h deleted file mode 100644 index 4baf81c6bd..0000000000 --- a/third_party/boringssl/include/openssl/asn1.h +++ /dev/null @@ -1,1234 +0,0 @@ -/* crypto/asn1/asn1.h */ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] - */ - -#ifndef HEADER_ASN1_H -#define HEADER_ASN1_H - -#include - -#include - -#include -#include - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define V_ASN1_UNIVERSAL 0x00 -#define V_ASN1_APPLICATION 0x40 -#define V_ASN1_CONTEXT_SPECIFIC 0x80 -#define V_ASN1_PRIVATE 0xc0 - -#define V_ASN1_CONSTRUCTED 0x20 -#define V_ASN1_PRIMITIVE_TAG 0x1f -#define V_ASN1_PRIMATIVE_TAG 0x1f - -#define V_ASN1_APP_CHOOSE -2 /* let the recipient choose */ -#define V_ASN1_OTHER -3 /* used in ASN1_TYPE */ -#define V_ASN1_ANY -4 /* used in ASN1 template code */ - -#define V_ASN1_NEG 0x100 /* negative flag */ - -#define V_ASN1_UNDEF -1 -#define V_ASN1_EOC 0 -#define V_ASN1_BOOLEAN 1 /**/ -#define V_ASN1_INTEGER 2 -#define V_ASN1_NEG_INTEGER (2 | V_ASN1_NEG) -#define V_ASN1_BIT_STRING 3 -#define V_ASN1_OCTET_STRING 4 -#define V_ASN1_NULL 5 -#define V_ASN1_OBJECT 6 -#define V_ASN1_OBJECT_DESCRIPTOR 7 -#define V_ASN1_EXTERNAL 8 -#define V_ASN1_REAL 9 -#define V_ASN1_ENUMERATED 10 -#define V_ASN1_NEG_ENUMERATED (10 | V_ASN1_NEG) -#define V_ASN1_UTF8STRING 12 -#define V_ASN1_SEQUENCE 16 -#define V_ASN1_SET 17 -#define V_ASN1_NUMERICSTRING 18 /**/ -#define V_ASN1_PRINTABLESTRING 19 -#define V_ASN1_T61STRING 20 -#define V_ASN1_TELETEXSTRING 20 /* alias */ -#define V_ASN1_VIDEOTEXSTRING 21 /**/ -#define V_ASN1_IA5STRING 22 -#define V_ASN1_UTCTIME 23 -#define V_ASN1_GENERALIZEDTIME 24 /**/ -#define V_ASN1_GRAPHICSTRING 25 /**/ -#define V_ASN1_ISO64STRING 26 /**/ -#define V_ASN1_VISIBLESTRING 26 /* alias */ -#define V_ASN1_GENERALSTRING 27 /**/ -#define V_ASN1_UNIVERSALSTRING 28 /**/ -#define V_ASN1_BMPSTRING 30 - -/* For use with d2i_ASN1_type_bytes() */ -#define B_ASN1_NUMERICSTRING 0x0001 -#define B_ASN1_PRINTABLESTRING 0x0002 -#define B_ASN1_T61STRING 0x0004 -#define B_ASN1_TELETEXSTRING 0x0004 -#define B_ASN1_VIDEOTEXSTRING 0x0008 -#define B_ASN1_IA5STRING 0x0010 -#define B_ASN1_GRAPHICSTRING 0x0020 -#define B_ASN1_ISO64STRING 0x0040 -#define B_ASN1_VISIBLESTRING 0x0040 -#define B_ASN1_GENERALSTRING 0x0080 -#define B_ASN1_UNIVERSALSTRING 0x0100 -#define B_ASN1_OCTET_STRING 0x0200 -#define B_ASN1_BIT_STRING 0x0400 -#define B_ASN1_BMPSTRING 0x0800 -#define B_ASN1_UNKNOWN 0x1000 -#define B_ASN1_UTF8STRING 0x2000 -#define B_ASN1_UTCTIME 0x4000 -#define B_ASN1_GENERALIZEDTIME 0x8000 -#define B_ASN1_SEQUENCE 0x10000 - -/* For use with ASN1_mbstring_copy() */ -#define MBSTRING_FLAG 0x1000 -#define MBSTRING_UTF8 (MBSTRING_FLAG) -#define MBSTRING_ASC (MBSTRING_FLAG|1) -#define MBSTRING_BMP (MBSTRING_FLAG|2) -#define MBSTRING_UNIV (MBSTRING_FLAG|4) - -#define SMIME_OLDMIME 0x400 -#define SMIME_CRLFEOL 0x800 -#define SMIME_STREAM 0x1000 - -#define DECLARE_ASN1_SET_OF(type) /* filled in by mkstack.pl */ -#define IMPLEMENT_ASN1_SET_OF(type) /* nothing, no longer needed */ - -/* We MUST make sure that, except for constness, asn1_ctx_st and - asn1_const_ctx are exactly the same. Fortunately, as soon as - the old ASN1 parsing macros are gone, we can throw this away - as well... */ -typedef struct asn1_ctx_st - { - unsigned char *p;/* work char pointer */ - int eos; /* end of sequence read for indefinite encoding */ - int error; /* error code to use when returning an error */ - int inf; /* constructed if 0x20, indefinite is 0x21 */ - int tag; /* tag from last 'get object' */ - int xclass; /* class from last 'get object' */ - long slen; /* length of last 'get object' */ - unsigned char *max; /* largest value of p allowed */ - unsigned char *q;/* temporary variable */ - unsigned char **pp;/* variable */ - int line; /* used in error processing */ - } ASN1_CTX; - -typedef struct asn1_const_ctx_st - { - const unsigned char *p;/* work char pointer */ - int eos; /* end of sequence read for indefinite encoding */ - int error; /* error code to use when returning an error */ - int inf; /* constructed if 0x20, indefinite is 0x21 */ - int tag; /* tag from last 'get object' */ - int xclass; /* class from last 'get object' */ - long slen; /* length of last 'get object' */ - const unsigned char *max; /* largest value of p allowed */ - const unsigned char *q;/* temporary variable */ - const unsigned char **pp;/* variable */ - int line; /* used in error processing */ - } ASN1_const_CTX; - -/* These are used internally in the ASN1_OBJECT to keep track of - * whether the names and data need to be free()ed */ -#define ASN1_OBJECT_FLAG_DYNAMIC 0x01 /* internal use */ -#define ASN1_OBJECT_FLAG_CRITICAL 0x02 /* critical x509v3 object id */ -#define ASN1_OBJECT_FLAG_DYNAMIC_STRINGS 0x04 /* internal use */ -#define ASN1_OBJECT_FLAG_DYNAMIC_DATA 0x08 /* internal use */ -struct asn1_object_st - { - const char *sn,*ln; - int nid; - int length; - const unsigned char *data; /* data remains const after init */ - int flags; /* Should we free this one */ - }; - -#define ASN1_STRING_FLAG_BITS_LEFT 0x08 /* Set if 0x07 has bits left value */ -/* This indicates that the ASN1_STRING is not a real value but just a place - * holder for the location where indefinite length constructed data should - * be inserted in the memory buffer - */ -#define ASN1_STRING_FLAG_NDEF 0x010 - -/* This flag is used by the CMS code to indicate that a string is not - * complete and is a place holder for content when it had all been - * accessed. The flag will be reset when content has been written to it. - */ - -#define ASN1_STRING_FLAG_CONT 0x020 -/* This flag is used by ASN1 code to indicate an ASN1_STRING is an MSTRING - * type. - */ -#define ASN1_STRING_FLAG_MSTRING 0x040 -/* This is the base type that holds just about everything :-) */ -struct asn1_string_st - { - int length; - int type; - unsigned char *data; - /* The value of the following field depends on the type being - * held. It is mostly being used for BIT_STRING so if the - * input data has a non-zero 'unused bits' value, it will be - * handled correctly */ - long flags; - }; - -/* ASN1_ENCODING structure: this is used to save the received - * encoding of an ASN1 type. This is useful to get round - * problems with invalid encodings which can break signatures. - */ - -typedef struct ASN1_ENCODING_st - { - unsigned char *enc; /* DER encoding */ - long len; /* Length of encoding */ - int modified; /* set to 1 if 'enc' is invalid */ - } ASN1_ENCODING; - -/* Used with ASN1 LONG type: if a long is set to this it is omitted */ -#define ASN1_LONG_UNDEF 0x7fffffffL - -#define STABLE_FLAGS_MALLOC 0x01 -#define STABLE_NO_MASK 0x02 -#define DIRSTRING_TYPE \ - (B_ASN1_PRINTABLESTRING|B_ASN1_T61STRING|B_ASN1_BMPSTRING|B_ASN1_UTF8STRING) -#define PKCS9STRING_TYPE (DIRSTRING_TYPE|B_ASN1_IA5STRING) - -typedef struct asn1_string_table_st { - int nid; - long minsize; - long maxsize; - unsigned long mask; - unsigned long flags; -} ASN1_STRING_TABLE; - -/* size limits: this stuff is taken straight from RFC2459 */ - -#define ub_name 32768 -#define ub_common_name 64 -#define ub_locality_name 128 -#define ub_state_name 128 -#define ub_organization_name 64 -#define ub_organization_unit_name 64 -#define ub_title 64 -#define ub_email_address 128 - -/* Declarations for template structures: for full definitions - * see asn1t.h - */ -typedef struct ASN1_TEMPLATE_st ASN1_TEMPLATE; -typedef struct ASN1_TLC_st ASN1_TLC; -/* This is just an opaque pointer */ -typedef struct ASN1_VALUE_st ASN1_VALUE; - -/* Declare ASN1 functions: the implement macro in in asn1t.h */ - -#define DECLARE_ASN1_FUNCTIONS(type) DECLARE_ASN1_FUNCTIONS_name(type, type) - -#define DECLARE_ASN1_ALLOC_FUNCTIONS(type) \ - DECLARE_ASN1_ALLOC_FUNCTIONS_name(type, type) - -#define DECLARE_ASN1_FUNCTIONS_name(type, name) \ - DECLARE_ASN1_ALLOC_FUNCTIONS_name(type, name) \ - DECLARE_ASN1_ENCODE_FUNCTIONS(type, name, name) - -#define DECLARE_ASN1_FUNCTIONS_fname(type, itname, name) \ - DECLARE_ASN1_ALLOC_FUNCTIONS_name(type, name) \ - DECLARE_ASN1_ENCODE_FUNCTIONS(type, itname, name) - -#define DECLARE_ASN1_ENCODE_FUNCTIONS(type, itname, name) \ - OPENSSL_EXPORT type *d2i_##name(type **a, const unsigned char **in, long len); \ - OPENSSL_EXPORT int i2d_##name(type *a, unsigned char **out); \ - DECLARE_ASN1_ITEM(itname) - -#define DECLARE_ASN1_ENCODE_FUNCTIONS_const(type, name) \ - OPENSSL_EXPORT type *d2i_##name(type **a, const unsigned char **in, long len); \ - OPENSSL_EXPORT int i2d_##name(const type *a, unsigned char **out); \ - DECLARE_ASN1_ITEM(name) - -#define DECLARE_ASN1_NDEF_FUNCTION(name) \ - OPENSSL_EXPORT int i2d_##name##_NDEF(name *a, unsigned char **out); - -#define DECLARE_ASN1_FUNCTIONS_const(name) \ - DECLARE_ASN1_ALLOC_FUNCTIONS(name) \ - DECLARE_ASN1_ENCODE_FUNCTIONS_const(name, name) - -#define DECLARE_ASN1_ALLOC_FUNCTIONS_name(type, name) \ - OPENSSL_EXPORT type *name##_new(void); \ - OPENSSL_EXPORT void name##_free(type *a); - -#define DECLARE_ASN1_PRINT_FUNCTION(stname) \ - DECLARE_ASN1_PRINT_FUNCTION_fname(stname, stname) - -#define DECLARE_ASN1_PRINT_FUNCTION_fname(stname, fname) \ - OPENSSL_EXPORT int fname##_print_ctx(BIO *out, stname *x, int indent, \ - const ASN1_PCTX *pctx); - -#define D2I_OF(type) type *(*)(type **,const unsigned char **,long) -#define I2D_OF(type) int (*)(type *,unsigned char **) -#define I2D_OF_const(type) int (*)(const type *,unsigned char **) - -#define CHECKED_D2I_OF(type, d2i) \ - ((d2i_of_void*) (1 ? d2i : ((D2I_OF(type))0))) -#define CHECKED_I2D_OF(type, i2d) \ - ((i2d_of_void*) (1 ? i2d : ((I2D_OF(type))0))) -#define CHECKED_NEW_OF(type, xnew) \ - ((void *(*)(void)) (1 ? xnew : ((type *(*)(void))0))) -#define CHECKED_PPTR_OF(type, p) \ - ((void**) (1 ? p : (type**)0)) - -#define TYPEDEF_D2I_OF(type) typedef type *d2i_of_##type(type **,const unsigned char **,long) -#define TYPEDEF_I2D_OF(type) typedef int i2d_of_##type(const type *,unsigned char **) -#define TYPEDEF_D2I2D_OF(type) TYPEDEF_D2I_OF(type); TYPEDEF_I2D_OF(type) - -TYPEDEF_D2I2D_OF(void); - -/* The following macros and typedefs allow an ASN1_ITEM - * to be embedded in a structure and referenced. Since - * the ASN1_ITEM pointers need to be globally accessible - * (possibly from shared libraries) they may exist in - * different forms. On platforms that support it the - * ASN1_ITEM structure itself will be globally exported. - * Other platforms will export a function that returns - * an ASN1_ITEM pointer. - * - * To handle both cases transparently the macros below - * should be used instead of hard coding an ASN1_ITEM - * pointer in a structure. - * - * The structure will look like this: - * - * typedef struct SOMETHING_st { - * ... - * ASN1_ITEM_EXP *iptr; - * ... - * } SOMETHING; - * - * It would be initialised as e.g.: - * - * SOMETHING somevar = {...,ASN1_ITEM_ref(X509),...}; - * - * and the actual pointer extracted with: - * - * const ASN1_ITEM *it = ASN1_ITEM_ptr(somevar.iptr); - * - * Finally an ASN1_ITEM pointer can be extracted from an - * appropriate reference with: ASN1_ITEM_rptr(X509). This - * would be used when a function takes an ASN1_ITEM * argument. - * - */ - -/* ASN1_ITEM pointer exported type */ -typedef const ASN1_ITEM ASN1_ITEM_EXP; - -/* Macro to obtain ASN1_ITEM pointer from exported type */ -#define ASN1_ITEM_ptr(iptr) (iptr) - -/* Macro to include ASN1_ITEM pointer from base type */ -#define ASN1_ITEM_ref(iptr) (&(iptr##_it)) - -#define ASN1_ITEM_rptr(ref) (&(ref##_it)) - -#define DECLARE_ASN1_ITEM(name) \ - extern OPENSSL_EXPORT const ASN1_ITEM name##_it; - -/* Parameters used by ASN1_STRING_print_ex() */ - -/* These determine which characters to escape: - * RFC2253 special characters, control characters and - * MSB set characters - */ - -#define ASN1_STRFLGS_ESC_2253 1 -#define ASN1_STRFLGS_ESC_CTRL 2 -#define ASN1_STRFLGS_ESC_MSB 4 - - -/* This flag determines how we do escaping: normally - * RC2253 backslash only, set this to use backslash and - * quote. - */ - -#define ASN1_STRFLGS_ESC_QUOTE 8 - - -/* These three flags are internal use only. */ - -/* Character is a valid PrintableString character */ -#define CHARTYPE_PRINTABLESTRING 0x10 -/* Character needs escaping if it is the first character */ -#define CHARTYPE_FIRST_ESC_2253 0x20 -/* Character needs escaping if it is the last character */ -#define CHARTYPE_LAST_ESC_2253 0x40 - -/* NB the internal flags are safely reused below by flags - * handled at the top level. - */ - -/* If this is set we convert all character strings - * to UTF8 first - */ - -#define ASN1_STRFLGS_UTF8_CONVERT 0x10 - -/* If this is set we don't attempt to interpret content: - * just assume all strings are 1 byte per character. This - * will produce some pretty odd looking output! - */ - -#define ASN1_STRFLGS_IGNORE_TYPE 0x20 - -/* If this is set we include the string type in the output */ -#define ASN1_STRFLGS_SHOW_TYPE 0x40 - -/* This determines which strings to display and which to - * 'dump' (hex dump of content octets or DER encoding). We can - * only dump non character strings or everything. If we - * don't dump 'unknown' they are interpreted as character - * strings with 1 octet per character and are subject to - * the usual escaping options. - */ - -#define ASN1_STRFLGS_DUMP_ALL 0x80 -#define ASN1_STRFLGS_DUMP_UNKNOWN 0x100 - -/* These determine what 'dumping' does, we can dump the - * content octets or the DER encoding: both use the - * RFC2253 #XXXXX notation. - */ - -#define ASN1_STRFLGS_DUMP_DER 0x200 - -/* All the string flags consistent with RFC2253, - * escaping control characters isn't essential in - * RFC2253 but it is advisable anyway. - */ - -#define ASN1_STRFLGS_RFC2253 (ASN1_STRFLGS_ESC_2253 | \ - ASN1_STRFLGS_ESC_CTRL | \ - ASN1_STRFLGS_ESC_MSB | \ - ASN1_STRFLGS_UTF8_CONVERT | \ - ASN1_STRFLGS_DUMP_UNKNOWN | \ - ASN1_STRFLGS_DUMP_DER) - -DECLARE_ASN1_SET_OF(ASN1_INTEGER) - -typedef struct asn1_type_st - { - int type; - union { - char *ptr; - ASN1_BOOLEAN boolean; - ASN1_STRING * asn1_string; - ASN1_OBJECT * object; - ASN1_INTEGER * integer; - ASN1_ENUMERATED * enumerated; - ASN1_BIT_STRING * bit_string; - ASN1_OCTET_STRING * octet_string; - ASN1_PRINTABLESTRING * printablestring; - ASN1_T61STRING * t61string; - ASN1_IA5STRING * ia5string; - ASN1_GENERALSTRING * generalstring; - ASN1_BMPSTRING * bmpstring; - ASN1_UNIVERSALSTRING * universalstring; - ASN1_UTCTIME * utctime; - ASN1_GENERALIZEDTIME * generalizedtime; - ASN1_VISIBLESTRING * visiblestring; - ASN1_UTF8STRING * utf8string; - /* set and sequence are left complete and still - * contain the set or sequence bytes */ - ASN1_STRING * set; - ASN1_STRING * sequence; - ASN1_VALUE * asn1_value; - } value; - } ASN1_TYPE; - -DECLARE_ASN1_SET_OF(ASN1_TYPE) - -typedef STACK_OF(ASN1_TYPE) ASN1_SEQUENCE_ANY; - -DECLARE_ASN1_ENCODE_FUNCTIONS_const(ASN1_SEQUENCE_ANY, ASN1_SEQUENCE_ANY) -DECLARE_ASN1_ENCODE_FUNCTIONS_const(ASN1_SEQUENCE_ANY, ASN1_SET_ANY) - -struct X509_algor_st - { - ASN1_OBJECT *algorithm; - ASN1_TYPE *parameter; - } /* X509_ALGOR */; -DEFINE_STACK_OF(X509_ALGOR); - -DECLARE_ASN1_FUNCTIONS(X509_ALGOR) - -typedef struct NETSCAPE_X509_st - { - ASN1_OCTET_STRING *header; - X509 *cert; - } NETSCAPE_X509; - -/* This is used to contain a list of bit names */ -typedef struct BIT_STRING_BITNAME_st { - int bitnum; - const char *lname; - const char *sname; -} BIT_STRING_BITNAME; - - -#define M_ASN1_STRING_length(x) ((x)->length) -#define M_ASN1_STRING_length_set(x, n) ((x)->length = (n)) -#define M_ASN1_STRING_type(x) ((x)->type) -#define M_ASN1_STRING_data(x) ((x)->data) - -/* Macros for string operations */ -#define M_ASN1_BIT_STRING_new() (ASN1_BIT_STRING *)\ - ASN1_STRING_type_new(V_ASN1_BIT_STRING) -#define M_ASN1_BIT_STRING_free(a) ASN1_STRING_free((ASN1_STRING *)a) -#define M_ASN1_BIT_STRING_dup(a) (ASN1_BIT_STRING *)\ - ASN1_STRING_dup((const ASN1_STRING *)a) -#define M_ASN1_BIT_STRING_cmp(a,b) ASN1_STRING_cmp(\ - (const ASN1_STRING *)a,(const ASN1_STRING *)b) -#define M_ASN1_BIT_STRING_set(a,b,c) ASN1_STRING_set((ASN1_STRING *)a,b,c) - -#define M_ASN1_INTEGER_new() (ASN1_INTEGER *)\ - ASN1_STRING_type_new(V_ASN1_INTEGER) -#define M_ASN1_INTEGER_free(a) ASN1_STRING_free((ASN1_STRING *)a) -#define M_ASN1_INTEGER_dup(a) (ASN1_INTEGER *)\ - ASN1_STRING_dup((const ASN1_STRING *)a) -#define M_ASN1_INTEGER_cmp(a,b) ASN1_STRING_cmp(\ - (const ASN1_STRING *)a,(const ASN1_STRING *)b) - -#define M_ASN1_ENUMERATED_new() (ASN1_ENUMERATED *)\ - ASN1_STRING_type_new(V_ASN1_ENUMERATED) -#define M_ASN1_ENUMERATED_free(a) ASN1_STRING_free((ASN1_STRING *)a) -#define M_ASN1_ENUMERATED_dup(a) (ASN1_ENUMERATED *)\ - ASN1_STRING_dup((const ASN1_STRING *)a) -#define M_ASN1_ENUMERATED_cmp(a,b) ASN1_STRING_cmp(\ - (const ASN1_STRING *)a,(const ASN1_STRING *)b) - -#define M_ASN1_OCTET_STRING_new() (ASN1_OCTET_STRING *)\ - ASN1_STRING_type_new(V_ASN1_OCTET_STRING) -#define M_ASN1_OCTET_STRING_free(a) ASN1_STRING_free((ASN1_STRING *)a) -#define M_ASN1_OCTET_STRING_dup(a) (ASN1_OCTET_STRING *)\ - ASN1_STRING_dup((const ASN1_STRING *)a) -#define M_ASN1_OCTET_STRING_cmp(a,b) ASN1_STRING_cmp(\ - (const ASN1_STRING *)a,(const ASN1_STRING *)b) -#define M_ASN1_OCTET_STRING_set(a,b,c) ASN1_STRING_set((ASN1_STRING *)a,b,c) -#define M_ASN1_OCTET_STRING_print(a,b) ASN1_STRING_print(a,(ASN1_STRING *)b) -#define M_i2d_ASN1_OCTET_STRING(a,pp) \ - i2d_ASN1_bytes((ASN1_STRING *)a,pp,V_ASN1_OCTET_STRING,\ - V_ASN1_UNIVERSAL) - -#define B_ASN1_TIME \ - B_ASN1_UTCTIME | \ - B_ASN1_GENERALIZEDTIME - -#define B_ASN1_PRINTABLE \ - B_ASN1_NUMERICSTRING| \ - B_ASN1_PRINTABLESTRING| \ - B_ASN1_T61STRING| \ - B_ASN1_IA5STRING| \ - B_ASN1_BIT_STRING| \ - B_ASN1_UNIVERSALSTRING|\ - B_ASN1_BMPSTRING|\ - B_ASN1_UTF8STRING|\ - B_ASN1_SEQUENCE|\ - B_ASN1_UNKNOWN - -#define B_ASN1_DIRECTORYSTRING \ - B_ASN1_PRINTABLESTRING| \ - B_ASN1_TELETEXSTRING|\ - B_ASN1_BMPSTRING|\ - B_ASN1_UNIVERSALSTRING|\ - B_ASN1_UTF8STRING - -#define B_ASN1_DISPLAYTEXT \ - B_ASN1_IA5STRING| \ - B_ASN1_VISIBLESTRING| \ - B_ASN1_BMPSTRING|\ - B_ASN1_UTF8STRING - -#define M_ASN1_PRINTABLE_new() ASN1_STRING_type_new(V_ASN1_T61STRING) -#define M_ASN1_PRINTABLE_free(a) ASN1_STRING_free((ASN1_STRING *)a) -#define M_i2d_ASN1_PRINTABLE(a,pp) i2d_ASN1_bytes((ASN1_STRING *)a,\ - pp,a->type,V_ASN1_UNIVERSAL) -#define M_d2i_ASN1_PRINTABLE(a,pp,l) \ - d2i_ASN1_type_bytes((ASN1_STRING **)a,pp,l, \ - B_ASN1_PRINTABLE) - -#define M_DIRECTORYSTRING_new() ASN1_STRING_type_new(V_ASN1_PRINTABLESTRING) -#define M_DIRECTORYSTRING_free(a) ASN1_STRING_free((ASN1_STRING *)a) -#define M_i2d_DIRECTORYSTRING(a,pp) i2d_ASN1_bytes((ASN1_STRING *)a,\ - pp,a->type,V_ASN1_UNIVERSAL) -#define M_d2i_DIRECTORYSTRING(a,pp,l) \ - d2i_ASN1_type_bytes((ASN1_STRING **)a,pp,l, \ - B_ASN1_DIRECTORYSTRING) - -#define M_DISPLAYTEXT_new() ASN1_STRING_type_new(V_ASN1_VISIBLESTRING) -#define M_DISPLAYTEXT_free(a) ASN1_STRING_free((ASN1_STRING *)a) -#define M_i2d_DISPLAYTEXT(a,pp) i2d_ASN1_bytes((ASN1_STRING *)a,\ - pp,a->type,V_ASN1_UNIVERSAL) -#define M_d2i_DISPLAYTEXT(a,pp,l) \ - d2i_ASN1_type_bytes((ASN1_STRING **)a,pp,l, \ - B_ASN1_DISPLAYTEXT) - -#define M_ASN1_PRINTABLESTRING_new() (ASN1_PRINTABLESTRING *)\ - ASN1_STRING_type_new(V_ASN1_PRINTABLESTRING) -#define M_ASN1_PRINTABLESTRING_free(a) ASN1_STRING_free((ASN1_STRING *)a) -#define M_i2d_ASN1_PRINTABLESTRING(a,pp) \ - i2d_ASN1_bytes((ASN1_STRING *)a,pp,V_ASN1_PRINTABLESTRING,\ - V_ASN1_UNIVERSAL) -#define M_d2i_ASN1_PRINTABLESTRING(a,pp,l) \ - (ASN1_PRINTABLESTRING *)d2i_ASN1_type_bytes\ - ((ASN1_STRING **)a,pp,l,B_ASN1_PRINTABLESTRING) - -#define M_ASN1_T61STRING_new() (ASN1_T61STRING *)\ - ASN1_STRING_type_new(V_ASN1_T61STRING) -#define M_ASN1_T61STRING_free(a) ASN1_STRING_free((ASN1_STRING *)a) -#define M_i2d_ASN1_T61STRING(a,pp) \ - i2d_ASN1_bytes((ASN1_STRING *)a,pp,V_ASN1_T61STRING,\ - V_ASN1_UNIVERSAL) -#define M_d2i_ASN1_T61STRING(a,pp,l) \ - (ASN1_T61STRING *)d2i_ASN1_type_bytes\ - ((ASN1_STRING **)a,pp,l,B_ASN1_T61STRING) - -#define M_ASN1_IA5STRING_new() (ASN1_IA5STRING *)\ - ASN1_STRING_type_new(V_ASN1_IA5STRING) -#define M_ASN1_IA5STRING_free(a) ASN1_STRING_free((ASN1_STRING *)a) -#define M_ASN1_IA5STRING_dup(a) \ - (ASN1_IA5STRING *)ASN1_STRING_dup((const ASN1_STRING *)a) -#define M_i2d_ASN1_IA5STRING(a,pp) \ - i2d_ASN1_bytes((ASN1_STRING *)a,pp,V_ASN1_IA5STRING,\ - V_ASN1_UNIVERSAL) -#define M_d2i_ASN1_IA5STRING(a,pp,l) \ - (ASN1_IA5STRING *)d2i_ASN1_type_bytes((ASN1_STRING **)a,pp,l,\ - B_ASN1_IA5STRING) - -#define M_ASN1_UTCTIME_new() (ASN1_UTCTIME *)\ - ASN1_STRING_type_new(V_ASN1_UTCTIME) -#define M_ASN1_UTCTIME_free(a) ASN1_STRING_free((ASN1_STRING *)a) -#define M_ASN1_UTCTIME_dup(a) (ASN1_UTCTIME *)\ - ASN1_STRING_dup((const ASN1_STRING *)a) - -#define M_ASN1_GENERALIZEDTIME_new() (ASN1_GENERALIZEDTIME *)\ - ASN1_STRING_type_new(V_ASN1_GENERALIZEDTIME) -#define M_ASN1_GENERALIZEDTIME_free(a) ASN1_STRING_free((ASN1_STRING *)a) -#define M_ASN1_GENERALIZEDTIME_dup(a) (ASN1_GENERALIZEDTIME *)ASN1_STRING_dup(\ - (const ASN1_STRING *)a) - -#define M_ASN1_TIME_new() (ASN1_TIME *)\ - ASN1_STRING_type_new(V_ASN1_UTCTIME) -#define M_ASN1_TIME_free(a) ASN1_STRING_free((ASN1_STRING *)a) -#define M_ASN1_TIME_dup(a) (ASN1_TIME *)\ - ASN1_STRING_dup((const ASN1_STRING *)a) - -#define M_ASN1_GENERALSTRING_new() (ASN1_GENERALSTRING *)\ - ASN1_STRING_type_new(V_ASN1_GENERALSTRING) -#define M_ASN1_GENERALSTRING_free(a) ASN1_STRING_free((ASN1_STRING *)a) -#define M_i2d_ASN1_GENERALSTRING(a,pp) \ - i2d_ASN1_bytes((ASN1_STRING *)a,pp,V_ASN1_GENERALSTRING,\ - V_ASN1_UNIVERSAL) -#define M_d2i_ASN1_GENERALSTRING(a,pp,l) \ - (ASN1_GENERALSTRING *)d2i_ASN1_type_bytes\ - ((ASN1_STRING **)a,pp,l,B_ASN1_GENERALSTRING) - -#define M_ASN1_UNIVERSALSTRING_new() (ASN1_UNIVERSALSTRING *)\ - ASN1_STRING_type_new(V_ASN1_UNIVERSALSTRING) -#define M_ASN1_UNIVERSALSTRING_free(a) ASN1_STRING_free((ASN1_STRING *)a) -#define M_i2d_ASN1_UNIVERSALSTRING(a,pp) \ - i2d_ASN1_bytes((ASN1_STRING *)a,pp,V_ASN1_UNIVERSALSTRING,\ - V_ASN1_UNIVERSAL) -#define M_d2i_ASN1_UNIVERSALSTRING(a,pp,l) \ - (ASN1_UNIVERSALSTRING *)d2i_ASN1_type_bytes\ - ((ASN1_STRING **)a,pp,l,B_ASN1_UNIVERSALSTRING) - -#define M_ASN1_BMPSTRING_new() (ASN1_BMPSTRING *)\ - ASN1_STRING_type_new(V_ASN1_BMPSTRING) -#define M_ASN1_BMPSTRING_free(a) ASN1_STRING_free((ASN1_STRING *)a) -#define M_i2d_ASN1_BMPSTRING(a,pp) \ - i2d_ASN1_bytes((ASN1_STRING *)a,pp,V_ASN1_BMPSTRING,\ - V_ASN1_UNIVERSAL) -#define M_d2i_ASN1_BMPSTRING(a,pp,l) \ - (ASN1_BMPSTRING *)d2i_ASN1_type_bytes\ - ((ASN1_STRING **)a,pp,l,B_ASN1_BMPSTRING) - -#define M_ASN1_VISIBLESTRING_new() (ASN1_VISIBLESTRING *)\ - ASN1_STRING_type_new(V_ASN1_VISIBLESTRING) -#define M_ASN1_VISIBLESTRING_free(a) ASN1_STRING_free((ASN1_STRING *)a) -#define M_i2d_ASN1_VISIBLESTRING(a,pp) \ - i2d_ASN1_bytes((ASN1_STRING *)a,pp,V_ASN1_VISIBLESTRING,\ - V_ASN1_UNIVERSAL) -#define M_d2i_ASN1_VISIBLESTRING(a,pp,l) \ - (ASN1_VISIBLESTRING *)d2i_ASN1_type_bytes\ - ((ASN1_STRING **)a,pp,l,B_ASN1_VISIBLESTRING) - -#define M_ASN1_UTF8STRING_new() (ASN1_UTF8STRING *)\ - ASN1_STRING_type_new(V_ASN1_UTF8STRING) -#define M_ASN1_UTF8STRING_free(a) ASN1_STRING_free((ASN1_STRING *)a) -#define M_i2d_ASN1_UTF8STRING(a,pp) \ - i2d_ASN1_bytes((ASN1_STRING *)a,pp,V_ASN1_UTF8STRING,\ - V_ASN1_UNIVERSAL) -#define M_d2i_ASN1_UTF8STRING(a,pp,l) \ - (ASN1_UTF8STRING *)d2i_ASN1_type_bytes\ - ((ASN1_STRING **)a,pp,l,B_ASN1_UTF8STRING) - - /* for the is_set parameter to i2d_ASN1_SET */ -#define IS_SEQUENCE 0 -#define IS_SET 1 - -DECLARE_ASN1_FUNCTIONS_fname(ASN1_TYPE, ASN1_ANY, ASN1_TYPE) - -OPENSSL_EXPORT int ASN1_TYPE_get(ASN1_TYPE *a); -OPENSSL_EXPORT void ASN1_TYPE_set(ASN1_TYPE *a, int type, void *value); -OPENSSL_EXPORT int ASN1_TYPE_set1(ASN1_TYPE *a, int type, const void *value); -OPENSSL_EXPORT int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b); - -OPENSSL_EXPORT ASN1_OBJECT * ASN1_OBJECT_new(void ); -OPENSSL_EXPORT void ASN1_OBJECT_free(ASN1_OBJECT *a); -OPENSSL_EXPORT int i2d_ASN1_OBJECT(ASN1_OBJECT *a,unsigned char **pp); -OPENSSL_EXPORT ASN1_OBJECT * c2i_ASN1_OBJECT(ASN1_OBJECT **a,const unsigned char **pp, - long length); -OPENSSL_EXPORT ASN1_OBJECT * d2i_ASN1_OBJECT(ASN1_OBJECT **a,const unsigned char **pp, - long length); - -DECLARE_ASN1_ITEM(ASN1_OBJECT) - -DECLARE_ASN1_SET_OF(ASN1_OBJECT) - -OPENSSL_EXPORT ASN1_STRING * ASN1_STRING_new(void); -OPENSSL_EXPORT void ASN1_STRING_free(ASN1_STRING *a); -OPENSSL_EXPORT int ASN1_STRING_copy(ASN1_STRING *dst, const ASN1_STRING *str); -OPENSSL_EXPORT ASN1_STRING * ASN1_STRING_dup(const ASN1_STRING *a); -OPENSSL_EXPORT ASN1_STRING * ASN1_STRING_type_new(int type ); -OPENSSL_EXPORT int ASN1_STRING_cmp(const ASN1_STRING *a, const ASN1_STRING *b); - /* Since this is used to store all sorts of things, via macros, for now, make - its data void * */ -OPENSSL_EXPORT int ASN1_STRING_set(ASN1_STRING *str, const void *data, int len); -OPENSSL_EXPORT void ASN1_STRING_set0(ASN1_STRING *str, void *data, int len); -OPENSSL_EXPORT int ASN1_STRING_length(const ASN1_STRING *x); -OPENSSL_EXPORT void ASN1_STRING_length_set(ASN1_STRING *x, int n); -OPENSSL_EXPORT int ASN1_STRING_type(ASN1_STRING *x); -OPENSSL_EXPORT unsigned char * ASN1_STRING_data(ASN1_STRING *x); - -DECLARE_ASN1_FUNCTIONS(ASN1_BIT_STRING) -OPENSSL_EXPORT int i2c_ASN1_BIT_STRING(ASN1_BIT_STRING *a,unsigned char **pp); -OPENSSL_EXPORT ASN1_BIT_STRING *c2i_ASN1_BIT_STRING(ASN1_BIT_STRING **a,const unsigned char **pp, long length); -OPENSSL_EXPORT int ASN1_BIT_STRING_set(ASN1_BIT_STRING *a, unsigned char *d, int length ); -OPENSSL_EXPORT int ASN1_BIT_STRING_set_bit(ASN1_BIT_STRING *a, int n, int value); -OPENSSL_EXPORT int ASN1_BIT_STRING_get_bit(ASN1_BIT_STRING *a, int n); -OPENSSL_EXPORT int ASN1_BIT_STRING_check(ASN1_BIT_STRING *a, unsigned char *flags, int flags_len); - -OPENSSL_EXPORT int ASN1_BIT_STRING_name_print(BIO *out, ASN1_BIT_STRING *bs, BIT_STRING_BITNAME *tbl, int indent); -OPENSSL_EXPORT int ASN1_BIT_STRING_num_asc(char *name, BIT_STRING_BITNAME *tbl); -OPENSSL_EXPORT int ASN1_BIT_STRING_set_asc(ASN1_BIT_STRING *bs, char *name, int value, BIT_STRING_BITNAME *tbl); - -OPENSSL_EXPORT int i2d_ASN1_BOOLEAN(int a,unsigned char **pp); -OPENSSL_EXPORT int d2i_ASN1_BOOLEAN(int *a,const unsigned char **pp,long length); - -DECLARE_ASN1_FUNCTIONS(ASN1_INTEGER) -OPENSSL_EXPORT int i2c_ASN1_INTEGER(ASN1_INTEGER *a,unsigned char **pp); -OPENSSL_EXPORT ASN1_INTEGER *c2i_ASN1_INTEGER(ASN1_INTEGER **a,const unsigned char **pp, long length); -OPENSSL_EXPORT ASN1_INTEGER *d2i_ASN1_UINTEGER(ASN1_INTEGER **a,const unsigned char **pp, long length); -OPENSSL_EXPORT ASN1_INTEGER * ASN1_INTEGER_dup(const ASN1_INTEGER *x); -OPENSSL_EXPORT int ASN1_INTEGER_cmp(const ASN1_INTEGER *x, const ASN1_INTEGER *y); - -DECLARE_ASN1_FUNCTIONS(ASN1_ENUMERATED) - -OPENSSL_EXPORT int ASN1_UTCTIME_check(const ASN1_UTCTIME *a); -OPENSSL_EXPORT ASN1_UTCTIME *ASN1_UTCTIME_set(ASN1_UTCTIME *s,time_t t); -OPENSSL_EXPORT ASN1_UTCTIME *ASN1_UTCTIME_adj(ASN1_UTCTIME *s, time_t t, int offset_day, long offset_sec); -OPENSSL_EXPORT int ASN1_UTCTIME_set_string(ASN1_UTCTIME *s, const char *str); -OPENSSL_EXPORT int ASN1_UTCTIME_cmp_time_t(const ASN1_UTCTIME *s, time_t t); -#if 0 -time_t ASN1_UTCTIME_get(const ASN1_UTCTIME *s); -#endif - -OPENSSL_EXPORT int ASN1_GENERALIZEDTIME_check(const ASN1_GENERALIZEDTIME *a); -OPENSSL_EXPORT ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_set(ASN1_GENERALIZEDTIME *s,time_t t); -OPENSSL_EXPORT ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_adj(ASN1_GENERALIZEDTIME *s, time_t t, int offset_day, long offset_sec); -OPENSSL_EXPORT int ASN1_GENERALIZEDTIME_set_string(ASN1_GENERALIZEDTIME *s, const char *str); -OPENSSL_EXPORT int ASN1_TIME_diff(int *pday, int *psec, const ASN1_TIME *from, const ASN1_TIME *to); - -DECLARE_ASN1_FUNCTIONS(ASN1_OCTET_STRING) -OPENSSL_EXPORT ASN1_OCTET_STRING * ASN1_OCTET_STRING_dup(const ASN1_OCTET_STRING *a); -OPENSSL_EXPORT int ASN1_OCTET_STRING_cmp(const ASN1_OCTET_STRING *a, const ASN1_OCTET_STRING *b); -OPENSSL_EXPORT int ASN1_OCTET_STRING_set(ASN1_OCTET_STRING *str, const unsigned char *data, int len); - -DECLARE_ASN1_FUNCTIONS(ASN1_VISIBLESTRING) -DECLARE_ASN1_FUNCTIONS(ASN1_UNIVERSALSTRING) -DECLARE_ASN1_FUNCTIONS(ASN1_UTF8STRING) -DECLARE_ASN1_FUNCTIONS(ASN1_NULL) -DECLARE_ASN1_FUNCTIONS(ASN1_BMPSTRING) - -OPENSSL_EXPORT int UTF8_getc(const unsigned char *str, int len, unsigned long *val); -OPENSSL_EXPORT int UTF8_putc(unsigned char *str, int len, unsigned long value); - -DECLARE_ASN1_FUNCTIONS_name(ASN1_STRING, ASN1_PRINTABLE) - -DECLARE_ASN1_FUNCTIONS_name(ASN1_STRING, DIRECTORYSTRING) -DECLARE_ASN1_FUNCTIONS_name(ASN1_STRING, DISPLAYTEXT) -DECLARE_ASN1_FUNCTIONS(ASN1_PRINTABLESTRING) -DECLARE_ASN1_FUNCTIONS(ASN1_T61STRING) -DECLARE_ASN1_FUNCTIONS(ASN1_IA5STRING) -DECLARE_ASN1_FUNCTIONS(ASN1_GENERALSTRING) -DECLARE_ASN1_FUNCTIONS(ASN1_UTCTIME) -DECLARE_ASN1_FUNCTIONS(ASN1_GENERALIZEDTIME) -DECLARE_ASN1_FUNCTIONS(ASN1_TIME) - -DECLARE_ASN1_ITEM(ASN1_OCTET_STRING_NDEF) - -OPENSSL_EXPORT ASN1_TIME *ASN1_TIME_set(ASN1_TIME *s,time_t t); -OPENSSL_EXPORT ASN1_TIME *ASN1_TIME_adj(ASN1_TIME *s,time_t t, int offset_day, long offset_sec); -OPENSSL_EXPORT int ASN1_TIME_check(ASN1_TIME *t); -OPENSSL_EXPORT ASN1_GENERALIZEDTIME *ASN1_TIME_to_generalizedtime(ASN1_TIME *t, ASN1_GENERALIZEDTIME **out); -OPENSSL_EXPORT int ASN1_TIME_set_string(ASN1_TIME *s, const char *str); - -OPENSSL_EXPORT int i2d_ASN1_SET(STACK_OF(OPENSSL_BLOCK) *a, unsigned char **pp, i2d_of_void *i2d, int ex_tag, int ex_class, int is_set); -OPENSSL_EXPORT STACK_OF(OPENSSL_BLOCK) *d2i_ASN1_SET(STACK_OF(OPENSSL_BLOCK) **a, - const unsigned char **pp, - long length, d2i_of_void *d2i, - void (*free_func)(OPENSSL_BLOCK), int ex_tag, - int ex_class); - -OPENSSL_EXPORT int i2a_ASN1_INTEGER(BIO *bp, ASN1_INTEGER *a); -OPENSSL_EXPORT int a2i_ASN1_INTEGER(BIO *bp,ASN1_INTEGER *bs,char *buf,int size); -OPENSSL_EXPORT int i2a_ASN1_ENUMERATED(BIO *bp, ASN1_ENUMERATED *a); -OPENSSL_EXPORT int a2i_ASN1_ENUMERATED(BIO *bp,ASN1_ENUMERATED *bs,char *buf,int size); -OPENSSL_EXPORT int i2a_ASN1_OBJECT(BIO *bp,ASN1_OBJECT *a); -OPENSSL_EXPORT int a2i_ASN1_STRING(BIO *bp,ASN1_STRING *bs,char *buf,int size); -OPENSSL_EXPORT int i2a_ASN1_STRING(BIO *bp, ASN1_STRING *a, int type); -OPENSSL_EXPORT int i2t_ASN1_OBJECT(char *buf,int buf_len,ASN1_OBJECT *a); - -OPENSSL_EXPORT int a2d_ASN1_OBJECT(unsigned char *out,int olen, const char *buf, int num); -OPENSSL_EXPORT ASN1_OBJECT *ASN1_OBJECT_create(int nid, unsigned char *data,int len, const char *sn, const char *ln); - -OPENSSL_EXPORT int ASN1_INTEGER_set(ASN1_INTEGER *a, long v); -OPENSSL_EXPORT long ASN1_INTEGER_get(const ASN1_INTEGER *a); -OPENSSL_EXPORT ASN1_INTEGER *BN_to_ASN1_INTEGER(const BIGNUM *bn, ASN1_INTEGER *ai); -OPENSSL_EXPORT BIGNUM *ASN1_INTEGER_to_BN(const ASN1_INTEGER *ai,BIGNUM *bn); - -OPENSSL_EXPORT int ASN1_ENUMERATED_set(ASN1_ENUMERATED *a, long v); -OPENSSL_EXPORT long ASN1_ENUMERATED_get(ASN1_ENUMERATED *a); -OPENSSL_EXPORT ASN1_ENUMERATED *BN_to_ASN1_ENUMERATED(BIGNUM *bn, ASN1_ENUMERATED *ai); -OPENSSL_EXPORT BIGNUM *ASN1_ENUMERATED_to_BN(ASN1_ENUMERATED *ai,BIGNUM *bn); - -/* General */ -/* given a string, return the correct type, max is the maximum length */ -OPENSSL_EXPORT int ASN1_PRINTABLE_type(const unsigned char *s, int max); - -OPENSSL_EXPORT int i2d_ASN1_bytes(ASN1_STRING *a, unsigned char **pp, int tag, int xclass); -OPENSSL_EXPORT ASN1_STRING *d2i_ASN1_bytes(ASN1_STRING **a, const unsigned char **pp, long length, int Ptag, int Pclass); -OPENSSL_EXPORT unsigned long ASN1_tag2bit(int tag); -/* type is one or more of the B_ASN1_ values. */ -OPENSSL_EXPORT ASN1_STRING *d2i_ASN1_type_bytes(ASN1_STRING **a,const unsigned char **pp, long length,int type); - -/* PARSING */ -OPENSSL_EXPORT int asn1_Finish(ASN1_CTX *c); -OPENSSL_EXPORT int asn1_const_Finish(ASN1_const_CTX *c); - -/* SPECIALS */ -OPENSSL_EXPORT int ASN1_get_object(const unsigned char **pp, long *plength, int *ptag, int *pclass, long omax); -OPENSSL_EXPORT int ASN1_check_infinite_end(unsigned char **p,long len); -OPENSSL_EXPORT int ASN1_const_check_infinite_end(const unsigned char **p,long len); -OPENSSL_EXPORT void ASN1_put_object(unsigned char **pp, int constructed, int length, int tag, int xclass); -OPENSSL_EXPORT int ASN1_put_eoc(unsigned char **pp); -OPENSSL_EXPORT int ASN1_object_size(int constructed, int length, int tag); - -/* Used to implement other functions */ -OPENSSL_EXPORT void *ASN1_dup(i2d_of_void *i2d, d2i_of_void *d2i, void *x); - -#define ASN1_dup_of(type,i2d,d2i,x) \ - ((type*)ASN1_dup(CHECKED_I2D_OF(type, i2d), \ - CHECKED_D2I_OF(type, d2i), \ - CHECKED_PTR_OF(type, x))) - -#define ASN1_dup_of_const(type,i2d,d2i,x) \ - ((type*)ASN1_dup(CHECKED_I2D_OF(const type, i2d), \ - CHECKED_D2I_OF(type, d2i), \ - CHECKED_PTR_OF(const type, x))) - -OPENSSL_EXPORT void *ASN1_item_dup(const ASN1_ITEM *it, void *x); - -/* ASN1 alloc/free macros for when a type is only used internally */ - -#define M_ASN1_new_of(type) (type *)ASN1_item_new(ASN1_ITEM_rptr(type)) -#define M_ASN1_free_of(x, type) \ - ASN1_item_free(CHECKED_PTR_OF(type, x), ASN1_ITEM_rptr(type)) - -#ifndef OPENSSL_NO_FP_API -OPENSSL_EXPORT void *ASN1_d2i_fp(void *(*xnew)(void), d2i_of_void *d2i, FILE *in, void **x); - -#define ASN1_d2i_fp_of(type,xnew,d2i,in,x) \ - ((type*)ASN1_d2i_fp(CHECKED_NEW_OF(type, xnew), \ - CHECKED_D2I_OF(type, d2i), \ - in, \ - CHECKED_PPTR_OF(type, x))) - -OPENSSL_EXPORT void *ASN1_item_d2i_fp(const ASN1_ITEM *it, FILE *in, void *x); -OPENSSL_EXPORT int ASN1_i2d_fp(i2d_of_void *i2d,FILE *out,void *x); - -#define ASN1_i2d_fp_of(type,i2d,out,x) \ - (ASN1_i2d_fp(CHECKED_I2D_OF(type, i2d), \ - out, \ - CHECKED_PTR_OF(type, x))) - -#define ASN1_i2d_fp_of_const(type,i2d,out,x) \ - (ASN1_i2d_fp(CHECKED_I2D_OF(const type, i2d), \ - out, \ - CHECKED_PTR_OF(const type, x))) - -OPENSSL_EXPORT int ASN1_item_i2d_fp(const ASN1_ITEM *it, FILE *out, void *x); -OPENSSL_EXPORT int ASN1_STRING_print_ex_fp(FILE *fp, ASN1_STRING *str, unsigned long flags); -#endif - -OPENSSL_EXPORT int ASN1_STRING_to_UTF8(unsigned char **out, ASN1_STRING *in); - -OPENSSL_EXPORT void *ASN1_d2i_bio(void *(*xnew)(void), d2i_of_void *d2i, BIO *in, void **x); - -#define ASN1_d2i_bio_of(type,xnew,d2i,in,x) \ - ((type*)ASN1_d2i_bio( CHECKED_NEW_OF(type, xnew), \ - CHECKED_D2I_OF(type, d2i), \ - in, \ - CHECKED_PPTR_OF(type, x))) - -OPENSSL_EXPORT void *ASN1_item_d2i_bio(const ASN1_ITEM *it, BIO *in, void *x); -OPENSSL_EXPORT int ASN1_i2d_bio(i2d_of_void *i2d,BIO *out, unsigned char *x); - -#define ASN1_i2d_bio_of(type,i2d,out,x) \ - (ASN1_i2d_bio(CHECKED_I2D_OF(type, i2d), \ - out, \ - CHECKED_PTR_OF(type, x))) - -#define ASN1_i2d_bio_of_const(type,i2d,out,x) \ - (ASN1_i2d_bio(CHECKED_I2D_OF(const type, i2d), \ - out, \ - CHECKED_PTR_OF(const type, x))) - -OPENSSL_EXPORT int ASN1_item_i2d_bio(const ASN1_ITEM *it, BIO *out, void *x); -OPENSSL_EXPORT int ASN1_UTCTIME_print(BIO *fp, const ASN1_UTCTIME *a); -OPENSSL_EXPORT int ASN1_GENERALIZEDTIME_print(BIO *fp, const ASN1_GENERALIZEDTIME *a); -OPENSSL_EXPORT int ASN1_TIME_print(BIO *fp, const ASN1_TIME *a); -OPENSSL_EXPORT int ASN1_STRING_print(BIO *bp, const ASN1_STRING *v); -OPENSSL_EXPORT int ASN1_STRING_print_ex(BIO *out, ASN1_STRING *str, unsigned long flags); -OPENSSL_EXPORT int ASN1_bn_print(BIO *bp, const char *number, const BIGNUM *num, unsigned char *buf, int off); -OPENSSL_EXPORT int ASN1_parse(BIO *bp,const unsigned char *pp,long len,int indent); -OPENSSL_EXPORT int ASN1_parse_dump(BIO *bp,const unsigned char *pp,long len,int indent,int dump); -OPENSSL_EXPORT const char *ASN1_tag2str(int tag); - -/* Used to load and write netscape format cert */ - -DECLARE_ASN1_FUNCTIONS(NETSCAPE_X509) - -int ASN1_UNIVERSALSTRING_to_string(ASN1_UNIVERSALSTRING *s); - -OPENSSL_EXPORT STACK_OF(OPENSSL_BLOCK) *ASN1_seq_unpack(const unsigned char *buf, int len, d2i_of_void *d2i, void (*free_func)(OPENSSL_BLOCK)); -OPENSSL_EXPORT unsigned char *ASN1_seq_pack(STACK_OF(OPENSSL_BLOCK) *safes, i2d_of_void *i2d, unsigned char **buf, int *len ); -OPENSSL_EXPORT void *ASN1_unpack_string(ASN1_STRING *oct, d2i_of_void *d2i); -OPENSSL_EXPORT void *ASN1_item_unpack(ASN1_STRING *oct, const ASN1_ITEM *it); -OPENSSL_EXPORT ASN1_STRING *ASN1_pack_string(void *obj, i2d_of_void *i2d, ASN1_OCTET_STRING **oct); - -#define ASN1_pack_string_of(type,obj,i2d,oct) \ - (ASN1_pack_string(CHECKED_PTR_OF(type, obj), \ - CHECKED_I2D_OF(type, i2d), \ - oct)) - -OPENSSL_EXPORT ASN1_STRING *ASN1_item_pack(void *obj, const ASN1_ITEM *it, ASN1_OCTET_STRING **oct); - -OPENSSL_EXPORT void ASN1_STRING_set_default_mask(unsigned long mask); -OPENSSL_EXPORT int ASN1_STRING_set_default_mask_asc(const char *p); -OPENSSL_EXPORT unsigned long ASN1_STRING_get_default_mask(void); -OPENSSL_EXPORT int ASN1_mbstring_copy(ASN1_STRING **out, const unsigned char *in, int len, int inform, unsigned long mask); -OPENSSL_EXPORT int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in, int len, int inform, unsigned long mask, long minsize, long maxsize); - -OPENSSL_EXPORT ASN1_STRING *ASN1_STRING_set_by_NID(ASN1_STRING **out, const unsigned char *in, int inlen, int inform, int nid); -OPENSSL_EXPORT ASN1_STRING_TABLE *ASN1_STRING_TABLE_get(int nid); -OPENSSL_EXPORT int ASN1_STRING_TABLE_add(int, long, long, unsigned long, unsigned long); -OPENSSL_EXPORT void ASN1_STRING_TABLE_cleanup(void); - -/* ASN1 template functions */ - -/* Old API compatible functions */ -OPENSSL_EXPORT ASN1_VALUE *ASN1_item_new(const ASN1_ITEM *it); -OPENSSL_EXPORT void ASN1_item_free(ASN1_VALUE *val, const ASN1_ITEM *it); -OPENSSL_EXPORT ASN1_VALUE * ASN1_item_d2i(ASN1_VALUE **val, const unsigned char **in, long len, const ASN1_ITEM *it); -OPENSSL_EXPORT int ASN1_item_i2d(ASN1_VALUE *val, unsigned char **out, const ASN1_ITEM *it); -OPENSSL_EXPORT int ASN1_item_ndef_i2d(ASN1_VALUE *val, unsigned char **out, const ASN1_ITEM *it); - -OPENSSL_EXPORT void ASN1_add_oid_module(void); - -OPENSSL_EXPORT ASN1_TYPE *ASN1_generate_nconf(char *str, CONF *nconf); -OPENSSL_EXPORT ASN1_TYPE *ASN1_generate_v3(char *str, X509V3_CTX *cnf); - -/* ASN1 Print flags */ - -/* Indicate missing OPTIONAL fields */ -#define ASN1_PCTX_FLAGS_SHOW_ABSENT 0x001 -/* Mark start and end of SEQUENCE */ -#define ASN1_PCTX_FLAGS_SHOW_SEQUENCE 0x002 -/* Mark start and end of SEQUENCE/SET OF */ -#define ASN1_PCTX_FLAGS_SHOW_SSOF 0x004 -/* Show the ASN1 type of primitives */ -#define ASN1_PCTX_FLAGS_SHOW_TYPE 0x008 -/* Don't show ASN1 type of ANY */ -#define ASN1_PCTX_FLAGS_NO_ANY_TYPE 0x010 -/* Don't show ASN1 type of MSTRINGs */ -#define ASN1_PCTX_FLAGS_NO_MSTRING_TYPE 0x020 -/* Don't show field names in SEQUENCE */ -#define ASN1_PCTX_FLAGS_NO_FIELD_NAME 0x040 -/* Show structure names of each SEQUENCE field */ -#define ASN1_PCTX_FLAGS_SHOW_FIELD_STRUCT_NAME 0x080 -/* Don't show structure name even at top level */ -#define ASN1_PCTX_FLAGS_NO_STRUCT_NAME 0x100 - -OPENSSL_EXPORT int ASN1_item_print(BIO *out, ASN1_VALUE *ifld, int indent, const ASN1_ITEM *it, const ASN1_PCTX *pctx); -OPENSSL_EXPORT ASN1_PCTX *ASN1_PCTX_new(void); -OPENSSL_EXPORT void ASN1_PCTX_free(ASN1_PCTX *p); -OPENSSL_EXPORT unsigned long ASN1_PCTX_get_flags(ASN1_PCTX *p); -OPENSSL_EXPORT void ASN1_PCTX_set_flags(ASN1_PCTX *p, unsigned long flags); -OPENSSL_EXPORT unsigned long ASN1_PCTX_get_nm_flags(ASN1_PCTX *p); -OPENSSL_EXPORT void ASN1_PCTX_set_nm_flags(ASN1_PCTX *p, unsigned long flags); -OPENSSL_EXPORT unsigned long ASN1_PCTX_get_cert_flags(ASN1_PCTX *p); -OPENSSL_EXPORT void ASN1_PCTX_set_cert_flags(ASN1_PCTX *p, unsigned long flags); -OPENSSL_EXPORT unsigned long ASN1_PCTX_get_oid_flags(ASN1_PCTX *p); -OPENSSL_EXPORT void ASN1_PCTX_set_oid_flags(ASN1_PCTX *p, unsigned long flags); -OPENSSL_EXPORT unsigned long ASN1_PCTX_get_str_flags(ASN1_PCTX *p); -OPENSSL_EXPORT void ASN1_PCTX_set_str_flags(ASN1_PCTX *p, unsigned long flags); - -OPENSSL_EXPORT const BIO_METHOD *BIO_f_asn1(void); - -OPENSSL_EXPORT BIO *BIO_new_NDEF(BIO *out, ASN1_VALUE *val, const ASN1_ITEM *it); - -OPENSSL_EXPORT int i2d_ASN1_bio_stream(BIO *out, ASN1_VALUE *val, BIO *in, int flags, const ASN1_ITEM *it); -OPENSSL_EXPORT int PEM_write_bio_ASN1_stream(BIO *out, ASN1_VALUE *val, BIO *in, int flags, const char *hdr, const ASN1_ITEM *it); -OPENSSL_EXPORT ASN1_VALUE *SMIME_read_ASN1(BIO *bio, BIO **bcont, const ASN1_ITEM *it); -OPENSSL_EXPORT int SMIME_crlf_copy(BIO *in, BIO *out, int flags); -OPENSSL_EXPORT int SMIME_text(BIO *in, BIO *out); - -/* BEGIN ERROR CODES */ -/* The following lines are auto generated by the script mkerr.pl. Any changes - * made after this point may be overwritten when the script is next run. - */ -void ERR_load_ASN1_strings(void); - -typedef int asn1_ps_func(BIO *b, unsigned char **pbuf, int *plen, void *parg); -OPENSSL_EXPORT int BIO_asn1_set_prefix(BIO *b, asn1_ps_func *prefix, asn1_ps_func *prefix_free); -OPENSSL_EXPORT int BIO_asn1_get_prefix(BIO *b, asn1_ps_func **pprefix, asn1_ps_func **pprefix_free); -OPENSSL_EXPORT int BIO_asn1_set_suffix(BIO *b, asn1_ps_func *suffix, asn1_ps_func *suffix_free); -OPENSSL_EXPORT int BIO_asn1_get_suffix(BIO *b, asn1_ps_func **psuffix, asn1_ps_func **psuffix_free); - -#ifdef __cplusplus -} -#endif - -#define ASN1_F_ASN1_BIT_STRING_set_bit 100 -#define ASN1_F_ASN1_ENUMERATED_set 101 -#define ASN1_F_ASN1_ENUMERATED_to_BN 102 -#define ASN1_F_ASN1_GENERALIZEDTIME_adj 103 -#define ASN1_F_ASN1_INTEGER_set 104 -#define ASN1_F_ASN1_INTEGER_to_BN 105 -#define ASN1_F_ASN1_OBJECT_new 106 -#define ASN1_F_ASN1_PCTX_new 107 -#define ASN1_F_ASN1_STRING_TABLE_add 108 -#define ASN1_F_ASN1_STRING_set 109 -#define ASN1_F_ASN1_STRING_type_new 110 -#define ASN1_F_ASN1_TIME_adj 111 -#define ASN1_F_ASN1_UTCTIME_adj 112 -#define ASN1_F_ASN1_d2i_fp 113 -#define ASN1_F_ASN1_dup 114 -#define ASN1_F_ASN1_generate_v3 115 -#define ASN1_F_ASN1_get_object 116 -#define ASN1_F_ASN1_i2d_bio 117 -#define ASN1_F_ASN1_i2d_fp 118 -#define ASN1_F_ASN1_item_d2i_fp 119 -#define ASN1_F_ASN1_item_dup 120 -#define ASN1_F_ASN1_item_ex_d2i 121 -#define ASN1_F_ASN1_item_i2d_bio 122 -#define ASN1_F_ASN1_item_i2d_fp 123 -#define ASN1_F_ASN1_item_pack 124 -#define ASN1_F_ASN1_item_unpack 125 -#define ASN1_F_ASN1_mbstring_ncopy 126 -#define ASN1_F_ASN1_template_new 127 -#define ASN1_F_BIO_new_NDEF 128 -#define ASN1_F_BN_to_ASN1_ENUMERATED 129 -#define ASN1_F_BN_to_ASN1_INTEGER 130 -#define ASN1_F_a2d_ASN1_OBJECT 131 -#define ASN1_F_a2i_ASN1_ENUMERATED 132 -#define ASN1_F_a2i_ASN1_INTEGER 133 -#define ASN1_F_a2i_ASN1_STRING 134 -#define ASN1_F_append_exp 135 -#define ASN1_F_asn1_cb 136 -#define ASN1_F_asn1_check_tlen 137 -#define ASN1_F_asn1_collate_primitive 138 -#define ASN1_F_asn1_collect 139 -#define ASN1_F_asn1_d2i_ex_primitive 140 -#define ASN1_F_asn1_d2i_read_bio 141 -#define ASN1_F_asn1_do_adb 142 -#define ASN1_F_asn1_ex_c2i 143 -#define ASN1_F_asn1_find_end 144 -#define ASN1_F_asn1_item_ex_combine_new 145 -#define ASN1_F_asn1_str2type 146 -#define ASN1_F_asn1_template_ex_d2i 147 -#define ASN1_F_asn1_template_noexp_d2i 148 -#define ASN1_F_bitstr_cb 149 -#define ASN1_F_c2i_ASN1_BIT_STRING 150 -#define ASN1_F_c2i_ASN1_INTEGER 151 -#define ASN1_F_c2i_ASN1_OBJECT 152 -#define ASN1_F_collect_data 153 -#define ASN1_F_d2i_ASN1_BOOLEAN 154 -#define ASN1_F_d2i_ASN1_OBJECT 155 -#define ASN1_F_d2i_ASN1_UINTEGER 156 -#define ASN1_F_d2i_ASN1_UTCTIME 157 -#define ASN1_F_d2i_ASN1_bytes 158 -#define ASN1_F_d2i_ASN1_type_bytes 159 -#define ASN1_F_i2d_ASN1_TIME 160 -#define ASN1_F_i2d_PrivateKey 161 -#define ASN1_F_long_c2i 162 -#define ASN1_F_parse_tagging 163 -#define ASN1_R_ASN1_LENGTH_MISMATCH 100 -#define ASN1_R_AUX_ERROR 101 -#define ASN1_R_BAD_GET_ASN1_OBJECT_CALL 102 -#define ASN1_R_BAD_OBJECT_HEADER 103 -#define ASN1_R_BMPSTRING_IS_WRONG_LENGTH 104 -#define ASN1_R_BN_LIB 105 -#define ASN1_R_BOOLEAN_IS_WRONG_LENGTH 106 -#define ASN1_R_BUFFER_TOO_SMALL 107 -#define ASN1_R_DECODE_ERROR 108 -#define ASN1_R_DEPTH_EXCEEDED 109 -#define ASN1_R_ENCODE_ERROR 110 -#define ASN1_R_ERROR_GETTING_TIME 111 -#define ASN1_R_EXPECTING_AN_ASN1_SEQUENCE 112 -#define ASN1_R_EXPECTING_AN_INTEGER 113 -#define ASN1_R_EXPECTING_AN_OBJECT 114 -#define ASN1_R_EXPECTING_A_BOOLEAN 115 -#define ASN1_R_EXPECTING_A_TIME 116 -#define ASN1_R_EXPLICIT_LENGTH_MISMATCH 117 -#define ASN1_R_EXPLICIT_TAG_NOT_CONSTRUCTED 118 -#define ASN1_R_FIELD_MISSING 119 -#define ASN1_R_FIRST_NUM_TOO_LARGE 120 -#define ASN1_R_HEADER_TOO_LONG 121 -#define ASN1_R_ILLEGAL_BITSTRING_FORMAT 122 -#define ASN1_R_ILLEGAL_BOOLEAN 123 -#define ASN1_R_ILLEGAL_CHARACTERS 124 -#define ASN1_R_ILLEGAL_FORMAT 125 -#define ASN1_R_ILLEGAL_HEX 126 -#define ASN1_R_ILLEGAL_IMPLICIT_TAG 127 -#define ASN1_R_ILLEGAL_INTEGER 128 -#define ASN1_R_ILLEGAL_NESTED_TAGGING 129 -#define ASN1_R_ILLEGAL_NULL 130 -#define ASN1_R_ILLEGAL_NULL_VALUE 131 -#define ASN1_R_ILLEGAL_OBJECT 132 -#define ASN1_R_ILLEGAL_OPTIONAL_ANY 133 -#define ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE 134 -#define ASN1_R_ILLEGAL_TAGGED_ANY 135 -#define ASN1_R_ILLEGAL_TIME_VALUE 136 -#define ASN1_R_INTEGER_NOT_ASCII_FORMAT 137 -#define ASN1_R_INTEGER_TOO_LARGE_FOR_LONG 138 -#define ASN1_R_INVALID_BIT_STRING_BITS_LEFT 139 -#define ASN1_R_INVALID_BMPSTRING_LENGTH 140 -#define ASN1_R_INVALID_DIGIT 141 -#define ASN1_R_INVALID_MODIFIER 142 -#define ASN1_R_INVALID_NUMBER 143 -#define ASN1_R_INVALID_OBJECT_ENCODING 144 -#define ASN1_R_INVALID_SEPARATOR 145 -#define ASN1_R_INVALID_TIME_FORMAT 146 -#define ASN1_R_INVALID_UNIVERSALSTRING_LENGTH 147 -#define ASN1_R_INVALID_UTF8STRING 148 -#define ASN1_R_LIST_ERROR 149 -#define ASN1_R_MALLOC_FAILURE 150 -#define ASN1_R_MISSING_ASN1_EOS 151 -#define ASN1_R_MISSING_EOC 152 -#define ASN1_R_MISSING_SECOND_NUMBER 153 -#define ASN1_R_MISSING_VALUE 154 -#define ASN1_R_MSTRING_NOT_UNIVERSAL 155 -#define ASN1_R_MSTRING_WRONG_TAG 156 -#define ASN1_R_NESTED_ASN1_ERROR 157 -#define ASN1_R_NESTED_ASN1_STRING 158 -#define ASN1_R_NON_HEX_CHARACTERS 159 -#define ASN1_R_NOT_ASCII_FORMAT 160 -#define ASN1_R_NOT_ENOUGH_DATA 161 -#define ASN1_R_NO_MATCHING_CHOICE_TYPE 162 -#define ASN1_R_NULL_IS_WRONG_LENGTH 163 -#define ASN1_R_OBJECT_NOT_ASCII_FORMAT 164 -#define ASN1_R_ODD_NUMBER_OF_CHARS 165 -#define ASN1_R_SECOND_NUMBER_TOO_LARGE 166 -#define ASN1_R_SEQUENCE_LENGTH_MISMATCH 167 -#define ASN1_R_SEQUENCE_NOT_CONSTRUCTED 168 -#define ASN1_R_SEQUENCE_OR_SET_NEEDS_CONFIG 169 -#define ASN1_R_SHORT_LINE 170 -#define ASN1_R_STREAMING_NOT_SUPPORTED 171 -#define ASN1_R_STRING_TOO_LONG 172 -#define ASN1_R_STRING_TOO_SHORT 173 -#define ASN1_R_TAG_VALUE_TOO_HIGH 174 -#define ASN1_R_TIME_NOT_ASCII_FORMAT 175 -#define ASN1_R_TOO_LONG 176 -#define ASN1_R_TYPE_NOT_CONSTRUCTED 177 -#define ASN1_R_TYPE_NOT_PRIMITIVE 178 -#define ASN1_R_UNEXPECTED_EOC 179 -#define ASN1_R_UNIVERSALSTRING_IS_WRONG_LENGTH 180 -#define ASN1_R_UNKNOWN_FORMAT 181 -#define ASN1_R_UNKNOWN_TAG 182 -#define ASN1_R_UNSUPPORTED_ANY_DEFINED_BY_TYPE 183 -#define ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE 184 -#define ASN1_R_UNSUPPORTED_TYPE 185 -#define ASN1_R_WRONG_TAG 186 -#define ASN1_R_WRONG_TYPE 187 - -#endif diff --git a/third_party/boringssl/include/openssl/asn1_mac.h b/third_party/boringssl/include/openssl/asn1_mac.h deleted file mode 100644 index 49b2a286b7..0000000000 --- a/third_party/boringssl/include/openssl/asn1_mac.h +++ /dev/null @@ -1,76 +0,0 @@ -/* crypto/asn1/asn1_mac.h */ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] - */ - -#ifndef HEADER_ASN1_MAC_H -#define HEADER_ASN1_MAC_H - -#include - -#ifdef __cplusplus -extern "C" { -#endif - - -OPENSSL_EXPORT int asn1_GetSequence(ASN1_const_CTX *c, long *length); - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/third_party/boringssl/include/openssl/asn1t.h b/third_party/boringssl/include/openssl/asn1t.h deleted file mode 100644 index 0f2560b715..0000000000 --- a/third_party/boringssl/include/openssl/asn1t.h +++ /dev/null @@ -1,907 +0,0 @@ -/* asn1t.h */ -/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL - * project 2000. - */ -/* ==================================================================== - * Copyright (c) 2000-2005 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * licensing@OpenSSL.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS 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. - * ==================================================================== - * - * This product includes cryptographic software written by Eric Young - * (eay@cryptsoft.com). This product includes software written by Tim - * Hudson (tjh@cryptsoft.com). - * - */ -#ifndef HEADER_ASN1T_H -#define HEADER_ASN1T_H - -#include -#include - -#ifdef OPENSSL_BUILD_SHLIBCRYPTO -# undef OPENSSL_EXTERN -# define OPENSSL_EXTERN OPENSSL_EXPORT -#endif - -/* ASN1 template defines, structures and functions */ - -#ifdef __cplusplus -extern "C" { -#endif - - -/* Macro to obtain ASN1_ADB pointer from a type (only used internally) */ -#define ASN1_ADB_ptr(iptr) ((const ASN1_ADB *)(iptr)) - - -/* Macros for start and end of ASN1_ITEM definition */ - -#define ASN1_ITEM_start(itname) \ - const ASN1_ITEM itname##_it = { - -#define ASN1_ITEM_end(itname) \ - }; - -/* Macros to aid ASN1 template writing */ - -#define ASN1_ITEM_TEMPLATE(tname) \ - static const ASN1_TEMPLATE tname##_item_tt - -#define ASN1_ITEM_TEMPLATE_END(tname) \ - ;\ - ASN1_ITEM_start(tname) \ - ASN1_ITYPE_PRIMITIVE,\ - -1,\ - &tname##_item_tt,\ - 0,\ - NULL,\ - 0,\ - #tname \ - ASN1_ITEM_end(tname) - - -/* This is a ASN1 type which just embeds a template */ - -/* This pair helps declare a SEQUENCE. We can do: - * - * ASN1_SEQUENCE(stname) = { - * ... SEQUENCE components ... - * } ASN1_SEQUENCE_END(stname) - * - * This will produce an ASN1_ITEM called stname_it - * for a structure called stname. - * - * If you want the same structure but a different - * name then use: - * - * ASN1_SEQUENCE(itname) = { - * ... SEQUENCE components ... - * } ASN1_SEQUENCE_END_name(stname, itname) - * - * This will create an item called itname_it using - * a structure called stname. - */ - -#define ASN1_SEQUENCE(tname) \ - static const ASN1_TEMPLATE tname##_seq_tt[] - -#define ASN1_SEQUENCE_END(stname) ASN1_SEQUENCE_END_name(stname, stname) - -#define ASN1_SEQUENCE_END_name(stname, tname) \ - ;\ - ASN1_ITEM_start(tname) \ - ASN1_ITYPE_SEQUENCE,\ - V_ASN1_SEQUENCE,\ - tname##_seq_tt,\ - sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\ - NULL,\ - sizeof(stname),\ - #stname \ - ASN1_ITEM_end(tname) - -#define ASN1_NDEF_SEQUENCE(tname) \ - ASN1_SEQUENCE(tname) - -#define ASN1_NDEF_SEQUENCE_cb(tname, cb) \ - ASN1_SEQUENCE_cb(tname, cb) - -#define ASN1_SEQUENCE_cb(tname, cb) \ - static const ASN1_AUX tname##_aux = {NULL, 0, 0, cb, 0}; \ - ASN1_SEQUENCE(tname) - -#define ASN1_BROKEN_SEQUENCE(tname) \ - static const ASN1_AUX tname##_aux = {NULL, ASN1_AFLG_BROKEN, 0, 0, 0}; \ - ASN1_SEQUENCE(tname) - -#define ASN1_SEQUENCE_ref(tname, cb) \ - static const ASN1_AUX tname##_aux = {NULL, ASN1_AFLG_REFCOUNT, offsetof(tname, references), cb, 0}; \ - ASN1_SEQUENCE(tname) - -#define ASN1_SEQUENCE_enc(tname, enc, cb) \ - static const ASN1_AUX tname##_aux = {NULL, ASN1_AFLG_ENCODING, 0, cb, offsetof(tname, enc)}; \ - ASN1_SEQUENCE(tname) - -#define ASN1_NDEF_SEQUENCE_END(tname) \ - ;\ - ASN1_ITEM_start(tname) \ - ASN1_ITYPE_NDEF_SEQUENCE,\ - V_ASN1_SEQUENCE,\ - tname##_seq_tt,\ - sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\ - NULL,\ - sizeof(tname),\ - #tname \ - ASN1_ITEM_end(tname) - -#define ASN1_BROKEN_SEQUENCE_END(stname) ASN1_SEQUENCE_END_ref(stname, stname) - -#define ASN1_SEQUENCE_END_enc(stname, tname) ASN1_SEQUENCE_END_ref(stname, tname) - -#define ASN1_SEQUENCE_END_cb(stname, tname) ASN1_SEQUENCE_END_ref(stname, tname) - -#define ASN1_SEQUENCE_END_ref(stname, tname) \ - ;\ - ASN1_ITEM_start(tname) \ - ASN1_ITYPE_SEQUENCE,\ - V_ASN1_SEQUENCE,\ - tname##_seq_tt,\ - sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\ - &tname##_aux,\ - sizeof(stname),\ - #stname \ - ASN1_ITEM_end(tname) - -#define ASN1_NDEF_SEQUENCE_END_cb(stname, tname) \ - ;\ - ASN1_ITEM_start(tname) \ - ASN1_ITYPE_NDEF_SEQUENCE,\ - V_ASN1_SEQUENCE,\ - tname##_seq_tt,\ - sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\ - &tname##_aux,\ - sizeof(stname),\ - #stname \ - ASN1_ITEM_end(tname) - - -/* This pair helps declare a CHOICE type. We can do: - * - * ASN1_CHOICE(chname) = { - * ... CHOICE options ... - * ASN1_CHOICE_END(chname) - * - * This will produce an ASN1_ITEM called chname_it - * for a structure called chname. The structure - * definition must look like this: - * typedef struct { - * int type; - * union { - * ASN1_SOMETHING *opt1; - * ASN1_SOMEOTHER *opt2; - * } value; - * } chname; - * - * the name of the selector must be 'type'. - * to use an alternative selector name use the - * ASN1_CHOICE_END_selector() version. - */ - -#define ASN1_CHOICE(tname) \ - static const ASN1_TEMPLATE tname##_ch_tt[] - -#define ASN1_CHOICE_cb(tname, cb) \ - static const ASN1_AUX tname##_aux = {NULL, 0, 0, cb, 0}; \ - ASN1_CHOICE(tname) - -#define ASN1_CHOICE_END(stname) ASN1_CHOICE_END_name(stname, stname) - -#define ASN1_CHOICE_END_name(stname, tname) ASN1_CHOICE_END_selector(stname, tname, type) - -#define ASN1_CHOICE_END_selector(stname, tname, selname) \ - ;\ - ASN1_ITEM_start(tname) \ - ASN1_ITYPE_CHOICE,\ - offsetof(stname,selname) ,\ - tname##_ch_tt,\ - sizeof(tname##_ch_tt) / sizeof(ASN1_TEMPLATE),\ - NULL,\ - sizeof(stname),\ - #stname \ - ASN1_ITEM_end(tname) - -#define ASN1_CHOICE_END_cb(stname, tname, selname) \ - ;\ - ASN1_ITEM_start(tname) \ - ASN1_ITYPE_CHOICE,\ - offsetof(stname,selname) ,\ - tname##_ch_tt,\ - sizeof(tname##_ch_tt) / sizeof(ASN1_TEMPLATE),\ - &tname##_aux,\ - sizeof(stname),\ - #stname \ - ASN1_ITEM_end(tname) - -/* This helps with the template wrapper form of ASN1_ITEM */ - -#define ASN1_EX_TEMPLATE_TYPE(flags, tag, name, type) { \ - (flags), (tag), 0,\ - #name, ASN1_ITEM_ref(type) } - -/* These help with SEQUENCE or CHOICE components */ - -/* used to declare other types */ - -#define ASN1_EX_TYPE(flags, tag, stname, field, type) { \ - (flags), (tag), offsetof(stname, field),\ - #field, ASN1_ITEM_ref(type) } - -/* used when the structure is combined with the parent */ - -#define ASN1_EX_COMBINE(flags, tag, type) { \ - (flags)|ASN1_TFLG_COMBINE, (tag), 0, NULL, ASN1_ITEM_ref(type) } - -/* implicit and explicit helper macros */ - -#define ASN1_IMP_EX(stname, field, type, tag, ex) \ - ASN1_EX_TYPE(ASN1_TFLG_IMPLICIT | ex, tag, stname, field, type) - -#define ASN1_EXP_EX(stname, field, type, tag, ex) \ - ASN1_EX_TYPE(ASN1_TFLG_EXPLICIT | ex, tag, stname, field, type) - -/* Any defined by macros: the field used is in the table itself */ - -#define ASN1_ADB_OBJECT(tblname) { ASN1_TFLG_ADB_OID, -1, 0, #tblname, (const ASN1_ITEM *)&(tblname##_adb) } -#define ASN1_ADB_INTEGER(tblname) { ASN1_TFLG_ADB_INT, -1, 0, #tblname, (const ASN1_ITEM *)&(tblname##_adb) } -/* Plain simple type */ -#define ASN1_SIMPLE(stname, field, type) ASN1_EX_TYPE(0,0, stname, field, type) - -/* OPTIONAL simple type */ -#define ASN1_OPT(stname, field, type) ASN1_EX_TYPE(ASN1_TFLG_OPTIONAL, 0, stname, field, type) - -/* IMPLICIT tagged simple type */ -#define ASN1_IMP(stname, field, type, tag) ASN1_IMP_EX(stname, field, type, tag, 0) - -/* IMPLICIT tagged OPTIONAL simple type */ -#define ASN1_IMP_OPT(stname, field, type, tag) ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL) - -/* Same as above but EXPLICIT */ - -#define ASN1_EXP(stname, field, type, tag) ASN1_EXP_EX(stname, field, type, tag, 0) -#define ASN1_EXP_OPT(stname, field, type, tag) ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL) - -/* SEQUENCE OF type */ -#define ASN1_SEQUENCE_OF(stname, field, type) \ - ASN1_EX_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, stname, field, type) - -/* OPTIONAL SEQUENCE OF */ -#define ASN1_SEQUENCE_OF_OPT(stname, field, type) \ - ASN1_EX_TYPE(ASN1_TFLG_SEQUENCE_OF|ASN1_TFLG_OPTIONAL, 0, stname, field, type) - -/* Same as above but for SET OF */ - -#define ASN1_SET_OF(stname, field, type) \ - ASN1_EX_TYPE(ASN1_TFLG_SET_OF, 0, stname, field, type) - -#define ASN1_SET_OF_OPT(stname, field, type) \ - ASN1_EX_TYPE(ASN1_TFLG_SET_OF|ASN1_TFLG_OPTIONAL, 0, stname, field, type) - -/* Finally compound types of SEQUENCE, SET, IMPLICIT, EXPLICIT and OPTIONAL */ - -#define ASN1_IMP_SET_OF(stname, field, type, tag) \ - ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_SET_OF) - -#define ASN1_EXP_SET_OF(stname, field, type, tag) \ - ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_SET_OF) - -#define ASN1_IMP_SET_OF_OPT(stname, field, type, tag) \ - ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_SET_OF|ASN1_TFLG_OPTIONAL) - -#define ASN1_EXP_SET_OF_OPT(stname, field, type, tag) \ - ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_SET_OF|ASN1_TFLG_OPTIONAL) - -#define ASN1_IMP_SEQUENCE_OF(stname, field, type, tag) \ - ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_SEQUENCE_OF) - -#define ASN1_IMP_SEQUENCE_OF_OPT(stname, field, type, tag) \ - ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_SEQUENCE_OF|ASN1_TFLG_OPTIONAL) - -#define ASN1_EXP_SEQUENCE_OF(stname, field, type, tag) \ - ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_SEQUENCE_OF) - -#define ASN1_EXP_SEQUENCE_OF_OPT(stname, field, type, tag) \ - ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_SEQUENCE_OF|ASN1_TFLG_OPTIONAL) - -/* EXPLICIT using indefinite length constructed form */ -#define ASN1_NDEF_EXP(stname, field, type, tag) \ - ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_NDEF) - -/* EXPLICIT OPTIONAL using indefinite length constructed form */ -#define ASN1_NDEF_EXP_OPT(stname, field, type, tag) \ - ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL|ASN1_TFLG_NDEF) - -/* Macros for the ASN1_ADB structure */ - -#define ASN1_ADB(name) \ - static const ASN1_ADB_TABLE name##_adbtbl[] - -#define ASN1_ADB_END(name, flags, field, app_table, def, none) \ - ;\ - static const ASN1_ADB name##_adb = {\ - flags,\ - offsetof(name, field),\ - app_table,\ - name##_adbtbl,\ - sizeof(name##_adbtbl) / sizeof(ASN1_ADB_TABLE),\ - def,\ - none\ - } - -#define ADB_ENTRY(val, template) {val, template} - -#define ASN1_ADB_TEMPLATE(name) \ - static const ASN1_TEMPLATE name##_tt - -/* This is the ASN1 template structure that defines - * a wrapper round the actual type. It determines the - * actual position of the field in the value structure, - * various flags such as OPTIONAL and the field name. - */ - -struct ASN1_TEMPLATE_st { -unsigned long flags; /* Various flags */ -long tag; /* tag, not used if no tagging */ -unsigned long offset; /* Offset of this field in structure */ -#ifndef NO_ASN1_FIELD_NAMES -const char *field_name; /* Field name */ -#endif -ASN1_ITEM_EXP *item; /* Relevant ASN1_ITEM or ASN1_ADB */ -}; - -/* Macro to extract ASN1_ITEM and ASN1_ADB pointer from ASN1_TEMPLATE */ - -#define ASN1_TEMPLATE_item(t) (t->item_ptr) -#define ASN1_TEMPLATE_adb(t) (t->item_ptr) - -typedef struct ASN1_ADB_TABLE_st ASN1_ADB_TABLE; -typedef struct ASN1_ADB_st ASN1_ADB; - -struct ASN1_ADB_st { - unsigned long flags; /* Various flags */ - unsigned long offset; /* Offset of selector field */ - STACK_OF(ASN1_ADB_TABLE) **app_items; /* Application defined items */ - const ASN1_ADB_TABLE *tbl; /* Table of possible types */ - long tblcount; /* Number of entries in tbl */ - const ASN1_TEMPLATE *default_tt; /* Type to use if no match */ - const ASN1_TEMPLATE *null_tt; /* Type to use if selector is NULL */ -}; - -struct ASN1_ADB_TABLE_st { - long value; /* NID for an object or value for an int */ - const ASN1_TEMPLATE tt; /* item for this value */ -}; - -/* template flags */ - -/* Field is optional */ -#define ASN1_TFLG_OPTIONAL (0x1) - -/* Field is a SET OF */ -#define ASN1_TFLG_SET_OF (0x1 << 1) - -/* Field is a SEQUENCE OF */ -#define ASN1_TFLG_SEQUENCE_OF (0x2 << 1) - -/* Special case: this refers to a SET OF that - * will be sorted into DER order when encoded *and* - * the corresponding STACK will be modified to match - * the new order. - */ -#define ASN1_TFLG_SET_ORDER (0x3 << 1) - -/* Mask for SET OF or SEQUENCE OF */ -#define ASN1_TFLG_SK_MASK (0x3 << 1) - -/* These flags mean the tag should be taken from the - * tag field. If EXPLICIT then the underlying type - * is used for the inner tag. - */ - -/* IMPLICIT tagging */ -#define ASN1_TFLG_IMPTAG (0x1 << 3) - - -/* EXPLICIT tagging, inner tag from underlying type */ -#define ASN1_TFLG_EXPTAG (0x2 << 3) - -#define ASN1_TFLG_TAG_MASK (0x3 << 3) - -/* context specific IMPLICIT */ -#define ASN1_TFLG_IMPLICIT ASN1_TFLG_IMPTAG|ASN1_TFLG_CONTEXT - -/* context specific EXPLICIT */ -#define ASN1_TFLG_EXPLICIT ASN1_TFLG_EXPTAG|ASN1_TFLG_CONTEXT - -/* If tagging is in force these determine the - * type of tag to use. Otherwise the tag is - * determined by the underlying type. These - * values reflect the actual octet format. - */ - -/* Universal tag */ -#define ASN1_TFLG_UNIVERSAL (0x0<<6) -/* Application tag */ -#define ASN1_TFLG_APPLICATION (0x1<<6) -/* Context specific tag */ -#define ASN1_TFLG_CONTEXT (0x2<<6) -/* Private tag */ -#define ASN1_TFLG_PRIVATE (0x3<<6) - -#define ASN1_TFLG_TAG_CLASS (0x3<<6) - -/* These are for ANY DEFINED BY type. In this case - * the 'item' field points to an ASN1_ADB structure - * which contains a table of values to decode the - * relevant type - */ - -#define ASN1_TFLG_ADB_MASK (0x3<<8) - -#define ASN1_TFLG_ADB_OID (0x1<<8) - -#define ASN1_TFLG_ADB_INT (0x1<<9) - -/* This flag means a parent structure is passed - * instead of the field: this is useful is a - * SEQUENCE is being combined with a CHOICE for - * example. Since this means the structure and - * item name will differ we need to use the - * ASN1_CHOICE_END_name() macro for example. - */ - -#define ASN1_TFLG_COMBINE (0x1<<10) - -/* This flag when present in a SEQUENCE OF, SET OF - * or EXPLICIT causes indefinite length constructed - * encoding to be used if required. - */ - -#define ASN1_TFLG_NDEF (0x1<<11) - -/* This is the actual ASN1 item itself */ - -struct ASN1_ITEM_st { -char itype; /* The item type, primitive, SEQUENCE, CHOICE or extern */ -long utype; /* underlying type */ -const ASN1_TEMPLATE *templates; /* If SEQUENCE or CHOICE this contains the contents */ -long tcount; /* Number of templates if SEQUENCE or CHOICE */ -const void *funcs; /* functions that handle this type */ -long size; /* Structure size (usually)*/ -#ifndef NO_ASN1_FIELD_NAMES -const char *sname; /* Structure name */ -#endif -}; - -/* These are values for the itype field and - * determine how the type is interpreted. - * - * For PRIMITIVE types the underlying type - * determines the behaviour if items is NULL. - * - * Otherwise templates must contain a single - * template and the type is treated in the - * same way as the type specified in the template. - * - * For SEQUENCE types the templates field points - * to the members, the size field is the - * structure size. - * - * For CHOICE types the templates field points - * to each possible member (typically a union) - * and the 'size' field is the offset of the - * selector. - * - * The 'funcs' field is used for application - * specific functions. - * - * For COMPAT types the funcs field gives a - * set of functions that handle this type, this - * supports the old d2i, i2d convention. - * - * The EXTERN type uses a new style d2i/i2d. - * The new style should be used where possible - * because it avoids things like the d2i IMPLICIT - * hack. - * - * MSTRING is a multiple string type, it is used - * for a CHOICE of character strings where the - * actual strings all occupy an ASN1_STRING - * structure. In this case the 'utype' field - * has a special meaning, it is used as a mask - * of acceptable types using the B_ASN1 constants. - * - * NDEF_SEQUENCE is the same as SEQUENCE except - * that it will use indefinite length constructed - * encoding if requested. - * - */ - -#define ASN1_ITYPE_PRIMITIVE 0x0 - -#define ASN1_ITYPE_SEQUENCE 0x1 - -#define ASN1_ITYPE_CHOICE 0x2 - -#define ASN1_ITYPE_COMPAT 0x3 - -#define ASN1_ITYPE_EXTERN 0x4 - -#define ASN1_ITYPE_MSTRING 0x5 - -#define ASN1_ITYPE_NDEF_SEQUENCE 0x6 - -/* Cache for ASN1 tag and length, so we - * don't keep re-reading it for things - * like CHOICE - */ - -struct ASN1_TLC_st{ - char valid; /* Values below are valid */ - int ret; /* return value */ - long plen; /* length */ - int ptag; /* class value */ - int pclass; /* class value */ - int hdrlen; /* header length */ -}; - -/* Typedefs for ASN1 function pointers */ - -typedef ASN1_VALUE * ASN1_new_func(void); -typedef void ASN1_free_func(ASN1_VALUE *a); -typedef ASN1_VALUE * ASN1_d2i_func(ASN1_VALUE **a, const unsigned char ** in, long length); -typedef int ASN1_i2d_func(ASN1_VALUE * a, unsigned char **in); - -typedef int ASN1_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_ITEM *it, - int tag, int aclass, char opt, ASN1_TLC *ctx); - -typedef int ASN1_ex_i2d(ASN1_VALUE **pval, unsigned char **out, const ASN1_ITEM *it, int tag, int aclass); -typedef int ASN1_ex_new_func(ASN1_VALUE **pval, const ASN1_ITEM *it); -typedef void ASN1_ex_free_func(ASN1_VALUE **pval, const ASN1_ITEM *it); - -typedef int ASN1_ex_print_func(BIO *out, ASN1_VALUE **pval, - int indent, const char *fname, - const ASN1_PCTX *pctx); - -typedef int ASN1_primitive_i2c(ASN1_VALUE **pval, unsigned char *cont, int *putype, const ASN1_ITEM *it); -typedef int ASN1_primitive_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len, int utype, char *free_cont, const ASN1_ITEM *it); -typedef int ASN1_primitive_print(BIO *out, ASN1_VALUE **pval, const ASN1_ITEM *it, int indent, const ASN1_PCTX *pctx); - -typedef struct ASN1_COMPAT_FUNCS_st { - ASN1_new_func *asn1_new; - ASN1_free_func *asn1_free; - ASN1_d2i_func *asn1_d2i; - ASN1_i2d_func *asn1_i2d; -} ASN1_COMPAT_FUNCS; - -typedef struct ASN1_EXTERN_FUNCS_st { - void *app_data; - ASN1_ex_new_func *asn1_ex_new; - ASN1_ex_free_func *asn1_ex_free; - ASN1_ex_free_func *asn1_ex_clear; - ASN1_ex_d2i *asn1_ex_d2i; - ASN1_ex_i2d *asn1_ex_i2d; - ASN1_ex_print_func *asn1_ex_print; -} ASN1_EXTERN_FUNCS; - -typedef struct ASN1_PRIMITIVE_FUNCS_st { - void *app_data; - unsigned long flags; - ASN1_ex_new_func *prim_new; - ASN1_ex_free_func *prim_free; - ASN1_ex_free_func *prim_clear; - ASN1_primitive_c2i *prim_c2i; - ASN1_primitive_i2c *prim_i2c; - ASN1_primitive_print *prim_print; -} ASN1_PRIMITIVE_FUNCS; - -/* This is the ASN1_AUX structure: it handles various - * miscellaneous requirements. For example the use of - * reference counts and an informational callback. - * - * The "informational callback" is called at various - * points during the ASN1 encoding and decoding. It can - * be used to provide minor customisation of the structures - * used. This is most useful where the supplied routines - * *almost* do the right thing but need some extra help - * at a few points. If the callback returns zero then - * it is assumed a fatal error has occurred and the - * main operation should be abandoned. - * - * If major changes in the default behaviour are required - * then an external type is more appropriate. - */ - -typedef int ASN1_aux_cb(int operation, ASN1_VALUE **in, const ASN1_ITEM *it, - void *exarg); - -typedef struct ASN1_AUX_st { - void *app_data; - int flags; - int ref_offset; /* Offset of reference value */ - ASN1_aux_cb *asn1_cb; - int enc_offset; /* Offset of ASN1_ENCODING structure */ -} ASN1_AUX; - -/* For print related callbacks exarg points to this structure */ -typedef struct ASN1_PRINT_ARG_st { - BIO *out; - int indent; - const ASN1_PCTX *pctx; -} ASN1_PRINT_ARG; - -/* For streaming related callbacks exarg points to this structure */ -typedef struct ASN1_STREAM_ARG_st { - /* BIO to stream through */ - BIO *out; - /* BIO with filters appended */ - BIO *ndef_bio; - /* Streaming I/O boundary */ - unsigned char **boundary; -} ASN1_STREAM_ARG; - -/* Flags in ASN1_AUX */ - -/* Use a reference count */ -#define ASN1_AFLG_REFCOUNT 1 -/* Save the encoding of structure (useful for signatures) */ -#define ASN1_AFLG_ENCODING 2 -/* The Sequence length is invalid */ -#define ASN1_AFLG_BROKEN 4 - -/* operation values for asn1_cb */ - -#define ASN1_OP_NEW_PRE 0 -#define ASN1_OP_NEW_POST 1 -#define ASN1_OP_FREE_PRE 2 -#define ASN1_OP_FREE_POST 3 -#define ASN1_OP_D2I_PRE 4 -#define ASN1_OP_D2I_POST 5 -#define ASN1_OP_I2D_PRE 6 -#define ASN1_OP_I2D_POST 7 -#define ASN1_OP_PRINT_PRE 8 -#define ASN1_OP_PRINT_POST 9 -#define ASN1_OP_STREAM_PRE 10 -#define ASN1_OP_STREAM_POST 11 -#define ASN1_OP_DETACHED_PRE 12 -#define ASN1_OP_DETACHED_POST 13 - -/* Macro to implement a primitive type */ -#define IMPLEMENT_ASN1_TYPE(stname) IMPLEMENT_ASN1_TYPE_ex(stname, stname, 0) -#define IMPLEMENT_ASN1_TYPE_ex(itname, vname, ex) \ - ASN1_ITEM_start(itname) \ - ASN1_ITYPE_PRIMITIVE, V_##vname, NULL, 0, NULL, ex, #itname \ - ASN1_ITEM_end(itname) - -/* Macro to implement a multi string type */ -#define IMPLEMENT_ASN1_MSTRING(itname, mask) \ - ASN1_ITEM_start(itname) \ - ASN1_ITYPE_MSTRING, mask, NULL, 0, NULL, sizeof(ASN1_STRING), #itname \ - ASN1_ITEM_end(itname) - -/* Macro to implement an ASN1_ITEM in terms of old style funcs */ - -#define IMPLEMENT_COMPAT_ASN1(sname) IMPLEMENT_COMPAT_ASN1_type(sname, V_ASN1_SEQUENCE) - -#define IMPLEMENT_COMPAT_ASN1_type(sname, tag) \ - static const ASN1_COMPAT_FUNCS sname##_ff = { \ - (ASN1_new_func *)sname##_new, \ - (ASN1_free_func *)sname##_free, \ - (ASN1_d2i_func *)d2i_##sname, \ - (ASN1_i2d_func *)i2d_##sname, \ - }; \ - ASN1_ITEM_start(sname) \ - ASN1_ITYPE_COMPAT, \ - tag, \ - NULL, \ - 0, \ - &sname##_ff, \ - 0, \ - #sname \ - ASN1_ITEM_end(sname) - -#define IMPLEMENT_EXTERN_ASN1(sname, tag, fptrs) \ - ASN1_ITEM_start(sname) \ - ASN1_ITYPE_EXTERN, \ - tag, \ - NULL, \ - 0, \ - &fptrs, \ - 0, \ - #sname \ - ASN1_ITEM_end(sname) - -/* Macro to implement standard functions in terms of ASN1_ITEM structures */ - -#define IMPLEMENT_ASN1_FUNCTIONS(stname) IMPLEMENT_ASN1_FUNCTIONS_fname(stname, stname, stname) - -#define IMPLEMENT_ASN1_FUNCTIONS_name(stname, itname) IMPLEMENT_ASN1_FUNCTIONS_fname(stname, itname, itname) - -#define IMPLEMENT_ASN1_FUNCTIONS_ENCODE_name(stname, itname) \ - IMPLEMENT_ASN1_FUNCTIONS_ENCODE_fname(stname, itname, itname) - -#define IMPLEMENT_STATIC_ASN1_ALLOC_FUNCTIONS(stname) \ - IMPLEMENT_ASN1_ALLOC_FUNCTIONS_pfname(static, stname, stname, stname) - -#define IMPLEMENT_ASN1_ALLOC_FUNCTIONS(stname) \ - IMPLEMENT_ASN1_ALLOC_FUNCTIONS_fname(stname, stname, stname) - -#define IMPLEMENT_ASN1_ALLOC_FUNCTIONS_pfname(pre, stname, itname, fname) \ - pre stname *fname##_new(void) \ - { \ - return (stname *)ASN1_item_new(ASN1_ITEM_rptr(itname)); \ - } \ - pre void fname##_free(stname *a) \ - { \ - ASN1_item_free((ASN1_VALUE *)a, ASN1_ITEM_rptr(itname)); \ - } - -#define IMPLEMENT_ASN1_ALLOC_FUNCTIONS_fname(stname, itname, fname) \ - stname *fname##_new(void) \ - { \ - return (stname *)ASN1_item_new(ASN1_ITEM_rptr(itname)); \ - } \ - void fname##_free(stname *a) \ - { \ - ASN1_item_free((ASN1_VALUE *)a, ASN1_ITEM_rptr(itname)); \ - } - -#define IMPLEMENT_ASN1_FUNCTIONS_fname(stname, itname, fname) \ - IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(stname, itname, fname) \ - IMPLEMENT_ASN1_ALLOC_FUNCTIONS_fname(stname, itname, fname) - -#define IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(stname, itname, fname) \ - stname *d2i_##fname(stname **a, const unsigned char **in, long len) \ - { \ - return (stname *)ASN1_item_d2i((ASN1_VALUE **)a, in, len, ASN1_ITEM_rptr(itname));\ - } \ - int i2d_##fname(stname *a, unsigned char **out) \ - { \ - return ASN1_item_i2d((ASN1_VALUE *)a, out, ASN1_ITEM_rptr(itname));\ - } - -#define IMPLEMENT_ASN1_NDEF_FUNCTION(stname) \ - int i2d_##stname##_NDEF(stname *a, unsigned char **out) \ - { \ - return ASN1_item_ndef_i2d((ASN1_VALUE *)a, out, ASN1_ITEM_rptr(stname));\ - } - -/* This includes evil casts to remove const: they will go away when full - * ASN1 constification is done. - */ -#define IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(stname, itname, fname) \ - stname *d2i_##fname(stname **a, const unsigned char **in, long len) \ - { \ - return (stname *)ASN1_item_d2i((ASN1_VALUE **)a, in, len, ASN1_ITEM_rptr(itname));\ - } \ - int i2d_##fname(const stname *a, unsigned char **out) \ - { \ - return ASN1_item_i2d((ASN1_VALUE *)a, out, ASN1_ITEM_rptr(itname));\ - } - -#define IMPLEMENT_ASN1_DUP_FUNCTION(stname) \ - stname * stname##_dup(stname *x) \ - { \ - return ASN1_item_dup(ASN1_ITEM_rptr(stname), x); \ - } - -#define IMPLEMENT_ASN1_PRINT_FUNCTION(stname) \ - IMPLEMENT_ASN1_PRINT_FUNCTION_fname(stname, stname, stname) - -#define IMPLEMENT_ASN1_PRINT_FUNCTION_fname(stname, itname, fname) \ - int fname##_print_ctx(BIO *out, stname *x, int indent, \ - const ASN1_PCTX *pctx) \ - { \ - return ASN1_item_print(out, (ASN1_VALUE *)x, indent, \ - ASN1_ITEM_rptr(itname), pctx); \ - } - -#define IMPLEMENT_ASN1_FUNCTIONS_const(name) \ - IMPLEMENT_ASN1_FUNCTIONS_const_fname(name, name, name) - -#define IMPLEMENT_ASN1_FUNCTIONS_const_fname(stname, itname, fname) \ - IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(stname, itname, fname) \ - IMPLEMENT_ASN1_ALLOC_FUNCTIONS_fname(stname, itname, fname) - -/* external definitions for primitive types */ - -DECLARE_ASN1_ITEM(ASN1_BOOLEAN) -DECLARE_ASN1_ITEM(ASN1_TBOOLEAN) -DECLARE_ASN1_ITEM(ASN1_FBOOLEAN) -DECLARE_ASN1_ITEM(ASN1_SEQUENCE) -DECLARE_ASN1_ITEM(CBIGNUM) -DECLARE_ASN1_ITEM(BIGNUM) -DECLARE_ASN1_ITEM(LONG) -DECLARE_ASN1_ITEM(ZLONG) - -DECLARE_STACK_OF(ASN1_VALUE) - -/* Functions used internally by the ASN1 code */ - -int ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it); -void ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it); -int ASN1_template_new(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt); -int ASN1_primitive_new(ASN1_VALUE **pval, const ASN1_ITEM *it); - -void ASN1_template_free(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt); -int ASN1_template_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_TEMPLATE *tt); -int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_ITEM *it, - int tag, int aclass, char opt, ASN1_TLC *ctx); - -int ASN1_item_ex_i2d(ASN1_VALUE **pval, unsigned char **out, const ASN1_ITEM *it, int tag, int aclass); -int ASN1_template_i2d(ASN1_VALUE **pval, unsigned char **out, const ASN1_TEMPLATE *tt); -void ASN1_primitive_free(ASN1_VALUE **pval, const ASN1_ITEM *it); - -int asn1_ex_i2c(ASN1_VALUE **pval, unsigned char *cont, int *putype, const ASN1_ITEM *it); -int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len, int utype, char *free_cont, const ASN1_ITEM *it); - -int asn1_get_choice_selector(ASN1_VALUE **pval, const ASN1_ITEM *it); -int asn1_set_choice_selector(ASN1_VALUE **pval, int value, const ASN1_ITEM *it); - -ASN1_VALUE ** asn1_get_field_ptr(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt); - -const ASN1_TEMPLATE *asn1_do_adb(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt, int nullerr); - -void asn1_refcount_set_one(ASN1_VALUE **pval, const ASN1_ITEM *it); -int asn1_refcount_dec_and_test_zero(ASN1_VALUE **pval, const ASN1_ITEM *it); - -void asn1_enc_init(ASN1_VALUE **pval, const ASN1_ITEM *it); -void asn1_enc_free(ASN1_VALUE **pval, const ASN1_ITEM *it); -int asn1_enc_restore(int *len, unsigned char **out, ASN1_VALUE **pval, const ASN1_ITEM *it); -int asn1_enc_save(ASN1_VALUE **pval, const unsigned char *in, int inlen, const ASN1_ITEM *it); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/third_party/boringssl/include/openssl/base.h b/third_party/boringssl/include/openssl/base.h deleted file mode 100644 index b769ad5348..0000000000 --- a/third_party/boringssl/include/openssl/base.h +++ /dev/null @@ -1,233 +0,0 @@ -/* ==================================================================== - * Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * openssl-core@openssl.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.openssl.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS 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. - * ==================================================================== - * - * This product includes cryptographic software written by Eric Young - * (eay@cryptsoft.com). This product includes software written by Tim - * Hudson (tjh@cryptsoft.com). */ - -#ifndef OPENSSL_HEADER_BASE_H -#define OPENSSL_HEADER_BASE_H - - -/* This file should be the first included by all BoringSSL headers. */ - -#include -#include -#include - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -#if defined(__x86_64) || defined(_M_AMD64) || defined(_M_X64) -#define OPENSSL_64_BIT -#define OPENSSL_X86_64 -#elif defined(__x86) || defined(__i386) || defined(__i386__) || defined(_M_IX86) -#define OPENSSL_32_BIT -#define OPENSSL_X86 -#elif defined(__aarch64__) -#define OPENSSL_64_BIT -#define OPENSSL_AARCH64 -#elif defined(__arm) || defined(__arm__) || defined(_M_ARM) -#define OPENSSL_32_BIT -#define OPENSSL_ARM -#elif defined(__aarch64__) -#define OPENSSL_64_BIT -#define OPENSSL_AARCH64 -#elif defined(__mips__) && !defined(__LP64__) -#define OPENSSL_32_BIT -#define OPENSSL_MIPS -#elif defined(__mips__) && defined(__LP64__) -#define OPENSSL_64_BIT -#define OPENSSL_MIPS64 -#elif defined(__pnacl__) -#define OPENSSL_32_BIT -#define OPENSSL_PNACL -#else -#error "Unknown target CPU" -#endif - -#if defined(__APPLE__) -#define OPENSSL_APPLE -#endif - -#if defined(WIN32) || defined(_WIN32) -#define OPENSSL_WINDOWS -#endif - -#if defined(TRUSTY) -#define OPENSSL_TRUSTY -#define OPENSSL_NO_THREADS -#endif - -#define OPENSSL_IS_BORINGSSL -#define OPENSSL_VERSION_NUMBER 0x10002000 - -#if defined(BORINGSSL_SHARED_LIBRARY) - -#if defined(OPENSSL_WINDOWS) - -#if defined(BORINGSSL_IMPLEMENTATION) -#define OPENSSL_EXPORT __declspec(dllexport) -#else -#define OPENSSL_EXPORT __declspec(dllimport) -#endif - -#else /* defined(OPENSSL_WINDOWS) */ - -#if defined(BORINGSSL_IMPLEMENTATION) -#define OPENSSL_EXPORT __attribute__((visibility("default"))) -#else -#define OPENSSL_EXPORT -#endif - -#endif /* defined(OPENSSL_WINDOWS) */ - -#else /* defined(BORINGSSL_SHARED_LIBRARY) */ - -#define OPENSSL_EXPORT - -#endif /* defined(BORINGSSL_SHARED_LIBRARY) */ - -/* CRYPTO_THREADID is a dummy value. */ -typedef int CRYPTO_THREADID; - -typedef int ASN1_BOOLEAN; -typedef int ASN1_NULL; -typedef struct ASN1_ITEM_st ASN1_ITEM; -typedef struct asn1_object_st ASN1_OBJECT; -typedef struct asn1_pctx_st ASN1_PCTX; -typedef struct asn1_string_st ASN1_BIT_STRING; -typedef struct asn1_string_st ASN1_BMPSTRING; -typedef struct asn1_string_st ASN1_ENUMERATED; -typedef struct asn1_string_st ASN1_GENERALIZEDTIME; -typedef struct asn1_string_st ASN1_GENERALSTRING; -typedef struct asn1_string_st ASN1_IA5STRING; -typedef struct asn1_string_st ASN1_INTEGER; -typedef struct asn1_string_st ASN1_OCTET_STRING; -typedef struct asn1_string_st ASN1_PRINTABLESTRING; -typedef struct asn1_string_st ASN1_STRING; -typedef struct asn1_string_st ASN1_T61STRING; -typedef struct asn1_string_st ASN1_TIME; -typedef struct asn1_string_st ASN1_UNIVERSALSTRING; -typedef struct asn1_string_st ASN1_UTCTIME; -typedef struct asn1_string_st ASN1_UTF8STRING; -typedef struct asn1_string_st ASN1_VISIBLESTRING; - -typedef struct AUTHORITY_KEYID_st AUTHORITY_KEYID; -typedef struct DIST_POINT_st DIST_POINT; -typedef struct ISSUING_DIST_POINT_st ISSUING_DIST_POINT; -typedef struct NAME_CONSTRAINTS_st NAME_CONSTRAINTS; -typedef struct X509_POLICY_CACHE_st X509_POLICY_CACHE; -typedef struct X509_POLICY_LEVEL_st X509_POLICY_LEVEL; -typedef struct X509_POLICY_NODE_st X509_POLICY_NODE; -typedef struct X509_POLICY_TREE_st X509_POLICY_TREE; -typedef struct X509_algor_st X509_ALGOR; -typedef struct X509_crl_st X509_CRL; -typedef struct X509_pubkey_st X509_PUBKEY; -typedef struct bignum_ctx BN_CTX; -typedef struct bignum_st BIGNUM; -typedef struct bio_method_st BIO_METHOD; -typedef struct bio_st BIO; -typedef struct bn_gencb_st BN_GENCB; -typedef struct bn_mont_ctx_st BN_MONT_CTX; -typedef struct buf_mem_st BUF_MEM; -typedef struct cbb_st CBB; -typedef struct cbs_st CBS; -typedef struct cmac_ctx_st CMAC_CTX; -typedef struct conf_st CONF; -typedef struct conf_value_st CONF_VALUE; -typedef struct dh_method DH_METHOD; -typedef struct dh_st DH; -typedef struct dsa_method DSA_METHOD; -typedef struct dsa_st DSA; -typedef struct ec_key_st EC_KEY; -typedef struct ecdsa_method_st ECDSA_METHOD; -typedef struct ecdsa_sig_st ECDSA_SIG; -typedef struct engine_st ENGINE; -typedef struct env_md_ctx_st EVP_MD_CTX; -typedef struct env_md_st EVP_MD; -typedef struct evp_aead_st EVP_AEAD; -typedef struct evp_cipher_ctx_st EVP_CIPHER_CTX; -typedef struct evp_cipher_st EVP_CIPHER; -typedef struct evp_pkey_asn1_method_st EVP_PKEY_ASN1_METHOD; -typedef struct evp_pkey_ctx_st EVP_PKEY_CTX; -typedef struct evp_pkey_method_st EVP_PKEY_METHOD; -typedef struct evp_pkey_st EVP_PKEY; -typedef struct hmac_ctx_st HMAC_CTX; -typedef struct md4_state_st MD4_CTX; -typedef struct md5_state_st MD5_CTX; -typedef struct pkcs8_priv_key_info_st PKCS8_PRIV_KEY_INFO; -typedef struct pkcs12_st PKCS12; -typedef struct rand_meth_st RAND_METHOD; -typedef struct rc4_key_st RC4_KEY; -typedef struct rsa_meth_st RSA_METHOD; -typedef struct rsa_st RSA; -typedef struct sha256_state_st SHA256_CTX; -typedef struct sha512_state_st SHA512_CTX; -typedef struct sha_state_st SHA_CTX; -typedef struct ssl_ctx_st SSL_CTX; -typedef struct ssl_st SSL; -typedef struct st_ERR_FNS ERR_FNS; -typedef struct v3_ext_ctx X509V3_CTX; -typedef struct x509_crl_method_st X509_CRL_METHOD; -typedef struct x509_revoked_st X509_REVOKED; -typedef struct x509_st X509; -typedef struct x509_store_ctx_st X509_STORE_CTX; -typedef struct x509_store_st X509_STORE; -typedef void *OPENSSL_BLOCK; - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_BASE_H */ diff --git a/third_party/boringssl/include/openssl/base64.h b/third_party/boringssl/include/openssl/base64.h deleted file mode 100644 index 7aee9907f9..0000000000 --- a/third_party/boringssl/include/openssl/base64.h +++ /dev/null @@ -1,179 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] */ - -#ifndef OPENSSL_HEADER_BASE64_H -#define OPENSSL_HEADER_BASE64_H - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* base64 functions. - * - * For historical reasons, these functions have the EVP_ prefix but just do - * base64 encoding and decoding. */ - - -typedef struct evp_encode_ctx_st EVP_ENCODE_CTX; - - -/* Encoding */ - -/* EVP_EncodeInit initialises |*ctx|, which is typically stack - * allocated, for an encoding operation. - * - * NOTE: The encoding operation breaks its output with newlines every - * 64 characters of output (48 characters of input). Use - * EVP_EncodeBlock to encode raw base64. */ -OPENSSL_EXPORT void EVP_EncodeInit(EVP_ENCODE_CTX *ctx); - -/* EVP_EncodeUpdate encodes |in_len| bytes from |in| and writes an encoded - * version of them to |out| and sets |*out_len| to the number of bytes written. - * Some state may be contained in |ctx| so |EVP_EncodeFinal| must be used to - * flush it before using the encoded data. */ -OPENSSL_EXPORT void EVP_EncodeUpdate(EVP_ENCODE_CTX *ctx, uint8_t *out, - int *out_len, const uint8_t *in, - size_t in_len); - -/* EVP_EncodeFinal flushes any remaining output bytes from |ctx| to |out| and - * sets |*out_len| to the number of bytes written. */ -OPENSSL_EXPORT void EVP_EncodeFinal(EVP_ENCODE_CTX *ctx, uint8_t *out, - int *out_len); - -/* EVP_EncodeBlock encodes |src_len| bytes from |src| and writes the - * result to |dst| with a trailing NUL. It returns the number of bytes - * written, not including this trailing NUL. */ -OPENSSL_EXPORT size_t EVP_EncodeBlock(uint8_t *dst, const uint8_t *src, - size_t src_len); - -/* EVP_EncodedLength sets |*out_len| to the number of bytes that will be needed - * to call |EVP_EncodeBlock| on an input of length |len|. This includes the - * final NUL that |EVP_EncodeBlock| writes. It returns one on success or zero - * on error. */ -OPENSSL_EXPORT int EVP_EncodedLength(size_t *out_len, size_t len); - - -/* Decoding */ - -/* EVP_DecodedLength sets |*out_len| to the maximum number of bytes - * that will be needed to call |EVP_DecodeBase64| on an input of - * length |len|. */ -OPENSSL_EXPORT int EVP_DecodedLength(size_t *out_len, size_t len); - -/* EVP_DecodeBase64 decodes |in_len| bytes from base64 and writes - * |*out_len| bytes to |out|. |max_out| is the size of the output - * buffer. If it is not enough for the maximum output size, the - * operation fails. */ -OPENSSL_EXPORT int EVP_DecodeBase64(uint8_t *out, size_t *out_len, - size_t max_out, const uint8_t *in, - size_t in_len); - -/* EVP_DecodeInit initialises |*ctx|, which is typically stack allocated, for - * a decoding operation. - * - * TODO(davidben): This isn't a straight-up base64 decode either. Document - * and/or fix exactly what's going on here; maximum line length and such. */ -OPENSSL_EXPORT void EVP_DecodeInit(EVP_ENCODE_CTX *ctx); - -/* EVP_DecodeUpdate decodes |in_len| bytes from |in| and writes the decoded - * data to |out| and sets |*out_len| to the number of bytes written. Some state - * may be contained in |ctx| so |EVP_DecodeFinal| must be used to flush it - * before using the encoded data. - * - * It returns -1 on error, one if a full line of input was processed and zero - * if the line was short (i.e. it was the last line). */ -OPENSSL_EXPORT int EVP_DecodeUpdate(EVP_ENCODE_CTX *ctx, uint8_t *out, - int *out_len, const uint8_t *in, - size_t in_len); - -/* EVP_DecodeFinal flushes any remaining output bytes from |ctx| to |out| and - * sets |*out_len| to the number of bytes written. It returns one on success - * and minus one on error. */ -OPENSSL_EXPORT int EVP_DecodeFinal(EVP_ENCODE_CTX *ctx, uint8_t *out, - int *out_len); - -/* Deprecated: EVP_DecodeBlock encodes |src_len| bytes from |src| and - * writes the result to |dst|. It returns the number of bytes written - * or -1 on error. - * - * WARNING: EVP_DecodeBlock's return value does not take padding into - * account. It also strips leading whitespace and trailing - * whitespace. */ -OPENSSL_EXPORT int EVP_DecodeBlock(uint8_t *dst, const uint8_t *src, - size_t src_len); - - -struct evp_encode_ctx_st { - unsigned num; /* number saved in a partial encode/decode */ - unsigned length; /* The length is either the output line length - * (in input bytes) or the shortest input line - * length that is ok. Once decoding begins, - * the length is adjusted up each time a longer - * line is decoded */ - uint8_t enc_data[80]; /* data to encode */ - unsigned line_num; /* number read on current line */ - int expect_nl; -}; - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_BASE64_H */ diff --git a/third_party/boringssl/include/openssl/bio.h b/third_party/boringssl/include/openssl/bio.h deleted file mode 100644 index 872465750b..0000000000 --- a/third_party/boringssl/include/openssl/bio.h +++ /dev/null @@ -1,910 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] */ - -#ifndef OPENSSL_HEADER_BIO_H -#define OPENSSL_HEADER_BIO_H - -#include - -#include /* For FILE */ - -#include /* for ERR_print_errors_fp */ -#include -#include -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* BIO abstracts over a file-descriptor like interface. */ - - -/* Allocation and freeing. */ - -DEFINE_STACK_OF(BIO); - -/* BIO_new creates a new BIO with the given type and a reference count of one. - * It returns the fresh |BIO|, or NULL on error. */ -OPENSSL_EXPORT BIO *BIO_new(const BIO_METHOD *type); - -/* BIO_free decrements the reference count of |bio|. If the reference count - * drops to zero, it (optionally) calls the BIO's callback with |BIO_CB_FREE|, - * frees the ex_data and then, if the BIO has a destroy callback for the - * method, calls it. Finally it frees |bio| itself. It then repeats that for - * the next BIO in the chain, if any. - * - * It returns one on success or zero otherwise. */ -OPENSSL_EXPORT int BIO_free(BIO *bio); - -/* BIO_vfree performs the same actions as |BIO_free|, but has a void return - * value. This is provided for API-compat. - * - * TODO(fork): remove. */ -OPENSSL_EXPORT void BIO_vfree(BIO *bio); - -/* BIO_up_ref increments the reference count of |bio| and returns it. */ -OPENSSL_EXPORT BIO *BIO_up_ref(BIO *bio); - - -/* Basic I/O. */ - -/* BIO_read attempts to read |len| bytes into |data|. It returns the number of - * bytes read, zero on EOF, or a negative number on error. */ -OPENSSL_EXPORT int BIO_read(BIO *bio, void *data, int len); - -/* BIO_gets "reads a line" from |bio| and puts at most |size| bytes into |buf|. - * It returns the number of bytes read or a negative number on error. The - * phrase "reads a line" is in quotes in the previous sentence because the - * exact operation depends on the BIO's method. For example, a digest BIO will - * return the digest in response to a |BIO_gets| call. - * - * TODO(fork): audit the set of BIOs that we end up needing. If all actually - * return a line for this call, remove the warning above. */ -OPENSSL_EXPORT int BIO_gets(BIO *bio, char *buf, int size); - -/* BIO_write writes |len| bytes from |data| to BIO. It returns the number of - * bytes written or a negative number on error. */ -OPENSSL_EXPORT int BIO_write(BIO *bio, const void *data, int len); - -/* BIO_puts writes a NUL terminated string from |buf| to |bio|. It returns the - * number of bytes written or a negative number on error. */ -OPENSSL_EXPORT int BIO_puts(BIO *bio, const char *buf); - -/* BIO_flush flushes any buffered output. It returns one on success and zero - * otherwise. */ -OPENSSL_EXPORT int BIO_flush(BIO *bio); - - -/* Low-level control functions. - * - * These are generic functions for sending control requests to a BIO. In - * general one should use the wrapper functions like |BIO_get_close|. */ - -/* BIO_ctrl sends the control request |cmd| to |bio|. The |cmd| argument should - * be one of the |BIO_C_*| values. */ -OPENSSL_EXPORT long BIO_ctrl(BIO *bio, int cmd, long larg, void *parg); - -/* BIO_ptr_ctrl acts like |BIO_ctrl| but passes the address of a |void*| - * pointer as |parg| and returns the value that is written to it, or NULL if - * the control request returns <= 0. */ -OPENSSL_EXPORT char *BIO_ptr_ctrl(BIO *bp, int cmd, long larg); - -/* BIO_int_ctrl acts like |BIO_ctrl| but passes the address of a copy of |iarg| - * as |parg|. */ -OPENSSL_EXPORT long BIO_int_ctrl(BIO *bp, int cmd, long larg, int iarg); - -/* BIO_reset resets |bio| to its initial state, the precise meaning of which - * depends on the concrete type of |bio|. It returns one on success and zero - * otherwise. */ -OPENSSL_EXPORT int BIO_reset(BIO *bio); - -/* BIO_set_flags ORs |flags| with |bio->flags|. */ -OPENSSL_EXPORT void BIO_set_flags(BIO *bio, int flags); - -/* BIO_test_flags returns |bio->flags| AND |flags|. */ -OPENSSL_EXPORT int BIO_test_flags(const BIO *bio, int flags); - -/* BIO_should_read returns non-zero if |bio| encountered a temporary error - * while reading (i.e. EAGAIN), indicating that the caller should retry the - * read. */ -OPENSSL_EXPORT int BIO_should_read(const BIO *bio); - -/* BIO_should_write returns non-zero if |bio| encountered a temporary error - * while writing (i.e. EAGAIN), indicating that the caller should retry the - * write. */ -OPENSSL_EXPORT int BIO_should_write(const BIO *bio); - -/* BIO_should_retry returns non-zero if the reason that caused a failed I/O - * operation is temporary and thus the operation should be retried. Otherwise, - * it was a permanent error and it returns zero. */ -OPENSSL_EXPORT int BIO_should_retry(const BIO *bio); - -/* BIO_should_io_special returns non-zero if |bio| encountered a temporary - * error while performing a special I/O operation, indicating that the caller - * should retry. The operation that caused the error is returned by - * |BIO_get_retry_reason|. */ -OPENSSL_EXPORT int BIO_should_io_special(const BIO *bio); - -/* BIO_RR_SSL_X509_LOOKUP indicates that an SSL BIO blocked because the SSL - * library returned with SSL_ERROR_WANT_X509_LOOKUP. - * - * TODO(fork): remove. */ -#define BIO_RR_SSL_X509_LOOKUP 0x01 - -/* BIO_RR_CONNECT indicates that a connect would have blocked */ -#define BIO_RR_CONNECT 0x02 - -/* BIO_RR_ACCEPT indicates that an accept would have blocked */ -#define BIO_RR_ACCEPT 0x03 - -/* BIO_RR_SSL_CHANNEL_ID_LOOKUP indicates that the ChannelID code cannot find - * a private key for a TLS connection. */ -#define BIO_RR_SSL_CHANNEL_ID_LOOKUP 0x04 - -/* BIO_get_retry_reason returns the special I/O operation that needs to be - * retried. The return value is one of the |BIO_RR_*| values. */ -OPENSSL_EXPORT int BIO_get_retry_reason(const BIO *bio); - -/* BIO_clear_flags ANDs |bio->flags| with the bitwise-complement of |flags|. */ -OPENSSL_EXPORT void BIO_clear_flags(BIO *bio, int flags); - -/* BIO_set_retry_read sets the |BIO_FLAGS_READ| and |BIO_FLAGS_SHOULD_RETRY| - * flags on |bio|. */ -OPENSSL_EXPORT void BIO_set_retry_read(BIO *bio); - -/* BIO_set_retry_read sets the |BIO_FLAGS_WRITE| and |BIO_FLAGS_SHOULD_RETRY| - * flags on |bio|. */ -OPENSSL_EXPORT void BIO_set_retry_write(BIO *bio); - -/* BIO_get_retry_flags gets the |BIO_FLAGS_READ|, |BIO_FLAGS_WRITE|, - * |BIO_FLAGS_IO_SPECIAL| and |BIO_FLAGS_SHOULD_RETRY| flags from |bio|. */ -OPENSSL_EXPORT int BIO_get_retry_flags(BIO *bio); - -/* BIO_clear_retry_flags clears the |BIO_FLAGS_READ|, |BIO_FLAGS_WRITE|, - * |BIO_FLAGS_IO_SPECIAL| and |BIO_FLAGS_SHOULD_RETRY| flags from |bio|. */ -OPENSSL_EXPORT void BIO_clear_retry_flags(BIO *bio); - -/* BIO_method_type returns the type of |bio|, which is one of the |BIO_TYPE_*| - * values. */ -OPENSSL_EXPORT int BIO_method_type(const BIO *bio); - -/* bio_info_cb is the type of a callback function that can be called for most - * BIO operations. The |event| argument is one of |BIO_CB_*| and can be ORed - * with |BIO_CB_RETURN| if the callback is being made after the operation in - * question. In that case, |return_value| will contain the return value from - * the operation. */ -typedef long (*bio_info_cb)(BIO *bio, int event, const char *parg, int cmd, - long larg, long return_value); - -/* BIO_callback_ctrl allows the callback function to be manipulated. The |cmd| - * arg will generally be |BIO_CTRL_SET_CALLBACK| but arbitary command values - * can be interpreted by the |BIO|. */ -OPENSSL_EXPORT long BIO_callback_ctrl(BIO *bio, int cmd, bio_info_cb fp); - -/* BIO_pending returns the number of bytes pending to be read. */ -OPENSSL_EXPORT size_t BIO_pending(const BIO *bio); - -/* BIO_ctrl_pending calls |BIO_pending| and exists only for compatibility with - * OpenSSL. */ -OPENSSL_EXPORT size_t BIO_ctrl_pending(const BIO *bio); - -/* BIO_wpending returns the number of bytes pending to be written. */ -OPENSSL_EXPORT size_t BIO_wpending(const BIO *bio); - -/* BIO_set_close sets the close flag for |bio|. The meaning of which depends on - * the type of |bio| but, for example, a memory BIO interprets the close flag - * as meaning that it owns its buffer. It returns one on success and zero - * otherwise. */ -OPENSSL_EXPORT int BIO_set_close(BIO *bio, int close_flag); - -/* BIO_set_callback sets a callback function that will be called before and - * after most operations. See the comment above |bio_info_cb|. */ -OPENSSL_EXPORT void BIO_set_callback(BIO *bio, bio_info_cb callback_func); - -/* BIO_set_callback_arg sets the opaque pointer value that can be read within a - * callback with |BIO_get_callback_arg|. */ -OPENSSL_EXPORT void BIO_set_callback_arg(BIO *bio, char *arg); - -/* BIO_get_callback_arg returns the last value of the opaque callback pointer - * set by |BIO_set_callback_arg|. */ -OPENSSL_EXPORT char *BIO_get_callback_arg(const BIO *bio); - -/* BIO_number_read returns the number of bytes that have been read from - * |bio|. */ -OPENSSL_EXPORT size_t BIO_number_read(const BIO *bio); - -/* BIO_number_written returns the number of bytes that have been written to - * |bio|. */ -OPENSSL_EXPORT size_t BIO_number_written(const BIO *bio); - - -/* Managing chains of BIOs. - * - * BIOs can be put into chains where the output of one is used as the input of - * the next etc. The most common case is a buffering BIO, which accepts and - * buffers writes until flushed into the next BIO in the chain. */ - -/* BIO_push adds |appended_bio| to the end of the chain with |bio| at the head. - * It returns |bio|. Note that |appended_bio| may be the head of a chain itself - * and thus this function can be used to join two chains. - * - * BIO_push takes ownership of the caller's reference to |appended_bio|. */ -OPENSSL_EXPORT BIO *BIO_push(BIO *bio, BIO *appended_bio); - -/* BIO_pop removes |bio| from the head of a chain and returns the next BIO in - * the chain, or NULL if there is no next BIO. - * - * The caller takes ownership of the chain's reference to |bio|. */ -OPENSSL_EXPORT BIO *BIO_pop(BIO *bio); - -/* BIO_next returns the next BIO in the chain after |bio|, or NULL if there is - * no such BIO. */ -OPENSSL_EXPORT BIO *BIO_next(BIO *bio); - -/* BIO_free_all calls |BIO_free|. - * - * TODO(fork): update callers and remove. */ -OPENSSL_EXPORT void BIO_free_all(BIO *bio); - -/* BIO_find_type walks a chain of BIOs and returns the first that matches - * |type|, which is one of the |BIO_TYPE_*| values. */ -OPENSSL_EXPORT BIO *BIO_find_type(BIO *bio, int type); - -/* BIO_copy_next_retry sets the retry flags and |retry_reason| of |bio| from - * the next BIO in the chain. */ -OPENSSL_EXPORT void BIO_copy_next_retry(BIO *bio); - - -/* Printf functions. - * - * These functions are versions of printf functions that output to a BIO rather - * than a FILE. */ -#ifdef __GNUC__ -#define __bio_h__attr__ __attribute__ -#else -#define __bio_h__attr__(x) -#endif -OPENSSL_EXPORT int BIO_printf(BIO *bio, const char *format, ...) - __bio_h__attr__((__format__(__printf__, 2, 3))); -#undef __bio_h__attr__ - - -/* Utility functions. */ - -/* BIO_indent prints min(|indent|, |max_indent|) spaces. It returns one on - * success and zero otherwise. */ -OPENSSL_EXPORT int BIO_indent(BIO *bio, unsigned indent, unsigned max_indent); - -/* BIO_hexdump writes a hex dump of |data| to |bio|. Each line will be indented - * by |indent| spaces. */ -OPENSSL_EXPORT int BIO_hexdump(BIO *bio, const uint8_t *data, size_t len, - unsigned indent); - -/* BIO_print_errors prints the current contents of the error stack to |bio| - * using human readable strings where possible. */ -OPENSSL_EXPORT void BIO_print_errors(BIO *bio); - -/* BIO_read_asn1 reads a single ASN.1 object from |bio|. If successful it sets - * |*out| to be an allocated buffer (that should be freed with |OPENSSL_free|), - * |*out_size| to the length, in bytes, of that buffer and returns one. - * Otherwise it returns zero. - * - * If the length of the object is greater than |max_len| or 2^32 then the - * function will fail. Long-form tags are not supported. If the length of the - * object is indefinite the full contents of |bio| are read, unless it would be - * greater than |max_len|, in which case the function fails. - * - * If the function fails then some unknown amount of data may have been read - * from |bio|. */ -OPENSSL_EXPORT int BIO_read_asn1(BIO *bio, uint8_t **out, size_t *out_len, - size_t max_len); - - -/* Memory BIOs. - * - * Memory BIOs can be used as a read-only source (with |BIO_new_mem_buf|) or a - * writable sink (with |BIO_new|, |BIO_s_mem| and |BIO_get_mem_buf|). Data - * written to a writable, memory BIO can be recalled by reading from it. - * - * Calling |BIO_reset| on a read-only BIO resets it to the original contents. - * On a writable BIO, it clears any data. - * - * If the close flag is set to |BIO_NOCLOSE| (not the default) then the - * underlying |BUF_MEM| will not be freed when the |BIO| is freed. - * - * Memory BIOs support |BIO_gets| and |BIO_puts|. - * - * |BIO_eof| is true if no data is in the BIO. - * - * |BIO_ctrl_pending| returns the number of bytes currently stored. */ - -/* BIO_s_mem returns a |BIO_METHOD| that uses a in-memory buffer. */ -OPENSSL_EXPORT const BIO_METHOD *BIO_s_mem(void); - -/* BIO_new_mem_buf creates BIO that reads and writes from |len| bytes at |buf|. - * It does not take ownership of |buf|. It returns the BIO or NULL on error. - * - * If |len| is negative, then |buf| is treated as a NUL-terminated string, but - * don't depend on this in new code. */ -OPENSSL_EXPORT BIO *BIO_new_mem_buf(void *buf, int len); - -/* BIO_mem_contents sets |*out_contents| to point to the current contents of - * |bio| and |*out_len| to contain the length of that data. It returns one on - * success and zero otherwise. */ -OPENSSL_EXPORT int BIO_mem_contents(const BIO *bio, - const uint8_t **out_contents, - size_t *out_len); - -/* BIO_get_mem_data sets |*contents| to point to the current contents of |bio| - * and returns the length of the data. - * - * WARNING: don't use this, use |BIO_mem_contents|. A return value of zero from - * this function can mean either that it failed or that the memory buffer is - * empty. */ -OPENSSL_EXPORT long BIO_get_mem_data(BIO *bio, char **contents); - -/* BIO_get_mem_ptr sets |*out| to a BUF_MEM containing the current contents of - * |bio|. It returns one on success or zero on error. */ -OPENSSL_EXPORT int BIO_get_mem_ptr(BIO *bio, BUF_MEM **out); - -/* BIO_set_mem_buf sets |b| as the contents of |bio|. If |take_ownership| is - * non-zero, then |b| will be freed when |bio| is closed. Returns one on - * success or zero otherwise. */ -OPENSSL_EXPORT int BIO_set_mem_buf(BIO *bio, BUF_MEM *b, int take_ownership); - -/* BIO_set_mem_eof_return sets the value that will be returned from reading - * |bio| when empty. If |eof_value| is zero then an empty memory BIO will - * return EOF (that is it will return zero and |BIO_should_retry| will be - * false). If |eof_value| is non zero then it will return |eof_value| when it - * is empty and it will set the read retry flag (that is |BIO_read_retry| is - * true). To avoid ambiguity with a normal positive return value, |eof_value| - * should be set to a negative value, typically -1. - * - * For a read-only BIO, the default is zero (EOF). For a writable BIO, the - * default is -1 so that additional data can be written once exhausted. */ -OPENSSL_EXPORT int BIO_set_mem_eof_return(BIO *bio, int eof_value); - - -/* File descriptor BIOs. - * - * File descriptor BIOs are wrappers around the system's |read| and |write| - * functions. If the close flag is set then then |close| is called on the - * underlying file descriptor when the BIO is freed. - * - * |BIO_reset| attempts to seek the file pointer to the start of file using - * |lseek|. - * - * |BIO_seek| sets the file pointer to position |off| from start of file using - * |lseek|. - * - * |BIO_tell| returns the current file position. */ - -/* BIO_s_fd returns a |BIO_METHOD| for file descriptor fds. */ -OPENSSL_EXPORT const BIO_METHOD *BIO_s_fd(void); - -/* BIO_new_fd creates a new file descriptor BIO wrapping |fd|. If |close_flag| - * is non-zero, then |fd| will be closed when the BIO is. */ -OPENSSL_EXPORT BIO *BIO_new_fd(int fd, int close_flag); - -/* BIO_set_fd sets the file descriptor of |bio| to |fd|. If |close_flag| is - * non-zero then |fd| will be closed when |bio| is. It returns one on success - * or zero on error. */ -OPENSSL_EXPORT int BIO_set_fd(BIO *bio, int fd, int close_flag); - -/* BIO_get_fd sets |*out_fd| to the file descriptor currently in use by |bio|. - * It returns one on success and zero on error. */ -OPENSSL_EXPORT int BIO_get_fd(BIO *bio, int *out_fd); - - -/* File BIOs. - * - * File BIOs are wrappers around a C |FILE| object. - * - * |BIO_flush| on a file BIO calls |fflush| on the wrapped stream. - * - * |BIO_reset| attempts to seek the file pointer to the start of file using - * |fseek|. - * - * |BIO_seek| sets the file pointer to the given position from the start of - * file using |fseek|. - * - * |BIO_eof| calls |feof|. - * - * Setting the close flag causes |fclose| to be called on the stream when the - * BIO is freed. */ - -/* BIO_s_file returns a BIO_METHOD that wraps a |FILE|. */ -OPENSSL_EXPORT const BIO_METHOD *BIO_s_file(void); - -/* BIO_new_file creates a file BIO by opening |filename| with the given mode. - * See the |fopen| manual page for details of the mode argument. */ -OPENSSL_EXPORT BIO *BIO_new_file(const char *filename, const char *mode); - -/* BIO_new_fp creates a new file BIO that wraps the given |FILE|. If - * |close_flag| is |BIO_CLOSE|, then |fclose| will be called on |stream| when - * the BIO is closed. */ -OPENSSL_EXPORT BIO *BIO_new_fp(FILE *stream, int close_flag); - -/* BIO_get_fp sets |*out_file| to the current |FILE| for |bio|. It returns one - * on success and zero otherwise. */ -OPENSSL_EXPORT int BIO_get_fp(BIO *bio, FILE **out_file); - -/* BIO_set_fp sets the |FILE| for |bio|. If |close_flag| is |BIO_CLOSE| then - * |fclose| will be called on |file| when |bio| is closed. It returns one on - * sucess and zero otherwise. */ -OPENSSL_EXPORT int BIO_set_fp(BIO *bio, FILE *file, int close_flag); - -/* BIO_read_filename opens |filename| for reading and sets the result as the - * |FILE| for |bio|. It returns one on success and zero otherwise. The |FILE| - * will be closed when |bio| is freed. */ -OPENSSL_EXPORT int BIO_read_filename(BIO *bio, const char *filename); - -/* BIO_write_filename opens |filename| for writing and sets the result as the - * |FILE| for |bio|. It returns one on success and zero otherwise. The |FILE| - * will be closed when |bio| is freed. */ -OPENSSL_EXPORT int BIO_write_filename(BIO *bio, const char *filename); - -/* BIO_append_filename opens |filename| for appending and sets the result as - * the |FILE| for |bio|. It returns one on success and zero otherwise. The - * |FILE| will be closed when |bio| is freed. */ -OPENSSL_EXPORT int BIO_append_filename(BIO *bio, const char *filename); - -/* BIO_rw_filename opens |filename| for reading and writing and sets the result - * as the |FILE| for |bio|. It returns one on success and zero otherwise. The - * |FILE| will be closed when |bio| is freed. */ -OPENSSL_EXPORT int BIO_rw_filename(BIO *bio, const char *filename); - - -/* Buffer BIOs. - * - * Buffer BIOs are a filter-type BIO, i.e. they are designed to be used in a - * chain of BIOs. They provide buffering to reduce the number of operations on - * the underlying BIOs. */ - -OPENSSL_EXPORT const BIO_METHOD *BIO_f_buffer(void); - -/* BIO_set_read_buffer_size sets the size, in bytes, of the read buffer and - * clears it. It returns one on success and zero on failure. */ -OPENSSL_EXPORT int BIO_set_read_buffer_size(BIO *bio, int buffer_size); - -/* BIO_set_write_buffer_size sets the size, in bytes, of the write buffer and - * clears it. It returns one on success and zero on failure. */ -OPENSSL_EXPORT int BIO_set_write_buffer_size(BIO *bio, int buffer_size); - - -/* Socket BIOs. */ - -OPENSSL_EXPORT const BIO_METHOD *BIO_s_socket(void); - -/* BIO_new_socket allocates and initialises a fresh BIO which will read and - * write to the socket |fd|. If |close_flag| is |BIO_CLOSE| then closing the - * BIO will close |fd|. It returns the fresh |BIO| or NULL on error. */ -OPENSSL_EXPORT BIO *BIO_new_socket(int fd, int close_flag); - - -/* Connect BIOs. - * - * A connection BIO creates a network connection and transfers data over the - * resulting socket. */ - -OPENSSL_EXPORT const BIO_METHOD *BIO_s_connect(void); - -/* BIO_new_connect returns a BIO that connects to the given hostname and port. - * The |host_and_optional_port| argument should be of the form - * "www.example.com" or "www.example.com:443". If the port is omitted, it must - * be provided with |BIO_set_conn_port|. - * - * It returns the new BIO on success, or NULL on error. */ -OPENSSL_EXPORT BIO *BIO_new_connect(const char *host_and_optional_port); - -/* BIO_set_conn_hostname sets |host_and_optional_port| as the hostname and - * optional port that |bio| will connect to. If the port is omitted, it must be - * provided with |BIO_set_conn_port|. - * - * It returns one on success and zero otherwise. */ -OPENSSL_EXPORT int BIO_set_conn_hostname(BIO *bio, - const char *host_and_optional_port); - -/* BIO_set_conn_port sets |port_str| as the port or service name that |bio| - * will connect to. It returns one on success and zero otherwise. */ -OPENSSL_EXPORT int BIO_set_conn_port(BIO *bio, const char *port_str); - -/* BIO_set_nbio sets whether |bio| will use non-blocking I/O operations. It - * returns one on success and zero otherwise. */ -OPENSSL_EXPORT int BIO_set_nbio(BIO *bio, int on); - - -/* Datagram BIOs. - * - * TODO(fork): not implemented. */ - -#define BIO_CTRL_DGRAM_QUERY_MTU 40 /* as kernel for current MTU */ - -#define BIO_CTRL_DGRAM_SET_MTU 42 /* set cached value for MTU. want to use - this if asking the kernel fails */ - -#define BIO_CTRL_DGRAM_MTU_EXCEEDED 43 /* check whether the MTU was exceed in - the previous write operation. */ - -#define BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT \ - 45 /* Next DTLS handshake timeout to adjust socket timeouts */ - -#define BIO_CTRL_DGRAM_GET_PEER 46 - -#define BIO_CTRL_DGRAM_GET_FALLBACK_MTU 47 - - -/* BIO Pairs. - * - * BIO pairs provide a "loopback" like system: a pair of BIOs where data - * written to one can be read from the other and vice versa. */ - -/* BIO_new_bio_pair sets |*out1| and |*out2| to two freshly created BIOs where - * data written to one can be read from the other and vice versa. The - * |writebuf1| argument gives the size of the buffer used in |*out1| and - * |writebuf2| for |*out2|. It returns one on success and zero on error. */ -OPENSSL_EXPORT int BIO_new_bio_pair(BIO **out1, size_t writebuf1, BIO **out2, - size_t writebuf2); - -/* BIO_new_bio_pair_external_buf is the same as |BIO_new_bio_pair| with the - * difference that the caller keeps ownership of the write buffers - * |ext_writebuf1_len| and |ext_writebuf2_len|. This is useful when using zero - * copy API for read and write operations, in cases where the buffers need to - * outlive the BIO pairs. It returns one on success and zero on error. */ -OPENSSL_EXPORT int BIO_new_bio_pair_external_buf(BIO** bio1_p, - size_t writebuf1_len, - uint8_t* ext_writebuf1, - BIO** bio2_p, - size_t writebuf2_len, - uint8_t* ext_writebuf2); - -/* BIO_ctrl_get_read_request returns the number of bytes that the other side of - * |bio| tried (unsuccessfully) to read. */ -OPENSSL_EXPORT size_t BIO_ctrl_get_read_request(BIO *bio); - -/* BIO_ctrl_get_write_guarantee returns the number of bytes that |bio| (which - * must have been returned by |BIO_new_bio_pair|) will accept on the next - * |BIO_write| call. */ -OPENSSL_EXPORT size_t BIO_ctrl_get_write_guarantee(BIO *bio); - -/* BIO_shutdown_wr marks |bio| as closed, from the point of view of the other - * side of the pair. Future |BIO_write| calls on |bio| will fail. It returns - * one on success and zero otherwise. */ -OPENSSL_EXPORT int BIO_shutdown_wr(BIO *bio); - - -/* Zero copy versions of BIO_read and BIO_write for BIO pairs. */ - -/* BIO_zero_copy_get_read_buf initiates a zero copy read operation. - * |out_read_buf| is set to the internal read buffer, and |out_buf_offset| is - * set to the current read position of |out_read_buf|. The number of bytes - * available for read from |out_read_buf| + |out_buf_offset| is returned in - * |out_available_bytes|. Note that this function might report fewer bytes - * available than |BIO_pending|, if the internal ring buffer is wrapped. It - * returns one on success. In case of error it returns zero and pushes to the - * error stack. - * - * The zero copy read operation is completed by calling - * |BIO_zero_copy_get_read_buf_done|. Neither |BIO_zero_copy_get_read_buf| nor - * any other I/O read operation may be called while a zero copy read operation - * is active. */ -OPENSSL_EXPORT int BIO_zero_copy_get_read_buf(BIO* bio, - uint8_t** out_read_buf, - size_t* out_buf_offset, - size_t* out_available_bytes); - -/* BIO_zero_copy_get_read_buf_done must be called after reading from a BIO using - * |BIO_zero_copy_get_read_buf| to finish the read operation. The |bytes_read| - * argument is the number of bytes read. - * - * It returns one on success. In case of error it returns zero and pushes to the - * error stack. */ -OPENSSL_EXPORT int BIO_zero_copy_get_read_buf_done(BIO* bio, size_t bytes_read); - -/* BIO_zero_copy_get_write_buf_done initiates a zero copy write operation. - * |out_write_buf| is set to to the internal write buffer, and |out_buf_offset| - * is set to the current write position of |out_write_buf|. - * The number of bytes available for write from |out_write_buf| + - * |out_buf_offset| is returned in |out_available_bytes|. Note that this - * function might report fewer bytes available than - * |BIO_ctrl_get_write_guarantee|, if the internal buffer is wrapped. It returns - * one on success. In case of error it returns zero and pushes to the error - * stack. - * - * The zero copy write operation is completed by calling - * |BIO_zero_copy_write_buf_done|. Neither |BIO_zero_copy_get_write_buf| - * nor any other I/O write operation may be called while a zero copy write - * operation is active. */ -OPENSSL_EXPORT int BIO_zero_copy_get_write_buf(BIO* bio, - uint8_t** out_write_buf, - size_t* out_buf_offset, - size_t* out_available_bytes); - -/* BIO_zero_copy_write_buf_done must be called after writing to a BIO using - * |BIO_zero_copy_get_write_buf_done| to finish the write operation. The - * |bytes_written| argument gives the number of bytes written. - * - * It returns one on success. In case of error it returns zero and pushes to the - * error stack. */ -OPENSSL_EXPORT int BIO_zero_copy_get_write_buf_done(BIO* bio, - size_t bytes_written); - - -/* BIO_NOCLOSE and |BIO_CLOSE| can be used as symbolic arguments when a "close - * flag" is passed to a BIO function. */ -#define BIO_NOCLOSE 0 -#define BIO_CLOSE 1 - -/* These are passed to the BIO callback */ -#define BIO_CB_FREE 0x01 -#define BIO_CB_READ 0x02 -#define BIO_CB_WRITE 0x03 -#define BIO_CB_PUTS 0x04 -#define BIO_CB_GETS 0x05 -#define BIO_CB_CTRL 0x06 - -/* The callback is called before and after the underling operation, - * The BIO_CB_RETURN flag indicates if it is after the call */ -#define BIO_CB_RETURN 0x80 - -/* These are values of the |cmd| argument to |BIO_ctrl|. */ -#define BIO_CTRL_RESET 1 /* opt - rewind/zero etc */ -#define BIO_CTRL_EOF 2 /* opt - are we at the eof */ -#define BIO_CTRL_INFO 3 /* opt - extra tit-bits */ -#define BIO_CTRL_SET 4 /* man - set the 'IO' type */ -#define BIO_CTRL_GET 5 /* man - get the 'IO' type */ -#define BIO_CTRL_GET_CLOSE 8 /* man - set the 'close' on free */ -#define BIO_CTRL_SET_CLOSE 9 /* man - set the 'close' on free */ -#define BIO_CTRL_PENDING 10 /* opt - is their more data buffered */ -#define BIO_CTRL_FLUSH 11 /* opt - 'flush' buffered output */ -#define BIO_CTRL_WPENDING 13 /* opt - number of bytes still to write */ -/* callback is int cb(BIO *bio,state,ret); */ -#define BIO_CTRL_SET_CALLBACK 14 /* opt - set callback function */ -#define BIO_CTRL_GET_CALLBACK 15 /* opt - set callback function */ -#define BIO_CTRL_SET_FILENAME 30 /* BIO_s_file special */ - - -/* Android compatibility section. - * - * A previous version of BoringSSL used in Android renamed ERR_print_errors_fp - * to BIO_print_errors_fp. It has subsequently been renamed back to - * ERR_print_errors_fp. */ -#define BIO_print_errors_fp ERR_print_errors_fp - - -/* Private functions */ - -#define BIO_FLAGS_READ 0x01 -#define BIO_FLAGS_WRITE 0x02 -#define BIO_FLAGS_IO_SPECIAL 0x04 -#define BIO_FLAGS_RWS (BIO_FLAGS_READ | BIO_FLAGS_WRITE | BIO_FLAGS_IO_SPECIAL) -#define BIO_FLAGS_SHOULD_RETRY 0x08 -#define BIO_FLAGS_BASE64_NO_NL 0x100 -/* This is used with memory BIOs: it means we shouldn't free up or change the - * data in any way. */ -#define BIO_FLAGS_MEM_RDONLY 0x200 - -/* These are the 'types' of BIOs */ -#define BIO_TYPE_NONE 0 -#define BIO_TYPE_MEM (1 | 0x0400) -#define BIO_TYPE_FILE (2 | 0x0400) -#define BIO_TYPE_FD (4 | 0x0400 | 0x0100) -#define BIO_TYPE_SOCKET (5 | 0x0400 | 0x0100) -#define BIO_TYPE_NULL (6 | 0x0400) -#define BIO_TYPE_SSL (7 | 0x0200) -#define BIO_TYPE_MD (8 | 0x0200) /* passive filter */ -#define BIO_TYPE_BUFFER (9 | 0x0200) /* filter */ -#define BIO_TYPE_CIPHER (10 | 0x0200) /* filter */ -#define BIO_TYPE_BASE64 (11 | 0x0200) /* filter */ -#define BIO_TYPE_CONNECT (12 | 0x0400 | 0x0100) /* socket - connect */ -#define BIO_TYPE_ACCEPT (13 | 0x0400 | 0x0100) /* socket for accept */ -#define BIO_TYPE_PROXY_CLIENT (14 | 0x0200) /* client proxy BIO */ -#define BIO_TYPE_PROXY_SERVER (15 | 0x0200) /* server proxy BIO */ -#define BIO_TYPE_NBIO_TEST (16 | 0x0200) /* server proxy BIO */ -#define BIO_TYPE_NULL_FILTER (17 | 0x0200) -#define BIO_TYPE_BER (18 | 0x0200) /* BER -> bin filter */ -#define BIO_TYPE_BIO (19 | 0x0400) /* (half a) BIO pair */ -#define BIO_TYPE_LINEBUFFER (20 | 0x0200) /* filter */ -#define BIO_TYPE_DGRAM (21 | 0x0400 | 0x0100) -#define BIO_TYPE_ASN1 (22 | 0x0200) /* filter */ -#define BIO_TYPE_COMP (23 | 0x0200) /* filter */ - -#define BIO_TYPE_DESCRIPTOR 0x0100 /* socket, fd, connect or accept */ -#define BIO_TYPE_FILTER 0x0200 -#define BIO_TYPE_SOURCE_SINK 0x0400 - -struct bio_method_st { - int type; - const char *name; - int (*bwrite)(BIO *, const char *, int); - int (*bread)(BIO *, char *, int); - /* TODO(fork): remove bputs. */ - int (*bputs)(BIO *, const char *); - int (*bgets)(BIO *, char *, int); - long (*ctrl)(BIO *, int, long, void *); - int (*create)(BIO *); - int (*destroy)(BIO *); - long (*callback_ctrl)(BIO *, int, bio_info_cb); -}; - -struct bio_st { - const BIO_METHOD *method; - /* bio, mode, argp, argi, argl, ret */ - long (*callback)(struct bio_st *, int, const char *, int, long, long); - char *cb_arg; /* first argument for the callback */ - - /* init is non-zero if this |BIO| has been initialised. */ - int init; - /* shutdown is often used by specific |BIO_METHOD|s to determine whether - * they own some underlying resource. This flag can often by controlled by - * |BIO_set_close|. For example, whether an fd BIO closes the underlying fd - * when it, itself, is closed. */ - int shutdown; - int flags; - int retry_reason; - /* num is a BIO-specific value. For example, in fd BIOs it's used to store a - * file descriptor. */ - int num; - CRYPTO_refcount_t references; - void *ptr; - /* next_bio points to the next |BIO| in a chain. This |BIO| owns a reference - * to |next_bio|. */ - struct bio_st *next_bio; /* used by filter BIOs */ - size_t num_read, num_write; -}; - -#define BIO_C_SET_CONNECT 100 -#define BIO_C_DO_STATE_MACHINE 101 -#define BIO_C_SET_NBIO 102 -#define BIO_C_SET_PROXY_PARAM 103 -#define BIO_C_SET_FD 104 -#define BIO_C_GET_FD 105 -#define BIO_C_SET_FILE_PTR 106 -#define BIO_C_GET_FILE_PTR 107 -#define BIO_C_SET_FILENAME 108 -#define BIO_C_SET_SSL 109 -#define BIO_C_GET_SSL 110 -#define BIO_C_SET_MD 111 -#define BIO_C_GET_MD 112 -#define BIO_C_GET_CIPHER_STATUS 113 -#define BIO_C_SET_BUF_MEM 114 -#define BIO_C_GET_BUF_MEM_PTR 115 -#define BIO_C_GET_BUFF_NUM_LINES 116 -#define BIO_C_SET_BUFF_SIZE 117 -#define BIO_C_SET_ACCEPT 118 -#define BIO_C_SSL_MODE 119 -#define BIO_C_GET_MD_CTX 120 -#define BIO_C_GET_PROXY_PARAM 121 -#define BIO_C_SET_BUFF_READ_DATA 122 /* data to read first */ -#define BIO_C_GET_CONNECT 123 -#define BIO_C_GET_ACCEPT 124 -#define BIO_C_SET_SSL_RENEGOTIATE_BYTES 125 -#define BIO_C_GET_SSL_NUM_RENEGOTIATES 126 -#define BIO_C_SET_SSL_RENEGOTIATE_TIMEOUT 127 -#define BIO_C_FILE_SEEK 128 -#define BIO_C_GET_CIPHER_CTX 129 -#define BIO_C_SET_BUF_MEM_EOF_RETURN 130/*return end of input value*/ -#define BIO_C_SET_BIND_MODE 131 -#define BIO_C_GET_BIND_MODE 132 -#define BIO_C_FILE_TELL 133 -#define BIO_C_GET_SOCKS 134 -#define BIO_C_SET_SOCKS 135 - -#define BIO_C_SET_WRITE_BUF_SIZE 136/* for BIO_s_bio */ -#define BIO_C_GET_WRITE_BUF_SIZE 137 -#define BIO_C_GET_WRITE_GUARANTEE 140 -#define BIO_C_GET_READ_REQUEST 141 -#define BIO_C_SHUTDOWN_WR 142 -#define BIO_C_NREAD0 143 -#define BIO_C_NREAD 144 -#define BIO_C_NWRITE0 145 -#define BIO_C_NWRITE 146 -#define BIO_C_RESET_READ_REQUEST 147 -#define BIO_C_SET_MD_CTX 148 - -#define BIO_C_SET_PREFIX 149 -#define BIO_C_GET_PREFIX 150 -#define BIO_C_SET_SUFFIX 151 -#define BIO_C_GET_SUFFIX 152 - -#define BIO_C_SET_EX_ARG 153 -#define BIO_C_GET_EX_ARG 154 - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#define BIO_F_BIO_callback_ctrl 100 -#define BIO_F_BIO_ctrl 101 -#define BIO_F_BIO_new 102 -#define BIO_F_BIO_new_file 103 -#define BIO_F_BIO_new_mem_buf 104 -#define BIO_F_BIO_zero_copy_get_read_buf 105 -#define BIO_F_BIO_zero_copy_get_read_buf_done 106 -#define BIO_F_BIO_zero_copy_get_write_buf 107 -#define BIO_F_BIO_zero_copy_get_write_buf_done 108 -#define BIO_F_bio_io 109 -#define BIO_F_bio_make_pair 110 -#define BIO_F_bio_write 111 -#define BIO_F_buffer_ctrl 112 -#define BIO_F_conn_ctrl 113 -#define BIO_F_conn_state 114 -#define BIO_F_file_ctrl 115 -#define BIO_F_file_read 116 -#define BIO_F_mem_write 117 -#define BIO_F_BIO_printf 118 -#define BIO_R_BAD_FOPEN_MODE 100 -#define BIO_R_BROKEN_PIPE 101 -#define BIO_R_CONNECT_ERROR 102 -#define BIO_R_ERROR_SETTING_NBIO 103 -#define BIO_R_INVALID_ARGUMENT 104 -#define BIO_R_IN_USE 105 -#define BIO_R_KEEPALIVE 106 -#define BIO_R_NBIO_CONNECT_ERROR 107 -#define BIO_R_NO_HOSTNAME_SPECIFIED 108 -#define BIO_R_NO_PORT_SPECIFIED 109 -#define BIO_R_NO_SUCH_FILE 110 -#define BIO_R_NULL_PARAMETER 111 -#define BIO_R_SYS_LIB 112 -#define BIO_R_UNABLE_TO_CREATE_SOCKET 113 -#define BIO_R_UNINITIALIZED 114 -#define BIO_R_UNSUPPORTED_METHOD 115 -#define BIO_R_WRITE_TO_READ_ONLY_BIO 116 - -#endif /* OPENSSL_HEADER_BIO_H */ diff --git a/third_party/boringssl/include/openssl/blowfish.h b/third_party/boringssl/include/openssl/blowfish.h deleted file mode 100644 index fa60d5336f..0000000000 --- a/third_party/boringssl/include/openssl/blowfish.h +++ /dev/null @@ -1,93 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] */ - -#ifndef OPENSSL_HEADER_BLOWFISH_H -#define OPENSSL_HEADER_BLOWFISH_H - -#include - -#ifdef __cplusplus -extern "C" { -#endif - - -#define BF_ENCRYPT 1 -#define BF_DECRYPT 0 - -#define BF_ROUNDS 16 -#define BF_BLOCK 8 - -typedef struct bf_key_st { - uint32_t P[BF_ROUNDS + 2]; - uint32_t S[4 * 256]; -} BF_KEY; - -OPENSSL_EXPORT void BF_set_key(BF_KEY *key, size_t len, const uint8_t *data); -OPENSSL_EXPORT void BF_encrypt(uint32_t *data, const BF_KEY *key); -OPENSSL_EXPORT void BF_decrypt(uint32_t *data, const BF_KEY *key); - -OPENSSL_EXPORT void BF_ecb_encrypt(const uint8_t *in, uint8_t *out, - const BF_KEY *key, int enc); -OPENSSL_EXPORT void BF_cbc_encrypt(const uint8_t *in, uint8_t *out, long length, - const BF_KEY *schedule, uint8_t *ivec, - int enc); - - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_HEADER_BLOWFISH_H */ diff --git a/third_party/boringssl/include/openssl/bn.h b/third_party/boringssl/include/openssl/bn.h deleted file mode 100644 index ec1c8ff5c3..0000000000 --- a/third_party/boringssl/include/openssl/bn.h +++ /dev/null @@ -1,875 +0,0 @@ -/* Copyright (C) 1995-1997 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] - */ -/* ==================================================================== - * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * openssl-core@openssl.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.openssl.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS 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. - * ==================================================================== - * - * This product includes cryptographic software written by Eric Young - * (eay@cryptsoft.com). This product includes software written by Tim - * Hudson (tjh@cryptsoft.com). - * - */ -/* ==================================================================== - * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. - * - * Portions of the attached software ("Contribution") are developed by - * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project. - * - * The Contribution is licensed pursuant to the Eric Young open source - * license provided above. - * - * The binary polynomial arithmetic software is originally written by - * Sheueling Chang Shantz and Douglas Stebila of Sun Microsystems - * Laboratories. */ - -#ifndef OPENSSL_HEADER_BN_H -#define OPENSSL_HEADER_BN_H - -#include -#include - -#include /* for PRIu64 and friends */ -#include /* for FILE* */ - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* BN provides support for working with arbitary sized integers. For example, - * although the largest integer supported by the compiler might be 64 bits, BN - * will allow you to work with numbers until you run out of memory. */ - - -/* BN_ULONG is the native word size when working with big integers. - * - * Note: on some platforms, inttypes.h does not define print format macros in - * C++ unless |__STDC_FORMAT_MACROS| defined. As this is a public header, bn.h - * does not define |__STDC_FORMAT_MACROS| itself. C++ source files which use the - * FMT macros must define it externally. */ -#if defined(OPENSSL_64_BIT) -#define BN_ULONG uint64_t -#define BN_BITS2 64 -#define BN_DEC_FMT1 "%" PRIu64 -#define BN_DEC_FMT2 "%019" PRIu64 -#define BN_HEX_FMT1 "%" PRIx64 -#elif defined(OPENSSL_32_BIT) -#define BN_ULONG uint32_t -#define BN_BITS2 32 -#define BN_DEC_FMT1 "%" PRIu32 -#define BN_DEC_FMT2 "%09" PRIu32 -#define BN_HEX_FMT1 "%" PRIx32 -#else -#error "Must define either OPENSSL_32_BIT or OPENSSL_64_BIT" -#endif - - -/* Allocation and freeing. */ - -/* BN_new creates a new, allocated BIGNUM and initialises it. */ -OPENSSL_EXPORT BIGNUM *BN_new(void); - -/* BN_init initialises a stack allocated |BIGNUM|. */ -OPENSSL_EXPORT void BN_init(BIGNUM *bn); - -/* BN_free frees the data referenced by |bn| and, if |bn| was originally - * allocated on the heap, frees |bn| also. */ -OPENSSL_EXPORT void BN_free(BIGNUM *bn); - -/* BN_clear_free erases and frees the data referenced by |bn| and, if |bn| was - * originally allocated on the heap, frees |bn| also. */ -OPENSSL_EXPORT void BN_clear_free(BIGNUM *bn); - -/* BN_dup allocates a new BIGNUM and sets it equal to |src|. It returns the - * allocated BIGNUM on success or NULL otherwise. */ -OPENSSL_EXPORT BIGNUM *BN_dup(const BIGNUM *src); - -/* BN_copy sets |dest| equal to |src| and returns |dest|. */ -OPENSSL_EXPORT BIGNUM *BN_copy(BIGNUM *dest, const BIGNUM *src); - -/* BN_clear sets |bn| to zero and erases the old data. */ -OPENSSL_EXPORT void BN_clear(BIGNUM *bn); - -/* BN_value_one returns a static BIGNUM with value 1. */ -OPENSSL_EXPORT const BIGNUM *BN_value_one(void); - -/* BN_with_flags initialises a stack allocated |BIGNUM| with pointers to the - * contents of |in| but with |flags| ORed into the flags field. - * - * Note: the two BIGNUMs share state and so |out| should /not/ be passed to - * |BN_free|. */ -OPENSSL_EXPORT void BN_with_flags(BIGNUM *out, const BIGNUM *in, int flags); - - -/* Basic functions. */ - -/* BN_num_bits returns the minimum number of bits needed to represent the - * absolute value of |bn|. */ -OPENSSL_EXPORT unsigned BN_num_bits(const BIGNUM *bn); - -/* BN_num_bytes returns the minimum number of bytes needed to represent the - * absolute value of |bn|. */ -OPENSSL_EXPORT unsigned BN_num_bytes(const BIGNUM *bn); - -/* BN_zero sets |bn| to zero. */ -OPENSSL_EXPORT void BN_zero(BIGNUM *bn); - -/* BN_one sets |bn| to one. It returns one on success or zero on allocation - * failure. */ -OPENSSL_EXPORT int BN_one(BIGNUM *bn); - -/* BN_set_word sets |bn| to |value|. It returns one on success or zero on - * allocation failure. */ -OPENSSL_EXPORT int BN_set_word(BIGNUM *bn, BN_ULONG value); - -/* BN_set_negative sets the sign of |bn|. */ -OPENSSL_EXPORT void BN_set_negative(BIGNUM *bn, int sign); - -/* BN_is_negative returns one if |bn| is negative and zero otherwise. */ -OPENSSL_EXPORT int BN_is_negative(const BIGNUM *bn); - -/* BN_get_flags returns |bn->flags| & |flags|. */ -OPENSSL_EXPORT int BN_get_flags(const BIGNUM *bn, int flags); - -/* BN_set_flags sets |flags| on |bn|. */ -OPENSSL_EXPORT void BN_set_flags(BIGNUM *bn, int flags); - - -/* Conversion functions. */ - -/* BN_bin2bn sets |*ret| to the value of |len| bytes from |in|, interpreted as - * a big-endian number, and returns |ret|. If |ret| is NULL then a fresh - * |BIGNUM| is allocated and returned. It returns NULL on allocation - * failure. */ -OPENSSL_EXPORT BIGNUM *BN_bin2bn(const uint8_t *in, size_t len, BIGNUM *ret); - -/* BN_bn2bin serialises the absolute value of |in| to |out| as a big-endian - * integer, which must have |BN_num_bytes| of space available. It returns the - * number of bytes written. */ -OPENSSL_EXPORT size_t BN_bn2bin(const BIGNUM *in, uint8_t *out); - -/* BN_bn2bin_padded serialises the absolute value of |in| to |out| as a - * big-endian integer. The integer is padded with leading zeros up to size - * |len|. If |len| is smaller than |BN_num_bytes|, the function fails and - * returns 0. Otherwise, it returns 1. */ -OPENSSL_EXPORT int BN_bn2bin_padded(uint8_t *out, size_t len, const BIGNUM *in); - -/* BN_bn2hex returns an allocated string that contains a NUL-terminated, hex - * representation of |bn|. If |bn| is negative, the first char in the resulting - * string will be '-'. Returns NULL on allocation failure. */ -OPENSSL_EXPORT char *BN_bn2hex(const BIGNUM *bn); - -/* BN_hex2bn parses the leading hex number from |in|, which may be proceeded by - * a '-' to indicate a negative number and may contain trailing, non-hex data. - * If |outp| is not NULL, it constructs a BIGNUM equal to the hex number and - * stores it in |*outp|. If |*outp| is NULL then it allocates a new BIGNUM and - * updates |*outp|. It returns the number of bytes of |in| processed or zero on - * error. */ -OPENSSL_EXPORT int BN_hex2bn(BIGNUM **outp, const char *in); - -/* BN_bn2dec returns an allocated string that contains a NUL-terminated, - * decimal representation of |bn|. If |bn| is negative, the first char in the - * resulting string will be '-'. Returns NULL on allocation failure. */ -OPENSSL_EXPORT char *BN_bn2dec(const BIGNUM *a); - -/* BN_dec2bn parses the leading decimal number from |in|, which may be - * proceeded by a '-' to indicate a negative number and may contain trailing, - * non-decimal data. If |outp| is not NULL, it constructs a BIGNUM equal to the - * decimal number and stores it in |*outp|. If |*outp| is NULL then it - * allocates a new BIGNUM and updates |*outp|. It returns the number of bytes - * of |in| processed or zero on error. */ -OPENSSL_EXPORT int BN_dec2bn(BIGNUM **outp, const char *in); - -/* BN_asc2bn acts like |BN_dec2bn| or |BN_hex2bn| depending on whether |in| - * begins with "0X" or "0x" (indicating hex) or not (indicating decimal). A - * leading '-' is still permitted and comes before the optional 0X/0x. It - * returns one on success or zero on error. */ -OPENSSL_EXPORT int BN_asc2bn(BIGNUM **outp, const char *in); - -/* BN_print writes a hex encoding of |a| to |bio|. It returns one on success - * and zero on error. */ -OPENSSL_EXPORT int BN_print(BIO *bio, const BIGNUM *a); - -/* BN_print_fp acts like |BIO_print|, but wraps |fp| in a |BIO| first. */ -OPENSSL_EXPORT int BN_print_fp(FILE *fp, const BIGNUM *a); - -/* BN_get_word returns the absolute value of |bn| as a single word. If |bn| is - * too large to be represented as a single word, the maximum possible value - * will be returned. */ -OPENSSL_EXPORT BN_ULONG BN_get_word(const BIGNUM *bn); - - -/* Internal functions. - * - * These functions are useful for code that is doing low-level manipulations of - * BIGNUM values. However, be sure that no other function in this file does - * what you want before turning to these. */ - -/* bn_correct_top decrements |bn->top| until |bn->d[top-1]| is non-zero or - * until |top| is zero. */ -OPENSSL_EXPORT void bn_correct_top(BIGNUM *bn); - -/* bn_wexpand ensures that |bn| has at least |words| works of space without - * altering its value. It returns one on success or zero on allocation - * failure. */ -OPENSSL_EXPORT BIGNUM *bn_wexpand(BIGNUM *bn, unsigned words); - - -/* BIGNUM pools. - * - * Certain BIGNUM operations need to use many temporary variables and - * allocating and freeing them can be quite slow. Thus such opertions typically - * take a |BN_CTX| parameter, which contains a pool of |BIGNUMs|. The |ctx| - * argument to a public function may be NULL, in which case a local |BN_CTX| - * will be created just for the lifetime of that call. - * - * A function must call |BN_CTX_start| first. Then, |BN_CTX_get| may be called - * repeatedly to obtain temporary |BIGNUM|s. All |BN_CTX_get| calls must be made - * before calling any other functions that use the |ctx| as an argument. - * - * Finally, |BN_CTX_end| must be called before returning from the function. - * When |BN_CTX_end| is called, the |BIGNUM| pointers obtained from - * |BN_CTX_get| become invalid. */ - -/* BN_CTX_new returns a new, empty BN_CTX or NULL on allocation failure. */ -OPENSSL_EXPORT BN_CTX *BN_CTX_new(void); - -/* BN_CTX_free frees all BIGNUMs contained in |ctx| and then frees |ctx| - * itself. */ -OPENSSL_EXPORT void BN_CTX_free(BN_CTX *ctx); - -/* BN_CTX_start "pushes" a new entry onto the |ctx| stack and allows future - * calls to |BN_CTX_get|. */ -OPENSSL_EXPORT void BN_CTX_start(BN_CTX *ctx); - -/* BN_CTX_get returns a new |BIGNUM|, or NULL on allocation failure. Once - * |BN_CTX_get| has returned NULL, all future calls will also return NULL until - * |BN_CTX_end| is called. */ -OPENSSL_EXPORT BIGNUM *BN_CTX_get(BN_CTX *ctx); - -/* BN_CTX_end invalidates all |BIGNUM|s returned from |BN_CTX_get| since the - * matching |BN_CTX_start| call. */ -OPENSSL_EXPORT void BN_CTX_end(BN_CTX *ctx); - - -/* Simple arithmetic */ - -/* BN_add sets |r| = |a| + |b|, where |r| may be the same pointer as either |a| - * or |b|. It returns one on success and zero on allocation failure. */ -OPENSSL_EXPORT int BN_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b); - -/* BN_uadd sets |r| = |a| + |b|, where |a| and |b| are non-negative and |r| may - * be the same pointer as either |a| or |b|. It returns one on success and zero - * on allocation failure. */ -OPENSSL_EXPORT int BN_uadd(BIGNUM *r, const BIGNUM *a, const BIGNUM *b); - -/* BN_add_word adds |w| to |a|. It returns one on success and zero otherwise. */ -OPENSSL_EXPORT int BN_add_word(BIGNUM *a, BN_ULONG w); - -/* BN_sub sets |r| = |a| - |b|, where |r| must be a distinct pointer from |a| - * and |b|. It returns one on success and zero on allocation failure. */ -OPENSSL_EXPORT int BN_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b); - -/* BN_usub sets |r| = |a| - |b|, where |a| and |b| are non-negative integers, - * |b| < |a| and |r| must be a distinct pointer from |a| and |b|. It returns - * one on success and zero on allocation failure. */ -OPENSSL_EXPORT int BN_usub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b); - -/* BN_sub_word subtracts |w| from |a|. It returns one on success and zero on - * allocation failure. */ -OPENSSL_EXPORT int BN_sub_word(BIGNUM *a, BN_ULONG w); - -/* BN_mul sets |r| = |a| * |b|, where |r| may be the same pointer as |a| or - * |b|. Returns one on success and zero otherwise. */ -OPENSSL_EXPORT int BN_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, - BN_CTX *ctx); - -/* BN_mul_word sets |bn| = |bn| * |w|. It returns one on success or zero on - * allocation failure. */ -OPENSSL_EXPORT int BN_mul_word(BIGNUM *bn, BN_ULONG w); - -/* BN_sqr sets |r| = |a|^2 (i.e. squares), where |r| may be the same pointer as - * |a|. Returns one on success and zero otherwise. This is more efficient than - * BN_mul(r, a, a, ctx). */ -OPENSSL_EXPORT int BN_sqr(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx); - -/* BN_div divides |numerator| by |divisor| and places the result in |quotient| - * and the remainder in |rem|. Either of |quotient| or |rem| may be NULL, in - * which case the respective value is not returned. The result is rounded - * towards zero; thus if |numerator| is negative, the remainder will be zero or - * negative. It returns one on success or zero on error. */ -OPENSSL_EXPORT int BN_div(BIGNUM *quotient, BIGNUM *rem, - const BIGNUM *numerator, const BIGNUM *divisor, - BN_CTX *ctx); - -/* BN_div_word sets |numerator| = |numerator|/|divisor| and returns the - * remainder or (BN_ULONG)-1 on error. */ -OPENSSL_EXPORT BN_ULONG BN_div_word(BIGNUM *numerator, BN_ULONG divisor); - -/* BN_sqrt sets |*out_sqrt| (which may be the same |BIGNUM| as |in|) to the - * square root of |in|, using |ctx|. It returns one on success or zero on - * error. Negative numbers and non-square numbers will result in an error with - * appropriate errors on the error queue. */ -OPENSSL_EXPORT int BN_sqrt(BIGNUM *out_sqrt, const BIGNUM *in, BN_CTX *ctx); - - -/* Comparison functions */ - -/* BN_cmp returns a value less than, equal to or greater than zero if |a| is - * less than, equal to or greater than |b|, respectively. */ -OPENSSL_EXPORT int BN_cmp(const BIGNUM *a, const BIGNUM *b); - -/* BN_ucmp returns a value less than, equal to or greater than zero if the - * absolute value of |a| is less than, equal to or greater than the absolute - * value of |b|, respectively. */ -OPENSSL_EXPORT int BN_ucmp(const BIGNUM *a, const BIGNUM *b); - -/* BN_abs_is_word returns one if the absolute value of |bn| equals |w| and zero - * otherwise. */ -OPENSSL_EXPORT int BN_abs_is_word(const BIGNUM *bn, BN_ULONG w); - -/* BN_is_zero returns one if |bn| is zero and zero otherwise. */ -OPENSSL_EXPORT int BN_is_zero(const BIGNUM *bn); - -/* BN_is_one returns one if |bn| equals one and zero otherwise. */ -OPENSSL_EXPORT int BN_is_one(const BIGNUM *bn); - -/* BN_is_word returns one if |bn| is exactly |w| and zero otherwise. */ -OPENSSL_EXPORT int BN_is_word(const BIGNUM *bn, BN_ULONG w); - -/* BN_is_odd returns one if |bn| is odd and zero otherwise. */ -OPENSSL_EXPORT int BN_is_odd(const BIGNUM *bn); - - -/* Bitwise operations. */ - -/* BN_lshift sets |r| equal to |a| << n. The |a| and |r| arguments may be the - * same |BIGNUM|. It returns one on success and zero on allocation failure. */ -OPENSSL_EXPORT int BN_lshift(BIGNUM *r, const BIGNUM *a, int n); - -/* BN_lshift1 sets |r| equal to |a| << 1, where |r| and |a| may be the same - * pointer. It returns one on success and zero on allocation failure. */ -OPENSSL_EXPORT int BN_lshift1(BIGNUM *r, const BIGNUM *a); - -/* BN_rshift sets |r| equal to |a| >> n, where |r| and |a| may be the same - * pointer. It returns one on success and zero on allocation failure. */ -OPENSSL_EXPORT int BN_rshift(BIGNUM *r, const BIGNUM *a, int n); - -/* BN_rshift1 sets |r| equal to |a| >> 1, where |r| and |a| may be the same - * pointer. It returns one on success and zero on allocation failure. */ -OPENSSL_EXPORT int BN_rshift1(BIGNUM *r, const BIGNUM *a); - -/* BN_set_bit sets the |n|th, least-significant bit in |a|. For example, if |a| - * is 2 then setting bit zero will make it 3. It returns one on success or zero - * on allocation failure. */ -OPENSSL_EXPORT int BN_set_bit(BIGNUM *a, int n); - -/* BN_clear_bit clears the |n|th, least-significant bit in |a|. For example, if - * |a| is 3, clearing bit zero will make it two. It returns one on success or - * zero on allocation failure. */ -OPENSSL_EXPORT int BN_clear_bit(BIGNUM *a, int n); - -/* BN_is_bit_set returns the value of the |n|th, least-significant bit in |a|, - * or zero if the bit doesn't exist. */ -OPENSSL_EXPORT int BN_is_bit_set(const BIGNUM *a, int n); - -/* BN_mask_bits truncates |a| so that it is only |n| bits long. It returns one - * on success or zero if |n| is greater than the length of |a| already. */ -OPENSSL_EXPORT int BN_mask_bits(BIGNUM *a, int n); - - -/* Modulo arithmetic. */ - -/* BN_mod_word returns |a| mod |w|. */ -OPENSSL_EXPORT BN_ULONG BN_mod_word(const BIGNUM *a, BN_ULONG w); - -/* BN_mod is a helper macro that calls |BN_div| and discards the quotient. */ -#define BN_mod(rem, numerator, divisor, ctx) \ - BN_div(NULL, (rem), (numerator), (divisor), (ctx)) - -/* BN_nnmod is a non-negative modulo function. It acts like |BN_mod|, but 0 <= - * |rem| < |divisor| is always true. It returns one on success and zero on - * error. */ -OPENSSL_EXPORT int BN_nnmod(BIGNUM *rem, const BIGNUM *numerator, - const BIGNUM *divisor, BN_CTX *ctx); - -/* BN_mod_add sets |r| = |a| + |b| mod |m|. It returns one on success and zero - * on error. */ -OPENSSL_EXPORT int BN_mod_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, - const BIGNUM *m, BN_CTX *ctx); - -/* BN_mod_add_quick acts like |BN_mod_add| but requires that |a| and |b| be - * non-negative and less than |m|. */ -OPENSSL_EXPORT int BN_mod_add_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, - const BIGNUM *m); - -/* BN_mod_sub sets |r| = |a| - |b| mod |m|. It returns one on success and zero - * on error. */ -OPENSSL_EXPORT int BN_mod_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, - const BIGNUM *m, BN_CTX *ctx); - -/* BN_mod_sub_quick acts like |BN_mod_sub| but requires that |a| and |b| be - * non-negative and less than |m|. */ -OPENSSL_EXPORT int BN_mod_sub_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, - const BIGNUM *m); - -/* BN_mod_mul sets |r| = |a|*|b| mod |m|. It returns one on success and zero - * on error. */ -OPENSSL_EXPORT int BN_mod_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, - const BIGNUM *m, BN_CTX *ctx); - -/* BN_mod_mul sets |r| = |a|^2 mod |m|. It returns one on success and zero - * on error. */ -OPENSSL_EXPORT int BN_mod_sqr(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, - BN_CTX *ctx); - -/* BN_mod_lshift sets |r| = (|a| << n) mod |m|, where |r| and |a| may be the - * same pointer. It returns one on success and zero on error. */ -OPENSSL_EXPORT int BN_mod_lshift(BIGNUM *r, const BIGNUM *a, int n, - const BIGNUM *m, BN_CTX *ctx); - -/* BN_mod_lshift_quick acts like |BN_mod_lshift| but requires that |a| be - * non-negative and less than |m|. */ -OPENSSL_EXPORT int BN_mod_lshift_quick(BIGNUM *r, const BIGNUM *a, int n, - const BIGNUM *m); - -/* BN_mod_lshift1 sets |r| = (|a| << 1) mod |m|, where |r| and |a| may be the - * same pointer. It returns one on success and zero on error. */ -OPENSSL_EXPORT int BN_mod_lshift1(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, - BN_CTX *ctx); - -/* BN_mod_lshift1_quick acts like |BN_mod_lshift1| but requires that |a| be - * non-negative and less than |m|. */ -OPENSSL_EXPORT int BN_mod_lshift1_quick(BIGNUM *r, const BIGNUM *a, - const BIGNUM *m); - -/* BN_mod_sqrt returns a |BIGNUM|, r, such that r^2 == a (mod p). */ -OPENSSL_EXPORT BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, - BN_CTX *ctx); - - -/* Random and prime number generation. */ - -/* BN_rand sets |rnd| to a random number of length |bits|. If |top| is zero, the - * most-significant bit, if any, will be set. If |top| is one, the two most - * significant bits, if any, will be set. - * - * If |top| is -1 then no extra action will be taken and |BN_num_bits(rnd)| may - * not equal |bits| if the most significant bits randomly ended up as zeros. - * - * If |bottom| is non-zero, the least-significant bit, if any, will be set. The - * function returns one on success or zero otherwise. */ -OPENSSL_EXPORT int BN_rand(BIGNUM *rnd, int bits, int top, int bottom); - -/* BN_pseudo_rand is an alias for |BN_rand|. */ -OPENSSL_EXPORT int BN_pseudo_rand(BIGNUM *rnd, int bits, int top, int bottom); - -/* BN_rand_range sets |rnd| to a random value [0..range). It returns one on - * success and zero otherwise. */ -OPENSSL_EXPORT int BN_rand_range(BIGNUM *rnd, const BIGNUM *range); - -/* BN_pseudo_rand_range is an alias for BN_rand_range. */ -OPENSSL_EXPORT int BN_pseudo_rand_range(BIGNUM *rnd, const BIGNUM *range); - -/* BN_generate_dsa_nonce generates a random number 0 <= out < range. Unlike - * BN_rand_range, it also includes the contents of |priv| and |message| in the - * generation so that an RNG failure isn't fatal as long as |priv| remains - * secret. This is intended for use in DSA and ECDSA where an RNG weakness - * leads directly to private key exposure unless this function is used. - * It returns one on success and zero on error. */ -OPENSSL_EXPORT int BN_generate_dsa_nonce(BIGNUM *out, const BIGNUM *range, - const BIGNUM *priv, - const uint8_t *message, - size_t message_len, BN_CTX *ctx); - -/* BN_GENCB holds a callback function that is used by generation functions that - * can take a very long time to complete. Use |BN_GENCB_set| to initialise a - * |BN_GENCB| structure. - * - * The callback receives the address of that |BN_GENCB| structure as its last - * argument and the user is free to put an arbitary pointer in |arg|. The other - * arguments are set as follows: - * event=BN_GENCB_GENERATED, n=i: after generating the i'th possible prime - * number. - * event=BN_GENCB_PRIME_TEST, n=-1: when finished trial division primality - * checks. - * event=BN_GENCB_PRIME_TEST, n=i: when the i'th primality test has finished. - * - * The callback can return zero to abort the generation progress or one to - * allow it to continue. - * - * When other code needs to call a BN generation function it will often take a - * BN_GENCB argument and may call the function with other argument values. */ -#define BN_GENCB_GENERATED 0 -#define BN_GENCB_PRIME_TEST 1 - -struct bn_gencb_st { - void *arg; /* callback-specific data */ - int (*callback)(int event, int n, struct bn_gencb_st *); -}; - -/* BN_GENCB_set configures |callback| to call |f| and sets |callout->arg| to - * |arg|. */ -OPENSSL_EXPORT void BN_GENCB_set(BN_GENCB *callback, - int (*f)(int event, int n, - struct bn_gencb_st *), - void *arg); - -/* BN_GENCB_call calls |callback|, if not NULL, and returns the return value of - * the callback, or 1 if |callback| is NULL. */ -OPENSSL_EXPORT int BN_GENCB_call(BN_GENCB *callback, int event, int n); - -/* BN_generate_prime_ex sets |ret| to a prime number of |bits| length. If safe - * is non-zero then the prime will be such that (ret-1)/2 is also a prime. - * (This is needed for Diffie-Hellman groups to ensure that the only subgroups - * are of size 2 and (p-1)/2.). - * - * If |add| is not NULL, the prime will fulfill the condition |ret| % |add| == - * |rem| in order to suit a given generator. (If |rem| is NULL then |ret| % - * |add| == 1.) - * - * If |cb| is not NULL, it will be called during processing to give an - * indication of progress. See the comments for |BN_GENCB|. It returns one on - * success and zero otherwise. */ -OPENSSL_EXPORT int BN_generate_prime_ex(BIGNUM *ret, int bits, int safe, - const BIGNUM *add, const BIGNUM *rem, - BN_GENCB *cb); - -/* BN_prime_checks is magic value that can be used as the |checks| argument to - * the primality testing functions in order to automatically select a number of - * Miller-Rabin checks that gives a false positive rate of ~2^{-80}. */ -#define BN_prime_checks 0 - -/* BN_primality_test sets |*is_probably_prime| to one if |candidate| is - * probably a prime number by the Miller-Rabin test or zero if it's certainly - * not. - * - * If |do_trial_division| is non-zero then |candidate| will be tested against a - * list of small primes before Miller-Rabin tests. The probability of this - * function returning a false positive is 2^{2*checks}. If |checks| is - * |BN_prime_checks| then a value that results in approximately 2^{-80} false - * positive probability is used. If |cb| is not NULL then it is called during - * the checking process. See the comment above |BN_GENCB|. - * - * The function returns one on success and zero on error. - * - * (If you are unsure whether you want |do_trial_division|, don't set it.) */ -OPENSSL_EXPORT int BN_primality_test(int *is_probably_prime, - const BIGNUM *candidate, int checks, - BN_CTX *ctx, int do_trial_division, - BN_GENCB *cb); - -/* BN_is_prime_fasttest_ex returns one if |candidate| is probably a prime - * number by the Miller-Rabin test, zero if it's certainly not and -1 on error. - * - * If |do_trial_division| is non-zero then |candidate| will be tested against a - * list of small primes before Miller-Rabin tests. The probability of this - * function returning one when |candidate| is composite is 2^{2*checks}. If - * |checks| is |BN_prime_checks| then a value that results in approximately - * 2^{-80} false positive probability is used. If |cb| is not NULL then it is - * called during the checking process. See the comment above |BN_GENCB|. - * - * WARNING: deprecated. Use |BN_primality_test|. */ -OPENSSL_EXPORT int BN_is_prime_fasttest_ex(const BIGNUM *candidate, int checks, - BN_CTX *ctx, int do_trial_division, - BN_GENCB *cb); - -/* BN_is_prime_ex acts the same as |BN_is_prime_fasttest_ex| with - * |do_trial_division| set to zero. - * - * WARNING: deprecated: Use |BN_primality_test|. */ -OPENSSL_EXPORT int BN_is_prime_ex(const BIGNUM *candidate, int checks, - BN_CTX *ctx, BN_GENCB *cb); - - -/* Number theory functions */ - -/* BN_gcd sets |r| = gcd(|a|, |b|). It returns one on success and zero - * otherwise. */ -OPENSSL_EXPORT int BN_gcd(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, - BN_CTX *ctx); - -/* BN_mod_inverse sets |out| equal to |a|^-1, mod |n|. If either of |a| or |n| - * have |BN_FLG_CONSTTIME| set then the operation is performed in constant - * time. If |out| is NULL, a fresh BIGNUM is allocated. It returns the result - * or NULL on error. */ -OPENSSL_EXPORT BIGNUM *BN_mod_inverse(BIGNUM *out, const BIGNUM *a, - const BIGNUM *n, BN_CTX *ctx); - -/* BN_kronecker returns the Kronecker symbol of |a| and |b| (which is -1, 0 or - * 1), or -2 on error. */ -OPENSSL_EXPORT int BN_kronecker(const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx); - - -/* Montgomery arithmetic. */ - -/* BN_MONT_CTX contains the precomputed values needed to work in a specific - * Montgomery domain. */ - -/* BN_MONT_CTX_new returns a fresh BN_MONT_CTX or NULL on allocation failure. */ -OPENSSL_EXPORT BN_MONT_CTX *BN_MONT_CTX_new(void); - -/* BN_MONT_CTX_init initialises a stack allocated |BN_MONT_CTX|. */ -OPENSSL_EXPORT void BN_MONT_CTX_init(BN_MONT_CTX *mont); - -/* BN_MONT_CTX_free frees the contexts of |mont| and, if it was originally - * allocated with |BN_MONT_CTX_new|, |mont| itself. */ -OPENSSL_EXPORT void BN_MONT_CTX_free(BN_MONT_CTX *mont); - -/* BN_MONT_CTX_copy sets |to| equal to |from|. It returns |to| on success or - * NULL on error. */ -OPENSSL_EXPORT BN_MONT_CTX *BN_MONT_CTX_copy(BN_MONT_CTX *to, - BN_MONT_CTX *from); - -/* BN_MONT_CTX_set sets up a Montgomery context given the modulus, |mod|. It - * returns one on success and zero on error. */ -OPENSSL_EXPORT int BN_MONT_CTX_set(BN_MONT_CTX *mont, const BIGNUM *mod, - BN_CTX *ctx); - -/* BN_MONT_CTX_set_locked takes |lock| and checks whether |*pmont| is NULL. If - * so, it creates a new |BN_MONT_CTX| and sets the modulus for it to |mod|. It - * then stores it as |*pmont| and returns it, or NULL on error. - * - * If |*pmont| is already non-NULL then the existing value is returned. */ -BN_MONT_CTX *BN_MONT_CTX_set_locked(BN_MONT_CTX **pmont, CRYPTO_MUTEX *lock, - const BIGNUM *mod, BN_CTX *bn_ctx); - -/* BN_to_montgomery sets |ret| equal to |a| in the Montgomery domain. It - * returns one on success and zero on error. */ -OPENSSL_EXPORT int BN_to_montgomery(BIGNUM *ret, const BIGNUM *a, - const BN_MONT_CTX *mont, BN_CTX *ctx); - -/* BN_from_montgomery sets |ret| equal to |a| * R^-1, i.e. translates values - * out of the Montgomery domain. It returns one on success or zero on error. */ -OPENSSL_EXPORT int BN_from_montgomery(BIGNUM *ret, const BIGNUM *a, - const BN_MONT_CTX *mont, BN_CTX *ctx); - -/* BN_mod_mul_montgomery set |r| equal to |a| * |b|, in the Montgomery domain. - * Both |a| and |b| must already be in the Montgomery domain (by - * |BN_to_montgomery|). It returns one on success or zero on error. */ -OPENSSL_EXPORT int BN_mod_mul_montgomery(BIGNUM *r, const BIGNUM *a, - const BIGNUM *b, - const BN_MONT_CTX *mont, BN_CTX *ctx); - - -/* Exponentiation. */ - -/* BN_exp sets |r| equal to |a|^{|p|}. It does so with a square-and-multiply - * algorithm that leaks side-channel information. It returns one on success or - * zero otherwise. */ -OPENSSL_EXPORT int BN_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, - BN_CTX *ctx); - -/* BN_mod_exp sets |r| equal to |a|^{|p|} mod |m|. It does so with the best - * algorithm for the values provided and can run in constant time if - * |BN_FLG_CONSTTIME| is set for |p|. It returns one on success or zero - * otherwise. */ -OPENSSL_EXPORT int BN_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, - const BIGNUM *m, BN_CTX *ctx); - -OPENSSL_EXPORT int BN_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, - const BIGNUM *m, BN_CTX *ctx, - BN_MONT_CTX *m_ctx); - -OPENSSL_EXPORT int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, - const BIGNUM *p, const BIGNUM *m, - BN_CTX *ctx, BN_MONT_CTX *in_mont); - -OPENSSL_EXPORT int BN_mod_exp_mont_word(BIGNUM *r, BN_ULONG a, const BIGNUM *p, - const BIGNUM *m, BN_CTX *ctx, - BN_MONT_CTX *m_ctx); -OPENSSL_EXPORT int BN_mod_exp2_mont(BIGNUM *r, const BIGNUM *a1, - const BIGNUM *p1, const BIGNUM *a2, - const BIGNUM *p2, const BIGNUM *m, - BN_CTX *ctx, BN_MONT_CTX *m_ctx); - - -/* Private functions */ - -struct bignum_st { - BN_ULONG *d; /* Pointer to an array of 'BN_BITS2' bit chunks in little-endian - order. */ - int top; /* Index of last used element in |d|, plus one. */ - int dmax; /* Size of |d|, in words. */ - int neg; /* one if the number is negative */ - int flags; /* bitmask of BN_FLG_* values */ -}; - -struct bn_mont_ctx_st { - BIGNUM RR; /* used to convert to montgomery form */ - BIGNUM N; /* The modulus */ - BIGNUM Ni; /* R*(1/R mod N) - N*Ni = 1 - * (Ni is only stored for bignum algorithm) */ - BN_ULONG n0[2]; /* least significant word(s) of Ni; - (type changed with 0.9.9, was "BN_ULONG n0;" before) */ - int flags; - int ri; /* number of bits in R */ -}; - -OPENSSL_EXPORT unsigned BN_num_bits_word(BN_ULONG l); - -#define BN_FLG_MALLOCED 0x01 -#define BN_FLG_STATIC_DATA 0x02 -/* avoid leaking exponent information through timing, BN_mod_exp_mont() will - * call BN_mod_exp_mont_consttime, BN_div() will call BN_div_no_branch, - * BN_mod_inverse() will call BN_mod_inverse_no_branch. */ -#define BN_FLG_CONSTTIME 0x04 - - -/* Android compatibility section. - * - * These functions are declared, temporarily, for Android because - * wpa_supplicant will take a little time to sync with upstream. Outside of - * Android they'll have no definition. */ - -OPENSSL_EXPORT BIGNUM *get_rfc3526_prime_1536(BIGNUM *bn); - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#define BN_F_BN_CTX_get 100 -#define BN_F_BN_CTX_new 101 -#define BN_F_BN_CTX_start 102 -#define BN_F_BN_bn2dec 103 -#define BN_F_BN_bn2hex 104 -#define BN_F_BN_div 105 -#define BN_F_BN_div_recp 106 -#define BN_F_BN_exp 107 -#define BN_F_BN_generate_dsa_nonce 108 -#define BN_F_BN_generate_prime_ex 109 -#define BN_F_BN_mod_exp2_mont 110 -#define BN_F_BN_mod_exp_mont 111 -#define BN_F_BN_mod_exp_mont_consttime 112 -#define BN_F_BN_mod_exp_mont_word 113 -#define BN_F_BN_mod_inverse 114 -#define BN_F_BN_mod_inverse_no_branch 115 -#define BN_F_BN_mod_lshift_quick 116 -#define BN_F_BN_mod_sqrt 117 -#define BN_F_BN_new 118 -#define BN_F_BN_rand 119 -#define BN_F_BN_rand_range 120 -#define BN_F_BN_sqrt 121 -#define BN_F_BN_usub 122 -#define BN_F_bn_wexpand 123 -#define BN_F_mod_exp_recp 124 -#define BN_F_BN_lshift 125 -#define BN_F_BN_rshift 126 -#define BN_R_ARG2_LT_ARG3 100 -#define BN_R_BAD_RECIPROCAL 101 -#define BN_R_BIGNUM_TOO_LONG 102 -#define BN_R_BITS_TOO_SMALL 103 -#define BN_R_CALLED_WITH_EVEN_MODULUS 104 -#define BN_R_DIV_BY_ZERO 105 -#define BN_R_EXPAND_ON_STATIC_BIGNUM_DATA 106 -#define BN_R_INPUT_NOT_REDUCED 107 -#define BN_R_INVALID_RANGE 108 -#define BN_R_NEGATIVE_NUMBER 109 -#define BN_R_NOT_A_SQUARE 110 -#define BN_R_NOT_INITIALIZED 111 -#define BN_R_NO_INVERSE 112 -#define BN_R_PRIVATE_KEY_TOO_LARGE 113 -#define BN_R_P_IS_NOT_PRIME 114 -#define BN_R_TOO_MANY_ITERATIONS 115 -#define BN_R_TOO_MANY_TEMPORARY_VARIABLES 116 - -#endif /* OPENSSL_HEADER_BN_H */ diff --git a/third_party/boringssl/include/openssl/buf.h b/third_party/boringssl/include/openssl/buf.h deleted file mode 100644 index 2b36ce4058..0000000000 --- a/third_party/boringssl/include/openssl/buf.h +++ /dev/null @@ -1,123 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] */ - -#ifndef OPENSSL_HEADER_BUFFER_H -#define OPENSSL_HEADER_BUFFER_H - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* Memory and string functions, see also mem.h. */ - - -/* BUF_MEM is a generic buffer object used by OpenSSL. */ -struct buf_mem_st { - size_t length; /* current number of bytes */ - char *data; - size_t max; /* size of buffer */ -}; - -/* BUF_MEM_new creates a new BUF_MEM which has no allocated data buffer. */ -OPENSSL_EXPORT BUF_MEM *BUF_MEM_new(void); - -/* BUF_MEM_free frees |buf->data| if needed and then frees |buf| itself. */ -OPENSSL_EXPORT void BUF_MEM_free(BUF_MEM *buf); - -/* BUF_MEM_grow ensures that |buf| has length |len| and allocates memory if - * needed. If the length of |buf| increased, the new bytes are filled with - * zeros. It returns the length of |buf|, or zero if there's an error. */ -OPENSSL_EXPORT size_t BUF_MEM_grow(BUF_MEM *buf, size_t len); - -/* BUF_MEM_grow_clean acts the same as |BUF_MEM_grow|, but clears the previous - * contents of memory if reallocing. */ -OPENSSL_EXPORT size_t BUF_MEM_grow_clean(BUF_MEM *str, size_t len); - -/* BUF_strdup returns an allocated, duplicate of |str|. */ -OPENSSL_EXPORT char *BUF_strdup(const char *str); - -/* BUF_strnlen returns the number of characters in |str|, excluding the NUL - * byte, but at most |max_len|. This function never reads more than |max_len| - * bytes from |str|. */ -OPENSSL_EXPORT size_t BUF_strnlen(const char *str, size_t max_len); - -/* BUF_strndup returns an allocated, duplicate of |str|, which is, at most, - * |size| bytes. The result is always NUL terminated. */ -OPENSSL_EXPORT char *BUF_strndup(const char *str, size_t size); - -/* BUF_memdup returns an allocated, duplicate of |size| bytes from |data|. */ -OPENSSL_EXPORT void *BUF_memdup(const void *data, size_t size); - -/* BUF_strlcpy acts like strlcpy(3). */ -OPENSSL_EXPORT size_t BUF_strlcpy(char *dst, const char *src, size_t dst_size); - -/* BUF_strlcat acts like strlcat(3). */ -OPENSSL_EXPORT size_t BUF_strlcat(char *dst, const char *src, size_t size); - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#define BUF_F_BUF_MEM_new 100 -#define BUF_F_BUF_memdup 101 -#define BUF_F_BUF_strndup 102 -#define BUF_F_buf_mem_grow 103 - -#endif /* OPENSSL_HEADER_BUFFER_H */ diff --git a/third_party/boringssl/include/openssl/buffer.h b/third_party/boringssl/include/openssl/buffer.h deleted file mode 100644 index c6b721c277..0000000000 --- a/third_party/boringssl/include/openssl/buffer.h +++ /dev/null @@ -1,18 +0,0 @@ -/* Copyright (c) 2015, Google Inc. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -/* This header is provided in order to make compiling against code that expects - OpenSSL easier. */ - -#include "buf.h" diff --git a/third_party/boringssl/include/openssl/bytestring.h b/third_party/boringssl/include/openssl/bytestring.h deleted file mode 100644 index 9963426ca3..0000000000 --- a/third_party/boringssl/include/openssl/bytestring.h +++ /dev/null @@ -1,325 +0,0 @@ -/* Copyright (c) 2014, Google Inc. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -#ifndef OPENSSL_HEADER_BYTESTRING_H -#define OPENSSL_HEADER_BYTESTRING_H - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* Bytestrings are used for parsing and building TLS and ASN.1 messages. - * - * A "CBS" (CRYPTO ByteString) represents a string of bytes in memory and - * provides utility functions for safely parsing length-prefixed structures - * like TLS and ASN.1 from it. - * - * A "CBB" (CRYPTO ByteBuilder) is a memory buffer that grows as needed and - * provides utility functions for building length-prefixed messages. */ - - -/* CRYPTO ByteString */ - -struct cbs_st { - const uint8_t *data; - size_t len; -}; - -/* CBS_init sets |cbs| to point to |data|. It does not take ownership of - * |data|. */ -OPENSSL_EXPORT void CBS_init(CBS *cbs, const uint8_t *data, size_t len); - -/* CBS_skip advances |cbs| by |len| bytes. It returns one on success and zero - * otherwise. */ -OPENSSL_EXPORT int CBS_skip(CBS *cbs, size_t len); - -/* CBS_data returns a pointer to the contents of |cbs|. */ -OPENSSL_EXPORT const uint8_t *CBS_data(const CBS *cbs); - -/* CBS_len returns the number of bytes remaining in |cbs|. */ -OPENSSL_EXPORT size_t CBS_len(const CBS *cbs); - -/* CBS_stow copies the current contents of |cbs| into |*out_ptr| and - * |*out_len|. If |*out_ptr| is not NULL, the contents are freed with - * OPENSSL_free. It returns one on success and zero on allocation failure. On - * success, |*out_ptr| should be freed with OPENSSL_free. If |cbs| is empty, - * |*out_ptr| will be NULL. */ -OPENSSL_EXPORT int CBS_stow(const CBS *cbs, uint8_t **out_ptr, size_t *out_len); - -/* CBS_strdup copies the current contents of |cbs| into |*out_ptr| as a - * NUL-terminated C string. If |*out_ptr| is not NULL, the contents are freed - * with OPENSSL_free. It returns one on success and zero on allocation - * failure. On success, |*out_ptr| should be freed with OPENSSL_free. - * - * NOTE: If |cbs| contains NUL bytes, the string will be truncated. Call - * |CBS_contains_zero_byte(cbs)| to check for NUL bytes. */ -OPENSSL_EXPORT int CBS_strdup(const CBS *cbs, char **out_ptr); - -/* CBS_contains_zero_byte returns one if the current contents of |cbs| contains - * a NUL byte and zero otherwise. */ -OPENSSL_EXPORT int CBS_contains_zero_byte(const CBS *cbs); - -/* CBS_mem_equal compares the current contents of |cbs| with the |len| bytes - * starting at |data|. If they're equal, it returns one, otherwise zero. If the - * lengths match, it uses a constant-time comparison. */ -OPENSSL_EXPORT int CBS_mem_equal(const CBS *cbs, const uint8_t *data, - size_t len); - -/* CBS_get_u8 sets |*out| to the next uint8_t from |cbs| and advances |cbs|. It - * returns one on success and zero on error. */ -OPENSSL_EXPORT int CBS_get_u8(CBS *cbs, uint8_t *out); - -/* CBS_get_u16 sets |*out| to the next, big-endian uint16_t from |cbs| and - * advances |cbs|. It returns one on success and zero on error. */ -OPENSSL_EXPORT int CBS_get_u16(CBS *cbs, uint16_t *out); - -/* CBS_get_u24 sets |*out| to the next, big-endian 24-bit value from |cbs| and - * advances |cbs|. It returns one on success and zero on error. */ -OPENSSL_EXPORT int CBS_get_u24(CBS *cbs, uint32_t *out); - -/* CBS_get_u32 sets |*out| to the next, big-endian uint32_t value from |cbs| - * and advances |cbs|. It returns one on success and zero on error. */ -OPENSSL_EXPORT int CBS_get_u32(CBS *cbs, uint32_t *out); - -/* CBS_get_bytes sets |*out| to the next |len| bytes from |cbs| and advances - * |cbs|. It returns one on success and zero on error. */ -OPENSSL_EXPORT int CBS_get_bytes(CBS *cbs, CBS *out, size_t len); - -/* CBS_get_u8_length_prefixed sets |*out| to the contents of an 8-bit, - * length-prefixed value from |cbs| and advances |cbs| over it. It returns one - * on success and zero on error. */ -OPENSSL_EXPORT int CBS_get_u8_length_prefixed(CBS *cbs, CBS *out); - -/* CBS_get_u16_length_prefixed sets |*out| to the contents of a 16-bit, - * big-endian, length-prefixed value from |cbs| and advances |cbs| over it. It - * returns one on success and zero on error. */ -OPENSSL_EXPORT int CBS_get_u16_length_prefixed(CBS *cbs, CBS *out); - -/* CBS_get_u24_length_prefixed sets |*out| to the contents of a 24-bit, - * big-endian, length-prefixed value from |cbs| and advances |cbs| over it. It - * returns one on success and zero on error. */ -OPENSSL_EXPORT int CBS_get_u24_length_prefixed(CBS *cbs, CBS *out); - - -/* Parsing ASN.1 */ - -#define CBS_ASN1_BOOLEAN 0x1 -#define CBS_ASN1_INTEGER 0x2 -#define CBS_ASN1_BITSTRING 0x3 -#define CBS_ASN1_OCTETSTRING 0x4 -#define CBS_ASN1_OBJECT 0x6 -#define CBS_ASN1_ENUMERATED 0xa -#define CBS_ASN1_SEQUENCE (0x10 | CBS_ASN1_CONSTRUCTED) -#define CBS_ASN1_SET (0x11 | CBS_ASN1_CONSTRUCTED) - -#define CBS_ASN1_CONSTRUCTED 0x20 -#define CBS_ASN1_CONTEXT_SPECIFIC 0x80 - -/* CBS_get_asn1 sets |*out| to the contents of DER-encoded, ASN.1 element (not - * including tag and length bytes) and advances |cbs| over it. The ASN.1 - * element must match |tag_value|. It returns one on success and zero - * on error. - * - * Tag numbers greater than 30 are not supported (i.e. short form only). */ -OPENSSL_EXPORT int CBS_get_asn1(CBS *cbs, CBS *out, unsigned tag_value); - -/* CBS_get_asn1_element acts like |CBS_get_asn1| but |out| will include the - * ASN.1 header bytes too. */ -OPENSSL_EXPORT int CBS_get_asn1_element(CBS *cbs, CBS *out, unsigned tag_value); - -/* CBS_peek_asn1_tag looks ahead at the next ASN.1 tag and returns one - * if the next ASN.1 element on |cbs| would have tag |tag_value|. If - * |cbs| is empty or the tag does not match, it returns zero. Note: if - * it returns one, CBS_get_asn1 may still fail if the rest of the - * element is malformed. */ -OPENSSL_EXPORT int CBS_peek_asn1_tag(const CBS *cbs, unsigned tag_value); - -/* CBS_get_any_asn1_element sets |*out| to contain the next ASN.1 element from - * |*cbs| (including header bytes) and advances |*cbs|. It sets |*out_tag| to - * the tag number and |*out_header_len| to the length of the ASN.1 header. Each - * of |out|, |out_tag|, and |out_header_len| may be NULL to ignore the value. - * - * Tag numbers greater than 30 are not supported (i.e. short form only). */ -OPENSSL_EXPORT int CBS_get_any_asn1_element(CBS *cbs, CBS *out, - unsigned *out_tag, - size_t *out_header_len); - -/* CBS_get_asn1_uint64 gets an ASN.1 INTEGER from |cbs| using |CBS_get_asn1| - * and sets |*out| to its value. It returns one on success and zero on error, - * where error includes the integer being negative, or too large to represent - * in 64 bits. */ -OPENSSL_EXPORT int CBS_get_asn1_uint64(CBS *cbs, uint64_t *out); - -/* CBS_get_optional_asn1 gets an optional explicitly-tagged element - * from |cbs| tagged with |tag| and sets |*out| to its contents. If - * present, it sets |*out_present| to one, otherwise zero. It returns - * one on success, whether or not the element was present, and zero on - * decode failure. */ -OPENSSL_EXPORT int CBS_get_optional_asn1(CBS *cbs, CBS *out, int *out_present, - unsigned tag); - -/* CBS_get_optional_asn1_octet_string gets an optional - * explicitly-tagged OCTET STRING from |cbs|. If present, it sets - * |*out| to the string and |*out_present| to one. Otherwise, it sets - * |*out| to empty and |*out_present| to zero. |out_present| may be - * NULL. It returns one on success, whether or not the element was - * present, and zero on decode failure. */ -OPENSSL_EXPORT int CBS_get_optional_asn1_octet_string(CBS *cbs, CBS *out, - int *out_present, - unsigned tag); - -/* CBS_get_optional_asn1_uint64 gets an optional explicitly-tagged - * INTEGER from |cbs|. If present, it sets |*out| to the - * value. Otherwise, it sets |*out| to |default_value|. It returns one - * on success, whether or not the element was present, and zero on - * decode failure. */ -OPENSSL_EXPORT int CBS_get_optional_asn1_uint64(CBS *cbs, uint64_t *out, - unsigned tag, - uint64_t default_value); - -/* CBS_get_optional_asn1_bool gets an optional, explicitly-tagged BOOLEAN from - * |cbs|. If present, it sets |*out| to either zero or one, based on the - * boolean. Otherwise, it sets |*out| to |default_value|. It returns one on - * success, whether or not the element was present, and zero on decode - * failure. */ -OPENSSL_EXPORT int CBS_get_optional_asn1_bool(CBS *cbs, int *out, unsigned tag, - int default_value); - - -/* CRYPTO ByteBuilder. - * - * |CBB| objects allow one to build length-prefixed serialisations. A |CBB| - * object is associated with a buffer and new buffers are created with - * |CBB_init|. Several |CBB| objects can point at the same buffer when a - * length-prefix is pending, however only a single |CBB| can be 'current' at - * any one time. For example, if one calls |CBB_add_u8_length_prefixed| then - * the new |CBB| points at the same buffer as the original. But if the original - * |CBB| is used then the length prefix is written out and the new |CBB| must - * not be used again. - * - * If one needs to force a length prefix to be written out because a |CBB| is - * going out of scope, use |CBB_flush|. */ - -struct cbb_buffer_st { - uint8_t *buf; - size_t len; /* The number of valid bytes. */ - size_t cap; /* The size of buf. */ - char can_resize; /* One iff |buf| is owned by this object. If not then |buf| - cannot be resized. */ -}; - -struct cbb_st { - struct cbb_buffer_st *base; - /* offset is the offset from the start of |base->buf| to the position of any - * pending length-prefix. */ - size_t offset; - /* child points to a child CBB if a length-prefix is pending. */ - struct cbb_st *child; - /* pending_len_len contains the number of bytes in a pending length-prefix, - * or zero if no length-prefix is pending. */ - uint8_t pending_len_len; - char pending_is_asn1; - /* is_top_level is true iff this is a top-level |CBB| (as opposed to a child - * |CBB|). Top-level objects are valid arguments for |CBB_finish|. */ - char is_top_level; -}; - -/* CBB_init initialises |cbb| with |initial_capacity|. Since a |CBB| grows as - * needed, the |initial_capacity| is just a hint. It returns one on success or - * zero on error. */ -OPENSSL_EXPORT int CBB_init(CBB *cbb, size_t initial_capacity); - -/* CBB_init_fixed initialises |cbb| to write to |len| bytes at |buf|. Since - * |buf| cannot grow, trying to write more than |len| bytes will cause CBB - * functions to fail. It returns one on success or zero on error. */ -OPENSSL_EXPORT int CBB_init_fixed(CBB *cbb, uint8_t *buf, size_t len); - -/* CBB_cleanup frees all resources owned by |cbb| and other |CBB| objects - * writing to the same buffer. This should be used in an error case where a - * serialisation is abandoned. */ -OPENSSL_EXPORT void CBB_cleanup(CBB *cbb); - -/* CBB_finish completes any pending length prefix and sets |*out_data| to a - * malloced buffer and |*out_len| to the length of that buffer. The caller - * takes ownership of the buffer and, unless the buffer was fixed with - * |CBB_init_fixed|, must call |OPENSSL_free| when done. - * - * It can only be called on a "top level" |CBB|, i.e. one initialised with - * |CBB_init| or |CBB_init_fixed|. It returns one on success and zero on - * error. */ -OPENSSL_EXPORT int CBB_finish(CBB *cbb, uint8_t **out_data, size_t *out_len); - -/* CBB_flush causes any pending length prefixes to be written out and any child - * |CBB| objects of |cbb| to be invalidated. It returns one on success or zero - * on error. */ -OPENSSL_EXPORT int CBB_flush(CBB *cbb); - -/* CBB_add_u8_length_prefixed sets |*out_contents| to a new child of |cbb|. The - * data written to |*out_contents| will be prefixed in |cbb| with an 8-bit - * length. It returns one on success or zero on error. */ -OPENSSL_EXPORT int CBB_add_u8_length_prefixed(CBB *cbb, CBB *out_contents); - -/* CBB_add_u16_length_prefixed sets |*out_contents| to a new child of |cbb|. - * The data written to |*out_contents| will be prefixed in |cbb| with a 16-bit, - * big-endian length. It returns one on success or zero on error. */ -OPENSSL_EXPORT int CBB_add_u16_length_prefixed(CBB *cbb, CBB *out_contents); - -/* CBB_add_u24_length_prefixed sets |*out_contents| to a new child of |cbb|. - * The data written to |*out_contents| will be prefixed in |cbb| with a 24-bit, - * big-endian length. It returns one on success or zero on error. */ -OPENSSL_EXPORT int CBB_add_u24_length_prefixed(CBB *cbb, CBB *out_contents); - -/* CBB_add_asn sets |*out_contents| to a |CBB| into which the contents of an - * ASN.1 object can be written. The |tag| argument will be used as the tag for - * the object. Passing in |tag| number 31 will return in an error since only - * single octet identifiers are supported. It returns one on success or zero - * on error. */ -OPENSSL_EXPORT int CBB_add_asn1(CBB *cbb, CBB *out_contents, uint8_t tag); - -/* CBB_add_bytes appends |len| bytes from |data| to |cbb|. It returns one on - * success and zero otherwise. */ -OPENSSL_EXPORT int CBB_add_bytes(CBB *cbb, const uint8_t *data, size_t len); - -/* CBB_add_space appends |len| bytes to |cbb| and sets |*out_data| to point to - * the beginning of that space. The caller must then write |len| bytes of - * actual contents to |*out_data|. It returns one on success and zero - * otherwise. */ -OPENSSL_EXPORT int CBB_add_space(CBB *cbb, uint8_t **out_data, size_t len); - -/* CBB_add_u8 appends an 8-bit number from |value| to |cbb|. It returns one on - * success and zero otherwise. */ -OPENSSL_EXPORT int CBB_add_u8(CBB *cbb, uint8_t value); - -/* CBB_add_u8 appends a 16-bit, big-endian number from |value| to |cbb|. It - * returns one on success and zero otherwise. */ -OPENSSL_EXPORT int CBB_add_u16(CBB *cbb, uint16_t value); - -/* CBB_add_u24 appends a 24-bit, big-endian number from |value| to |cbb|. It - * returns one on success and zero otherwise. */ -OPENSSL_EXPORT int CBB_add_u24(CBB *cbb, uint32_t value); - -/* CBB_add_asn1_uint64 writes an ASN.1 INTEGER into |cbb| using |CBB_add_asn1| - * and writes |value| in its contents. It returns one on success and zero on - * error. */ -OPENSSL_EXPORT int CBB_add_asn1_uint64(CBB *cbb, uint64_t value); - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_BYTESTRING_H */ diff --git a/third_party/boringssl/include/openssl/cast.h b/third_party/boringssl/include/openssl/cast.h deleted file mode 100644 index 802172394e..0000000000 --- a/third_party/boringssl/include/openssl/cast.h +++ /dev/null @@ -1,96 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] */ - -#ifndef OPENSSL_HEADER_CAST_H -#define OPENSSL_HEADER_CAST_H - -#include - -#ifdef __cplusplus -extern "C" { -#endif - - -#define CAST_ENCRYPT 1 -#define CAST_DECRYPT 0 - -#define CAST_BLOCK 8 -#define CAST_KEY_LENGTH 16 - -typedef struct cast_key_st { - uint32_t data[32]; - int short_key; /* Use reduced rounds for short key */ -} CAST_KEY; - -OPENSSL_EXPORT void CAST_set_key(CAST_KEY *key, size_t len, - const uint8_t *data); -OPENSSL_EXPORT void CAST_ecb_encrypt(const uint8_t *in, uint8_t *out, - const CAST_KEY *key, int enc); -OPENSSL_EXPORT void CAST_encrypt(uint32_t *data, const CAST_KEY *key); -OPENSSL_EXPORT void CAST_decrypt(uint32_t *data, const CAST_KEY *key); -OPENSSL_EXPORT void CAST_cbc_encrypt(const uint8_t *in, uint8_t *out, - long length, const CAST_KEY *ks, - uint8_t *iv, int enc); - -OPENSSL_EXPORT void CAST_cfb64_encrypt(const uint8_t *in, uint8_t *out, - long length, const CAST_KEY *schedule, - uint8_t *ivec, int *num, int enc); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_HEADER_CAST_H */ diff --git a/third_party/boringssl/include/openssl/chacha.h b/third_party/boringssl/include/openssl/chacha.h deleted file mode 100644 index ce53d49fda..0000000000 --- a/third_party/boringssl/include/openssl/chacha.h +++ /dev/null @@ -1,37 +0,0 @@ -/* Copyright (c) 2014, Google Inc. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -#ifndef OPENSSL_HEADER_CHACHA_H -#define OPENSSL_HEADER_CHACHA_H - -#include - -#ifdef __cplusplus -extern "C" { -#endif - - -/* CRYPTO_chacha_20 encrypts |in_len| bytes from |in| with the given key and - * nonce and writes the result to |out|, which may be equal to |in|. The - * initial block counter is specified by |counter|. */ -void CRYPTO_chacha_20(uint8_t *out, const uint8_t *in, - size_t in_len, const uint8_t key[32], - const uint8_t nonce[8], size_t counter); - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_CHACHA_H */ diff --git a/third_party/boringssl/include/openssl/cipher.h b/third_party/boringssl/include/openssl/cipher.h deleted file mode 100644 index 3e496f15b5..0000000000 --- a/third_party/boringssl/include/openssl/cipher.h +++ /dev/null @@ -1,598 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] */ - -#ifndef OPENSSL_HEADER_CIPHER_H -#define OPENSSL_HEADER_CIPHER_H - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* Ciphers. */ - - -/* Cipher primitives. - * - * The following functions return |EVP_CIPHER| objects that implement the named - * cipher algorithm. */ - -OPENSSL_EXPORT const EVP_CIPHER *EVP_rc4(void); - -OPENSSL_EXPORT const EVP_CIPHER *EVP_des_cbc(void); -OPENSSL_EXPORT const EVP_CIPHER *EVP_des_ecb(void); -OPENSSL_EXPORT const EVP_CIPHER *EVP_des_ede3_cbc(void); - -OPENSSL_EXPORT const EVP_CIPHER *EVP_aes_128_ecb(void); -OPENSSL_EXPORT const EVP_CIPHER *EVP_aes_128_cbc(void); -OPENSSL_EXPORT const EVP_CIPHER *EVP_aes_128_ctr(void); -OPENSSL_EXPORT const EVP_CIPHER *EVP_aes_128_ofb(void); - -OPENSSL_EXPORT const EVP_CIPHER *EVP_aes_256_ecb(void); -OPENSSL_EXPORT const EVP_CIPHER *EVP_aes_256_cbc(void); -OPENSSL_EXPORT const EVP_CIPHER *EVP_aes_256_ctr(void); -OPENSSL_EXPORT const EVP_CIPHER *EVP_aes_256_ofb(void); - -/* Deprecated AES-GCM implementations that set |EVP_CIPH_FLAG_CUSTOM_CIPHER|. - * Use |EVP_aead_aes_128_gcm| and |EVP_aead_aes_256_gcm| instead. */ -OPENSSL_EXPORT const EVP_CIPHER *EVP_aes_128_gcm(void); -OPENSSL_EXPORT const EVP_CIPHER *EVP_aes_256_gcm(void); - -/* Deprecated 192-bit version of AES. */ -OPENSSL_EXPORT const EVP_CIPHER *EVP_aes_192_ecb(void); -OPENSSL_EXPORT const EVP_CIPHER *EVP_aes_192_cbc(void); -OPENSSL_EXPORT const EVP_CIPHER *EVP_aes_192_ctr(void); -OPENSSL_EXPORT const EVP_CIPHER *EVP_aes_192_gcm(void); - -/* EVP_enc_null returns a 'cipher' that passes plaintext through as - * ciphertext. */ -OPENSSL_EXPORT const EVP_CIPHER *EVP_enc_null(void); - -/* EVP_rc2_40_cbc returns a cipher that implements 40-bit RC2 in CBC mode. This - * is obviously very, very weak and is included only in order to read PKCS#12 - * files, which often encrypt the certificate chain using this cipher. It is - * deliberately not exported. */ -const EVP_CIPHER *EVP_rc2_40_cbc(void); - -/* EVP_get_cipherbynid returns the cipher corresponding to the given NID, or - * NULL if no such cipher is known. */ -OPENSSL_EXPORT const EVP_CIPHER *EVP_get_cipherbynid(int nid); - - -/* Cipher context allocation. - * - * An |EVP_CIPHER_CTX| represents the state of an encryption or decryption in - * progress. */ - -/* EVP_CIPHER_CTX_init initialises an, already allocated, |EVP_CIPHER_CTX|. */ -OPENSSL_EXPORT void EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *ctx); - -/* EVP_CIPHER_CTX_new allocates a fresh |EVP_CIPHER_CTX|, calls - * |EVP_CIPHER_CTX_init| and returns it, or NULL on allocation failure. */ -OPENSSL_EXPORT EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void); - -/* EVP_CIPHER_CTX_cleanup frees any memory referenced by |ctx|. It returns - * one. */ -OPENSSL_EXPORT int EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *ctx); - -/* EVP_CIPHER_CTX_free calls |EVP_CIPHER_CTX_cleanup| on |ctx| and then frees - * |ctx| itself. */ -OPENSSL_EXPORT void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx); - -/* EVP_CIPHER_CTX_copy sets |out| to be a duplicate of the current state of - * |in|. The |out| argument must have been previously initialised. */ -OPENSSL_EXPORT int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, - const EVP_CIPHER_CTX *in); - - -/* Cipher context configuration. */ - -/* EVP_CipherInit_ex configures |ctx| for a fresh encryption (or decryption, if - * |enc| is zero) operation using |cipher|. If |ctx| has been previously - * configured with a cipher then |cipher|, |key| and |iv| may be |NULL| and - * |enc| may be -1 to reuse the previous values. The operation will use |key| - * as the key and |iv| as the IV (if any). These should have the correct - * lengths given by |EVP_CIPHER_key_length| and |EVP_CIPHER_iv_length|. It - * returns one on success and zero on error. */ -OPENSSL_EXPORT int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, - const EVP_CIPHER *cipher, ENGINE *engine, - const uint8_t *key, const uint8_t *iv, - int enc); - -/* EVP_EncryptInit_ex calls |EVP_CipherInit_ex| with |enc| equal to one. */ -OPENSSL_EXPORT int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, - const EVP_CIPHER *cipher, ENGINE *impl, - const uint8_t *key, const uint8_t *iv); - -/* EVP_DecryptInit_ex calls |EVP_CipherInit_ex| with |enc| equal to zero. */ -OPENSSL_EXPORT int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, - const EVP_CIPHER *cipher, ENGINE *impl, - const uint8_t *key, const uint8_t *iv); - - -/* Cipher operations. */ - -/* EVP_EncryptUpdate encrypts |in_len| bytes from |in| to |out|. The number - * of output bytes may be up to |in_len| plus the block length minus one and - * |out| must have sufficient space. The number of bytes actually output is - * written to |*out_len|. It returns one on success and zero otherwise. */ -OPENSSL_EXPORT int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, uint8_t *out, - int *out_len, const uint8_t *in, - int in_len); - -/* EVP_EncryptFinal_ex writes at most a block of ciphertext to |out| and sets - * |*out_len| to the number of bytes written. If padding is enabled (the - * default) then standard padding is applied to create the final block. If - * padding is disabled (with |EVP_CIPHER_CTX_set_padding|) then any partial - * block remaining will cause an error. The function returns one on success and - * zero otherwise. */ -OPENSSL_EXPORT int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, uint8_t *out, - int *out_len); - -/* EVP_DecryptUpdate decrypts |in_len| bytes from |in| to |out|. The number of - * output bytes may be up to |in_len| plus the block length minus one and |out| - * must have sufficient space. The number of bytes actually output is written - * to |*out_len|. It returns one on success and zero otherwise. */ -OPENSSL_EXPORT int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, uint8_t *out, - int *out_len, const uint8_t *in, - int in_len); - -/* EVP_DecryptFinal_ex writes at most a block of ciphertext to |out| and sets - * |*out_len| to the number of bytes written. If padding is enabled (the - * default) then padding is removed from the final block. - * - * WARNING: it is unsafe to call this function with unauthenticted - * ciphertext if padding is enabled. */ -OPENSSL_EXPORT int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, - int *out_len); - -/* EVP_Cipher performs a one-shot encryption/decryption operation. No partial - * blocks are maintained between calls. However, any internal cipher state is - * still updated. For CBC-mode ciphers, the IV is updated to the final - * ciphertext block. For stream ciphers, the stream is advanced past the bytes - * used. It returns one on success and zero otherwise, unless |EVP_CIPHER_flags| - * has |EVP_CIPH_FLAG_CUSTOM_CIPHER| set. Then it returns the number of bytes - * written or -1 on error. - * - * WARNING: this differs from the usual return value convention when using - * |EVP_CIPH_FLAG_CUSTOM_CIPHER|. - * - * TODO(davidben): The normal ciphers currently never fail, even if, e.g., - * |in_len| is not a multiple of the block size for CBC-mode decryption. The - * input just gets rounded up while the output gets truncated. This should - * either be officially documented or fail. */ -OPENSSL_EXPORT int EVP_Cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, - const uint8_t *in, size_t in_len); - -/* EVP_CipherUpdate calls either |EVP_EncryptUpdate| or |EVP_DecryptUpdate| - * depending on how |ctx| has been setup. */ -OPENSSL_EXPORT int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, uint8_t *out, - int *out_len, const uint8_t *in, - int in_len); - -/* EVP_CipherFinal_ex calls either |EVP_EncryptFinal_ex| or - * |EVP_DecryptFinal_ex| depending on how |ctx| has been setup. */ -OPENSSL_EXPORT int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, uint8_t *out, - int *out_len); - - -/* Cipher context accessors. */ - -/* EVP_CIPHER_CTX_cipher returns the |EVP_CIPHER| underlying |ctx|, or NULL if - * none has been set. */ -OPENSSL_EXPORT const EVP_CIPHER *EVP_CIPHER_CTX_cipher( - const EVP_CIPHER_CTX *ctx); - -/* EVP_CIPHER_CTX_nid returns a NID identifying the |EVP_CIPHER| underlying - * |ctx| (e.g. |NID_aes_128_gcm|). It will crash if no cipher has been - * configured. */ -OPENSSL_EXPORT int EVP_CIPHER_CTX_nid(const EVP_CIPHER_CTX *ctx); - -/* EVP_CIPHER_CTX_block_size returns the block size, in bytes, of the cipher - * underlying |ctx|, or one if the cipher is a stream cipher. It will crash if - * no cipher has been configured. */ -OPENSSL_EXPORT unsigned EVP_CIPHER_CTX_block_size(const EVP_CIPHER_CTX *ctx); - -/* EVP_CIPHER_CTX_key_length returns the key size, in bytes, of the cipher - * underlying |ctx| or zero if no cipher has been configured. */ -OPENSSL_EXPORT unsigned EVP_CIPHER_CTX_key_length(const EVP_CIPHER_CTX *ctx); - -/* EVP_CIPHER_CTX_iv_length returns the IV size, in bytes, of the cipher - * underlying |ctx|. It will crash if no cipher has been configured. */ -OPENSSL_EXPORT unsigned EVP_CIPHER_CTX_iv_length(const EVP_CIPHER_CTX *ctx); - -/* EVP_CIPHER_CTX_get_app_data returns the opaque, application data pointer for - * |ctx|, or NULL if none has been set. */ -OPENSSL_EXPORT void *EVP_CIPHER_CTX_get_app_data(const EVP_CIPHER_CTX *ctx); - -/* EVP_CIPHER_CTX_set_app_data sets the opaque, application data pointer for - * |ctx| to |data|. */ -OPENSSL_EXPORT void EVP_CIPHER_CTX_set_app_data(EVP_CIPHER_CTX *ctx, - void *data); - -/* EVP_CIPHER_CTX_flags returns a value which is the OR of zero or more - * |EVP_CIPH_*| flags. It will crash if no cipher has been configured. */ -OPENSSL_EXPORT uint32_t EVP_CIPHER_CTX_flags(const EVP_CIPHER_CTX *ctx); - -/* EVP_CIPHER_CTX_mode returns one of the |EVP_CIPH_*| cipher mode values - * enumerated below. It will crash if no cipher has been configured. */ -OPENSSL_EXPORT uint32_t EVP_CIPHER_CTX_mode(const EVP_CIPHER_CTX *ctx); - -/* EVP_CIPHER_CTX_ctrl is an |ioctl| like function. The |command| argument - * should be one of the |EVP_CTRL_*| values. The |arg| and |ptr| arguments are - * specific to the command in question. */ -OPENSSL_EXPORT int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int command, - int arg, void *ptr); - -/* EVP_CIPHER_CTX_set_padding sets whether padding is enabled for |ctx| and - * returns one. Pass a non-zero |pad| to enable padding (the default) or zero - * to disable. */ -OPENSSL_EXPORT int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *ctx, int pad); - -/* EVP_CIPHER_CTX_set_key_length sets the key length for |ctx|. This is only - * valid for ciphers that can take a variable length key. It returns one on - * success and zero on error. */ -OPENSSL_EXPORT int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *ctx, unsigned key_len); - - -/* Cipher accessors. */ - -/* EVP_CIPHER_nid returns a NID identifing |cipher|. (For example, - * |NID_aes_128_gcm|.) */ -OPENSSL_EXPORT int EVP_CIPHER_nid(const EVP_CIPHER *cipher); - -/* EVP_CIPHER_block_size returns the block size, in bytes, for |cipher|, or one - * if |cipher| is a stream cipher. */ -OPENSSL_EXPORT unsigned EVP_CIPHER_block_size(const EVP_CIPHER *cipher); - -/* EVP_CIPHER_key_length returns the key size, in bytes, for |cipher|. If - * |cipher| can take a variable key length then this function returns the - * default key length and |EVP_CIPHER_flags| will return a value with - * |EVP_CIPH_VARIABLE_LENGTH| set. */ -OPENSSL_EXPORT unsigned EVP_CIPHER_key_length(const EVP_CIPHER *cipher); - -/* EVP_CIPHER_iv_length returns the IV size, in bytes, of |cipher|, or zero if - * |cipher| doesn't take an IV. */ -OPENSSL_EXPORT unsigned EVP_CIPHER_iv_length(const EVP_CIPHER *cipher); - -/* EVP_CIPHER_flags returns a value which is the OR of zero or more - * |EVP_CIPH_*| flags. */ -OPENSSL_EXPORT uint32_t EVP_CIPHER_flags(const EVP_CIPHER *cipher); - -/* EVP_CIPHER_mode returns one of the cipher mode values enumerated below. */ -OPENSSL_EXPORT uint32_t EVP_CIPHER_mode(const EVP_CIPHER *cipher); - - -/* Key derivation. */ - -/* EVP_BytesToKey generates a key and IV for the cipher |type| by iterating - * |md| |count| times using |data| and |salt|. On entry, the |key| and |iv| - * buffers must have enough space to hold a key and IV for |type|. It returns - * the length of the key on success or zero on error. */ -OPENSSL_EXPORT int EVP_BytesToKey(const EVP_CIPHER *type, const EVP_MD *md, - const uint8_t *salt, const uint8_t *data, - size_t data_len, unsigned count, uint8_t *key, - uint8_t *iv); - - -/* Cipher modes (for |EVP_CIPHER_mode|). */ - -#define EVP_CIPH_STREAM_CIPHER 0x0 -#define EVP_CIPH_ECB_MODE 0x1 -#define EVP_CIPH_CBC_MODE 0x2 -#define EVP_CIPH_CFB_MODE 0x3 -#define EVP_CIPH_OFB_MODE 0x4 -#define EVP_CIPH_CTR_MODE 0x5 -#define EVP_CIPH_GCM_MODE 0x6 - - -/* Cipher flags (for |EVP_CIPHER_flags|). */ - -/* EVP_CIPH_VARIABLE_LENGTH indicates that the cipher takes a variable length - * key. */ -#define EVP_CIPH_VARIABLE_LENGTH 0x40 - -/* EVP_CIPH_ALWAYS_CALL_INIT indicates that the |init| function for the cipher - * should always be called when initialising a new operation, even if the key - * is NULL to indicate that the same key is being used. */ -#define EVP_CIPH_ALWAYS_CALL_INIT 0x80 - -/* EVP_CIPH_CUSTOM_IV indicates that the cipher manages the IV itself rather - * than keeping it in the |iv| member of |EVP_CIPHER_CTX|. */ -#define EVP_CIPH_CUSTOM_IV 0x100 - -/* EVP_CIPH_CTRL_INIT indicates that EVP_CTRL_INIT should be used when - * initialising an |EVP_CIPHER_CTX|. */ -#define EVP_CIPH_CTRL_INIT 0x200 - -/* EVP_CIPH_FLAG_CUSTOM_CIPHER indicates that the cipher manages blocking - * itself. This causes EVP_(En|De)crypt_ex to be simple wrapper functions. */ -#define EVP_CIPH_FLAG_CUSTOM_CIPHER 0x400 - -/* EVP_CIPH_FLAG_AEAD_CIPHER specifies that the cipher is an AEAD. This is an - * older version of the proper AEAD interface. See aead.h for the current - * one. */ -#define EVP_CIPH_FLAG_AEAD_CIPHER 0x800 - -/* EVP_CIPH_CUSTOM_COPY indicates that the |ctrl| callback should be called - * with |EVP_CTRL_COPY| at the end of normal |EVP_CIPHER_CTX_copy| - * processing. */ -#define EVP_CIPH_CUSTOM_COPY 0x1000 - - -/* Deprecated functions */ - -/* EVP_CipherInit acts like EVP_CipherInit_ex except that |EVP_CIPHER_CTX_init| - * is called on |cipher| first, if |cipher| is not NULL. */ -OPENSSL_EXPORT int EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, - const uint8_t *key, const uint8_t *iv, - int enc); - -/* EVP_EncryptInit calls |EVP_CipherInit| with |enc| equal to one. */ -OPENSSL_EXPORT int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, - const EVP_CIPHER *cipher, const uint8_t *key, - const uint8_t *iv); - -/* EVP_DecryptInit calls |EVP_CipherInit| with |enc| equal to zero. */ -OPENSSL_EXPORT int EVP_DecryptInit(EVP_CIPHER_CTX *ctx, - const EVP_CIPHER *cipher, const uint8_t *key, - const uint8_t *iv); - -/* EVP_add_cipher_alias does nothing and returns one. */ -OPENSSL_EXPORT int EVP_add_cipher_alias(const char *a, const char *b); - -/* EVP_get_cipherbyname returns an |EVP_CIPHER| given a human readable name in - * |name|, or NULL if the name is unknown. */ -OPENSSL_EXPORT const EVP_CIPHER *EVP_get_cipherbyname(const char *name); - - -/* Private functions. */ - -/* EVP_CIPH_NO_PADDING disables padding in block ciphers. */ -#define EVP_CIPH_NO_PADDING 0x800 - -/* EVP_CIPHER_CTX_ctrl commands. */ -#define EVP_CTRL_INIT 0x0 -#define EVP_CTRL_SET_KEY_LENGTH 0x1 -#define EVP_CTRL_GET_RC2_KEY_BITS 0x2 -#define EVP_CTRL_SET_RC2_KEY_BITS 0x3 -#define EVP_CTRL_GET_RC5_ROUNDS 0x4 -#define EVP_CTRL_SET_RC5_ROUNDS 0x5 -#define EVP_CTRL_RAND_KEY 0x6 -#define EVP_CTRL_PBE_PRF_NID 0x7 -#define EVP_CTRL_COPY 0x8 -#define EVP_CTRL_GCM_SET_IVLEN 0x9 -#define EVP_CTRL_GCM_GET_TAG 0x10 -#define EVP_CTRL_GCM_SET_TAG 0x11 -#define EVP_CTRL_GCM_SET_IV_FIXED 0x12 -#define EVP_CTRL_GCM_IV_GEN 0x13 -#define EVP_CTRL_AEAD_SET_MAC_KEY 0x17 -/* Set the GCM invocation field, decrypt only */ -#define EVP_CTRL_GCM_SET_IV_INV 0x18 - -/* GCM TLS constants */ -/* Length of fixed part of IV derived from PRF */ -#define EVP_GCM_TLS_FIXED_IV_LEN 4 -/* Length of explicit part of IV part of TLS records */ -#define EVP_GCM_TLS_EXPLICIT_IV_LEN 8 -/* Length of tag for TLS */ -#define EVP_GCM_TLS_TAG_LEN 16 - -#define EVP_MAX_KEY_LENGTH 64 -#define EVP_MAX_IV_LENGTH 16 -#define EVP_MAX_BLOCK_LENGTH 32 - -struct evp_cipher_ctx_st { - /* cipher contains the underlying cipher for this context. */ - const EVP_CIPHER *cipher; - - /* app_data is a pointer to opaque, user data. */ - void *app_data; /* application stuff */ - - /* cipher_data points to the |cipher| specific state. */ - void *cipher_data; - - /* key_len contains the length of the key, which may differ from - * |cipher->key_len| if the cipher can take a variable key length. */ - unsigned key_len; - - /* encrypt is one if encrypting and zero if decrypting. */ - int encrypt; - - /* flags contains the OR of zero or more |EVP_CIPH_*| flags, above. */ - uint32_t flags; - - /* oiv contains the original IV value. */ - uint8_t oiv[EVP_MAX_IV_LENGTH]; - - /* iv contains the current IV value, which may have been updated. */ - uint8_t iv[EVP_MAX_IV_LENGTH]; - - /* buf contains a partial block which is used by, for example, CTR mode to - * store unused keystream bytes. */ - uint8_t buf[EVP_MAX_BLOCK_LENGTH]; - - /* buf_len contains the number of bytes of a partial block contained in - * |buf|. */ - int buf_len; - - /* num contains the number of bytes of |iv| which are valid for modes that - * manage partial blocks themselves. */ - int num; - - /* final_used is non-zero if the |final| buffer contains plaintext. */ - int final_used; - - /* block_mask contains |cipher->block_size| minus one. (The block size - * assumed to be a power of two.) */ - int block_mask; - - uint8_t final[EVP_MAX_BLOCK_LENGTH]; /* possible final block */ -} /* EVP_CIPHER_CTX */; - -typedef struct evp_cipher_info_st { - const EVP_CIPHER *cipher; - unsigned char iv[EVP_MAX_IV_LENGTH]; -} EVP_CIPHER_INFO; - -struct evp_cipher_st { - /* type contains a NID identifing the cipher. (e.g. NID_aes_128_gcm.) */ - int nid; - - /* block_size contains the block size, in bytes, of the cipher, or 1 for a - * stream cipher. */ - unsigned block_size; - - /* key_len contains the key size, in bytes, for the cipher. If the cipher - * takes a variable key size then this contains the default size. */ - unsigned key_len; - - /* iv_len contains the IV size, in bytes, or zero if inapplicable. */ - unsigned iv_len; - - /* ctx_size contains the size, in bytes, of the per-key context for this - * cipher. */ - unsigned ctx_size; - - /* flags contains the OR of a number of flags. See |EVP_CIPH_*|. */ - uint32_t flags; - - /* app_data is a pointer to opaque, user data. */ - void *app_data; - - int (*init)(EVP_CIPHER_CTX *ctx, const uint8_t *key, const uint8_t *iv, - int enc); - - int (*cipher)(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in, - size_t inl); - - /* cleanup, if non-NULL, releases memory associated with the context. It is - * called if |EVP_CTRL_INIT| succeeds. Note that |init| may not have been - * called at this point. */ - void (*cleanup)(EVP_CIPHER_CTX *); - - int (*ctrl)(EVP_CIPHER_CTX *, int type, int arg, void *ptr); -}; - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#define CIPHER_F_EVP_AEAD_CTX_init 100 -#define CIPHER_F_EVP_AEAD_CTX_open 101 -#define CIPHER_F_EVP_AEAD_CTX_seal 102 -#define CIPHER_F_EVP_CIPHER_CTX_copy 103 -#define CIPHER_F_EVP_CIPHER_CTX_ctrl 104 -#define CIPHER_F_EVP_CIPHER_CTX_set_key_length 105 -#define CIPHER_F_EVP_CipherInit_ex 106 -#define CIPHER_F_EVP_DecryptFinal_ex 107 -#define CIPHER_F_EVP_EncryptFinal_ex 108 -#define CIPHER_F_aead_aes_gcm_init 109 -#define CIPHER_F_aead_aes_gcm_open 110 -#define CIPHER_F_aead_aes_gcm_seal 111 -#define CIPHER_F_aead_aes_key_wrap_init 112 -#define CIPHER_F_aead_aes_key_wrap_open 113 -#define CIPHER_F_aead_aes_key_wrap_seal 114 -#define CIPHER_F_aead_chacha20_poly1305_init 115 -#define CIPHER_F_aead_chacha20_poly1305_open 116 -#define CIPHER_F_aead_chacha20_poly1305_seal 117 -#define CIPHER_F_aead_rc4_md5_tls_init 118 -#define CIPHER_F_aead_rc4_md5_tls_open 119 -#define CIPHER_F_aead_rc4_md5_tls_seal 120 -#define CIPHER_F_aead_ssl3_ensure_cipher_init 121 -#define CIPHER_F_aead_ssl3_init 122 -#define CIPHER_F_aead_ssl3_open 123 -#define CIPHER_F_aead_ssl3_seal 124 -#define CIPHER_F_aead_tls_ensure_cipher_init 125 -#define CIPHER_F_aead_tls_init 126 -#define CIPHER_F_aead_tls_open 127 -#define CIPHER_F_aead_tls_seal 128 -#define CIPHER_F_aes_init_key 129 -#define CIPHER_F_aesni_init_key 130 -#define CIPHER_F_EVP_AEAD_CTX_init_with_direction 131 -#define CIPHER_F_aead_aes_ctr_hmac_sha256_init 132 -#define CIPHER_F_aead_aes_ctr_hmac_sha256_open 133 -#define CIPHER_F_aead_aes_ctr_hmac_sha256_seal 134 -#define CIPHER_R_AES_KEY_SETUP_FAILED 100 -#define CIPHER_R_BAD_DECRYPT 101 -#define CIPHER_R_BAD_KEY_LENGTH 102 -#define CIPHER_R_BUFFER_TOO_SMALL 103 -#define CIPHER_R_CTRL_NOT_IMPLEMENTED 104 -#define CIPHER_R_CTRL_OPERATION_NOT_IMPLEMENTED 105 -#define CIPHER_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH 106 -#define CIPHER_R_INITIALIZATION_ERROR 107 -#define CIPHER_R_INPUT_NOT_INITIALIZED 108 -#define CIPHER_R_INVALID_AD_SIZE 109 -#define CIPHER_R_INVALID_KEY_LENGTH 110 -#define CIPHER_R_INVALID_NONCE_SIZE 111 -#define CIPHER_R_INVALID_OPERATION 112 -#define CIPHER_R_IV_TOO_LARGE 113 -#define CIPHER_R_NO_CIPHER_SET 114 -#define CIPHER_R_OUTPUT_ALIASES_INPUT 115 -#define CIPHER_R_TAG_TOO_LARGE 116 -#define CIPHER_R_TOO_LARGE 117 -#define CIPHER_R_UNSUPPORTED_AD_SIZE 118 -#define CIPHER_R_UNSUPPORTED_INPUT_SIZE 119 -#define CIPHER_R_UNSUPPORTED_KEY_SIZE 120 -#define CIPHER_R_UNSUPPORTED_NONCE_SIZE 121 -#define CIPHER_R_UNSUPPORTED_TAG_SIZE 122 -#define CIPHER_R_WRONG_FINAL_BLOCK_LENGTH 123 -#define CIPHER_R_NO_DIRECTION_SET 124 - -#endif /* OPENSSL_HEADER_CIPHER_H */ diff --git a/third_party/boringssl/include/openssl/cmac.h b/third_party/boringssl/include/openssl/cmac.h deleted file mode 100644 index 183f41bca0..0000000000 --- a/third_party/boringssl/include/openssl/cmac.h +++ /dev/null @@ -1,76 +0,0 @@ -/* Copyright (c) 2015, Google Inc. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -#ifndef OPENSSL_HEADER_CMAC_H -#define OPENSSL_HEADER_CMAC_H - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* CMAC. - * - * CMAC is a MAC based on AES-CBC and defined in - * https://tools.ietf.org/html/rfc4493#section-2.3. */ - - -/* One-shot functions. */ - -/* AES_CMAC calculates the 16-byte, CMAC authenticator of |in_len| bytes of - * |in| and writes it to |out|. The |key_len| may be 16 or 32 bytes to select - * between AES-128 and AES-256. It returns one on success or zero on error. */ -OPENSSL_EXPORT int AES_CMAC(uint8_t out[16], const uint8_t *key, size_t key_len, - const uint8_t *in, size_t in_len); - - -/* Incremental interface. */ - -/* CMAC_CTX_new allocates a fresh |CMAC_CTX| and returns it, or NULL on - * error. */ -OPENSSL_EXPORT CMAC_CTX *CMAC_CTX_new(void); - -/* CMAC_CTX_free frees a |CMAC_CTX|. */ -OPENSSL_EXPORT void CMAC_CTX_free(CMAC_CTX *ctx); - -/* CMAC_Init configures |ctx| to use the given |key| and |cipher|. The CMAC RFC - * only specifies the use of AES-128 thus |key_len| should be 16 and |cipher| - * should be |EVP_aes_128_cbc()|. However, this implementation also supports - * AES-256 by setting |key_len| to 32 and |cipher| to |EVP_aes_256_cbc()|. The - * |engine| argument is ignored. - * - * It returns one on success or zero on error. */ -OPENSSL_EXPORT int CMAC_Init(CMAC_CTX *ctx, const void *key, size_t key_len, - const EVP_CIPHER *cipher, ENGINE *engine); - - -/* CMAC_Reset resets |ctx| so that a fresh message can be authenticated. */ -OPENSSL_EXPORT int CMAC_Reset(CMAC_CTX *ctx); - -/* CMAC_Update processes |in_len| bytes of message from |in|. It returns one on - * success or zero on error. */ -OPENSSL_EXPORT int CMAC_Update(CMAC_CTX *ctx, const uint8_t *in, size_t in_len); - -/* CMAC_Final sets |*out_len| to 16 and, if |out| is not NULL, writes 16 bytes - * of authenticator to it. It returns one on success or zero on error. */ -OPENSSL_EXPORT int CMAC_Final(CMAC_CTX *ctx, uint8_t *out, size_t *out_len); - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_CBC_H */ diff --git a/third_party/boringssl/include/openssl/conf.h b/third_party/boringssl/include/openssl/conf.h deleted file mode 100644 index 84fc94f99e..0000000000 --- a/third_party/boringssl/include/openssl/conf.h +++ /dev/null @@ -1,149 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] */ - -#ifndef OPENSSL_HEADER_CONF_H -#define OPENSSL_HEADER_CONF_H - -#include - -#include -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* Config files look like: - * - * # Comment - * - * # This key is in the default section. - * key=value - * - * [section_name] - * key2=value2 - * - * Config files are representated by a |CONF|. */ - -struct conf_value_st { - char *section; - char *name; - char *value; -}; - -struct conf_st { - LHASH_OF(CONF_VALUE) *data; -}; - - -/* NCONF_new returns a fresh, empty |CONF|, or NULL on error. The |method| - * argument must be NULL. */ -CONF *NCONF_new(void *method); - -/* NCONF_free frees all the data owned by |conf| and then |conf| itself. */ -void NCONF_free(CONF *conf); - -/* NCONF_load parses the file named |filename| and adds the values found to - * |conf|. It returns one on success and zero on error. In the event of an - * error, if |out_error_line| is not NULL, |*out_error_line| is set to the - * number of the line that contained the error. */ -int NCONF_load(CONF *conf, const char *filename, long *out_error_line); - -/* NCONF_load_bio acts like |NCONF_load| but reads from |bio| rather than from - * a named file. */ -int NCONF_load_bio(CONF *conf, BIO *bio, long *out_error_line); - -/* NCONF_get_section returns a stack of values for a given section in |conf|. - * If |section| is NULL, the default section is returned. It returns NULL on - * error. */ -STACK_OF(CONF_VALUE) *NCONF_get_section(const CONF *conf, const char *section); - -/* NCONF_get_string returns the value of the key |name|, in section |section|. - * The |section| argument may be NULL to indicate the default section. It - * returns the value or NULL on error. */ -const char *NCONF_get_string(const CONF *conf, const char *section, - const char *name); - - -/* Utility functions */ - -/* CONF_parse_list takes a list separated by 'sep' and calls |list_cb| giving - * the start and length of each member, optionally stripping leading and - * trailing whitespace. This can be used to parse comma separated lists for - * example. If |list_cb| returns <= 0, then the iteration is halted and that - * value is returned immediately. Otherwise it returns one. Note that |list_cb| - * may be called on an empty member. */ -int CONF_parse_list(const char *list, char sep, int remove_whitespace, - int (*list_cb)(const char *elem, int len, void *usr), - void *arg); - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#define CONF_F_CONF_parse_list 100 -#define CONF_F_NCONF_load 101 -#define CONF_F_def_load_bio 102 -#define CONF_F_str_copy 103 -#define CONF_R_LIST_CANNOT_BE_NULL 100 -#define CONF_R_MISSING_CLOSE_SQUARE_BRACKET 101 -#define CONF_R_MISSING_EQUAL_SIGN 102 -#define CONF_R_NO_CLOSE_BRACE 103 -#define CONF_R_UNABLE_TO_CREATE_NEW_SECTION 104 -#define CONF_R_VARIABLE_HAS_NO_VALUE 105 - -#endif /* OPENSSL_HEADER_THREAD_H */ diff --git a/third_party/boringssl/include/openssl/cpu.h b/third_party/boringssl/include/openssl/cpu.h deleted file mode 100644 index 83ec473fab..0000000000 --- a/third_party/boringssl/include/openssl/cpu.h +++ /dev/null @@ -1,121 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] - * - * This product includes cryptographic software written by Eric Young - * (eay@cryptsoft.com). This product includes software written by Tim - * Hudson (tjh@cryptsoft.com). */ - -#ifndef OPENSSL_HEADER_CPU_H -#define OPENSSL_HEADER_CPU_H - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* Runtime CPU feature support */ - - -#if defined(OPENSSL_X86) || defined(OPENSSL_X86_64) -/* OPENSSL_ia32cap_P contains the Intel CPUID bits when running on an x86 or - * x86-64 system. - * - * Index 0: - * EDX for CPUID where EAX = 1 - * Bit 30 is used to indicate an Intel CPU - * Index 1: - * ECX for CPUID where EAX = 1 - * Index 2: - * EBX for CPUID where EAX = 7 - * - * Note: the CPUID bits are pre-adjusted for the OSXSAVE bit and the YMM and XMM - * bits in XCR0, so it is not necessary to check those. */ -extern uint32_t OPENSSL_ia32cap_P[4]; -#endif - -#if defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64) -/* CRYPTO_is_NEON_capable returns true if the current CPU has a NEON unit. Note - * that |OPENSSL_armcap_P| also exists and contains the same information in a - * form that's easier for assembly to use. */ -OPENSSL_EXPORT char CRYPTO_is_NEON_capable(void); - -/* CRYPTO_set_NEON_capable sets the return value of |CRYPTO_is_NEON_capable|. - * By default, unless the code was compiled with |-mfpu=neon|, NEON is assumed - * not to be present. It is not autodetected. Calling this with a zero - * argument also causes |CRYPTO_is_NEON_functional| to return false. */ -OPENSSL_EXPORT void CRYPTO_set_NEON_capable(char neon_capable); - -/* CRYPTO_is_NEON_functional returns true if the current CPU has a /working/ - * NEON unit. Some phones have a NEON unit, but the Poly1305 NEON code causes - * it to fail. See https://code.google.com/p/chromium/issues/detail?id=341598 */ -OPENSSL_EXPORT char CRYPTO_is_NEON_functional(void); - -/* CRYPTO_set_NEON_functional sets the "NEON functional" flag. For - * |CRYPTO_is_NEON_functional| to return true, both this flag and the NEON flag - * must be true. By default NEON is assumed to be functional if the code was - * compiled with |-mfpu=neon| or if |CRYPTO_set_NEON_capable| has been called - * with a non-zero argument. */ -OPENSSL_EXPORT void CRYPTO_set_NEON_functional(char neon_functional); -#endif /* OPENSSL_ARM */ - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_CPU_H */ diff --git a/third_party/boringssl/include/openssl/crypto.h b/third_party/boringssl/include/openssl/crypto.h deleted file mode 100644 index 3af1547d87..0000000000 --- a/third_party/boringssl/include/openssl/crypto.h +++ /dev/null @@ -1,63 +0,0 @@ -/* Copyright (c) 2014, Google Inc. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -#ifndef OPENSSL_HEADER_CRYPTO_H -#define OPENSSL_HEADER_CRYPTO_H - -#include - -/* Upstream OpenSSL defines |OPENSSL_malloc|, etc., in crypto.h rather than - * mem.h. */ -#include - - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* crypto.h contains functions for initializing the crypto library. */ - - -/* CRYPTO_library_init initializes the crypto library. It must be called if the - * library is built with BORINGSSL_NO_STATIC_INITIALIZER. Otherwise, it does - * nothing and a static initializer is used instead. */ -OPENSSL_EXPORT void CRYPTO_library_init(void); - - -/* Deprecated functions. */ - -#define OPENSSL_VERSION_TEXT "BoringSSL" - -#define SSLEAY_VERSION 0 - -/* SSLeay_version is a compatibility function that returns the string - * "BoringSSL". */ -OPENSSL_EXPORT const char *SSLeay_version(int unused); - -/* SSLeay is a compatibility function that returns OPENSSL_VERSION_NUMBER from - * base.h. */ -OPENSSL_EXPORT unsigned long SSLeay(void); - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#define CRYPTO_F_CRYPTO_get_ex_new_index 100 -#define CRYPTO_F_CRYPTO_set_ex_data 101 -#define CRYPTO_F_get_class 102 -#define CRYPTO_F_get_func_pointers 103 - -#endif /* OPENSSL_HEADER_CRYPTO_H */ diff --git a/third_party/boringssl/include/openssl/des.h b/third_party/boringssl/include/openssl/des.h deleted file mode 100644 index 6e1b0cfe5f..0000000000 --- a/third_party/boringssl/include/openssl/des.h +++ /dev/null @@ -1,149 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] */ - -#ifndef OPENSSL_HEADER_DES_H -#define OPENSSL_HEADER_DES_H - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* DES. */ - - -typedef struct DES_cblock_st { - uint8_t bytes[8]; -} DES_cblock; - -typedef struct DES_ks { - union { - DES_cblock cblock; - /* make sure things are correct size on machines with - * 8 byte longs */ - uint32_t deslong[2]; - } ks[16]; -} DES_key_schedule; - - -#define DES_KEY_SZ (sizeof(DES_cblock)) -#define DES_SCHEDULE_SZ (sizeof(DES_key_schedule)) - -#define DES_ENCRYPT 1 -#define DES_DECRYPT 0 - -#define DES_CBC_MODE 0 -#define DES_PCBC_MODE 1 - -/* DES_set_key performs a key schedule and initialises |schedule| with |key|. */ -OPENSSL_EXPORT void DES_set_key(const DES_cblock *key, - DES_key_schedule *schedule); - -/* DES_set_odd_parity sets the parity bits (the least-significant bits in each - * byte) of |key| given the other bits in each byte. */ -OPENSSL_EXPORT void DES_set_odd_parity(DES_cblock *key); - -/* DES_ecb_encrypt encrypts (or decrypts, if |is_encrypt| is |DES_DECRYPT|) a - * single DES block (8 bytes) from in to out, using the key configured in - * |schedule|. */ -OPENSSL_EXPORT void DES_ecb_encrypt(const DES_cblock *in, DES_cblock *out, - const DES_key_schedule *schedule, - int is_encrypt); - -/* DES_ncbc_encrypt encrypts (or decrypts, if |enc| is |DES_DECRYPT|) |len| - * bytes from |in| to |out| with DES in CBC mode. */ -OPENSSL_EXPORT void DES_ncbc_encrypt(const uint8_t *in, uint8_t *out, - size_t len, - const DES_key_schedule *schedule, - DES_cblock *ivec, int enc); - -/* DES_ecb3_encrypt encrypts (or decrypts, if |enc| is |DES_DECRYPT|) a single - * block (8 bytes) of data from |input| to |output| using 3DES. */ -OPENSSL_EXPORT void DES_ecb3_encrypt(const DES_cblock *input, - DES_cblock *output, - const DES_key_schedule *ks1, - const DES_key_schedule *ks2, - const DES_key_schedule *ks3, - int enc); - -/* DES_ede3_cbc_encrypt encrypts (or decrypts, if |enc| is |DES_DECRYPT|) |len| - * bytes from |in| to |out| with 3DES in CBC mode. 3DES uses three keys, thus - * the function takes three different |DES_key_schedule|s. */ -OPENSSL_EXPORT void DES_ede3_cbc_encrypt(const uint8_t *in, uint8_t *out, - size_t len, - const DES_key_schedule *ks1, - const DES_key_schedule *ks2, - const DES_key_schedule *ks3, - DES_cblock *ivec, int enc); - -/* DES_ede2_cbc_encrypt encrypts (or decrypts, if |enc| is |DES_DECRYPT|) |len| - * bytes from |in| to |out| with 3DES in CBC mode. With this keying option, the - * first and third 3DES keys are identical. Thus, this function takes only two - * different |DES_key_schedule|s. */ -OPENSSL_EXPORT void DES_ede2_cbc_encrypt(const uint8_t *in, uint8_t *out, - size_t len, - const DES_key_schedule *ks1, - const DES_key_schedule *ks2, - DES_cblock *ivec, int enc); - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_DES_H */ diff --git a/third_party/boringssl/include/openssl/dh.h b/third_party/boringssl/include/openssl/dh.h deleted file mode 100644 index 17574d51ed..0000000000 --- a/third_party/boringssl/include/openssl/dh.h +++ /dev/null @@ -1,274 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] */ - -#ifndef OPENSSL_HEADER_DH_H -#define OPENSSL_HEADER_DH_H - -#include - -#include -#include -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* DH contains functions for performing Diffie-Hellman key agreement in - * multiplicative groups. */ - - -/* Allocation and destruction. */ - -/* DH_new returns a new, empty DH object or NULL on error. */ -OPENSSL_EXPORT DH *DH_new(void); - -/* DH_new_method acts the same as |DH_new| but takes an explicit |ENGINE|. */ -OPENSSL_EXPORT DH *DH_new_method(const ENGINE *engine); - -/* DH_free decrements the reference count of |dh| and frees it if the reference - * count drops to zero. */ -OPENSSL_EXPORT void DH_free(DH *dh); - -/* DH_up_ref increments the reference count of |dh|. */ -OPENSSL_EXPORT int DH_up_ref(DH *dh); - - -/* Standard parameters. - * - * These functions return new DH objects with standard parameters configured - * that use the given ENGINE, which may be NULL. They return NULL on allocation - * failure. */ - -/* These parameters are taken from RFC 5114. */ - -OPENSSL_EXPORT DH *DH_get_1024_160(const ENGINE *engine); -OPENSSL_EXPORT DH *DH_get_2048_224(const ENGINE *engine); -OPENSSL_EXPORT DH *DH_get_2048_256(const ENGINE *engine); - - -/* Parameter generation. */ - -#define DH_GENERATOR_2 2 -#define DH_GENERATOR_5 5 - -/* DH_generate_parameters_ex generates a suitable Diffie-Hellman group with a - * prime that is |prime_bits| long and stores it in |dh|. The generator of the - * group will be |generator|, which should be |DH_GENERATOR_2| unless there's a - * good reason to use a different value. The |cb| argument contains a callback - * function that will be called during the generation. See the documentation in - * |bn.h| about this. In addition to the callback invocations from |BN|, |cb| - * will also be called with |event| equal to three when the generation is - * complete. */ -OPENSSL_EXPORT int DH_generate_parameters_ex(DH *dh, int prime_bits, - int generator, BN_GENCB *cb); - - -/* Diffie-Hellman operations. */ - -/* DH_generate_key generates a new, random, private key and stores it in - * |dh|. It returns one on success and zero on error. */ -OPENSSL_EXPORT int DH_generate_key(DH *dh); - -/* DH_compute_key calculates the shared key between |dh| and |peers_key| and - * writes it as a big-endian integer into |out|, which must have |DH_size| - * bytes of space. It returns the number of bytes written, or a negative number - * on error. */ -OPENSSL_EXPORT int DH_compute_key(uint8_t *out, const BIGNUM *peers_key, - DH *dh); - - -/* Utility functions. */ - -/* DH_size returns the number of bytes in the DH group's prime. */ -OPENSSL_EXPORT int DH_size(const DH *dh); - -/* DH_num_bits returns the minimum number of bits needed to represent the - * absolute value of the DH group's prime. */ -OPENSSL_EXPORT unsigned DH_num_bits(const DH *dh); - -#define DH_CHECK_P_NOT_PRIME 0x01 -#define DH_CHECK_P_NOT_SAFE_PRIME 0x02 -#define DH_CHECK_UNABLE_TO_CHECK_GENERATOR 0x04 -#define DH_CHECK_NOT_SUITABLE_GENERATOR 0x08 -#define DH_CHECK_Q_NOT_PRIME 0x10 -#define DH_CHECK_INVALID_Q_VALUE 0x20 -#define DH_CHECK_INVALID_J_VALUE 0x40 - -/* These are compatibility defines. */ -#define DH_NOT_SUITABLE_GENERATOR DH_CHECK_NOT_SUITABLE_GENERATOR -#define DH_UNABLE_TO_CHECK_GENERATOR DH_CHECK_UNABLE_TO_CHECK_GENERATOR - -/* DH_check checks the suitability of |dh| as a Diffie-Hellman group. and sets - * |DH_CHECK_*| flags in |*out_flags| if it finds any errors. It returns one if - * |*out_flags| was successfully set and zero on error. - * - * Note: these checks may be quite computationally expensive. */ -OPENSSL_EXPORT int DH_check(const DH *dh, int *out_flags); - -#define DH_CHECK_PUBKEY_TOO_SMALL 1 -#define DH_CHECK_PUBKEY_TOO_LARGE 2 - -/* DH_check_pub_key checks the suitability of |pub_key| as a public key for the - * DH group in |dh| and sets |DH_CHECK_PUBKEY_*| flags in |*out_flags| if it - * finds any errors. It returns one if |*out_flags| was successfully set and - * zero on error. */ -OPENSSL_EXPORT int DH_check_pub_key(const DH *dh, const BIGNUM *pub_key, - int *out_flags); - -/* DHparams_dup allocates a fresh |DH| and copies the parameters from |dh| into - * it. It returns the new |DH| or NULL on error. */ -OPENSSL_EXPORT DH *DHparams_dup(const DH *dh); - - -/* ASN.1 functions. */ - -/* d2i_DHparams parses an ASN.1, DER encoded Diffie-Hellman parameters - * structure from |len| bytes at |*inp|. If |ret| is not NULL then, on exit, a - * pointer to the result is in |*ret|. If |*ret| is already non-NULL on entry - * then the result is written directly into |*ret|, otherwise a fresh |DH| is - * allocated. On successful exit, |*inp| is advanced past the DER structure. It - * returns the result or NULL on error. */ -OPENSSL_EXPORT DH *d2i_DHparams(DH **ret, const unsigned char **inp, long len); - -/* i2d_DHparams marshals |in| to an ASN.1, DER structure. If |outp| is not NULL - * then the result is written to |*outp| and |*outp| is advanced just past the - * output. It returns the number of bytes in the result, whether written or - * not, or a negative value on error. */ -OPENSSL_EXPORT int i2d_DHparams(const DH *in, unsigned char **outp); - - -/* ex_data functions. - * - * See |ex_data.h| for details. */ - -OPENSSL_EXPORT int DH_get_ex_new_index(long argl, void *argp, - CRYPTO_EX_new *new_func, - CRYPTO_EX_dup *dup_func, - CRYPTO_EX_free *free_func); -OPENSSL_EXPORT int DH_set_ex_data(DH *d, int idx, void *arg); -OPENSSL_EXPORT void *DH_get_ex_data(DH *d, int idx); - - -/* dh_method contains function pointers to override the implementation of DH. - * See |engine.h| for details. */ -struct dh_method { - struct openssl_method_common_st common; - - /* app_data is an opaque pointer for the method to use. */ - void *app_data; - - /* init is called just before the return of |DH_new_method|. It returns one - * on success or zero on error. */ - int (*init)(DH *dh); - - /* finish is called before |dh| is destructed. */ - void (*finish)(DH *dh); - - /* generate_parameters is called by |DH_generate_parameters_ex|. */ - int (*generate_parameters)(DH *dh, int prime_bits, int generator, - BN_GENCB *cb); - - /* generate_parameters is called by |DH_generate_key|. */ - int (*generate_key)(DH *dh); - - /* compute_key is called by |DH_compute_key|. */ - int (*compute_key)(DH *dh, uint8_t *out, const BIGNUM *pub_key); -}; - -struct dh_st { - DH_METHOD *meth; - - BIGNUM *p; - BIGNUM *g; - BIGNUM *pub_key; /* g^x */ - BIGNUM *priv_key; /* x */ - - /* priv_length contains the length, in bits, of the private value. If zero, - * the private value will be the same length as |p|. */ - unsigned priv_length; - - CRYPTO_MUTEX method_mont_p_lock; - BN_MONT_CTX *method_mont_p; - - /* Place holders if we want to do X9.42 DH */ - BIGNUM *q; - BIGNUM *j; - unsigned char *seed; - int seedlen; - BIGNUM *counter; - - int flags; - CRYPTO_refcount_t references; - CRYPTO_EX_DATA ex_data; -}; - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#define DH_F_DH_new_method 100 -#define DH_F_compute_key 101 -#define DH_F_generate_key 102 -#define DH_F_generate_parameters 103 -#define DH_R_BAD_GENERATOR 100 -#define DH_R_INVALID_PUBKEY 101 -#define DH_R_MODULUS_TOO_LARGE 102 -#define DH_R_NO_PRIVATE_VALUE 103 - -#endif /* OPENSSL_HEADER_DH_H */ diff --git a/third_party/boringssl/include/openssl/digest.h b/third_party/boringssl/include/openssl/digest.h deleted file mode 100644 index 2ea4ec4d7d..0000000000 --- a/third_party/boringssl/include/openssl/digest.h +++ /dev/null @@ -1,265 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] */ - -#ifndef OPENSSL_HEADER_DIGEST_H -#define OPENSSL_HEADER_DIGEST_H - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* Digest functions. - * - * An EVP_MD abstracts the details of a specific hash function allowing code to - * deal with the concept of a "hash function" without needing to know exactly - * which hash function it is. */ - - -/* Hash algorithms. - * - * The following functions return |EVP_MD| objects that implement the named hash - * function. */ - -OPENSSL_EXPORT const EVP_MD *EVP_md4(void); -OPENSSL_EXPORT const EVP_MD *EVP_md5(void); -OPENSSL_EXPORT const EVP_MD *EVP_sha1(void); -OPENSSL_EXPORT const EVP_MD *EVP_sha224(void); -OPENSSL_EXPORT const EVP_MD *EVP_sha256(void); -OPENSSL_EXPORT const EVP_MD *EVP_sha384(void); -OPENSSL_EXPORT const EVP_MD *EVP_sha512(void); - -/* EVP_md5_sha1 is a TLS-specific |EVP_MD| which computes the concatenation of - * MD5 and SHA-1, as used in TLS 1.1 and below. */ -OPENSSL_EXPORT const EVP_MD *EVP_md5_sha1(void); - -/* EVP_get_digestbynid returns an |EVP_MD| for the given NID, or NULL if no - * such digest is known. */ -OPENSSL_EXPORT const EVP_MD *EVP_get_digestbynid(int nid); - -/* EVP_get_digestbyobj returns an |EVP_MD| for the given |ASN1_OBJECT|, or NULL - * if no such digest is known. */ -OPENSSL_EXPORT const EVP_MD *EVP_get_digestbyobj(const ASN1_OBJECT *obj); - - -/* Digest contexts. - * - * An EVP_MD_CTX represents the state of a specific digest operation in - * progress. */ - -/* EVP_MD_CTX_init initialises an, already allocated, |EVP_MD_CTX|. */ -OPENSSL_EXPORT void EVP_MD_CTX_init(EVP_MD_CTX *ctx); - -/* EVP_MD_CTX_create allocates and initialises a fresh |EVP_MD_CTX| and returns - * it, or NULL on allocation failure. */ -OPENSSL_EXPORT EVP_MD_CTX *EVP_MD_CTX_create(void); - -/* EVP_MD_CTX_cleanup frees any resources owned by |ctx| and resets it to a - * freshly initialised state. It does not free |ctx| itself. It returns one. */ -OPENSSL_EXPORT int EVP_MD_CTX_cleanup(EVP_MD_CTX *ctx); - -/* EVP_MD_CTX_destroy calls |EVP_MD_CTX_cleanup| and then frees |ctx| itself. */ -OPENSSL_EXPORT void EVP_MD_CTX_destroy(EVP_MD_CTX *ctx); - -/* EVP_MD_CTX_copy_ex sets |out|, which must already be initialised, to be a - * copy of |in|. It returns one on success and zero on error. */ -OPENSSL_EXPORT int EVP_MD_CTX_copy_ex(EVP_MD_CTX *out, const EVP_MD_CTX *in); - - -/* Digest operations. */ - -/* EVP_DigestInit_ex configures |ctx|, which must already have been - * initialised, for a fresh hashing operation using |type|. It returns one on - * success and zero otherwise. */ -OPENSSL_EXPORT int EVP_DigestInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, - ENGINE *engine); - -/* EVP_DigestInit acts like |EVP_DigestInit_ex| except that |ctx| is - * initialised before use. */ -OPENSSL_EXPORT int EVP_DigestInit(EVP_MD_CTX *ctx, const EVP_MD *type); - -/* EVP_DigestUpdate hashes |len| bytes from |data| into the hashing operation - * in |ctx|. It returns one. */ -OPENSSL_EXPORT int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *data, - size_t len); - -/* EVP_MAX_MD_SIZE is the largest digest size supported. Functions that output - * a digest generally require the buffer have at least this much space. */ -#define EVP_MAX_MD_SIZE 64 /* SHA-512 is the longest so far. */ - -/* EVP_DigestFinal_ex finishes the digest in |ctx| and writes the output to - * |md_out|. At most |EVP_MAX_MD_SIZE| bytes are written. If |out_size| is not - * NULL then |*out_size| is set to the number of bytes written. It returns one. - * After this call, the hash cannot be updated or finished again until - * |EVP_DigestInit_ex| is called to start another hashing operation. */ -OPENSSL_EXPORT int EVP_DigestFinal_ex(EVP_MD_CTX *ctx, uint8_t *md_out, - unsigned int *out_size); - -/* EVP_DigestFinal acts like |EVP_DigestFinal_ex| except that - * |EVP_MD_CTX_cleanup| is called on |ctx| before returning. */ -OPENSSL_EXPORT int EVP_DigestFinal(EVP_MD_CTX *ctx, uint8_t *md_out, - unsigned int *out_size); - -/* EVP_Digest performs a complete hashing operation in one call. It hashes - * |len| bytes from |data| and writes the digest to |md_out|. At most - * |EVP_MAX_MD_SIZE| bytes are written. If |out_size| is not NULL then - * |*out_size| is set to the number of bytes written. It returns one on success - * and zero otherwise. */ -OPENSSL_EXPORT int EVP_Digest(const void *data, size_t len, uint8_t *md_out, - unsigned int *md_out_size, const EVP_MD *type, - ENGINE *impl); - - -/* Digest function accessors. - * - * These functions allow code to learn details about an abstract hash - * function. */ - -/* EVP_MD_type returns a NID identifing |md|. (For example, |NID_sha256|.) */ -OPENSSL_EXPORT int EVP_MD_type(const EVP_MD *md); - -/* EVP_MD_flags returns the flags for |md|, which is a set of |EVP_MD_FLAG_*| - * values, ORed together. */ -OPENSSL_EXPORT uint32_t EVP_MD_flags(const EVP_MD *md); - -/* EVP_MD_size returns the digest size of |md|, in bytes. */ -OPENSSL_EXPORT size_t EVP_MD_size(const EVP_MD *md); - -/* EVP_MD_block_size returns the native block-size of |md|. */ -OPENSSL_EXPORT size_t EVP_MD_block_size(const EVP_MD *md); - -/* EVP_MD_FLAG_PKEY_DIGEST indicates the the digest function is used with a - * specific public key in order to verify signatures. (For example, - * EVP_dss1.) */ -#define EVP_MD_FLAG_PKEY_DIGEST 1 - -/* EVP_MD_FLAG_DIGALGID_ABSENT indicates that the parameter type in an X.509 - * DigestAlgorithmIdentifier representing this digest function should be - * undefined rather than NULL. */ -#define EVP_MD_FLAG_DIGALGID_ABSENT 2 - - -/* Deprecated functions. */ - -/* EVP_MD_CTX_copy sets |out|, which must /not/ be initialised, to be a copy of - * |in|. It returns one on success and zero on error. */ -OPENSSL_EXPORT int EVP_MD_CTX_copy(EVP_MD_CTX *out, const EVP_MD_CTX *in); - -/* EVP_add_digest does nothing and returns one. It exists only for - * compatibility with OpenSSL. */ -OPENSSL_EXPORT int EVP_add_digest(const EVP_MD *digest); - -/* EVP_get_cipherbyname returns an |EVP_MD| given a human readable name in - * |name|, or NULL if the name is unknown. */ -OPENSSL_EXPORT const EVP_MD *EVP_get_digestbyname(const char *); - - -/* Digest operation accessors. */ - -/* EVP_MD_CTX_md returns the underlying digest function, or NULL if one has not - * been set. */ -OPENSSL_EXPORT const EVP_MD *EVP_MD_CTX_md(const EVP_MD_CTX *ctx); - -/* EVP_MD_CTX_size returns the digest size of |ctx|. It will crash if a digest - * hasn't been set on |ctx|. */ -OPENSSL_EXPORT unsigned EVP_MD_CTX_size(const EVP_MD_CTX *ctx); - -/* EVP_MD_CTX_block_size returns the block size of the digest function used by - * |ctx|. It will crash if a digest hasn't been set on |ctx|. */ -OPENSSL_EXPORT unsigned EVP_MD_CTX_block_size(const EVP_MD_CTX *ctx); - -/* EVP_MD_CTX_type returns a NID describing the digest function used by |ctx|. - * (For example, |NID_sha256|.) It will crash if a digest hasn't been set on - * |ctx|. */ -OPENSSL_EXPORT int EVP_MD_CTX_type(const EVP_MD_CTX *ctx); - - -struct evp_md_pctx_ops; - -struct env_md_ctx_st { - /* digest is the underlying digest function, or NULL if not set. */ - const EVP_MD *digest; - /* flags is the OR of a number of |EVP_MD_CTX_FLAG_*| values. */ - uint32_t flags; - /* md_data points to a block of memory that contains the hash-specific - * context. */ - void *md_data; - /* update is usually copied from |digest->update| but can differ in some - * cases, i.e. HMAC. - * TODO(davidben): Remove this hook once |EVP_PKEY_HMAC| is gone. */ - void (*update)(EVP_MD_CTX *ctx, const void *data, size_t count); - - /* pctx is an opaque (at this layer) pointer to additional context that - * EVP_PKEY functions may store in this object. */ - EVP_PKEY_CTX *pctx; - - /* pctx_ops, if not NULL, points to a vtable that contains functions to - * manipulate |pctx|. */ - const struct evp_md_pctx_ops *pctx_ops; -} /* EVP_MD_CTX */; - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#define DIGEST_F_EVP_DigestInit_ex 100 -#define DIGEST_F_EVP_MD_CTX_copy_ex 101 -#define DIGEST_R_INPUT_NOT_INITIALIZED 100 - -#endif /* OPENSSL_HEADER_DIGEST_H */ diff --git a/third_party/boringssl/include/openssl/dsa.h b/third_party/boringssl/include/openssl/dsa.h deleted file mode 100644 index 7274e4c8c9..0000000000 --- a/third_party/boringssl/include/openssl/dsa.h +++ /dev/null @@ -1,379 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] - * - * The DSS routines are based on patches supplied by - * Steven Schoch . */ - -#ifndef OPENSSL_HEADER_DSA_H -#define OPENSSL_HEADER_DSA_H - -#include - -#include -#include -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* DSA contains functions for signing and verifing with the Digital Signature - * Algorithm. */ - - -/* Allocation and destruction. */ - -/* DSA_new returns a new, empty DSA object or NULL on error. */ -OPENSSL_EXPORT DSA *DSA_new(void); - -/* DSA_new_method acts the same as |DH_new| but takes an explicit |ENGINE|. */ -OPENSSL_EXPORT DSA *DSA_new_method(const ENGINE *engine); - -/* DSA_free decrements the reference count of |dsa| and frees it if the - * reference count drops to zero. */ -OPENSSL_EXPORT void DSA_free(DSA *dsa); - -/* DSA_up_ref increments the reference count of |dsa|. */ -OPENSSL_EXPORT int DSA_up_ref(DSA *dsa); - - -/* Parameter generation. */ - -/* DSA_generate_parameters_ex generates a set of DSA parameters by following - * the procedure given in FIPS 186-4, appendix A. - * (http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf) - * - * The larger prime will have a length of |bits| (e.g. 2048). The |seed| value - * allows others to generate and verify the same parameters and should be - * random input which is kept for reference. If |out_counter| or |out_h| are - * not NULL then the counter and h value used in the generation are written to - * them. - * - * The |cb| argument is passed to |BN_generate_prime_ex| and is thus called - * during the generation process in order to indicate progress. See the - * comments for that function for details. In addition to the calls made by - * |BN_generate_prime_ex|, |DSA_generate_parameters_ex| will call it with - * |event| equal to 2 and 3 at different stages of the process. - * - * It returns one on success and zero otherwise. */ -OPENSSL_EXPORT int DSA_generate_parameters_ex(DSA *dsa, unsigned bits, - const uint8_t *seed, - size_t seed_len, int *out_counter, - unsigned long *out_h, - BN_GENCB *cb); - -/* DSAparams_dup returns a freshly allocated |DSA| that contains a copy of the - * parameters from |dsa|. It returns NULL on error. */ -OPENSSL_EXPORT DSA *DSAparams_dup(const DSA *dsa); - - -/* Key generation. */ - -/* DSA_generate_key generates a public/private key pair in |dsa|, which must - * already have parameters setup. It returns one on success and zero on - * error. */ -OPENSSL_EXPORT int DSA_generate_key(DSA *dsa); - - -/* Signatures. */ - -/* DSA_SIG contains a DSA signature as a pair of integers. */ -typedef struct DSA_SIG_st { - BIGNUM *r, *s; -} DSA_SIG; - -/* DSA_SIG_new returns a freshly allocated, DIG_SIG structure or NULL on error. - * Both |r| and |s| in the signature will be NULL. */ -OPENSSL_EXPORT DSA_SIG *DSA_SIG_new(void); - -/* DSA_SIG_free frees the contents of |sig| and then frees |sig| itself. */ -OPENSSL_EXPORT void DSA_SIG_free(DSA_SIG *sig); - -/* DSA_do_sign returns a signature of the hash in |digest| by the key in |dsa| - * and returns an allocated, DSA_SIG structure, or NULL on error. */ -OPENSSL_EXPORT DSA_SIG *DSA_do_sign(const uint8_t *digest, size_t digest_len, - DSA *dsa); - -/* DSA_do_verify verifies that |sig| is a valid signature, by the public key in - * |dsa|, of the hash in |digest|. It returns one if so, zero if invalid and -1 - * on error. - * - * WARNING: do not use. This function returns -1 for error, 0 for invalid and 1 - * for valid. However, this is dangerously different to the usual OpenSSL - * convention and could be a disaster if a user did |if (DSA_do_verify(...))|. - * Because of this, |DSA_check_signature| is a safer version of this. - * - * TODO(fork): deprecate. */ -OPENSSL_EXPORT int DSA_do_verify(const uint8_t *digest, size_t digest_len, - DSA_SIG *sig, const DSA *dsa); - -/* DSA_do_check_signature sets |*out_valid| to zero. Then it verifies that |sig| - * is a valid signature, by the public key in |dsa| of the hash in |digest| - * and, if so, it sets |*out_valid| to one. - * - * It returns one if it was able to verify the signature as valid or invalid, - * and zero on error. */ -OPENSSL_EXPORT int DSA_do_check_signature(int *out_valid, const uint8_t *digest, - size_t digest_len, DSA_SIG *sig, - const DSA *dsa); - - -/* ASN.1 signatures. - * - * These functions also perform DSA signature operations, but deal with ASN.1 - * encoded signatures as opposed to raw |BIGNUM|s. If you don't know what - * encoding a DSA signature is in, it's probably ASN.1. */ - -/* DSA_sign signs |digest| with the key in |dsa| and writes the resulting - * signature, in ASN.1 form, to |out_sig| and the length of the signature to - * |*out_siglen|. There must be, at least, |DSA_size(dsa)| bytes of space in - * |out_sig|. It returns one on success and zero otherwise. - * - * (The |type| argument is ignored.) */ -OPENSSL_EXPORT int DSA_sign(int type, const uint8_t *digest, size_t digest_len, - uint8_t *out_sig, unsigned int *out_siglen, - DSA *dsa); - -/* DSA_verify verifies that |sig| is a valid, ASN.1 signature, by the public - * key in |dsa|, of the hash in |digest|. It returns one if so, zero if invalid - * and -1 on error. - * - * (The |type| argument is ignored.) - * - * WARNING: do not use. This function returns -1 for error, 0 for invalid and 1 - * for valid. However, this is dangerously different to the usual OpenSSL - * convention and could be a disaster if a user did |if (DSA_do_verify(...))|. - * Because of this, |DSA_check_signature| is a safer version of this. - * - * TODO(fork): deprecate. */ -OPENSSL_EXPORT int DSA_verify(int type, const uint8_t *digest, - size_t digest_len, const uint8_t *sig, - size_t sig_len, const DSA *dsa); - -/* DSA_check_signature sets |*out_valid| to zero. Then it verifies that |sig| - * is a valid, ASN.1 signature, by the public key in |dsa|, of the hash in - * |digest|. If so, it sets |*out_valid| to one. - * - * It returns one if it was able to verify the signature as valid or invalid, - * and zero on error. */ -OPENSSL_EXPORT int DSA_check_signature(int *out_valid, const uint8_t *digest, - size_t digest_len, const uint8_t *sig, - size_t sig_len, const DSA *dsa); - -/* DSA_size returns the size, in bytes, of an ASN.1 encoded, DSA signature - * generated by |dsa|. Parameters must already have been setup in |dsa|. */ -OPENSSL_EXPORT int DSA_size(const DSA *dsa); - - -/* ASN.1 encoding. */ - -/* d2i_DSA_SIG parses an ASN.1, DER-encoded, DSA signature from |len| bytes at - * |*inp|. If |out_sig| is not NULL then, on exit, a pointer to the result is - * in |*out_sig|. If |*out_sig| is already non-NULL on entry then the result is - * written directly into |*out_sig|, otherwise a fresh |DSA_SIG| is allocated. - * On successful exit, |*inp| is advanced past the DER structure. It returns - * the result or NULL on error. */ -OPENSSL_EXPORT DSA_SIG *d2i_DSA_SIG(DSA_SIG **out_sig, const uint8_t **inp, - long len); - -/* i2d_DSA_SIG marshals |in| to an ASN.1, DER structure. If |outp| is not NULL - * then the result is written to |*outp| and |*outp| is advanced just past the - * output. It returns the number of bytes in the result, whether written or not, - * or a negative value on error. */ -OPENSSL_EXPORT int i2d_DSA_SIG(const DSA_SIG *in, uint8_t **outp); - -/* d2i_DSAPublicKey parses an ASN.1, DER-encoded, DSA public key from |len| - * bytes at |*inp|. If |out| is not NULL then, on exit, a pointer to the result - * is in |*out|. If |*out| is already non-NULL on entry then the result is - * written directly into |*out|, otherwise a fresh |DSA| is allocated. On - * successful exit, |*inp| is advanced past the DER structure. It returns the - * result or NULL on error. */ -OPENSSL_EXPORT DSA *d2i_DSAPublicKey(DSA **out, const uint8_t **inp, long len); - -/* i2d_DSAPublicKey marshals a public key from |in| to an ASN.1, DER structure. - * If |outp| is not NULL then the result is written to |*outp| and |*outp| is - * advanced just past the output. It returns the number of bytes in the result, - * whether written or not, or a negative value on error. */ -OPENSSL_EXPORT int i2d_DSAPublicKey(const DSA *in, unsigned char **outp); - -/* d2i_DSAPrivateKey parses an ASN.1, DER-encoded, DSA private key from |len| - * bytes at |*inp|. If |out| is not NULL then, on exit, a pointer to the result - * is in |*out|. If |*out| is already non-NULL on entry then the result is - * written directly into |*out|, otherwise a fresh |DSA| is allocated. On - * successful exit, |*inp| is advanced past the DER structure. It returns the - * result or NULL on error. */ -OPENSSL_EXPORT DSA *d2i_DSAPrivateKey(DSA **out, const uint8_t **inp, long len); - -/* i2d_DSAPrivateKey marshals a private key from |in| to an ASN.1, DER structure. - * If |outp| is not NULL then the result is written to |*outp| and |*outp| is - * advanced just past the output. It returns the number of bytes in the result, - * whether written or not, or a negative value on error. */ -OPENSSL_EXPORT int i2d_DSAPrivateKey(const DSA *in, unsigned char **outp); - -/* d2i_DSAparams parses ASN.1, DER-encoded, DSA parameters from |len| bytes at - * |*inp|. If |out| is not NULL then, on exit, a pointer to the result is in - * |*out|. If |*out| is already non-NULL on entry then the result is written - * directly into |*out|, otherwise a fresh |DSA| is allocated. On successful - * exit, |*inp| is advanced past the DER structure. It returns the result or - * NULL on error. */ -OPENSSL_EXPORT DSA *d2i_DSAparams(DSA **out, const uint8_t **inp, long len); - -/* i2d_DSAparams marshals DSA parameters from |in| to an ASN.1, DER structure. - * If |outp| is not NULL then the result is written to |*outp| and |*outp| is - * advanced just past the output. It returns the number of bytes in the result, - * whether written or not, or a negative value on error. */ -OPENSSL_EXPORT int i2d_DSAparams(const DSA *in, unsigned char **outp); - - -/* Precomputation. */ - -/* DSA_sign_setup precomputes the message independent part of the DSA signature - * and writes them to |*out_kinv| and |*out_r|. Returns one on success, zero on - * error. - * - * TODO(fork): decide what to do with this. Since making DSA* opaque there's no - * way for the user to install them. Also, it forces the DSA* not to be const - * when passing to the signing function. */ -OPENSSL_EXPORT int DSA_sign_setup(const DSA *dsa, BN_CTX *ctx, - BIGNUM **out_kinv, BIGNUM **out_r); - - -/* Conversion. */ - -/* DSA_dup_DH returns a |DH| constructed from the parameters of |dsa|. This is - * sometimes needed when Diffie-Hellman parameters are stored in the form of - * DSA parameters. It returns an allocated |DH| on success or NULL on error. */ -OPENSSL_EXPORT DH *DSA_dup_DH(const DSA *dsa); - - -/* ex_data functions. - * - * See |ex_data.h| for details. */ - -OPENSSL_EXPORT int DSA_get_ex_new_index(long argl, void *argp, - CRYPTO_EX_new *new_func, - CRYPTO_EX_dup *dup_func, - CRYPTO_EX_free *free_func); -OPENSSL_EXPORT int DSA_set_ex_data(DSA *d, int idx, void *arg); -OPENSSL_EXPORT void *DSA_get_ex_data(const DSA *d, int idx); - - -struct dsa_method { - struct openssl_method_common_st common; - - void *app_data; - - int (*init)(DSA *dsa); - int (*finish)(DSA *dsa); - - DSA_SIG *(*sign)(const uint8_t *digest, size_t digest_len, DSA *dsa); - - int (*sign_setup)(const DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp, - const uint8_t *digest, size_t digest_len); - - int (*verify)(int *out_valid, const uint8_t *digest, size_t digest_len, - DSA_SIG *sig, const DSA *dsa); - - /* generate_parameters, if non-NULL, is used to generate DSA parameters. */ - int (*generate_parameters)(DSA *dsa, unsigned bits, const uint8_t *seed, - size_t seed_len, int *counter_ret, - unsigned long *h_ret, BN_GENCB *cb); - - /* keygen, if non-NULL, is used to generate DSA keys. */ - int (*keygen)(DSA *dsa); -}; - -struct dsa_st { - long version; - int write_params; - BIGNUM *p; - BIGNUM *q; /* == 20 */ - BIGNUM *g; - - BIGNUM *pub_key; /* y public key */ - BIGNUM *priv_key; /* x private key */ - - BIGNUM *kinv; /* Signing pre-calc */ - BIGNUM *r; /* Signing pre-calc */ - - int flags; - /* Normally used to cache montgomery values */ - CRYPTO_MUTEX method_mont_p_lock; - BN_MONT_CTX *method_mont_p; - CRYPTO_refcount_t references; - CRYPTO_EX_DATA ex_data; - DSA_METHOD *meth; - /* functional reference if 'meth' is ENGINE-provided */ - ENGINE *engine; -}; - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#define DSA_F_DSA_new_method 100 -#define DSA_F_dsa_sig_cb 101 -#define DSA_F_sign 102 -#define DSA_F_sign_setup 103 -#define DSA_F_verify 104 -#define DSA_R_BAD_Q_VALUE 100 -#define DSA_R_MISSING_PARAMETERS 101 -#define DSA_R_MODULUS_TOO_LARGE 102 -#define DSA_R_NEED_NEW_SETUP_VALUES 103 - -#endif /* OPENSSL_HEADER_DSA_H */ diff --git a/third_party/boringssl/include/openssl/dtls1.h b/third_party/boringssl/include/openssl/dtls1.h deleted file mode 100644 index 38ca801cb1..0000000000 --- a/third_party/boringssl/include/openssl/dtls1.h +++ /dev/null @@ -1,16 +0,0 @@ -/* Copyright (c) 2015, Google Inc. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -/* This header is provided in order to make compiling against code that expects - OpenSSL easier. */ diff --git a/third_party/boringssl/include/openssl/ec.h b/third_party/boringssl/include/openssl/ec.h deleted file mode 100644 index 25b455185e..0000000000 --- a/third_party/boringssl/include/openssl/ec.h +++ /dev/null @@ -1,433 +0,0 @@ -/* Originally written by Bodo Moeller for the OpenSSL project. - * ==================================================================== - * Copyright (c) 1998-2005 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * openssl-core@openssl.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.openssl.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS 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. - * ==================================================================== - * - * This product includes cryptographic software written by Eric Young - * (eay@cryptsoft.com). This product includes software written by Tim - * Hudson (tjh@cryptsoft.com). - * - */ -/* ==================================================================== - * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. - * - * Portions of the attached software ("Contribution") are developed by - * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project. - * - * The Contribution is licensed pursuant to the OpenSSL open source - * license provided above. - * - * The elliptic curve binary polynomial software is originally written by - * Sheueling Chang Shantz and Douglas Stebila of Sun Microsystems - * Laboratories. */ - -#ifndef OPENSSL_HEADER_EC_H -#define OPENSSL_HEADER_EC_H - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* Low-level operations on elliptic curves. */ - - -typedef struct ec_group_st EC_GROUP; -typedef struct ec_point_st EC_POINT; - -/** Enum for the point conversion form as defined in X9.62 (ECDSA) - * for the encoding of a elliptic curve point (x,y) */ -typedef enum { - /** the point is encoded as z||x, where the octet z specifies - * which solution of the quadratic equation y is */ - POINT_CONVERSION_COMPRESSED = 2, - /** the point is encoded as z||x||y, where z is the octet 0x02 */ - POINT_CONVERSION_UNCOMPRESSED = 4 -} point_conversion_form_t; - - -/* Elliptic curve groups. */ - -/* EC_GROUP_new_by_curve_name returns a fresh EC_GROUP object for the elliptic - * curve specified by |nid|, or NULL on error. - * - * The supported NIDs are: - * NID_secp224r1, - * NID_X9_62_prime256v1, - * NID_secp384r1, - * NID_secp521r1 */ -OPENSSL_EXPORT EC_GROUP *EC_GROUP_new_by_curve_name(int nid); - -/* EC_GROUP_free frees |group| and the data that it points to. */ -OPENSSL_EXPORT void EC_GROUP_free(EC_GROUP *group); - -/* EC_GROUP_dup returns a fresh |EC_GROUP| which is equal to |a| or NULL on - * error. */ -OPENSSL_EXPORT EC_GROUP *EC_GROUP_dup(const EC_GROUP *a); - -/* EC_GROUP_cmp returns zero if |a| and |b| are the same group and non-zero - * otherwise. */ -OPENSSL_EXPORT int EC_GROUP_cmp(const EC_GROUP *a, const EC_GROUP *b, - BN_CTX *ignored); - -/* EC_GROUP_get0_generator returns a pointer to the internal |EC_POINT| object - * in |group| that specifies the generator for the group. */ -OPENSSL_EXPORT const EC_POINT *EC_GROUP_get0_generator(const EC_GROUP *group); - -/* EC_GROUP_get_order sets |*order| to the order of |group|, if it's not - * NULL. It returns one on success and zero otherwise. |ctx| is ignored. */ -OPENSSL_EXPORT int EC_GROUP_get_order(const EC_GROUP *group, BIGNUM *order, - BN_CTX *ctx); - -/* EC_GROUP_get_cofactor sets |*cofactor| to the cofactor of |group| using - * |ctx|, if it's not NULL. It returns one on success and zero otherwise. */ -OPENSSL_EXPORT int EC_GROUP_get_cofactor(const EC_GROUP *group, - BIGNUM *cofactor, BN_CTX *ctx); - -/* EC_GROUP_get_curve_GFp gets various parameters about a group. It sets - * |*out_p| to the order of the coordinate field and |*out_a| and |*out_b| to - * the parameters of the curve when expressed as y² = x³ + ax + b. Any of the - * output parameters can be NULL. It returns one on success and zero on - * error. */ -OPENSSL_EXPORT int EC_GROUP_get_curve_GFp(const EC_GROUP *group, BIGNUM *out_p, - BIGNUM *out_a, BIGNUM *out_b, - BN_CTX *ctx); - -/* EC_GROUP_get_curve_name returns a NID that identifies |group|. */ -OPENSSL_EXPORT int EC_GROUP_get_curve_name(const EC_GROUP *group); - -/* EC_GROUP_get_degree returns the number of bits needed to represent an - * element of the field underlying |group|. */ -OPENSSL_EXPORT int EC_GROUP_get_degree(const EC_GROUP *group); - -/* EC_GROUP_precompute_mult precomputes multiplies of the generator in order to - * speed up operations that involve calculating generator multiples. It returns - * one on sucess and zero otherwise. If |ctx| is not NULL, it may be used. */ -OPENSSL_EXPORT int EC_GROUP_precompute_mult(EC_GROUP *group, BN_CTX *ctx); - -/* EC_GROUP_have_precompute_mult returns one if |group| contains precomputed - * generator multiples. */ -OPENSSL_EXPORT int EC_GROUP_have_precompute_mult(const EC_GROUP *group); - - -/* Points on elliptic curves. */ - -/* EC_POINT_new returns a fresh |EC_POINT| object in the given group, or NULL - * on error. */ -OPENSSL_EXPORT EC_POINT *EC_POINT_new(const EC_GROUP *group); - -/* EC_POINT_free frees |point| and the data that it points to. */ -OPENSSL_EXPORT void EC_POINT_free(EC_POINT *point); - -/* EC_POINT_clear_free clears the data that |point| points to, frees it and - * then frees |point| itself. */ -OPENSSL_EXPORT void EC_POINT_clear_free(EC_POINT *point); - -/* EC_POINT_copy sets |*dest| equal to |*src|. It returns one on success and - * zero otherwise. */ -OPENSSL_EXPORT int EC_POINT_copy(EC_POINT *dest, const EC_POINT *src); - -/* EC_POINT_dup returns a fresh |EC_POINT| that contains the same values as - * |src|, or NULL on error. */ -OPENSSL_EXPORT EC_POINT *EC_POINT_dup(const EC_POINT *src, - const EC_GROUP *group); - -/* EC_POINT_set_to_infinity sets |point| to be the "point at infinity" for the - * given group. */ -OPENSSL_EXPORT int EC_POINT_set_to_infinity(const EC_GROUP *group, - EC_POINT *point); - -/* EC_POINT_is_at_infinity returns one iff |point| is the point at infinity and - * zero otherwise. */ -OPENSSL_EXPORT int EC_POINT_is_at_infinity(const EC_GROUP *group, - const EC_POINT *point); - -/* EC_POINT_is_on_curve returns one if |point| is an element of |group| and - * zero otheriwse. If |ctx| is non-NULL, it may be used. */ -OPENSSL_EXPORT int EC_POINT_is_on_curve(const EC_GROUP *group, - const EC_POINT *point, BN_CTX *ctx); - -/* EC_POINT_cmp returns zero if |a| is equal to |b|, greater than zero is - * non-equal and -1 on error. If |ctx| is not NULL, it may be used. */ -OPENSSL_EXPORT int EC_POINT_cmp(const EC_GROUP *group, const EC_POINT *a, - const EC_POINT *b, BN_CTX *ctx); - -/* EC_POINT_make_affine converts |point| to affine form, internally. It returns - * one on success and zero otherwise. If |ctx| is not NULL, it may be used. */ -OPENSSL_EXPORT int EC_POINT_make_affine(const EC_GROUP *group, EC_POINT *point, - BN_CTX *ctx); - -/* EC_POINTs_make_affine converts |num| points from |points| to affine form, - * internally. It returns one on success and zero otherwise. If |ctx| is not - * NULL, it may be used. */ -OPENSSL_EXPORT int EC_POINTs_make_affine(const EC_GROUP *group, size_t num, - EC_POINT *points[], BN_CTX *ctx); - - -/* Point conversion. */ - -/* EC_POINT_get_affine_coordinates_GFp sets |x| and |y| to the affine value of - * |point| using |ctx|, if it's not NULL. It returns one on success and zero - * otherwise. */ -OPENSSL_EXPORT int EC_POINT_get_affine_coordinates_GFp(const EC_GROUP *group, - const EC_POINT *point, - BIGNUM *x, BIGNUM *y, - BN_CTX *ctx); - -/* EC_POINT_set_affine_coordinates sets the value of |p| to be (|x|, |y|). The - * |ctx| argument may be used if not NULL. */ -OPENSSL_EXPORT int EC_POINT_set_affine_coordinates_GFp(const EC_GROUP *group, - EC_POINT *point, - const BIGNUM *x, - const BIGNUM *y, - BN_CTX *ctx); - -/* EC_POINT_point2oct serialises |point| into the X9.62 form given by |form| - * into, at most, |len| bytes at |buf|. It returns the number of bytes written - * or zero on error if |buf| is non-NULL, else the number of bytes needed. The - * |ctx| argument may be used if not NULL. */ -OPENSSL_EXPORT size_t EC_POINT_point2oct(const EC_GROUP *group, - const EC_POINT *point, - point_conversion_form_t form, - uint8_t *buf, size_t len, BN_CTX *ctx); - -/* EC_POINT_oct2point sets |point| from |len| bytes of X9.62 format - * serialisation in |buf|. It returns one on success and zero otherwise. The - * |ctx| argument may be used if not NULL. */ -OPENSSL_EXPORT int EC_POINT_oct2point(const EC_GROUP *group, EC_POINT *point, - const uint8_t *buf, size_t len, - BN_CTX *ctx); - -/* EC_POINT_set_compressed_coordinates_GFp sets |point| to equal the point with - * the given |x| coordinate and the y coordinate specified by |y_bit| (see - * X9.62). It returns one on success and zero otherwise. */ -OPENSSL_EXPORT int EC_POINT_set_compressed_coordinates_GFp( - const EC_GROUP *group, EC_POINT *point, const BIGNUM *x, int y_bit, - BN_CTX *ctx); - - -/* Group operations. */ - -/* EC_POINT_add sets |r| equal to |a| plus |b|. It returns one on success and - * zero otherwise. If |ctx| is not NULL, it may be used. */ -OPENSSL_EXPORT int EC_POINT_add(const EC_GROUP *group, EC_POINT *r, - const EC_POINT *a, const EC_POINT *b, - BN_CTX *ctx); - -/* EC_POINT_dbl sets |r| equal to |a| plus |a|. It returns one on success and - * zero otherwise. If |ctx| is not NULL, it may be used. */ -OPENSSL_EXPORT int EC_POINT_dbl(const EC_GROUP *group, EC_POINT *r, - const EC_POINT *a, BN_CTX *ctx); - -/* EC_POINT_dbl sets |a| equal to minus |a|. It returns one on success and zero - * otherwise. If |ctx| is not NULL, it may be used. */ -OPENSSL_EXPORT int EC_POINT_invert(const EC_GROUP *group, EC_POINT *a, - BN_CTX *ctx); - -/* EC_POINT_mul sets r = generator*n + q*m. It returns one on success and zero - * otherwise. If |ctx| is not NULL, it may be used. */ -OPENSSL_EXPORT int EC_POINT_mul(const EC_GROUP *group, EC_POINT *r, - const BIGNUM *n, const EC_POINT *q, - const BIGNUM *m, BN_CTX *ctx); - -/* EC_POINTs_mul sets r = generator*n + sum(p[i]*m[i]). It returns one on - * success and zero otherwise. If |ctx| is not NULL, it may be used. */ -OPENSSL_EXPORT int EC_POINTs_mul(const EC_GROUP *group, EC_POINT *r, - const BIGNUM *n, size_t num, - const EC_POINT *p[], const BIGNUM *m[], - BN_CTX *ctx); - - -/* Deprecated functions. */ - -/* EC_GROUP_new_curve_GFp creates a new, arbitrary elliptic curve group based - * on the equation y² = x³ + a·x + b. It returns the new group or NULL on - * error. - * - * |EC_GROUP|s returned by this function will always compare as unequal via - * |EC_GROUP_cmp| (even to themselves). |EC_GROUP_get_curve_name| will always - * return |NID_undef|. */ -OPENSSL_EXPORT EC_GROUP *EC_GROUP_new_curve_GFp(const BIGNUM *p, - const BIGNUM *a, - const BIGNUM *b, BN_CTX *ctx); - -/* EC_GROUP_set_generator sets the generator for |group| to |generator|, which - * must have the given order and cofactor. This should only be used with - * |EC_GROUP| objects returned by |EC_GROUP_new_curve_GFp|. */ -OPENSSL_EXPORT int EC_GROUP_set_generator(EC_GROUP *group, - const EC_POINT *generator, - const BIGNUM *order, - const BIGNUM *cofactor); - -/* EC_GROUP_set_asn1_flag does nothing. */ -OPENSSL_EXPORT void EC_GROUP_set_asn1_flag(EC_GROUP *group, int flag); - -#define OPENSSL_EC_NAMED_CURVE 0 - -typedef struct ec_method_st EC_METHOD; - -/* EC_GROUP_method_of returns NULL. */ -OPENSSL_EXPORT const EC_METHOD *EC_GROUP_method_of(const EC_GROUP *group); - -/* EC_METHOD_get_field_type returns NID_X9_62_prime_field. */ -OPENSSL_EXPORT int EC_METHOD_get_field_type(const EC_METHOD *meth); - -/* EC_GROUP_set_point_conversion_form aborts the process if |form| is not - * |POINT_CONVERSION_UNCOMPRESSED| and otherwise does nothing. */ -OPENSSL_EXPORT void EC_GROUP_set_point_conversion_form( - EC_GROUP *group, point_conversion_form_t form); - - -/* Old code expects to get EC_KEY from ec.h. */ -#if !defined(OPENSSL_HEADER_EC_KEY_H) -#include -#endif - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#define EC_F_EC_GROUP_copy 100 -#define EC_F_EC_GROUP_get_curve_GFp 101 -#define EC_F_EC_GROUP_get_degree 102 -#define EC_F_EC_GROUP_new_by_curve_name 103 -#define EC_F_EC_KEY_check_key 104 -#define EC_F_EC_KEY_copy 105 -#define EC_F_EC_KEY_generate_key 106 -#define EC_F_EC_KEY_new_method 107 -#define EC_F_EC_KEY_set_public_key_affine_coordinates 108 -#define EC_F_EC_POINT_add 109 -#define EC_F_EC_POINT_cmp 110 -#define EC_F_EC_POINT_copy 111 -#define EC_F_EC_POINT_dbl 112 -#define EC_F_EC_POINT_dup 113 -#define EC_F_EC_POINT_get_affine_coordinates_GFp 114 -#define EC_F_EC_POINT_invert 115 -#define EC_F_EC_POINT_is_at_infinity 116 -#define EC_F_EC_POINT_is_on_curve 117 -#define EC_F_EC_POINT_make_affine 118 -#define EC_F_EC_POINT_new 119 -#define EC_F_EC_POINT_oct2point 120 -#define EC_F_EC_POINT_point2oct 121 -#define EC_F_EC_POINT_set_affine_coordinates_GFp 122 -#define EC_F_EC_POINT_set_compressed_coordinates_GFp 123 -#define EC_F_EC_POINT_set_to_infinity 124 -#define EC_F_EC_POINTs_make_affine 125 -#define EC_F_compute_wNAF 126 -#define EC_F_d2i_ECPKParameters 127 -#define EC_F_d2i_ECParameters 128 -#define EC_F_d2i_ECPrivateKey 129 -#define EC_F_ec_GFp_mont_field_decode 130 -#define EC_F_ec_GFp_mont_field_encode 131 -#define EC_F_ec_GFp_mont_field_mul 132 -#define EC_F_ec_GFp_mont_field_set_to_one 133 -#define EC_F_ec_GFp_mont_field_sqr 134 -#define EC_F_ec_GFp_mont_group_set_curve 135 -#define EC_F_ec_GFp_simple_group_check_discriminant 136 -#define EC_F_ec_GFp_simple_group_set_curve 137 -#define EC_F_ec_GFp_simple_make_affine 138 -#define EC_F_ec_GFp_simple_oct2point 139 -#define EC_F_ec_GFp_simple_point2oct 140 -#define EC_F_ec_GFp_simple_point_get_affine_coordinates 141 -#define EC_F_ec_GFp_simple_point_set_affine_coordinates 142 -#define EC_F_ec_GFp_simple_points_make_affine 143 -#define EC_F_ec_GFp_simple_set_compressed_coordinates 144 -#define EC_F_ec_asn1_group2pkparameters 145 -#define EC_F_ec_asn1_pkparameters2group 146 -#define EC_F_ec_group_new 147 -#define EC_F_ec_group_new_curve_GFp 148 -#define EC_F_ec_group_new_from_data 149 -#define EC_F_ec_point_set_Jprojective_coordinates_GFp 150 -#define EC_F_ec_pre_comp_new 151 -#define EC_F_ec_wNAF_mul 152 -#define EC_F_ec_wNAF_precompute_mult 153 -#define EC_F_i2d_ECPKParameters 154 -#define EC_F_i2d_ECParameters 155 -#define EC_F_i2d_ECPrivateKey 156 -#define EC_F_i2o_ECPublicKey 157 -#define EC_F_o2i_ECPublicKey 158 -#define EC_F_BN_to_felem 159 -#define EC_F_ec_GFp_nistp256_group_set_curve 160 -#define EC_F_ec_GFp_nistp256_point_get_affine_coordinates 161 -#define EC_F_ec_GFp_nistp256_points_mul 162 -#define EC_F_ec_group_copy 163 -#define EC_F_nistp256_pre_comp_new 164 -#define EC_F_EC_KEY_new_by_curve_name 165 -#define EC_F_EC_GROUP_new_curve_GFp 166 -#define EC_R_BUFFER_TOO_SMALL 100 -#define EC_R_COORDINATES_OUT_OF_RANGE 101 -#define EC_R_D2I_ECPKPARAMETERS_FAILURE 102 -#define EC_R_EC_GROUP_NEW_BY_NAME_FAILURE 103 -#define EC_R_GROUP2PKPARAMETERS_FAILURE 104 -#define EC_R_I2D_ECPKPARAMETERS_FAILURE 105 -#define EC_R_INCOMPATIBLE_OBJECTS 106 -#define EC_R_INVALID_COMPRESSED_POINT 107 -#define EC_R_INVALID_COMPRESSION_BIT 108 -#define EC_R_INVALID_ENCODING 109 -#define EC_R_INVALID_FIELD 110 -#define EC_R_INVALID_FORM 111 -#define EC_R_INVALID_GROUP_ORDER 112 -#define EC_R_INVALID_PRIVATE_KEY 113 -#define EC_R_MISSING_PARAMETERS 114 -#define EC_R_MISSING_PRIVATE_KEY 115 -#define EC_R_NON_NAMED_CURVE 116 -#define EC_R_NOT_INITIALIZED 117 -#define EC_R_PKPARAMETERS2GROUP_FAILURE 118 -#define EC_R_POINT_AT_INFINITY 119 -#define EC_R_POINT_IS_NOT_ON_CURVE 120 -#define EC_R_SLOT_FULL 121 -#define EC_R_UNDEFINED_GENERATOR 122 -#define EC_R_UNKNOWN_GROUP 123 -#define EC_R_UNKNOWN_ORDER 124 -#define EC_R_WRONG_ORDER 125 -#define EC_R_BIGNUM_OUT_OF_RANGE 126 -#define EC_R_WRONG_CURVE_PARAMETERS 127 - -#endif /* OPENSSL_HEADER_EC_H */ diff --git a/third_party/boringssl/include/openssl/ec_key.h b/third_party/boringssl/include/openssl/ec_key.h deleted file mode 100644 index ee64030b8e..0000000000 --- a/third_party/boringssl/include/openssl/ec_key.h +++ /dev/null @@ -1,286 +0,0 @@ -/* Originally written by Bodo Moeller for the OpenSSL project. - * ==================================================================== - * Copyright (c) 1998-2005 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * openssl-core@openssl.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.openssl.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS 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. - * ==================================================================== - * - * This product includes cryptographic software written by Eric Young - * (eay@cryptsoft.com). This product includes software written by Tim - * Hudson (tjh@cryptsoft.com). - * - */ -/* ==================================================================== - * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. - * - * Portions of the attached software ("Contribution") are developed by - * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project. - * - * The Contribution is licensed pursuant to the OpenSSL open source - * license provided above. - * - * The elliptic curve binary polynomial software is originally written by - * Sheueling Chang Shantz and Douglas Stebila of Sun Microsystems - * Laboratories. */ - -#ifndef OPENSSL_HEADER_EC_KEY_H -#define OPENSSL_HEADER_EC_KEY_H - -#include - -#include -#include -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* ec_key.h contains functions that handle elliptic-curve points that are - * public/private keys. */ - - -/* EC key objects. */ - -/* EC_KEY_new returns a fresh |EC_KEY| object or NULL on error. */ -OPENSSL_EXPORT EC_KEY *EC_KEY_new(void); - -/* EC_KEY_new_method acts the same as |EC_KEY_new|, but takes an explicit - * |ENGINE|. */ -OPENSSL_EXPORT EC_KEY *EC_KEY_new_method(const ENGINE *engine); - -/* EC_KEY_new_by_curve_name returns a fresh EC_KEY for group specified by |nid| - * or NULL on error. */ -OPENSSL_EXPORT EC_KEY *EC_KEY_new_by_curve_name(int nid); - -/* EC_KEY_free frees all the data owned by |key| and |key| itself. */ -OPENSSL_EXPORT void EC_KEY_free(EC_KEY *key); - -/* EC_KEY_copy sets |dst| equal to |src| and returns |dst| or NULL on error. */ -OPENSSL_EXPORT EC_KEY *EC_KEY_copy(EC_KEY *dst, const EC_KEY *src); - -/* EC_KEY_dup returns a fresh copy of |src| or NULL on error. */ -OPENSSL_EXPORT EC_KEY *EC_KEY_dup(const EC_KEY *src); - -/* EC_KEY_up_ref increases the reference count of |key|. It returns one on - * success and zero otherwise. */ -OPENSSL_EXPORT int EC_KEY_up_ref(EC_KEY *key); - -/* EC_KEY_is_opaque returns one if |key| is opaque and doesn't expose its key - * material. Otherwise it return zero. */ -OPENSSL_EXPORT int EC_KEY_is_opaque(const EC_KEY *key); - -/* EC_KEY_get0_group returns a pointer to the |EC_GROUP| object inside |key|. */ -OPENSSL_EXPORT const EC_GROUP *EC_KEY_get0_group(const EC_KEY *key); - -/* EC_KEY_set_group sets the |EC_GROUP| object that |key| will use to |group|. - * It returns one on success and zero otherwise. */ -OPENSSL_EXPORT int EC_KEY_set_group(EC_KEY *key, const EC_GROUP *group); - -/* EC_KEY_get0_private_key returns a pointer to the private key inside |key|. */ -OPENSSL_EXPORT const BIGNUM *EC_KEY_get0_private_key(const EC_KEY *key); - -/* EC_KEY_set_private_key sets the private key of |key| to |priv|. It returns - * one on success and zero otherwise. */ -OPENSSL_EXPORT int EC_KEY_set_private_key(EC_KEY *key, const BIGNUM *prv); - -/* EC_KEY_get0_public_key returns a pointer to the public key point inside - * |key|. */ -OPENSSL_EXPORT const EC_POINT *EC_KEY_get0_public_key(const EC_KEY *key); - -/* EC_KEY_set_public_key sets the public key of |key| to |pub|, by copying it. - * It returns one on success and zero otherwise. */ -OPENSSL_EXPORT int EC_KEY_set_public_key(EC_KEY *key, const EC_POINT *pub); - -#define EC_PKEY_NO_PARAMETERS 0x001 -#define EC_PKEY_NO_PUBKEY 0x002 - -/* EC_KEY_get_enc_flags returns the encoding flags for |key|, which is a - * bitwise-OR of |EC_PKEY_*| values. */ -OPENSSL_EXPORT unsigned EC_KEY_get_enc_flags(const EC_KEY *key); - -/* EC_KEY_set_enc_flags sets the encoding flags for |key|, which is a - * bitwise-OR of |EC_PKEY_*| values. */ -OPENSSL_EXPORT void EC_KEY_set_enc_flags(EC_KEY *key, unsigned flags); - -/* EC_KEY_get_conv_form returns the conversation form that will be used by - * |key|. */ -OPENSSL_EXPORT point_conversion_form_t EC_KEY_get_conv_form(const EC_KEY *key); - -/* EC_KEY_set_conv_form sets the conversion form to be used by |key|. */ -OPENSSL_EXPORT void EC_KEY_set_conv_form(EC_KEY *key, - point_conversion_form_t cform); - -/* EC_KEY_precompute_mult precomputes multiplies of the generator of the - * underlying group in order to speed up operations that calculate generator - * multiples. If |ctx| is not NULL, it may be used. It returns one on success - * and zero otherwise. */ -OPENSSL_EXPORT int EC_KEY_precompute_mult(EC_KEY *key, BN_CTX *ctx); - -/* EC_KEY_check_key performs several checks on |key| (possibly including an - * expensive check that the public key is in the primary subgroup). It returns - * one if all checks pass and zero otherwise. If it returns zero then detail - * about the problem can be found on the error stack. */ -OPENSSL_EXPORT int EC_KEY_check_key(const EC_KEY *key); - -/* EC_KEY_set_public_key_affine_coordinates sets the public key in |key| to - * (|x|, |y|). It returns one on success and zero otherwise. */ -OPENSSL_EXPORT int EC_KEY_set_public_key_affine_coordinates(EC_KEY *key, - BIGNUM *x, - BIGNUM *y); - - -/* Key generation. */ - -/* EC_KEY_generate_key generates a random, private key, calculates the - * corresponding public key and stores both in |key|. It returns one on success - * or zero otherwise. */ -OPENSSL_EXPORT int EC_KEY_generate_key(EC_KEY *key); - - -/* Serialisation. */ - -/* d2i_ECPrivateKey parses an ASN.1, DER-encoded, private key from |len| bytes - * at |*inp|. If |out_key| is not NULL then, on exit, a pointer to the result - * is in |*out_key|. If |*out_key| is already non-NULL on entry then the result - * is written directly into |*out_key|, otherwise a fresh |EC_KEY| is - * allocated. On successful exit, |*inp| is advanced past the DER structure. It - * returns the result or NULL on error. */ -OPENSSL_EXPORT EC_KEY *d2i_ECPrivateKey(EC_KEY **out_key, const uint8_t **inp, - long len); - -/* i2d_ECParameters marshals an EC private key from |key| to an ASN.1, DER - * structure. If |outp| is not NULL then the result is written to |*outp| and - * |*outp| is advanced just past the output. It returns the number of bytes in - * the result, whether written or not, or a negative value on error. */ -OPENSSL_EXPORT int i2d_ECPrivateKey(const EC_KEY *key, uint8_t **outp); - -/* d2i_ECParameters parses an ASN.1, DER-encoded, set of EC parameters from - * |len| bytes at |*inp|. If |out_key| is not NULL then, on exit, a pointer to - * the result is in |*out_key|. If |*out_key| is already non-NULL on entry then - * the result is written directly into |*out_key|, otherwise a fresh |EC_KEY| - * is allocated. On successful exit, |*inp| is advanced past the DER structure. - * It returns the result or NULL on error. */ -OPENSSL_EXPORT EC_KEY *d2i_ECParameters(EC_KEY **out_key, const uint8_t **inp, - long len); - -/* i2d_ECParameters marshals EC parameters from |key| to an ASN.1, DER - * structure. If |outp| is not NULL then the result is written to |*outp| and - * |*outp| is advanced just past the output. It returns the number of bytes in - * the result, whether written or not, or a negative value on error. */ -OPENSSL_EXPORT int i2d_ECParameters(const EC_KEY *key, uint8_t **outp); - -/* o2i_ECPublicKey parses an EC point from |len| bytes at |*inp| into - * |*out_key|. Note that this differs from the d2i format in that |*out_key| - * must be non-NULL. On successful exit, |*inp| is advanced past the DER - * structure. It returns |*out_key| or NULL on error. */ -OPENSSL_EXPORT EC_KEY *o2i_ECPublicKey(EC_KEY **out_key, const uint8_t **inp, - long len); - -/* i2o_ECPublicKey marshals an EC point from |key|. If |outp| is not NULL then - * the result is written to |*outp| and |*outp| is advanced just past the - * output. It returns the number of bytes in the result, whether written or - * not, or a negative value on error. */ -OPENSSL_EXPORT int i2o_ECPublicKey(const EC_KEY *key, unsigned char **outp); - - -/* ex_data functions. - * - * These functions are wrappers. See |ex_data.h| for details. */ - -OPENSSL_EXPORT int EC_KEY_get_ex_new_index(long argl, void *argp, - CRYPTO_EX_new *new_func, - CRYPTO_EX_dup *dup_func, - CRYPTO_EX_free *free_func); -OPENSSL_EXPORT int EC_KEY_set_ex_data(EC_KEY *r, int idx, void *arg); -OPENSSL_EXPORT void *EC_KEY_get_ex_data(const EC_KEY *r, int idx); - - -/* ECDSA method. */ - -/* ECDSA_FLAG_OPAQUE specifies that this ECDSA_METHOD does not expose its key - * material. This may be set if, for instance, it is wrapping some other crypto - * API, like a platform key store. */ -#define ECDSA_FLAG_OPAQUE 1 - -/* ecdsa_method_st is a structure of function pointers for implementing ECDSA. - * See engine.h. */ -struct ecdsa_method_st { - struct openssl_method_common_st common; - - void *app_data; - - int (*init)(EC_KEY *key); - int (*finish)(EC_KEY *key); - - /* group_order_size returns the number of bytes needed to represent the order - * of the group. This is used to calculate the maximum size of an ECDSA - * signature in |ECDSA_size|. */ - size_t (*group_order_size)(const EC_KEY *key); - - /* sign matches the arguments and behaviour of |ECDSA_sign|. */ - int (*sign)(const uint8_t *digest, size_t digest_len, uint8_t *sig, - unsigned int *sig_len, EC_KEY *eckey); - - /* verify matches the arguments and behaviour of |ECDSA_verify|. */ - int (*verify)(const uint8_t *digest, size_t digest_len, const uint8_t *sig, - size_t sig_len, EC_KEY *eckey); - - int flags; -}; - - -/* Deprecated functions. */ - -/* EC_KEY_set_asn1_flag does nothing. */ -OPENSSL_EXPORT void EC_KEY_set_asn1_flag(EC_KEY *key, int flag); - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_EC_KEY_H */ diff --git a/third_party/boringssl/include/openssl/ecdh.h b/third_party/boringssl/include/openssl/ecdh.h deleted file mode 100644 index 27a8578127..0000000000 --- a/third_party/boringssl/include/openssl/ecdh.h +++ /dev/null @@ -1,103 +0,0 @@ -/* ==================================================================== - * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. - * - * The Elliptic Curve Public-Key Crypto Library (ECC Code) included - * herein is developed by SUN MICROSYSTEMS, INC., and is contributed - * to the OpenSSL project. - * - * The ECC Code is licensed pursuant to the OpenSSL open source - * license provided below. - * - * The ECDH software is originally written by Douglas Stebila of - * Sun Microsystems Laboratories. - * - */ -/* ==================================================================== - * Copyright (c) 2000-2002 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * licensing@OpenSSL.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS 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. - * ==================================================================== - * - * This product includes cryptographic software written by Eric Young - * (eay@cryptsoft.com). This product includes software written by Tim - * Hudson (tjh@cryptsoft.com). */ - -#ifndef OPENSSL_HEADER_ECDH_H -#define OPENSSL_HEADER_ECDH_H - -#include - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* Elliptic curve Diffie-Hellman. */ - - -/* ECDH_compute_key calculates the shared key between |pub_key| and |priv_key|. - * If |KDF| is not NULL, then it is called with the bytes of the shared key and - * the parameter |out|. When |KDF| returns, the value of |*outlen| becomes the - * return value. Otherwise, as many bytes of the shared key as will fit are - * copied directly to, at most, |outlen| bytes at |out|. It returns the number - * of bytes written to |out|, or -1 on error. */ -OPENSSL_EXPORT int ECDH_compute_key(void *out, size_t outlen, - const EC_POINT *pub_key, EC_KEY *priv_key, - void *(*KDF)(const void *in, size_t inlen, - void *out, size_t *outlen)); - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#define ECDH_F_ECDH_compute_key 100 -#define ECDH_R_KDF_FAILED 100 -#define ECDH_R_NO_PRIVATE_VALUE 101 -#define ECDH_R_POINT_ARITHMETIC_FAILURE 102 - -#endif /* OPENSSL_HEADER_ECDH_H */ diff --git a/third_party/boringssl/include/openssl/ecdsa.h b/third_party/boringssl/include/openssl/ecdsa.h deleted file mode 100644 index e045463456..0000000000 --- a/third_party/boringssl/include/openssl/ecdsa.h +++ /dev/null @@ -1,182 +0,0 @@ -/* ==================================================================== - * Copyright (c) 1998-2005 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * openssl-core@OpenSSL.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS 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. - * ==================================================================== - * - * This product includes cryptographic software written by Eric Young - * (eay@cryptsoft.com). This product includes software written by Tim - * Hudson (tjh@cryptsoft.com). */ - -#ifndef OPENSSL_HEADER_ECDSA_H -#define OPENSSL_HEADER_ECDSA_H - -#include - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* ECDSA contains functions for signing and verifying with the Digital Signature - * Algorithm over elliptic curves. */ - - -/* Signing and verifing. */ - -/* ECDSA_sign signs |digest_len| bytes from |digest| with |key| and writes the - * resulting signature to |sig|, which must have |ECDSA_size(key)| bytes of - * space. On successful exit, |*sig_len| is set to the actual number of bytes - * written. The |type| argument should be zero. It returns one on success and - * zero otherwise. */ -OPENSSL_EXPORT int ECDSA_sign(int type, const uint8_t *digest, - size_t digest_len, uint8_t *sig, - unsigned int *sig_len, EC_KEY *key); - -/* ECDSA_verify verifies that |sig_len| bytes from |sig| constitute a valid - * signature by |key| of |digest|. (The |type| argument should be zero.) It - * returns one on success or zero if the signature is invalid or an error - * occured. */ -OPENSSL_EXPORT int ECDSA_verify(int type, const uint8_t *digest, - size_t digest_len, const uint8_t *sig, - size_t sig_len, EC_KEY *key); - -/* ECDSA_size returns the maximum size of an ECDSA signature using |key|. It - * returns zero on error. */ -OPENSSL_EXPORT size_t ECDSA_size(const EC_KEY *key); - - -/* Low-level signing and verification. - * - * Low-level functions handle signatures as |ECDSA_SIG| structures which allow - * the two values in an ECDSA signature to be handled separately. */ - -struct ecdsa_sig_st { - BIGNUM *r; - BIGNUM *s; -}; - -/* ECDSA_SIG_new returns a fresh |ECDSA_SIG| structure or NULL on error. */ -OPENSSL_EXPORT ECDSA_SIG *ECDSA_SIG_new(void); - -/* ECDSA_SIG_free frees |sig| its member |BIGNUM|s. */ -OPENSSL_EXPORT void ECDSA_SIG_free(ECDSA_SIG *sig); - -/* ECDSA_sign signs |digest_len| bytes from |digest| with |key| and returns the - * resulting signature structure, or NULL on error. */ -OPENSSL_EXPORT ECDSA_SIG *ECDSA_do_sign(const uint8_t *digest, - size_t digest_len, EC_KEY *key); - -/* ECDSA_verify verifies that |sig| constitutes a valid signature by |key| of - * |digest|. It returns one on success or zero if the signature is invalid or - * on error. */ -OPENSSL_EXPORT int ECDSA_do_verify(const uint8_t *digest, size_t digest_len, - const ECDSA_SIG *sig, EC_KEY *key); - - -/* Signing with precomputation. - * - * Parts of the ECDSA signature can be independent of the message to be signed - * thus it's possible to precompute them and reduce the signing latency. - * - * TODO(fork): remove support for this as it cannot support safe-randomness. */ - -/* ECDSA_sign_setup precomputes parts of an ECDSA signing operation. It sets - * |*kinv| and |*rp| to the precomputed values and uses the |ctx| argument, if - * not NULL. It returns one on success and zero otherwise. */ -OPENSSL_EXPORT int ECDSA_sign_setup(EC_KEY *eckey, BN_CTX *ctx, BIGNUM **kinv, - BIGNUM **rp); - -/* ECDSA_do_sign_ex is the same as |ECDSA_do_sign| but takes precomputed values - * as generated by |ECDSA_sign_setup|. */ -OPENSSL_EXPORT ECDSA_SIG *ECDSA_do_sign_ex(const uint8_t *digest, - size_t digest_len, - const BIGNUM *kinv, const BIGNUM *rp, - EC_KEY *eckey); - -/* ECDSA_sign_ex is the same as |ECDSA_sign| but takes precomputed values as - * generated by |ECDSA_sign_setup|. */ -OPENSSL_EXPORT int ECDSA_sign_ex(int type, const uint8_t *digest, - size_t digest_len, uint8_t *sig, - unsigned int *sig_len, const BIGNUM *kinv, - const BIGNUM *rp, EC_KEY *eckey); - - -/* ASN.1 functions. */ - -/* d2i_ECDSA_SIG parses an ASN.1, DER-encoded, signature from |len| bytes at - * |*inp|. If |out| is not NULL then, on exit, a pointer to the result is in - * |*out|. If |*out| is already non-NULL on entry then the result is written - * directly into |*out|, otherwise a fresh |ECDSA_SIG| is allocated. On - * successful exit, |*inp| is advanced past the DER structure. It returns the - * result or NULL on error. */ -OPENSSL_EXPORT ECDSA_SIG *d2i_ECDSA_SIG(ECDSA_SIG **out, const uint8_t **inp, - long len); - -/* i2d_ECDSA_SIG marshals a signature from |sig| to an ASN.1, DER - * structure. If |outp| is not NULL then the result is written to |*outp| and - * |*outp| is advanced just past the output. It returns the number of bytes in - * the result, whether written or not, or a negative value on error. */ -OPENSSL_EXPORT int i2d_ECDSA_SIG(const ECDSA_SIG *sig, uint8_t **outp); - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#define ECDSA_F_ECDSA_do_sign_ex 100 -#define ECDSA_F_ECDSA_do_verify 101 -#define ECDSA_F_ECDSA_sign_ex 102 -#define ECDSA_F_digest_to_bn 103 -#define ECDSA_F_ecdsa_sign_setup 104 -#define ECDSA_R_BAD_SIGNATURE 100 -#define ECDSA_R_MISSING_PARAMETERS 101 -#define ECDSA_R_NEED_NEW_SETUP_VALUES 102 -#define ECDSA_R_NOT_IMPLEMENTED 103 -#define ECDSA_R_RANDOM_NUMBER_GENERATION_FAILED 104 - -#endif /* OPENSSL_HEADER_ECDSA_H */ diff --git a/third_party/boringssl/include/openssl/engine.h b/third_party/boringssl/include/openssl/engine.h deleted file mode 100644 index d3d278a69b..0000000000 --- a/third_party/boringssl/include/openssl/engine.h +++ /dev/null @@ -1,107 +0,0 @@ -/* Copyright (c) 2014, Google Inc. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -#ifndef OPENSSL_HEADER_ENGINE_H -#define OPENSSL_HEADER_ENGINE_H - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* Engines are collections of methods. Methods are tables of function pointers, - * defined for certain algorithms, that allow operations on those algorithms to - * be overridden via a callback. This can be used, for example, to implement an - * RSA* that forwards operations to a hardware module. - * - * Methods are reference counted but |ENGINE|s are not. When creating a method, - * you should zero the whole structure and fill in the function pointers that - * you wish before setting it on an |ENGINE|. Any functions pointers that - * are NULL indicate that the default behaviour should be used. */ - - -/* Allocation and destruction. */ - -/* ENGINE_new returns an empty ENGINE that uses the default method for all - * algorithms. */ -OPENSSL_EXPORT ENGINE *ENGINE_new(void); - -/* ENGINE_free decrements the reference counts for all methods linked from - * |engine| and frees |engine| itself. */ -OPENSSL_EXPORT void ENGINE_free(ENGINE *engine); - - -/* Method accessors. - * - * Method accessors take a method pointer and the size of the structure. The - * size allows for ABI compatibility in the case that the method structure is - * extended with extra elements at the end. Methods are always copied by the - * set functions. - * - * Set functions return one on success and zero on allocation failure. */ - -OPENSSL_EXPORT int ENGINE_set_DH_method(ENGINE *engine, const DH_METHOD *method, - size_t method_size); -OPENSSL_EXPORT DH_METHOD *ENGINE_get_DH_method(const ENGINE *engine); - -OPENSSL_EXPORT int ENGINE_set_DSA_method(ENGINE *engine, - const DSA_METHOD *method, - size_t method_size); -OPENSSL_EXPORT DSA_METHOD *ENGINE_get_DSA_method(const ENGINE *engine); - -OPENSSL_EXPORT int ENGINE_set_RSA_method(ENGINE *engine, - const RSA_METHOD *method, - size_t method_size); -OPENSSL_EXPORT RSA_METHOD *ENGINE_get_RSA_method(const ENGINE *engine); - -OPENSSL_EXPORT int ENGINE_set_ECDSA_method(ENGINE *engine, - const ECDSA_METHOD *method, - size_t method_size); -OPENSSL_EXPORT ECDSA_METHOD *ENGINE_get_ECDSA_method(const ENGINE *engine); - - -/* Generic method functions. - * - * These functions take a void* type but actually operate on all method - * structures. */ - -/* METHOD_ref increments the reference count of |method|. This is a no-op for - * now because all methods are currently static. */ -void METHOD_ref(void *method); - -/* METHOD_unref decrements the reference count of |method| and frees it if the - * reference count drops to zero. This is a no-op for now because all methods - * are currently static. */ -void METHOD_unref(void *method); - - -/* Private functions. */ - -/* openssl_method_common_st contains the common part of all method structures. - * This must be the first member of all method structures. */ -struct openssl_method_common_st { - int references; /* dummy – not used. */ - char is_static; -}; - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#define ENGINE_R_OPERATION_NOT_SUPPORTED 100 - -#endif /* OPENSSL_HEADER_ENGINE_H */ diff --git a/third_party/boringssl/include/openssl/err.h b/third_party/boringssl/include/openssl/err.h deleted file mode 100644 index 30dc4afe9b..0000000000 --- a/third_party/boringssl/include/openssl/err.h +++ /dev/null @@ -1,509 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] - */ -/* ==================================================================== - * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * openssl-core@openssl.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.openssl.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS 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. - * ==================================================================== - * - * This product includes cryptographic software written by Eric Young - * (eay@cryptsoft.com). This product includes software written by Tim - * Hudson (tjh@cryptsoft.com). */ - -#ifndef OPENSSL_HEADER_ERR_H -#define OPENSSL_HEADER_ERR_H - -#include - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* Error queue handling functions. - * - * Errors in OpenSSL are generally signalled by the return value of a function. - * When a function fails it may add an entry to a per-thread error queue, - * which is managed by the functions in this header. - * - * Each error contains: - * 1) The library (i.e. ec, pem, rsa) which created it. - * 2) A function identifier and reason code. - * 3) The file and line number of the call that added the error. - * 4) A pointer to some error specific data, which may be NULL. - * - * The library identifier, function identifier and reason code are packed in a - * uint32_t and there exist various functions for unpacking it. - * - * The typical behaviour is that an error will occur deep in a call queue and - * that code will push an error onto the error queue. As the error queue - * unwinds, other functions will push their own errors. Thus, the "least - * recent" error is the most specific and the other errors will provide a - * backtrace of sorts. */ - - -/* Startup and shutdown. */ - -/* ERR_load_BIO_strings does nothing. - * - * TODO(fork): remove. libjingle calls this. */ -OPENSSL_EXPORT void ERR_load_BIO_strings(void); - -/* ERR_load_ERR_strings does nothing. */ -OPENSSL_EXPORT void ERR_load_ERR_strings(void); - -/* ERR_load_crypto_strings does nothing. */ -OPENSSL_EXPORT void ERR_load_crypto_strings(void); - -/* ERR_free_strings does nothing. */ -OPENSSL_EXPORT void ERR_free_strings(void); - - -/* Reading and formatting errors. */ - -/* ERR_get_error gets the packed error code for the least recent error and - * removes that error from the queue. If there are no errors in the queue then - * it returns zero. */ -OPENSSL_EXPORT uint32_t ERR_get_error(void); - -/* ERR_get_error_line acts like |ERR_get_error|, except that the file and line - * number of the call that added the error are also returned. */ -OPENSSL_EXPORT uint32_t ERR_get_error_line(const char **file, int *line); - -/* ERR_get_error_line_data acts like |ERR_get_error_line|, but also returns the - * error-specific data pointer and flags. The flags are a bitwise-OR of - * |ERR_FLAG_*| values. The error-specific data is owned by the error queue - * and the pointer becomes invalid after the next call that affects the same - * thread's error queue. If |*flags| contains |ERR_FLAG_STRING| then |*data| is - * human-readable. */ -OPENSSL_EXPORT uint32_t ERR_get_error_line_data(const char **file, int *line, - const char **data, int *flags); - -/* The "peek" functions act like the |ERR_get_error| functions, above, but they - * do not remove the error from the queue. */ -OPENSSL_EXPORT uint32_t ERR_peek_error(void); -OPENSSL_EXPORT uint32_t ERR_peek_error_line(const char **file, int *line); -OPENSSL_EXPORT uint32_t ERR_peek_error_line_data(const char **file, int *line, - const char **data, int *flags); - -/* The "peek last" functions act like the "peek" functions, above, except that - * they return the most recent error. */ -OPENSSL_EXPORT uint32_t ERR_peek_last_error(void); -OPENSSL_EXPORT uint32_t ERR_peek_last_error_line(const char **file, int *line); -OPENSSL_EXPORT uint32_t ERR_peek_last_error_line_data(const char **file, - int *line, - const char **data, - int *flags); - -/* ERR_error_string generates a human-readable string representing - * |packed_error|, places it at |buf| (which must be at least - * ERR_ERROR_STRING_BUF_LEN bytes long) and returns |buf|. If |buf| is NULL, - * the error string is placed in a static buffer which is returned. (The static - * buffer may be overridden by concurrent calls in other threads so this form - * is deprecated.) - * - * The string will have the following format: - * - * error:[error code]:[library name]:[function name]:[reason string] - * - * error code is an 8 digit hexadecimal number; library name, function name - * and reason string are ASCII text. - * - * TODO(fork): remove in favour of |ERR_error_string_n|. */ -OPENSSL_EXPORT char *ERR_error_string(uint32_t packed_error, char *buf); -#define ERR_ERROR_STRING_BUF_LEN 256 - -/* ERR_error_string_n is a variant of |ERR_error_string| that writes at most - * len characters (including the terminating NUL) and truncates the string if - * necessary. If |len| is greater than zero then |buf| is always NUL - * terminated. */ -OPENSSL_EXPORT void ERR_error_string_n(uint32_t packed_error, char *buf, - size_t len); - -/* ERR_lib_error_string returns a string representation of the library that - * generated |packed_error|. */ -OPENSSL_EXPORT const char *ERR_lib_error_string(uint32_t packed_error); - -/* ERR_func_error_string returns a string representation of the function that - * generated |packed_error|. */ -OPENSSL_EXPORT const char *ERR_func_error_string(uint32_t packed_error); - -/* ERR_reason_error_string returns a string representation of the reason for - * |packed_error|. */ -OPENSSL_EXPORT const char *ERR_reason_error_string(uint32_t packed_error); - -/* ERR_print_errors_callback_t is the type of a function used by - * |ERR_print_errors_cb|. It takes a pointer to a human readable string (and - * its length) that describes an entry in the error queue. The |ctx| argument - * is an opaque pointer given to |ERR_print_errors_cb|. - * - * It should return one on success or zero on error, which will stop the - * iteration over the error queue. */ -typedef int (*ERR_print_errors_callback_t)(const char *str, size_t len, - void *ctx); - -/* ERR_print_errors_cb calls |callback| with a string representation of each - * error in the current thread's error queue, from the least recent to the most - * recent error. - * - * The string will have the following format (which differs from - * |ERR_error_string|): - * - * [thread id]:error:[error code]:[library name]:[function name]: - * [reason string]:[file]:[line number]:[optional string data] - * - * (All in one line.) - * - * The callback can return one to continue the iteration or zero to stop it. - * The |ctx| argument is an opaque value that is passed through to the - * callback. */ -OPENSSL_EXPORT void ERR_print_errors_cb(ERR_print_errors_callback_t callback, - void *ctx); - - -/* ERR_print_errors_fp prints the current contents of the error stack to |file| - * using human readable strings where possible. */ -OPENSSL_EXPORT void ERR_print_errors_fp(FILE *file); - -/* Clearing errors. */ - -/* ERR_clear_error clears the error queue for the current thread. */ -OPENSSL_EXPORT void ERR_clear_error(void); - -/* ERR_remove_thread_state clears the error queue for the current thread if - * |tid| is NULL. Otherwise it calls |assert(0)|, because it's no longer - * possible to delete the error queue for other threads. - * - * Error queues are thread-local data and are deleted automatically. You do not - * need to call this function. Use |ERR_clear_error|. */ -OPENSSL_EXPORT void ERR_remove_thread_state(const CRYPTO_THREADID *tid); - - -/* Custom errors. */ - -/* ERR_get_next_error_library returns a value suitable for passing as the - * |library| argument to |ERR_put_error|. This is intended for code that wishes - * to push its own, non-standard errors to the error queue. */ -OPENSSL_EXPORT int ERR_get_next_error_library(void); - - -/* Deprecated functions. */ - -/* |ERR_remove_state| calls |ERR_clear_error|. */ -OPENSSL_EXPORT void ERR_remove_state(unsigned long pid); - - -/* Private functions. */ - -/* ERR_clear_system_error clears the system's error value (i.e. errno). */ -OPENSSL_EXPORT void ERR_clear_system_error(void); - -/* OPENSSL_PUT_ERROR is used by OpenSSL code to add an error to the error - * queue. */ -#define OPENSSL_PUT_ERROR(library, func, reason) \ - ERR_put_error(ERR_LIB_##library, library##_F_##func, reason, __FILE__, \ - __LINE__) - -/* OPENSSL_PUT_SYSTEM_ERROR is used by OpenSSL code to add an error from the - * operating system to the error queue. */ -/* TODO(fork): include errno. */ -#define OPENSSL_PUT_SYSTEM_ERROR(func) \ - ERR_put_error(ERR_LIB_SYS, SYS_F_##func, 0, __FILE__, __LINE__); - -/* ERR_put_error adds an error to the error queue, dropping the least recent - * error if neccessary for space reasons. */ -OPENSSL_EXPORT void ERR_put_error(int library, int func, int reason, - const char *file, unsigned line); - -/* ERR_add_error_data takes a variable number (|count|) of const char* - * pointers, concatenates them and sets the result as the data on the most - * recent error. */ -OPENSSL_EXPORT void ERR_add_error_data(unsigned count, ...); - -/* ERR_add_error_dataf takes a printf-style format and arguments, and sets the - * result as the data on the most recent error. */ -OPENSSL_EXPORT void ERR_add_error_dataf(const char *format, ...); - -/* ERR_set_mark "marks" the most recent error for use with |ERR_pop_to_mark|. - * It returns one if an error was marked and zero if there are no errors. */ -OPENSSL_EXPORT int ERR_set_mark(void); - -/* ERR_pop_to_mark removes errors from the most recent to the least recent - * until (and not including) a "marked" error. It returns zero if no marked - * error was found (and thus all errors were removed) and one otherwise. Errors - * are marked using |ERR_set_mark|. */ -OPENSSL_EXPORT int ERR_pop_to_mark(void); - -struct err_error_st { - /* file contains the filename where the error occured. */ - const char *file; - /* data contains optional data. It must be freed with |OPENSSL_free| if - * |flags&ERR_FLAG_MALLOCED|. */ - char *data; - /* packed contains the error library, function and reason, as packed by - * ERR_PACK. */ - uint32_t packed; - /* line contains the line number where the error occured. */ - uint16_t line; - /* flags contains a bitwise-OR of ERR_FLAG_* values. */ - uint8_t flags; -}; - -/* ERR_FLAG_STRING means that the |data| member is a NUL-terminated string that - * can be printed. */ -#define ERR_FLAG_STRING 1 -/* ERR_TXT_STRING is provided for compatibility with code that assumes that - * it's using OpenSSL. */ -#define ERR_TXT_STRING ERR_FLAG_STRING - -/* ERR_FLAG_PUBLIC_MASK is applied to the flags field before it is returned - * from functions like |ERR_get_error_line_data|. */ -#define ERR_FLAG_PUBLIC_MASK 0xf - -/* The following flag values are internal and are masked when flags are - * returned from functions like |ERR_get_error_line_data|. */ - -/* ERR_FLAG_MALLOCED means the the |data| member must be freed when no longer - * needed. */ -#define ERR_FLAG_MALLOCED 16 -/* ERR_FLAG_MARK is used to indicate a reversion point in the queue. See - * |ERR_pop_to_mark|. */ -#define ERR_FLAG_MARK 32 - -/* ERR_NUM_ERRORS is the limit of the number of errors in the queue. */ -#define ERR_NUM_ERRORS 16 - -/* ERR_STATE contains the per-thread, error queue. */ -typedef struct err_state_st { - /* errors contains the ERR_NUM_ERRORS most recent errors, organised as a ring - * buffer. */ - struct err_error_st errors[ERR_NUM_ERRORS]; - /* top contains the index one past the most recent error. If |top| equals - * |bottom| then the queue is empty. */ - unsigned top; - /* bottom contains the index of the last error in the queue. */ - unsigned bottom; - - /* to_free, if not NULL, contains a pointer owned by this structure that was - * previously a |data| pointer of one of the elements of |errors|. */ - void *to_free; -} ERR_STATE; - -enum { - ERR_LIB_NONE = 1, - ERR_LIB_SYS, - ERR_LIB_BN, - ERR_LIB_RSA, - ERR_LIB_DH, - ERR_LIB_EVP, - ERR_LIB_BUF, - ERR_LIB_OBJ, - ERR_LIB_PEM, - ERR_LIB_DSA, - ERR_LIB_X509, - ERR_LIB_ASN1, - ERR_LIB_CONF, - ERR_LIB_CRYPTO, - ERR_LIB_EC, - ERR_LIB_SSL, - ERR_LIB_BIO, - ERR_LIB_PKCS7, - ERR_LIB_PKCS8, - ERR_LIB_X509V3, - ERR_LIB_RAND, - ERR_LIB_ENGINE, - ERR_LIB_OCSP, - ERR_LIB_UI, - ERR_LIB_COMP, - ERR_LIB_ECDSA, - ERR_LIB_ECDH, - ERR_LIB_HMAC, - ERR_LIB_DIGEST, - ERR_LIB_CIPHER, - ERR_LIB_USER, - ERR_LIB_HKDF, - ERR_NUM_LIBS -}; - -#define ERR_R_SYS_LIB ERR_LIB_SYS -#define ERR_R_BN_LIB ERR_LIB_BN -#define ERR_R_RSA_LIB ERR_LIB_RSA -#define ERR_R_DH_LIB ERR_LIB_DH -#define ERR_R_EVP_LIB ERR_LIB_EVP -#define ERR_R_BUF_LIB ERR_LIB_BUF -#define ERR_R_OBJ_LIB ERR_LIB_OBJ -#define ERR_R_PEM_LIB ERR_LIB_PEM -#define ERR_R_DSA_LIB ERR_LIB_DSA -#define ERR_R_X509_LIB ERR_LIB_X509 -#define ERR_R_ASN1_LIB ERR_LIB_ASN1 -#define ERR_R_CONF_LIB ERR_LIB_CONF -#define ERR_R_CRYPTO_LIB ERR_LIB_CRYPTO -#define ERR_R_EC_LIB ERR_LIB_EC -#define ERR_R_SSL_LIB ERR_LIB_SSL -#define ERR_R_BIO_LIB ERR_LIB_BIO -#define ERR_R_PKCS7_LIB ERR_LIB_PKCS7 -#define ERR_R_PKCS8_LIB ERR_LIB_PKCS8 -#define ERR_R_X509V3_LIB ERR_LIB_X509V3 -#define ERR_R_RAND_LIB ERR_LIB_RAND -#define ERR_R_DSO_LIB ERR_LIB_DSO -#define ERR_R_ENGINE_LIB ERR_LIB_ENGINE -#define ERR_R_OCSP_LIB ERR_LIB_OCSP -#define ERR_R_UI_LIB ERR_LIB_UI -#define ERR_R_COMP_LIB ERR_LIB_COMP -#define ERR_R_ECDSA_LIB ERR_LIB_ECDSA -#define ERR_R_ECDH_LIB ERR_LIB_ECDH -#define ERR_R_STORE_LIB ERR_LIB_STORE -#define ERR_R_FIPS_LIB ERR_LIB_FIPS -#define ERR_R_CMS_LIB ERR_LIB_CMS -#define ERR_R_TS_LIB ERR_LIB_TS -#define ERR_R_HMAC_LIB ERR_LIB_HMAC -#define ERR_R_JPAKE_LIB ERR_LIB_JPAKE -#define ERR_R_USER_LIB ERR_LIB_USER -#define ERR_R_DIGEST_LIB ERR_LIB_DIGEST -#define ERR_R_CIPHER_LIB ERR_LIB_CIPHER -#define ERR_R_HKDF_LIB ERR_LIB_HKDF - -/* Global reasons. */ -#define ERR_R_FATAL 64 -#define ERR_R_MALLOC_FAILURE (1 | ERR_R_FATAL) -#define ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED (2 | ERR_R_FATAL) -#define ERR_R_PASSED_NULL_PARAMETER (3 | ERR_R_FATAL) -#define ERR_R_INTERNAL_ERROR (4 | ERR_R_FATAL) -#define ERR_R_OVERFLOW (5 | ERR_R_FATAL) - -/* System error functions */ -#define SYS_F_fopen 100 -#define SYS_F_fclose 101 -#define SYS_F_fread 102 -#define SYS_F_fwrite 103 -#define SYS_F_socket 104 -#define SYS_F_setsockopt 105 -#define SYS_F_connect 106 -#define SYS_F_getaddrinfo 107 - -#define ERR_PACK(lib, func, reason) \ - (((((uint32_t)lib) & 0xff) << 24) | ((((uint32_t)func) & 0xfff) << 12) | \ - ((((uint32_t)reason) & 0xfff))) - -#define ERR_GET_LIB(packed_error) ((int)(((packed_error) >> 24) & 0xff)) -#define ERR_GET_FUNC(packed_error) ((int)(((packed_error) >> 12) & 0xfff)) -#define ERR_GET_REASON(packed_error) ((int)((packed_error) & 0xfff)) - -/* OPENSSL_DECLARE_ERROR_REASON is used by util/make_errors.h (which generates - * the error defines) to recognise that an additional reason value is needed. - * This is needed when the reason value is used outside of an - * |OPENSSL_PUT_ERROR| macro. The resulting define will be - * ${lib}_R_${reason}. */ -#define OPENSSL_DECLARE_ERROR_REASON(lib, reason) - -/* OPENSSL_DECLARE_ERROR_FUNCTION is used by util/make_errors.h (which - * generates the error * defines to recognise that an additional function value - * is needed. This is * needed when the function value is used outside of an - * |OPENSSL_PUT_ERROR| * macro. The resulting define will be - * ${lib}_F_${reason}. */ -#define OPENSSL_DECLARE_ERROR_FUNCTION(lib, function_name) - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_ERR_H */ diff --git a/third_party/boringssl/include/openssl/evp.h b/third_party/boringssl/include/openssl/evp.h deleted file mode 100644 index 490a9514c3..0000000000 --- a/third_party/boringssl/include/openssl/evp.h +++ /dev/null @@ -1,826 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] */ - -#ifndef OPENSSL_HEADER_EVP_H -#define OPENSSL_HEADER_EVP_H - -#include - -#include - -/* OpenSSL included digest and cipher functions in this header so we include - * them for users that still expect that. - * - * TODO(fork): clean up callers so that they include what they use. */ -#include -#include -#include -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* EVP abstracts over public/private key algorithms. */ - - -/* Public key objects. */ - -/* EVP_PKEY_new creates a new, empty public-key object and returns it or NULL - * on allocation failure. */ -OPENSSL_EXPORT EVP_PKEY *EVP_PKEY_new(void); - -/* EVP_PKEY_free frees all data referenced by |pkey| and then frees |pkey| - * itself. */ -OPENSSL_EXPORT void EVP_PKEY_free(EVP_PKEY *pkey); - -/* EVP_PKEY_up_ref increments the reference count of |pkey| and returns it. */ -OPENSSL_EXPORT EVP_PKEY *EVP_PKEY_up_ref(EVP_PKEY *pkey); - -/* EVP_PKEY_is_opaque returns one if |pkey| is opaque. Opaque keys are backed by - * custom implementations which do not expose key material and parameters. It is - * an error to attempt to duplicate, export, or compare an opaque key. */ -OPENSSL_EXPORT int EVP_PKEY_is_opaque(const EVP_PKEY *pkey); - -/* EVP_PKEY_supports_digest returns one if |pkey| supports digests of - * type |md|. This is intended for use with EVP_PKEYs backing custom - * implementations which can't sign all digests. */ -OPENSSL_EXPORT int EVP_PKEY_supports_digest(const EVP_PKEY *pkey, - const EVP_MD *md); - -/* EVP_PKEY_cmp compares |a| and |b| and returns one if they are equal, zero if - * not and a negative number on error. - * - * WARNING: this differs from the traditional return value of a "cmp" - * function. */ -OPENSSL_EXPORT int EVP_PKEY_cmp(const EVP_PKEY *a, const EVP_PKEY *b); - -/* EVP_PKEY_copy_parameters sets the parameters of |to| to equal the parameters - * of |from|. It returns one on success and zero on error. */ -OPENSSL_EXPORT int EVP_PKEY_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from); - -/* EVP_PKEY_missing_parameters returns one if |pkey| is missing needed - * parameters or zero if not, or if the algorithm doesn't take parameters. */ -OPENSSL_EXPORT int EVP_PKEY_missing_parameters(const EVP_PKEY *pkey); - -/* EVP_PKEY_size returns the maximum size, in bytes, of a signature signed by - * |pkey|. For an RSA key, this returns the number of bytes needed to represent - * the modulus. For an EC key, this returns the maximum size of a DER-encoded - * ECDSA signature. */ -OPENSSL_EXPORT int EVP_PKEY_size(const EVP_PKEY *pkey); - -/* EVP_PKEY_bits returns the "size", in bits, of |pkey|. For an RSA key, this - * returns the bit length of the modulus. For an EC key, this returns the bit - * length of the group order. */ -OPENSSL_EXPORT int EVP_PKEY_bits(EVP_PKEY *pkey); - -/* EVP_PKEY_id returns the type of |pkey|, which is one of the |EVP_PKEY_*| - * values. */ -OPENSSL_EXPORT int EVP_PKEY_id(const EVP_PKEY *pkey); - -/* EVP_PKEY_type returns a canonicalised form of |NID|. For example, - * |EVP_PKEY_RSA2| will be turned into |EVP_PKEY_RSA|. */ -OPENSSL_EXPORT int EVP_PKEY_type(int nid); - -/* Deprecated: EVP_PKEY_new_mac_key allocates a fresh |EVP_PKEY| of the given - * type (e.g. |EVP_PKEY_HMAC|), sets |mac_key| as the MAC key and "generates" a - * new key, suitable for signing. It returns the fresh |EVP_PKEY|, or NULL on - * error. Use |HMAC_CTX| directly instead. */ -OPENSSL_EXPORT EVP_PKEY *EVP_PKEY_new_mac_key(int type, ENGINE *engine, - const uint8_t *mac_key, - size_t mac_key_len); - - -/* Getting and setting concrete public key types. - * - * The following functions get and set the underlying public key in an - * |EVP_PKEY| object. The |set1| functions take an additional reference to the - * underlying key and return one on success or zero on error. The |assign| - * functions adopt the caller's reference. The getters return a fresh reference - * to the underlying object. */ - -OPENSSL_EXPORT int EVP_PKEY_set1_RSA(EVP_PKEY *pkey, RSA *key); -OPENSSL_EXPORT int EVP_PKEY_assign_RSA(EVP_PKEY *pkey, RSA *key); -OPENSSL_EXPORT RSA *EVP_PKEY_get1_RSA(EVP_PKEY *pkey); - -OPENSSL_EXPORT int EVP_PKEY_set1_DSA(EVP_PKEY *pkey, struct dsa_st *key); -OPENSSL_EXPORT int EVP_PKEY_assign_DSA(EVP_PKEY *pkey, DSA *key); -OPENSSL_EXPORT struct dsa_st *EVP_PKEY_get1_DSA(EVP_PKEY *pkey); - -OPENSSL_EXPORT int EVP_PKEY_set1_EC_KEY(EVP_PKEY *pkey, struct ec_key_st *key); -OPENSSL_EXPORT int EVP_PKEY_assign_EC_KEY(EVP_PKEY *pkey, EC_KEY *key); -OPENSSL_EXPORT struct ec_key_st *EVP_PKEY_get1_EC_KEY(EVP_PKEY *pkey); - -OPENSSL_EXPORT int EVP_PKEY_set1_DH(EVP_PKEY *pkey, struct dh_st *key); -OPENSSL_EXPORT int EVP_PKEY_assign_DH(EVP_PKEY *pkey, DH *key); -OPENSSL_EXPORT struct dh_st *EVP_PKEY_get1_DH(EVP_PKEY *pkey); - -#define EVP_PKEY_NONE NID_undef -#define EVP_PKEY_RSA NID_rsaEncryption -#define EVP_PKEY_RSA2 NID_rsa -#define EVP_PKEY_DSA NID_dsa -#define EVP_PKEY_DH NID_dhKeyAgreement -#define EVP_PKEY_DHX NID_dhpublicnumber -#define EVP_PKEY_EC NID_X9_62_id_ecPublicKey - -/* Deprecated: Use |HMAC_CTX| directly instead. */ -#define EVP_PKEY_HMAC NID_hmac - -/* EVP_PKEY_assign sets the underlying key of |pkey| to |key|, which must be of - * the given type. The |type| argument should be one of the |EVP_PKEY_*| - * values. */ -OPENSSL_EXPORT int EVP_PKEY_assign(EVP_PKEY *pkey, int type, void *key); - -/* EVP_PKEY_set_type sets the type of |pkey| to |type|, which should be one of - * the |EVP_PKEY_*| values. It returns one if sucessful or zero otherwise. If - * |pkey| is NULL, it simply reports whether the type is known. */ -OPENSSL_EXPORT int EVP_PKEY_set_type(EVP_PKEY *pkey, int type); - -/* EVP_PKEY_cmp_parameters compares the parameters of |a| and |b|. It returns - * one if they match, zero if not, or a negative number of on error. - * - * WARNING: the return value differs from the usual return value convention. */ -OPENSSL_EXPORT int EVP_PKEY_cmp_parameters(const EVP_PKEY *a, - const EVP_PKEY *b); - - -/* ASN.1 functions */ - -/* d2i_PrivateKey parses an ASN.1, DER-encoded, private key from |len| bytes at - * |*inp|. If |out| is not NULL then, on exit, a pointer to the result is in - * |*out|. If |*out| is already non-NULL on entry then the result is written - * directly into |*out|, otherwise a fresh |EVP_PKEY| is allocated. On - * successful exit, |*inp| is advanced past the DER structure. It returns the - * result or NULL on error. */ -OPENSSL_EXPORT EVP_PKEY *d2i_PrivateKey(int type, EVP_PKEY **out, - const uint8_t **inp, long len); - -/* d2i_AutoPrivateKey acts the same as |d2i_PrivateKey|, but detects the type - * of the private key. */ -OPENSSL_EXPORT EVP_PKEY *d2i_AutoPrivateKey(EVP_PKEY **out, const uint8_t **inp, - long len); - -/* i2d_PrivateKey marshals a private key from |key| to an ASN.1, DER - * structure. If |outp| is not NULL then the result is written to |*outp| and - * |*outp| is advanced just past the output. It returns the number of bytes in - * the result, whether written or not, or a negative value on error. */ -OPENSSL_EXPORT int i2d_PrivateKey(const EVP_PKEY *key, uint8_t **outp); - -/* i2d_PublicKey marshals a public key from |key| to an ASN.1, DER - * structure. If |outp| is not NULL then the result is written to |*outp| and - * |*outp| is advanced just past the output. It returns the number of bytes in - * the result, whether written or not, or a negative value on error. */ -OPENSSL_EXPORT int i2d_PublicKey(EVP_PKEY *key, uint8_t **outp); - - -/* Signing */ - -/* EVP_DigestSignInit sets up |ctx| for a signing operation with |type| and - * |pkey|. The |ctx| argument must have been initialised with - * |EVP_MD_CTX_init|. If |pctx| is not NULL, the |EVP_PKEY_CTX| of the signing - * operation will be written to |*pctx|; this can be used to set alternative - * signing options. - * - * It returns one on success, or zero on error. */ -OPENSSL_EXPORT int EVP_DigestSignInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, - const EVP_MD *type, ENGINE *e, - EVP_PKEY *pkey); - -/* EVP_DigestSignUpdate appends |len| bytes from |data| to the data which will - * be signed in |EVP_DigestSignFinal|. It returns one. */ -OPENSSL_EXPORT int EVP_DigestSignUpdate(EVP_MD_CTX *ctx, const void *data, - size_t len); - -/* EVP_DigestSignFinal signs the data that has been included by one or more - * calls to |EVP_DigestSignUpdate|. If |out_sig| is NULL then |*out_sig_len| is - * set to the maximum number of output bytes. Otherwise, on entry, - * |*out_sig_len| must contain the length of the |out_sig| buffer. If the call - * is successful, the signature is written to |out_sig| and |*out_sig_len| is - * set to its length. - * - * It returns one on success, or zero on error. */ -OPENSSL_EXPORT int EVP_DigestSignFinal(EVP_MD_CTX *ctx, uint8_t *out_sig, - size_t *out_sig_len); - -/* EVP_DigestSignAlgorithm encodes the signing parameters of |ctx| as an - * AlgorithmIdentifer and saves the result in |algor|. - * - * It returns one on success, or zero on error. - * - * TODO(davidben): This API should eventually lose the dependency on - * crypto/asn1/. */ -OPENSSL_EXPORT int EVP_DigestSignAlgorithm(EVP_MD_CTX *ctx, X509_ALGOR *algor); - - -/* Verifying */ - -/* EVP_DigestVerifyInit sets up |ctx| for a signature verification operation - * with |type| and |pkey|. The |ctx| argument must have been initialised with - * |EVP_MD_CTX_init|. If |pctx| is not NULL, the |EVP_PKEY_CTX| of the signing - * operation will be written to |*pctx|; this can be used to set alternative - * signing options. - * - * It returns one on success, or zero on error. */ -OPENSSL_EXPORT int EVP_DigestVerifyInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, - const EVP_MD *type, ENGINE *e, - EVP_PKEY *pkey); - -/* EVP_DigestVerifyInitFromAlgorithm sets up |ctx| for a signature verification - * operation with public key |pkey| and parameters from |algor|. The |ctx| - * argument must have been initialised with |EVP_MD_CTX_init|. - * - * It returns one on success, or zero on error. - * - * TODO(davidben): This API should eventually lose the dependency on - * crypto/asn1/. */ -OPENSSL_EXPORT int EVP_DigestVerifyInitFromAlgorithm(EVP_MD_CTX *ctx, - X509_ALGOR *algor, - EVP_PKEY *pkey); - -/* EVP_DigestVerifyUpdate appends |len| bytes from |data| to the data which - * will be verified by |EVP_DigestVerifyFinal|. It returns one. */ -OPENSSL_EXPORT int EVP_DigestVerifyUpdate(EVP_MD_CTX *ctx, const void *data, - size_t len); - -/* EVP_DigestVerifyFinal verifies that |sig_len| bytes of |sig| are a valid - * signature for the data that has been included by one or more calls to - * |EVP_DigestVerifyUpdate|. It returns one on success and zero otherwise. */ -OPENSSL_EXPORT int EVP_DigestVerifyFinal(EVP_MD_CTX *ctx, const uint8_t *sig, - size_t sig_len); - - -/* Signing (old functions) */ - -/* EVP_SignInit_ex configures |ctx|, which must already have been initialised, - * for a fresh signing operation using the hash function |type|. It returns one - * on success and zero otherwise. - * - * (In order to initialise |ctx|, either obtain it initialised with - * |EVP_MD_CTX_create|, or use |EVP_MD_CTX_init|.) */ -OPENSSL_EXPORT int EVP_SignInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, - ENGINE *impl); - -/* EVP_SignInit is a deprecated version of |EVP_SignInit_ex|. - * - * TODO(fork): remove. */ -OPENSSL_EXPORT int EVP_SignInit(EVP_MD_CTX *ctx, const EVP_MD *type); - -/* EVP_SignUpdate appends |len| bytes from |data| to the data which will be - * signed in |EVP_SignFinal|. */ -OPENSSL_EXPORT int EVP_SignUpdate(EVP_MD_CTX *ctx, const void *data, - size_t len); - -/* EVP_SignFinal signs the data that has been included by one or more calls to - * |EVP_SignUpdate|, using the key |pkey|, and writes it to |sig|. On entry, - * |sig| must point to at least |EVP_PKEY_size(pkey)| bytes of space. The - * actual size of the signature is written to |*out_sig_len|. - * - * It returns one on success and zero otherwise. - * - * It does not modify |ctx|, thus it's possible to continue to use |ctx| in - * order to sign a longer message. */ -OPENSSL_EXPORT int EVP_SignFinal(const EVP_MD_CTX *ctx, uint8_t *sig, - unsigned int *out_sig_len, EVP_PKEY *pkey); - - -/* Verifying (old functions) */ - -/* EVP_VerifyInit_ex configures |ctx|, which must already have been - * initialised, for a fresh signature verification operation using the hash - * function |type|. It returns one on success and zero otherwise. - * - * (In order to initialise |ctx|, either obtain it initialised with - * |EVP_MD_CTX_create|, or use |EVP_MD_CTX_init|.) */ -OPENSSL_EXPORT int EVP_VerifyInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, - ENGINE *impl); - -/* EVP_VerifyInit is a deprecated version of |EVP_VerifyInit_ex|. - * - * TODO(fork): remove. */ -OPENSSL_EXPORT int EVP_VerifyInit(EVP_MD_CTX *ctx, const EVP_MD *type); - -/* EVP_VerifyUpdate appends |len| bytes from |data| to the data which will be - * signed in |EVP_VerifyFinal|. */ -OPENSSL_EXPORT int EVP_VerifyUpdate(EVP_MD_CTX *ctx, const void *data, - size_t len); - -/* EVP_VerifyFinal verifies that |sig_len| bytes of |sig| are a valid - * signature, by |pkey|, for the data that has been included by one or more - * calls to |EVP_VerifyUpdate|. - * - * It returns one on success and zero otherwise. - * - * It does not modify |ctx|, thus it's possible to continue to use |ctx| in - * order to sign a longer message. */ -OPENSSL_EXPORT int EVP_VerifyFinal(EVP_MD_CTX *ctx, const uint8_t *sig, - size_t sig_len, EVP_PKEY *pkey); - - -/* Printing */ - -/* EVP_PKEY_print_public prints a textual representation of the public key in - * |pkey| to |out|. Returns one on success or zero otherwise. */ -OPENSSL_EXPORT int EVP_PKEY_print_public(BIO *out, const EVP_PKEY *pkey, - int indent, ASN1_PCTX *pctx); - -/* EVP_PKEY_print_public prints a textual representation of the private key in - * |pkey| to |out|. Returns one on success or zero otherwise. */ -OPENSSL_EXPORT int EVP_PKEY_print_private(BIO *out, const EVP_PKEY *pkey, - int indent, ASN1_PCTX *pctx); - -/* EVP_PKEY_print_public prints a textual representation of the parameters in - * |pkey| to |out|. Returns one on success or zero otherwise. */ -OPENSSL_EXPORT int EVP_PKEY_print_params(BIO *out, const EVP_PKEY *pkey, - int indent, ASN1_PCTX *pctx); - - -/* Password stretching. - * - * Password stretching functions take a low-entropy password and apply a slow - * function that results in a key suitable for use in symmetric - * cryptography. */ - -/* PKCS5_PBKDF2_HMAC computes |iterations| iterations of PBKDF2 of |password| - * and |salt|, using |digest|, and outputs |key_len| bytes to |out_key|. It - * returns one on success and zero on error. */ -OPENSSL_EXPORT int PKCS5_PBKDF2_HMAC(const char *password, size_t password_len, - const uint8_t *salt, size_t salt_len, - unsigned iterations, const EVP_MD *digest, - size_t key_len, uint8_t *out_key); - -/* PKCS5_PBKDF2_HMAC_SHA1 is the same as PKCS5_PBKDF2_HMAC, but with |digest| - * fixed to |EVP_sha1|. */ -OPENSSL_EXPORT int PKCS5_PBKDF2_HMAC_SHA1(const char *password, - size_t password_len, const uint8_t *salt, - size_t salt_len, unsigned iterations, - size_t key_len, uint8_t *out_key); - - -/* Public key contexts. - * - * |EVP_PKEY_CTX| objects hold the context of an operation (e.g. signing or - * encrypting) that uses a public key. */ - -/* EVP_PKEY_CTX_new allocates a fresh |EVP_PKEY_CTX| for use with |pkey|. It - * returns the context or NULL on error. */ -OPENSSL_EXPORT EVP_PKEY_CTX *EVP_PKEY_CTX_new(EVP_PKEY *pkey, ENGINE *e); - -/* EVP_PKEY_CTX_new allocates a fresh |EVP_PKEY_CTX| for a key of type |id| - * (e.g. |EVP_PKEY_HMAC|). This can be used for key generation where - * |EVP_PKEY_CTX_new| can't be used because there isn't an |EVP_PKEY| to pass - * it. It returns the context or NULL on error. */ -OPENSSL_EXPORT EVP_PKEY_CTX *EVP_PKEY_CTX_new_id(int id, ENGINE *e); - -/* EVP_KEY_CTX_free frees |ctx| and the data it owns. */ -OPENSSL_EXPORT void EVP_PKEY_CTX_free(EVP_PKEY_CTX *ctx); - -/* EVP_PKEY_CTX_dup allocates a fresh |EVP_PKEY_CTX| and sets it equal to the - * state of |ctx|. It returns the fresh |EVP_PKEY_CTX| or NULL on error. */ -OPENSSL_EXPORT EVP_PKEY_CTX *EVP_PKEY_CTX_dup(EVP_PKEY_CTX *ctx); - -/* EVP_PKEY_CTX_get0_pkey returns the |EVP_PKEY| associated with |ctx|. */ -OPENSSL_EXPORT EVP_PKEY *EVP_PKEY_CTX_get0_pkey(EVP_PKEY_CTX *ctx); - -/* EVP_PKEY_CTX_set_app_data sets an opaque pointer on |ctx|. */ -OPENSSL_EXPORT void EVP_PKEY_CTX_set_app_data(EVP_PKEY_CTX *ctx, void *data); - -/* EVP_PKEY_CTX_get_app_data returns the opaque pointer from |ctx| that was - * previously set with |EVP_PKEY_CTX_set_app_data|, or NULL if none has been - * set. */ -OPENSSL_EXPORT void *EVP_PKEY_CTX_get_app_data(EVP_PKEY_CTX *ctx); - -/* EVP_PKEY_sign_init initialises an |EVP_PKEY_CTX| for a signing operation. It - * should be called before |EVP_PKEY_sign|. - * - * It returns one on success or zero on error. */ -OPENSSL_EXPORT int EVP_PKEY_sign_init(EVP_PKEY_CTX *ctx); - -/* EVP_PKEY_sign signs |data_len| bytes from |data| using |ctx|. If |sig| is - * NULL, the maximum size of the signature is written to - * |out_sig_len|. Otherwise, |*sig_len| must contain the number of bytes of - * space available at |sig|. If sufficient, the signature will be written to - * |sig| and |*sig_len| updated with the true length. - * - * WARNING: Setting |sig| to NULL only gives the maximum size of the - * signature. The actual signature may be smaller. - * - * It returns one on success or zero on error. (Note: this differs from - * OpenSSL, which can also return negative values to indicate an error. ) */ -OPENSSL_EXPORT int EVP_PKEY_sign(EVP_PKEY_CTX *ctx, uint8_t *sig, - size_t *sig_len, const uint8_t *data, - size_t data_len); - -/* EVP_PKEY_verify_init initialises an |EVP_PKEY_CTX| for a signature - * verification operation. It should be called before |EVP_PKEY_verify|. - * - * It returns one on success or zero on error. */ -OPENSSL_EXPORT int EVP_PKEY_verify_init(EVP_PKEY_CTX *ctx); - -/* EVP_PKEY_verify verifies that |sig_len| bytes from |sig| are a valid signature - * for |data|. - * - * It returns one on success or zero on error. */ -OPENSSL_EXPORT int EVP_PKEY_verify(EVP_PKEY_CTX *ctx, const uint8_t *sig, - size_t sig_len, const uint8_t *data, - size_t data_len); - -/* EVP_PKEY_encrypt_init initialises an |EVP_PKEY_CTX| for an encryption - * operation. It should be called before |EVP_PKEY_encrypt|. - * - * It returns one on success or zero on error. */ -OPENSSL_EXPORT int EVP_PKEY_encrypt_init(EVP_PKEY_CTX *ctx); - -/* EVP_PKEY_encrypt encrypts |in_len| bytes from |in|. If |out| is NULL, the - * maximum size of the ciphertext is written to |out_len|. Otherwise, |*out_len| - * must contain the number of bytes of space available at |out|. If sufficient, - * the ciphertext will be written to |out| and |*out_len| updated with the true - * length. - * - * WARNING: Setting |out| to NULL only gives the maximum size of the - * ciphertext. The actual ciphertext may be smaller. - * - * It returns one on success or zero on error. */ -OPENSSL_EXPORT int EVP_PKEY_encrypt(EVP_PKEY_CTX *ctx, uint8_t *out, - size_t *out_len, const uint8_t *in, - size_t in_len); - -/* EVP_PKEY_decrypt_init initialises an |EVP_PKEY_CTX| for a decryption - * operation. It should be called before |EVP_PKEY_decrypt|. - * - * It returns one on success or zero on error. */ -OPENSSL_EXPORT int EVP_PKEY_decrypt_init(EVP_PKEY_CTX *ctx); - -/* EVP_PKEY_decrypt decrypts |in_len| bytes from |in|. If |out| is NULL, the - * maximum size of the plaintext is written to |out_len|. Otherwise, |*out_len| - * must contain the number of bytes of space available at |out|. If sufficient, - * the ciphertext will be written to |out| and |*out_len| updated with the true - * length. - * - * WARNING: Setting |out| to NULL only gives the maximum size of the - * plaintext. The actual plaintext may be smaller. - * - * It returns one on success or zero on error. */ -OPENSSL_EXPORT int EVP_PKEY_decrypt(EVP_PKEY_CTX *ctx, uint8_t *out, - size_t *out_len, const uint8_t *in, - size_t in_len); - -/* EVP_PKEY_derive_init initialises an |EVP_PKEY_CTX| for a key derivation - * operation. It should be called before |EVP_PKEY_derive_set_peer| and - * |EVP_PKEY_derive|. - * - * It returns one on success or zero on error. */ -OPENSSL_EXPORT int EVP_PKEY_derive_init(EVP_PKEY_CTX *ctx); - -/* EVP_PKEY_derive_set_peer sets the peer's key to be used for key derivation - * by |ctx| to |peer|. It should be called after |EVP_PKEY_derive_init|. (For - * example, this is used to set the peer's key in (EC)DH.) It returns one on - * success and zero on error. */ -OPENSSL_EXPORT int EVP_PKEY_derive_set_peer(EVP_PKEY_CTX *ctx, EVP_PKEY *peer); - -/* EVP_PKEY_derive derives a shared key between the two keys configured in - * |ctx|. If |key| is non-NULL then, on entry, |out_key_len| must contain the - * amount of space at |key|. If sufficient then the shared key will be written - * to |key| and |*out_key_len| will be set to the length. If |key| is NULL then - * |out_key_len| will be set to the maximum length. - * - * WARNING: Setting |out| to NULL only gives the maximum size of the key. The - * actual key may be smaller. - * - * It returns one on success and zero on error. */ -OPENSSL_EXPORT int EVP_PKEY_derive(EVP_PKEY_CTX *ctx, uint8_t *key, - size_t *out_key_len); - -/* EVP_PKEY_keygen_init initialises an |EVP_PKEY_CTX| for a key generation - * operation. It should be called before |EVP_PKEY_keygen|. - * - * It returns one on success or zero on error. */ -OPENSSL_EXPORT int EVP_PKEY_keygen_init(EVP_PKEY_CTX *ctx); - -/* EVP_PKEY_keygen performs a key generation operation using the values from - * |ctx| and sets |*ppkey| to a fresh |EVP_PKEY| containing the resulting key. - * It returns one on success or zero on error. */ -OPENSSL_EXPORT int EVP_PKEY_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY **ppkey); - - -/* Generic control functions. */ - -/* EVP_PKEY_CTX_set_signature_md sets |md| as the digest to be used in a - * signature operation. It returns one on success or zero on error. */ -OPENSSL_EXPORT int EVP_PKEY_CTX_set_signature_md(EVP_PKEY_CTX *ctx, - const EVP_MD *md); - -/* EVP_PKEY_CTX_get_signature_md sets |*out_md| to the digest to be used in a - * signature operation. It returns one on success or zero on error. */ -OPENSSL_EXPORT int EVP_PKEY_CTX_get_signature_md(EVP_PKEY_CTX *ctx, - const EVP_MD **out_md); - - -/* RSA specific control functions. */ - -/* EVP_PKEY_CTX_set_rsa_padding sets the padding type to use. It should be one - * of the |RSA_*_PADDING| values. Returns one on success or zero on error. */ -OPENSSL_EXPORT int EVP_PKEY_CTX_set_rsa_padding(EVP_PKEY_CTX *ctx, int padding); - -/* EVP_PKEY_CTX_get_rsa_padding sets |*out_padding| to the current padding - * value, which is one of the |RSA_*_PADDING| values. Returns one on success or - * zero on error. */ -OPENSSL_EXPORT int EVP_PKEY_CTX_get_rsa_padding(EVP_PKEY_CTX *ctx, - int *out_padding); - -/* EVP_PKEY_CTX_set_rsa_pss_saltlen sets the length of the salt in a PSS-padded - * signature. A value of -1 cause the salt to be the same length as the digest - * in the signature. A value of -2 causes the salt to be the maximum length - * that will fit. Otherwise the value gives the size of the salt in bytes. - * - * Returns one on success or zero on error. */ -OPENSSL_EXPORT int EVP_PKEY_CTX_set_rsa_pss_saltlen(EVP_PKEY_CTX *ctx, - int salt_len); - -/* EVP_PKEY_CTX_get_rsa_pss_saltlen sets |*out_salt_len| to the salt length of - * a PSS-padded signature. See the documentation for - * |EVP_PKEY_CTX_set_rsa_pss_saltlen| for details of the special values that it - * can take. - * - * Returns one on success or zero on error. */ -OPENSSL_EXPORT int EVP_PKEY_CTX_get_rsa_pss_saltlen(EVP_PKEY_CTX *ctx, - int *out_salt_len); - -/* EVP_PKEY_CTX_set_rsa_keygen_bits sets the size of the desired RSA modulus, - * in bits, for key generation. Returns one on success or zero on - * error. */ -OPENSSL_EXPORT int EVP_PKEY_CTX_set_rsa_keygen_bits(EVP_PKEY_CTX *ctx, - int bits); - -/* EVP_PKEY_CTX_set_rsa_keygen_pubexp sets |e| as the public exponent for key - * generation. Returns one on success or zero on error. */ -OPENSSL_EXPORT int EVP_PKEY_CTX_set_rsa_keygen_pubexp(EVP_PKEY_CTX *ctx, - BIGNUM *e); - -/* EVP_PKEY_CTX_set_rsa_oaep_md sets |md| as the digest used in OAEP padding. - * Returns one on success or zero on error. */ -OPENSSL_EXPORT int EVP_PKEY_CTX_set_rsa_oaep_md(EVP_PKEY_CTX *ctx, - const EVP_MD *md); - -/* EVP_PKEY_CTX_get_rsa_oaep_md sets |*out_md| to the digest function used in - * OAEP padding. Returns one on success or zero on error. */ -OPENSSL_EXPORT int EVP_PKEY_CTX_get_rsa_oaep_md(EVP_PKEY_CTX *ctx, - const EVP_MD **out_md); - -/* EVP_PKEY_CTX_set_rsa_mgf1_md sets |md| as the digest used in MGF1. Returns - * one on success or zero on error. */ -OPENSSL_EXPORT int EVP_PKEY_CTX_set_rsa_mgf1_md(EVP_PKEY_CTX *ctx, - const EVP_MD *md); - -/* EVP_PKEY_CTX_get_rsa_mgf1_md sets |*out_md| to the digest function used in - * MGF1. Returns one on success or zero on error. */ -OPENSSL_EXPORT int EVP_PKEY_CTX_get_rsa_mgf1_md(EVP_PKEY_CTX *ctx, - const EVP_MD **out_md); - -/* EVP_PKEY_CTX_set0_rsa_oaep_label sets |label_len| bytes from |label| as the - * label used in OAEP. DANGER: On success, this call takes ownership of |label| - * and will call |OPENSSL_free| on it when |ctx| is destroyed. - * - * Returns one on success or zero on error. */ -OPENSSL_EXPORT int EVP_PKEY_CTX_set0_rsa_oaep_label(EVP_PKEY_CTX *ctx, - const uint8_t *label, - size_t label_len); - -/* EVP_PKEY_CTX_get0_rsa_oaep_label sets |*out_label| to point to the internal - * buffer containing the OAEP label (which may be NULL) and returns the length - * of the label or a negative value on error. - * - * WARNING: the return value differs from the usual return value convention. */ -OPENSSL_EXPORT int EVP_PKEY_CTX_get0_rsa_oaep_label(EVP_PKEY_CTX *ctx, - const uint8_t **out_label); - - -/* Deprecated functions. */ - -/* EVP_PKEY_dup adds one to the reference count of |pkey| and returns - * |pkey|. - * - * WARNING: this is a |_dup| function that doesn't actually duplicate! Use - * |EVP_PKEY_up_ref| if you want to increment the reference count without - * confusion. */ -OPENSSL_EXPORT EVP_PKEY *EVP_PKEY_dup(EVP_PKEY *pkey); - - -/* Private functions */ - -/* OpenSSL_add_all_algorithms does nothing. */ -OPENSSL_EXPORT void OpenSSL_add_all_algorithms(void); - -/* OpenSSL_add_all_ciphers does nothing. */ -OPENSSL_EXPORT void OpenSSL_add_all_ciphers(void); - -/* OpenSSL_add_all_digests does nothing. */ -OPENSSL_EXPORT void OpenSSL_add_all_digests(void); - -/* EVP_cleanup does nothing. */ -OPENSSL_EXPORT void EVP_cleanup(void); - -/* EVP_PKEY_asn1_find returns the ASN.1 method table for the given |nid|, which - * should be one of the |EVP_PKEY_*| values. It returns NULL if |nid| is - * unknown. */ -OPENSSL_EXPORT const EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_find(ENGINE **pengine, - int nid); - -/* TODO(fork): move to PEM? */ -OPENSSL_EXPORT const EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_find_str( - ENGINE **pengine, const char *name, size_t len); - -struct evp_pkey_st { - CRYPTO_refcount_t references; - - /* type contains one of the EVP_PKEY_* values or NID_undef and determines - * which element (if any) of the |pkey| union is valid. */ - int type; - - union { - char *ptr; - struct rsa_st *rsa; /* RSA */ - struct dsa_st *dsa; /* DSA */ - struct dh_st *dh; /* DH */ - struct ec_key_st *ec; /* ECC */ - } pkey; - - /* ameth contains a pointer to a method table that contains many ASN.1 - * methods for the key type. */ - const EVP_PKEY_ASN1_METHOD *ameth; -} /* EVP_PKEY */; - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#define EVP_F_EVP_PKEY_derive_init 108 -#define EVP_F_EVP_PKEY_encrypt 110 -#define EVP_F_EVP_PKEY_encrypt_init 111 -#define EVP_F_EVP_PKEY_get1_DH 112 -#define EVP_F_EVP_PKEY_get1_EC_KEY 114 -#define EVP_F_EVP_PKEY_get1_RSA 115 -#define EVP_F_EVP_PKEY_keygen 116 -#define EVP_F_EVP_PKEY_sign 120 -#define EVP_F_EVP_PKEY_sign_init 121 -#define EVP_F_EVP_PKEY_verify 122 -#define EVP_F_EVP_PKEY_verify_init 123 -#define EVP_F_d2i_AutoPrivateKey 125 -#define EVP_F_d2i_PrivateKey 126 -#define EVP_F_do_EC_KEY_print 127 -#define EVP_F_do_sigver_init 129 -#define EVP_F_eckey_param2type 130 -#define EVP_F_eckey_param_decode 131 -#define EVP_F_eckey_priv_decode 132 -#define EVP_F_eckey_priv_encode 133 -#define EVP_F_eckey_pub_decode 134 -#define EVP_F_eckey_pub_encode 135 -#define EVP_F_eckey_type2param 136 -#define EVP_F_evp_pkey_ctx_new 137 -#define EVP_F_hmac_signctx 138 -#define EVP_F_i2d_PublicKey 139 -#define EVP_F_old_ec_priv_decode 140 -#define EVP_F_old_rsa_priv_decode 141 -#define EVP_F_pkey_ec_ctrl 142 -#define EVP_F_pkey_ec_derive 143 -#define EVP_F_pkey_ec_keygen 144 -#define EVP_F_pkey_ec_paramgen 145 -#define EVP_F_pkey_ec_sign 146 -#define EVP_F_pkey_rsa_ctrl 147 -#define EVP_F_pkey_rsa_decrypt 148 -#define EVP_F_pkey_rsa_encrypt 149 -#define EVP_F_pkey_rsa_sign 150 -#define EVP_F_rsa_algor_to_md 151 -#define EVP_F_rsa_digest_verify_init_from_algorithm 152 -#define EVP_F_rsa_mgf1_to_md 153 -#define EVP_F_rsa_priv_decode 154 -#define EVP_F_rsa_priv_encode 155 -#define EVP_F_rsa_pss_to_ctx 156 -#define EVP_F_rsa_pub_decode 157 -#define EVP_F_pkey_hmac_ctrl 158 -#define EVP_F_EVP_PKEY_CTX_get0_rsa_oaep_label 159 -#define EVP_F_EVP_DigestSignAlgorithm 160 -#define EVP_F_EVP_DigestVerifyInitFromAlgorithm 161 -#define EVP_F_EVP_PKEY_CTX_ctrl 162 -#define EVP_F_EVP_PKEY_CTX_dup 163 -#define EVP_F_EVP_PKEY_copy_parameters 164 -#define EVP_F_EVP_PKEY_decrypt 165 -#define EVP_F_EVP_PKEY_decrypt_init 166 -#define EVP_F_EVP_PKEY_derive 167 -#define EVP_F_EVP_PKEY_derive_set_peer 168 -#define EVP_F_EVP_PKEY_get1_DSA 169 -#define EVP_F_EVP_PKEY_keygen_init 170 -#define EVP_F_EVP_PKEY_new 171 -#define EVP_F_EVP_PKEY_set_type 172 -#define EVP_F_check_padding_md 173 -#define EVP_F_do_dsa_print 174 -#define EVP_F_do_rsa_print 175 -#define EVP_F_dsa_param_decode 176 -#define EVP_F_dsa_priv_decode 177 -#define EVP_F_dsa_priv_encode 178 -#define EVP_F_dsa_pub_decode 179 -#define EVP_F_dsa_pub_encode 180 -#define EVP_F_dsa_sig_print 181 -#define EVP_F_old_dsa_priv_decode 182 -#define EVP_R_BUFFER_TOO_SMALL 100 -#define EVP_R_COMMAND_NOT_SUPPORTED 101 -#define EVP_R_DIFFERENT_KEY_TYPES 104 -#define EVP_R_DIFFERENT_PARAMETERS 105 -#define EVP_R_EXPECTING_AN_EC_KEY_KEY 107 -#define EVP_R_EXPECTING_A_DH_KEY 109 -#define EVP_R_EXPECTING_A_DSA_KEY 110 -#define EVP_R_ILLEGAL_OR_UNSUPPORTED_PADDING_MODE 111 -#define EVP_R_INVALID_CURVE 112 -#define EVP_R_INVALID_DIGEST_LENGTH 113 -#define EVP_R_INVALID_DIGEST_TYPE 114 -#define EVP_R_INVALID_KEYBITS 115 -#define EVP_R_INVALID_MGF1_MD 116 -#define EVP_R_INVALID_PADDING_MODE 118 -#define EVP_R_INVALID_PSS_PARAMETERS 119 -#define EVP_R_INVALID_SALT_LENGTH 121 -#define EVP_R_INVALID_TRAILER 122 -#define EVP_R_KEYS_NOT_SET 123 -#define EVP_R_MISSING_PARAMETERS 124 -#define EVP_R_NO_DEFAULT_DIGEST 125 -#define EVP_R_NO_KEY_SET 126 -#define EVP_R_NO_MDC2_SUPPORT 127 -#define EVP_R_NO_NID_FOR_CURVE 128 -#define EVP_R_NO_OPERATION_SET 129 -#define EVP_R_NO_PARAMETERS_SET 130 -#define EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE 131 -#define EVP_R_OPERATON_NOT_INITIALIZED 132 -#define EVP_R_UNKNOWN_DIGEST 133 -#define EVP_R_UNKNOWN_MASK_DIGEST 134 -#define EVP_R_UNSUPPORTED_ALGORITHM 138 -#define EVP_R_UNSUPPORTED_MASK_ALGORITHM 139 -#define EVP_R_UNSUPPORTED_MASK_PARAMETER 140 -#define EVP_R_EXPECTING_AN_RSA_KEY 141 -#define EVP_R_INVALID_OPERATION 142 -#define EVP_R_DECODE_ERROR 143 -#define EVP_R_INVALID_PSS_SALTLEN 144 -#define EVP_R_UNKNOWN_PUBLIC_KEY_TYPE 145 -#define EVP_R_CONTEXT_NOT_INITIALISED 146 -#define EVP_R_DIGEST_AND_KEY_TYPE_NOT_SUPPORTED 147 -#define EVP_R_WRONG_PUBLIC_KEY_TYPE 148 -#define EVP_R_UNKNOWN_SIGNATURE_ALGORITHM 149 -#define EVP_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM 150 -#define EVP_R_BN_DECODE_ERROR 151 -#define EVP_R_PARAMETER_ENCODING_ERROR 152 -#define EVP_R_UNSUPPORTED_PUBLIC_KEY_TYPE 153 -#define EVP_R_UNSUPPORTED_SIGNATURE_TYPE 154 - -#endif /* OPENSSL_HEADER_EVP_H */ diff --git a/third_party/boringssl/include/openssl/ex_data.h b/third_party/boringssl/include/openssl/ex_data.h deleted file mode 100644 index 2303eb4250..0000000000 --- a/third_party/boringssl/include/openssl/ex_data.h +++ /dev/null @@ -1,214 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] - */ -/* ==================================================================== - * Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * openssl-core@openssl.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.openssl.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS 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. - * ==================================================================== - * - * This product includes cryptographic software written by Eric Young - * (eay@cryptsoft.com). This product includes software written by Tim - * Hudson (tjh@cryptsoft.com). */ - -#ifndef OPENSSL_HEADER_EX_DATA_H -#define OPENSSL_HEADER_EX_DATA_H - -#include - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* ex_data is a mechanism for associating arbitrary extra data with objects. - * For each type of object that supports ex_data, different users can be - * assigned indexes in which to store their data. Each index has callback - * functions that are called when a new object of that type is created, freed - * and duplicated. */ - - -typedef struct crypto_ex_data_st CRYPTO_EX_DATA; - - -/* Type-specific functions. - * - * Each type that supports ex_data provides three functions: */ - -#if 0 /* Sample */ - -/* |TYPE_get_ex_new_index| allocates a new index for |TYPE|. See the - * descriptions of the callback typedefs for details of when they are - * called. Any of the callback arguments may be NULL. The |argl| and |argp| - * arguments are opaque values that are passed to the callbacks. It returns the - * new index or a negative number on error. - * - * TODO(fork): this should follow the standard calling convention. */ -OPENSSL_EXPORT int TYPE_get_ex_new_index(long argl, void *argp, - CRYPTO_EX_new *new_func, - CRYPTO_EX_dup *dup_func, - CRYPTO_EX_free *free_func); - -/* |TYPE_set_ex_data| sets an extra data pointer on |t|. The |index| argument - * should have been returned from a previous call to |TYPE_get_ex_new_index|. */ -OPENSSL_EXPORT int TYPE_set_ex_data(TYPE *t, int index, void *arg); - -/* |TYPE_get_ex_data| returns an extra data pointer for |t|, or NULL if no such - * pointer exists. The |index| argument should have been returned from a - * previous call to |TYPE_get_ex_new_index|. */ -OPENSSL_EXPORT void *TYPE_get_ex_data(const TYPE *t, int index); - -#endif /* Sample */ - - -/* Callback types. */ - -/* CRYPTO_EX_new is the type of a callback function that is called whenever a - * new object of a given class is created. For example, if this callback has - * been passed to |SSL_get_ex_new_index| then it'll be called each time an SSL* - * is created. - * - * The callback is passed the new object (i.e. the SSL*) in |parent|. The - * arguments |argl| and |argp| contain opaque values that were given to - * |CRYPTO_get_ex_new_index|. The callback should return one on success, but - * the value is ignored. - * - * TODO(fork): the |ptr| argument is always NULL, no? */ -typedef int CRYPTO_EX_new(void *parent, void *ptr, CRYPTO_EX_DATA *ad, - int index, long argl, void *argp); - -/* CRYPTO_EX_free is a callback function that is called when an object of the - * class is being destroyed. See |CRYPTO_EX_new| for a discussion of the - * arguments. - * - * If |CRYPTO_get_ex_new_index| was called after the creation of objects of the - * class that this applies to then, when those those objects are destroyed, - * this callback will be called with a NULL value for |ptr|. */ -typedef void CRYPTO_EX_free(void *parent, void *ptr, CRYPTO_EX_DATA *ad, - int index, long argl, void *argp); - -/* CRYPTO_EX_dup is a callback function that is called when an object of the - * class is being copied and thus the ex_data linked to it also needs to be - * copied. On entry, |*from_d| points to the data for this index from the - * original object. When the callback returns, |*from_d| will be set as the - * data for this index in |to|. - * - * If |CRYPTO_get_ex_new_index| was called after the creation of objects of the - * class that this applies to then, when those those objects are copies, this - * callback will be called with a NULL value for |*from_d|. */ -typedef int CRYPTO_EX_dup(CRYPTO_EX_DATA *to, const CRYPTO_EX_DATA *from, - void **from_d, int index, long argl, void *argp); - - -/* Deprecated functions. */ - -/* CRYPTO_cleanup_all_ex_data does nothing. */ -OPENSSL_EXPORT void CRYPTO_cleanup_all_ex_data(void); - -struct crypto_ex_data_st { - STACK_OF(void) *sk; -}; - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_EX_DATA_H */ diff --git a/third_party/boringssl/include/openssl/hkdf.h b/third_party/boringssl/include/openssl/hkdf.h deleted file mode 100644 index 4091b84beb..0000000000 --- a/third_party/boringssl/include/openssl/hkdf.h +++ /dev/null @@ -1,45 +0,0 @@ -/* Copyright (c) 2014, Google Inc. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -#ifndef OPENSSL_HEADER_HKDF_H -#define OPENSSL_HEADER_HKDF_H - -#include - -#ifdef __cplusplus -extern "C" { -#endif - - -/* Computes HKDF (as specified by RFC 5869) of initial keying material |secret| - * with |salt| and |info| using |digest|, and outputs |out_len| bytes to - * |out_key|. It returns one on success and zero on error. - * - * HKDF is an Extract-and-Expand algorithm. It does not do any key stretching, - * and as such, is not suited to be used alone to generate a key from a - * password. */ -OPENSSL_EXPORT int HKDF(uint8_t *out_key, size_t out_len, const EVP_MD *digest, - const uint8_t *secret, size_t secret_len, - const uint8_t *salt, size_t salt_len, - const uint8_t *info, size_t info_len); - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#define HKDF_F_HKDF 100 -#define HKDF_R_OUTPUT_TOO_LARGE 100 - -#endif /* OPENSSL_HEADER_HKDF_H */ diff --git a/third_party/boringssl/include/openssl/hmac.h b/third_party/boringssl/include/openssl/hmac.h deleted file mode 100644 index e521212d4c..0000000000 --- a/third_party/boringssl/include/openssl/hmac.h +++ /dev/null @@ -1,160 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] */ - -#ifndef OPENSSL_HEADER_HMAC_H -#define OPENSSL_HEADER_HMAC_H - -#include - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* HMAC contains functions for constructing PRFs from Merkle–Damgård hash - * functions using HMAC. */ - - -/* One-shot operation. */ - -/* HMAC calculates the HMAC of |data_len| bytes of |data|, using the given key - * and hash function, and writes the result to |out|. On entry, |out| must - * contain |EVP_MAX_MD_SIZE| bytes of space. The actual length of the result is - * written to |*out_len|. It returns |out| or NULL on error. */ -OPENSSL_EXPORT uint8_t *HMAC(const EVP_MD *evp_md, const void *key, - size_t key_len, const uint8_t *data, - size_t data_len, uint8_t *out, - unsigned int *out_len); - - -/* Incremental operation. */ - -/* HMAC_CTX_init initialises |ctx| for use in an HMAC operation. It's assumed - * that HMAC_CTX objects will be allocated on the stack thus no allocation - * function is provided. If needed, allocate |sizeof(HMAC_CTX)| and call - * |HMAC_CTX_init| on it. */ -OPENSSL_EXPORT void HMAC_CTX_init(HMAC_CTX *ctx); - -/* HMAC_CTX_cleanup frees data owned by |ctx|. */ -OPENSSL_EXPORT void HMAC_CTX_cleanup(HMAC_CTX *ctx); - -/* HMAC_Init_ex sets up an initialised |HMAC_CTX| to use |md| as the hash - * function and |key| as the key. For a non-initial call, |md| may be NULL, in - * which case the previous hash function will be used. If the hash function has - * not changed and |key| is NULL, |ctx| reuses the previous key. It returns one - * on success or zero otherwise. - * - * WARNING: NULL and empty keys are ambiguous on non-initial calls. Passing NULL - * |key| but repeating the previous |md| reuses the previous key rather than the - * empty key. */ -OPENSSL_EXPORT int HMAC_Init_ex(HMAC_CTX *ctx, const void *key, size_t key_len, - const EVP_MD *md, ENGINE *impl); - -/* HMAC_Update hashes |data_len| bytes from |data| into the current HMAC - * operation in |ctx|. It returns one. */ -OPENSSL_EXPORT int HMAC_Update(HMAC_CTX *ctx, const uint8_t *data, - size_t data_len); - -/* HMAC_Final completes the HMAC operation in |ctx| and writes the result to - * |out| and the sets |*out_len| to the length of the result. On entry, |out| - * must contain at least |EVP_MAX_MD_SIZE| bytes of space. It returns one on - * success or zero on error. */ -OPENSSL_EXPORT int HMAC_Final(HMAC_CTX *ctx, uint8_t *out, - unsigned int *out_len); - - -/* Utility functions. */ - -/* HMAC_size returns the size, in bytes, of the HMAC that will be produced by - * |ctx|. On entry, |ctx| must have been setup with |HMAC_Init_ex|. */ -OPENSSL_EXPORT size_t HMAC_size(const HMAC_CTX *ctx); - -/* HMAC_CTX_copy_ex sets |dest| equal to |src|. On entry, |dest| must have been - * initialised by calling |HMAC_CTX_init|. It returns one on success and zero - * on error. */ -OPENSSL_EXPORT int HMAC_CTX_copy_ex(HMAC_CTX *dest, const HMAC_CTX *src); - - -/* Deprecated functions. */ - -OPENSSL_EXPORT int HMAC_Init(HMAC_CTX *ctx, const void *key, int key_len, - const EVP_MD *md); - -/* HMAC_CTX_copy calls |HMAC_CTX_init| on |dest| and then sets it equal to - * |src|. On entry, |dest| must /not/ be initialised for an operation with - * |HMAC_Init_ex|. It returns one on success and zero on error. */ -OPENSSL_EXPORT int HMAC_CTX_copy(HMAC_CTX *dest, const HMAC_CTX *src); - - -/* Private functions */ - -#define HMAC_MAX_MD_CBLOCK 128 /* largest known is SHA512 */ - -struct hmac_ctx_st { - const EVP_MD *md; - EVP_MD_CTX md_ctx; - EVP_MD_CTX i_ctx; - EVP_MD_CTX o_ctx; -} /* HMAC_CTX */; - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_HMAC_H */ diff --git a/third_party/boringssl/include/openssl/lhash.h b/third_party/boringssl/include/openssl/lhash.h deleted file mode 100644 index d2ee982ebc..0000000000 --- a/third_party/boringssl/include/openssl/lhash.h +++ /dev/null @@ -1,191 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] */ - -#ifndef OPENSSL_HEADER_LHASH_H -#define OPENSSL_HEADER_LHASH_H - -#include -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* lhash is a traditional, chaining hash table that automatically expands and - * contracts as needed. One should not use the lh_* functions directly, rather - * use the type-safe macro wrappers: - * - * A hash table of a specific type of object has type |LHASH_OF(type)|. This - * can be defined (once) with |DEFINE_LHASH_OF(type)| and declared where needed - * with |DECLARE_LHASH_OF(type)|. For example: - * - * struct foo { - * int bar; - * }; - * - * DEFINE_LHASH_OF(struct foo); - * - * Although note that the hash table will contain /pointers/ to |foo|. - * - * A macro will be defined for each of the lh_* functions below. For - * LHASH_OF(foo), the macros would be lh_foo_new, lh_foo_num_items etc. */ - - -#define LHASH_OF(type) struct lhash_st_##type - -#define DEFINE_LHASH_OF(type) LHASH_OF(type) { int dummy; } - -#define DECLARE_LHASH_OF(type) LHASH_OF(type); - -/* The make_macros.sh script in this directory parses the following lines and - * generates the lhash_macros.h file that contains macros for the following - * types of stacks: - * - * LHASH_OF:ASN1_OBJECT - * LHASH_OF:CONF_VALUE - * LHASH_OF:SSL_SESSION */ - -#define IN_LHASH_H -#include -#undef IN_LHASH_H - - -/* lhash_item_st is an element of a hash chain. It points to the opaque data - * for this element and to the next item in the chain. The linked-list is NULL - * terminated. */ -typedef struct lhash_item_st { - void *data; - struct lhash_item_st *next; - /* hash contains the cached, hash value of |data|. */ - uint32_t hash; -} LHASH_ITEM; - -/* lhash_cmp_func is a comparison function that returns a value equal, or not - * equal, to zero depending on whether |*a| is equal, or not equal to |*b|, - * respectively. Note the difference between this and |stack_cmp_func| in that - * this takes pointers to the objects directly. */ -typedef int (*lhash_cmp_func)(const void *a, const void *b); - -/* lhash_hash_func is a function that maps an object to a uniformly distributed - * uint32_t. */ -typedef uint32_t (*lhash_hash_func)(const void *a); - -typedef struct lhash_st { - /* num_items contains the total number of items in the hash table. */ - size_t num_items; - /* buckets is an array of |num_buckets| pointers. Each points to the head of - * a chain of LHASH_ITEM objects that have the same hash value, mod - * |num_buckets|. */ - LHASH_ITEM **buckets; - /* num_buckets contains the length of |buckets|. This value is always >= - * kMinNumBuckets. */ - size_t num_buckets; - /* callback_depth contains the current depth of |lh_doall| or |lh_doall_arg| - * calls. If non-zero then this suppresses resizing of the |buckets| array, - * which would otherwise disrupt the iteration. */ - unsigned callback_depth; - - lhash_cmp_func comp; - lhash_hash_func hash; -} _LHASH; - -/* lh_new returns a new, empty hash table or NULL on error. If |comp| is NULL, - * |strcmp| will be used. If |hash| is NULL, a generic hash function will be - * used. */ -OPENSSL_EXPORT _LHASH *lh_new(lhash_hash_func hash, lhash_cmp_func comp); - -/* lh_free frees the hash table itself but none of the elements. See - * |lh_doall|. */ -OPENSSL_EXPORT void lh_free(_LHASH *lh); - -/* lh_num_items returns the number of items in |lh|. */ -OPENSSL_EXPORT size_t lh_num_items(const _LHASH *lh); - -/* lh_retrieve finds an element equal to |data| in the hash table and returns - * it. If no such element exists, it returns NULL. */ -OPENSSL_EXPORT void *lh_retrieve(const _LHASH *lh, const void *data); - -/* lh_insert inserts |data| into the hash table. If an existing element is - * equal to |data| (with respect to the comparison function) then |*old_data| - * will be set to that value and it will be replaced. Otherwise, or in the - * event of an error, |*old_data| will be set to NULL. It returns one on - * success or zero in the case of an allocation error. */ -OPENSSL_EXPORT int lh_insert(_LHASH *lh, void **old_data, void *data); - -/* lh_delete removes an element equal to |data| from the hash table and returns - * it. If no such element is found, it returns NULL. */ -OPENSSL_EXPORT void *lh_delete(_LHASH *lh, const void *data); - -/* lh_doall calls |func| on each element of the hash table. - * TODO(fork): rename this */ -OPENSSL_EXPORT void lh_doall(_LHASH *lh, void (*func)(void *)); - -/* lh_doall_arg calls |func| on each element of the hash table and also passes - * |arg| as the second argument. - * TODO(fork): rename this */ -OPENSSL_EXPORT void lh_doall_arg(_LHASH *lh, void (*func)(void *, void *), - void *arg); - -/* lh_strhash is the default hash function which processes NUL-terminated - * strings. */ -OPENSSL_EXPORT uint32_t lh_strhash(const char *c); - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_STACK_H */ diff --git a/third_party/boringssl/include/openssl/lhash_macros.h b/third_party/boringssl/include/openssl/lhash_macros.h deleted file mode 100644 index 1d981073ea..0000000000 --- a/third_party/boringssl/include/openssl/lhash_macros.h +++ /dev/null @@ -1,132 +0,0 @@ -/* Copyright (c) 2014, Google Inc. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -#if !defined(IN_LHASH_H) -#error "Don't include this file directly. Include lhash.h" -#endif - -/* ASN1_OBJECT */ -#define lh_ASN1_OBJECT_new(hash, comp) \ - ((LHASH_OF(ASN1_OBJECT) *)lh_new( \ - CHECKED_CAST(lhash_hash_func, uint32_t (*)(const ASN1_OBJECT *), hash), \ - CHECKED_CAST(lhash_cmp_func, \ - int (*)(const ASN1_OBJECT *a, const ASN1_OBJECT *b), \ - comp))) - -#define lh_ASN1_OBJECT_free(lh) \ - lh_free(CHECKED_CAST(_LHASH *, LHASH_OF(ASN1_OBJECT) *, lh)); - -#define lh_ASN1_OBJECT_num_items(lh) \ - lh_num_items(CHECKED_CAST(_LHASH *, LHASH_OF(ASN1_OBJECT) *, lh)) - -#define lh_ASN1_OBJECT_retrieve(lh, data) \ - ((ASN1_OBJECT *)lh_retrieve( \ - CHECKED_CAST(_LHASH *, LHASH_OF(ASN1_OBJECT) *, lh), \ - CHECKED_CAST(void *, ASN1_OBJECT *, data))) - -#define lh_ASN1_OBJECT_insert(lh, old_data, data) \ - lh_insert(CHECKED_CAST(_LHASH *, LHASH_OF(ASN1_OBJECT) *, lh), \ - CHECKED_CAST(void **, ASN1_OBJECT **, old_data), \ - CHECKED_CAST(void *, ASN1_OBJECT *, data)) - -#define lh_ASN1_OBJECT_delete(lh, data) \ - ((ASN1_OBJECT *)lh_delete( \ - CHECKED_CAST(_LHASH *, LHASH_OF(ASN1_OBJECT) *, lh), \ - CHECKED_CAST(void *, ASN1_OBJECT *, data))) - -#define lh_ASN1_OBJECT_doall(lh, func) \ - lh_doall(CHECKED_CAST(_LHASH *, LHASH_OF(ASN1_OBJECT) *, lh), \ - CHECKED_CAST(void (*)(void *), void (*)(ASN1_OBJECT *), func)); - -#define lh_ASN1_OBJECT_doall_arg(lh, func, arg) \ - lh_doall_arg(CHECKED_CAST(_LHASH *, LHASH_OF(ASN1_OBJECT) *, lh), \ - CHECKED_CAST(void (*)(void *, void *), \ - void (*)(ASN1_OBJECT *, void *), func), \ - arg); - -/* CONF_VALUE */ -#define lh_CONF_VALUE_new(hash, comp) \ - ((LHASH_OF(CONF_VALUE) *)lh_new( \ - CHECKED_CAST(lhash_hash_func, uint32_t (*)(const CONF_VALUE *), hash), \ - CHECKED_CAST(lhash_cmp_func, \ - int (*)(const CONF_VALUE *a, const CONF_VALUE *b), comp))) - -#define lh_CONF_VALUE_free(lh) \ - lh_free(CHECKED_CAST(_LHASH *, LHASH_OF(CONF_VALUE) *, lh)); - -#define lh_CONF_VALUE_num_items(lh) \ - lh_num_items(CHECKED_CAST(_LHASH *, LHASH_OF(CONF_VALUE) *, lh)) - -#define lh_CONF_VALUE_retrieve(lh, data) \ - ((CONF_VALUE *)lh_retrieve( \ - CHECKED_CAST(_LHASH *, LHASH_OF(CONF_VALUE) *, lh), \ - CHECKED_CAST(void *, CONF_VALUE *, data))) - -#define lh_CONF_VALUE_insert(lh, old_data, data) \ - lh_insert(CHECKED_CAST(_LHASH *, LHASH_OF(CONF_VALUE) *, lh), \ - CHECKED_CAST(void **, CONF_VALUE **, old_data), \ - CHECKED_CAST(void *, CONF_VALUE *, data)) - -#define lh_CONF_VALUE_delete(lh, data) \ - ((CONF_VALUE *)lh_delete(CHECKED_CAST(_LHASH *, LHASH_OF(CONF_VALUE) *, lh), \ - CHECKED_CAST(void *, CONF_VALUE *, data))) - -#define lh_CONF_VALUE_doall(lh, func) \ - lh_doall(CHECKED_CAST(_LHASH *, LHASH_OF(CONF_VALUE) *, lh), \ - CHECKED_CAST(void (*)(void *), void (*)(CONF_VALUE *), func)); - -#define lh_CONF_VALUE_doall_arg(lh, func, arg) \ - lh_doall_arg(CHECKED_CAST(_LHASH *, LHASH_OF(CONF_VALUE) *, lh), \ - CHECKED_CAST(void (*)(void *, void *), \ - void (*)(CONF_VALUE *, void *), func), \ - arg); - -/* SSL_SESSION */ -#define lh_SSL_SESSION_new(hash, comp) \ - ((LHASH_OF(SSL_SESSION) *)lh_new( \ - CHECKED_CAST(lhash_hash_func, uint32_t (*)(const SSL_SESSION *), hash), \ - CHECKED_CAST(lhash_cmp_func, \ - int (*)(const SSL_SESSION *a, const SSL_SESSION *b), \ - comp))) - -#define lh_SSL_SESSION_free(lh) \ - lh_free(CHECKED_CAST(_LHASH *, LHASH_OF(SSL_SESSION) *, lh)); - -#define lh_SSL_SESSION_num_items(lh) \ - lh_num_items(CHECKED_CAST(_LHASH *, LHASH_OF(SSL_SESSION) *, lh)) - -#define lh_SSL_SESSION_retrieve(lh, data) \ - ((SSL_SESSION *)lh_retrieve( \ - CHECKED_CAST(_LHASH *, LHASH_OF(SSL_SESSION) *, lh), \ - CHECKED_CAST(void *, SSL_SESSION *, data))) - -#define lh_SSL_SESSION_insert(lh, old_data, data) \ - lh_insert(CHECKED_CAST(_LHASH *, LHASH_OF(SSL_SESSION) *, lh), \ - CHECKED_CAST(void **, SSL_SESSION **, old_data), \ - CHECKED_CAST(void *, SSL_SESSION *, data)) - -#define lh_SSL_SESSION_delete(lh, data) \ - ((SSL_SESSION *)lh_delete( \ - CHECKED_CAST(_LHASH *, LHASH_OF(SSL_SESSION) *, lh), \ - CHECKED_CAST(void *, SSL_SESSION *, data))) - -#define lh_SSL_SESSION_doall(lh, func) \ - lh_doall(CHECKED_CAST(_LHASH *, LHASH_OF(SSL_SESSION) *, lh), \ - CHECKED_CAST(void (*)(void *), void (*)(SSL_SESSION *), func)); - -#define lh_SSL_SESSION_doall_arg(lh, func, arg) \ - lh_doall_arg(CHECKED_CAST(_LHASH *, LHASH_OF(SSL_SESSION) *, lh), \ - CHECKED_CAST(void (*)(void *, void *), \ - void (*)(SSL_SESSION *, void *), func), \ - arg); diff --git a/third_party/boringssl/include/openssl/md4.h b/third_party/boringssl/include/openssl/md4.h deleted file mode 100644 index ce4fa99bb8..0000000000 --- a/third_party/boringssl/include/openssl/md4.h +++ /dev/null @@ -1,101 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] */ - -#ifndef OPENSSL_HEADER_MD4_H -#define OPENSSL_HEADER_MD4_H - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* MD4. */ - -/* MD4_CBLOCK is the block size of MD4. */ -#define MD4_CBLOCK 64 - -/* MD4_DIGEST_LENGTH is the length of an MD4 digest. */ -#define MD4_DIGEST_LENGTH 16 - -/* MD41_Init initialises |md4| and returns one. */ -OPENSSL_EXPORT int MD4_Init(MD4_CTX *md4); - -/* MD4_Update adds |len| bytes from |data| to |md4| and returns one. */ -OPENSSL_EXPORT int MD4_Update(MD4_CTX *md4, const void *data, size_t len); - -/* MD4_Final adds the final padding to |md4| and writes the resulting digest to - * |md|, which must have at least |MD4_DIGEST_LENGTH| bytes of space. It - * returns one. */ -OPENSSL_EXPORT int MD4_Final(uint8_t *md, MD4_CTX *md4); - -/* MD4_Transform is a low-level function that performs a single, MD4 block - * transformation using the state from |md4| and 64 bytes from |block|. */ -OPENSSL_EXPORT void MD4_Transform(MD4_CTX *md4, const uint8_t *block); - -struct md4_state_st { - uint32_t A, B, C, D; - uint32_t Nl, Nh; - uint32_t data[16]; - unsigned int num; -}; - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_MD4_H */ diff --git a/third_party/boringssl/include/openssl/md5.h b/third_party/boringssl/include/openssl/md5.h deleted file mode 100644 index efedc983de..0000000000 --- a/third_party/boringssl/include/openssl/md5.h +++ /dev/null @@ -1,106 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] */ - -#ifndef OPENSSL_HEADER_MD5_H -#define OPENSSL_HEADER_MD5_H - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* MD5. */ - - -/* MD5_CBLOCK is the block size of MD5. */ -#define MD5_CBLOCK 64 - -/* MD5_DIGEST_LENGTH is the length of an MD5 digest. */ -#define MD5_DIGEST_LENGTH 16 - -/* MD51_Init initialises |md5| and returns one. */ -OPENSSL_EXPORT int MD5_Init(MD5_CTX *md5); - -/* MD5_Update adds |len| bytes from |data| to |md5| and returns one. */ -OPENSSL_EXPORT int MD5_Update(MD5_CTX *md5, const void *data, size_t len); - -/* MD5_Final adds the final padding to |md5| and writes the resulting digest to - * |md|, which must have at least |MD5_DIGEST_LENGTH| bytes of space. It - * returns one. */ -OPENSSL_EXPORT int MD5_Final(uint8_t *md, MD5_CTX *md5); - -/* MD5 writes the digest of |len| bytes from |data| to |out| and returns |out|. - * There must be at least |MD5_DIGEST_LENGTH| bytes of space in |out|. */ -OPENSSL_EXPORT uint8_t *MD5(const uint8_t *data, size_t len, uint8_t *out); - -/* MD5_Transform is a low-level function that performs a single, MD5 block - * transformation using the state from |md5| and 64 bytes from |block|. */ -OPENSSL_EXPORT void MD5_Transform(MD5_CTX *md5, const uint8_t *block); - -struct md5_state_st { - uint32_t A, B, C, D; - uint32_t Nl, Nh; - uint32_t data[16]; - unsigned int num; -}; - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_MD5_H */ diff --git a/third_party/boringssl/include/openssl/mem.h b/third_party/boringssl/include/openssl/mem.h deleted file mode 100644 index 42ec46a073..0000000000 --- a/third_party/boringssl/include/openssl/mem.h +++ /dev/null @@ -1,139 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] */ - -#ifndef OPENSSL_HEADER_MEM_H -#define OPENSSL_HEADER_MEM_H - -#include - -#include -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* Memory and string functions, see also buf.h. - * - * OpenSSL has, historically, had a complex set of malloc debugging options. - * However, that was written in a time before Valgrind and ASAN. Since we now - * have those tools, the OpenSSL allocation functions are simply macros around - * the standard memory functions. */ - - -#define OPENSSL_malloc malloc -#define OPENSSL_realloc realloc -#define OPENSSL_free free - -/* OPENSSL_realloc_clean acts like |realloc|, but clears the previous memory - * buffer. Because this is implemented as a wrapper around |malloc|, it needs - * to be given the size of the buffer pointed to by |ptr|. */ -void *OPENSSL_realloc_clean(void *ptr, size_t old_size, size_t new_size); - -/* OPENSSL_cleanse zeros out |len| bytes of memory at |ptr|. This is similar to - * |memset_s| from C11. */ -OPENSSL_EXPORT void OPENSSL_cleanse(void *ptr, size_t len); - -/* CRYPTO_memcmp returns zero iff the |len| bytes at |a| and |b| are equal. It - * takes an amount of time dependent on |len|, but independent of the contents - * of |a| and |b|. Unlike memcmp, it cannot be used to put elements into a - * defined order as the return value when a != b is undefined, other than to be - * non-zero. */ -OPENSSL_EXPORT int CRYPTO_memcmp(const void *a, const void *b, size_t len); - -/* OPENSSL_hash32 implements the 32 bit, FNV-1a hash. */ -OPENSSL_EXPORT uint32_t OPENSSL_hash32(const void *ptr, size_t len); - -/* OPENSSL_strdup has the same behaviour as strdup(3). */ -OPENSSL_EXPORT char *OPENSSL_strdup(const char *s); - -/* OPENSSL_strnlen has the same behaviour as strnlen(3). */ -OPENSSL_EXPORT size_t OPENSSL_strnlen(const char *s, size_t len); - -/* OPENSSL_strcasecmp has the same behaviour as strcasecmp(3). */ -OPENSSL_EXPORT int OPENSSL_strcasecmp(const char *a, const char *b); - -/* OPENSSL_strncasecmp has the same behaviour as strncasecmp(3). */ -OPENSSL_EXPORT int OPENSSL_strncasecmp(const char *a, const char *b, size_t n); - -/* DECIMAL_SIZE returns an upper bound for the length of the decimal - * representation of the given type. */ -#define DECIMAL_SIZE(type) ((sizeof(type)*8+2)/3+1) - -/* Printf functions. - * - * These functions are either OpenSSL wrappers for standard functions (i.e. - * |BIO_snprintf| and |BIO_vsnprintf|) which don't exist in C89, or are - * versions of printf functions that output to a BIO rather than a FILE. */ -#ifdef __GNUC__ -#define __bio_h__attr__ __attribute__ -#else -#define __bio_h__attr__(x) -#endif -OPENSSL_EXPORT int BIO_snprintf(char *buf, size_t n, const char *format, ...) - __bio_h__attr__((__format__(__printf__, 3, 4))); - -OPENSSL_EXPORT int BIO_vsnprintf(char *buf, size_t n, const char *format, - va_list args) - __bio_h__attr__((__format__(__printf__, 3, 0))); -#undef __bio_h__attr__ - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_MEM_H */ diff --git a/third_party/boringssl/include/openssl/modes.h b/third_party/boringssl/include/openssl/modes.h deleted file mode 100644 index 220adec552..0000000000 --- a/third_party/boringssl/include/openssl/modes.h +++ /dev/null @@ -1,223 +0,0 @@ -/* ==================================================================== - * Copyright (c) 2008 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * openssl-core@openssl.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.openssl.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS 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 OPENSSL_HEADER_MODES_H -#define OPENSSL_HEADER_MODES_H - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* modes.h contains functions that implement various block-cipher modes. */ - - -/* block128_f is the type of a 128-bit, block cipher. */ -typedef void (*block128_f)(const uint8_t in[16], uint8_t out[16], - const void *key); - - -/* CTR. */ - -/* ctr128_f is the type of a function that performs CTR-mode encryption. */ -typedef void (*ctr128_f)(const uint8_t *in, uint8_t *out, size_t blocks, - const void *key, const uint8_t ivec[16]); - -/* CRYPTO_ctr128_encrypt encrypts (or decrypts, it's the same in CTR mode) - * |len| bytes from |in| to |out| using |block| in counter mode. There's no - * requirement that |len| be a multiple of any value and any partial blocks are - * stored in |ecount_buf| and |*num|, which must be zeroed before the initial - * call. The counter is a 128-bit, big-endian value in |ivec| and is - * incremented by this function. */ -OPENSSL_EXPORT void CRYPTO_ctr128_encrypt(const uint8_t *in, uint8_t *out, - size_t len, const void *key, - uint8_t ivec[16], - uint8_t ecount_buf[16], - unsigned int *num, block128_f block); - -/* CRYPTO_ctr128_encrypt_ctr32 acts like |CRYPTO_ctr128_encrypt| but takes - * |ctr|, a function that performs CTR mode but only deals with the lower 32 - * bits of the counter. This is useful when |ctr| can be an optimised - * function. */ -OPENSSL_EXPORT void CRYPTO_ctr128_encrypt_ctr32( - const uint8_t *in, uint8_t *out, size_t len, const void *key, - uint8_t ivec[16], uint8_t ecount_buf[16], unsigned int *num, ctr128_f ctr); - - -/* GCM. */ - -typedef struct gcm128_context GCM128_CONTEXT; - -/* CRYPTO_gcm128_new allocates a fresh |GCM128_CONTEXT| and calls - * |CRYPTO_gcm128_init|. It returns the new context, or NULL on error. */ -OPENSSL_EXPORT GCM128_CONTEXT *CRYPTO_gcm128_new(void *key, block128_f block); - -/* CRYPTO_gcm128_init initialises |ctx| to use |block| (typically AES) with the - * given key. */ -OPENSSL_EXPORT void CRYPTO_gcm128_init(GCM128_CONTEXT *ctx, void *key, - block128_f block); - -/* CRYPTO_gcm128_setiv sets the IV (nonce) for |ctx|. */ -OPENSSL_EXPORT void CRYPTO_gcm128_setiv(GCM128_CONTEXT *ctx, const uint8_t *iv, - size_t len); - -/* CRYPTO_gcm128_aad sets the authenticated data for an instance of GCM. This - * must be called before and data is encrypted. It returns one on success and - * zero otherwise. */ -OPENSSL_EXPORT int CRYPTO_gcm128_aad(GCM128_CONTEXT *ctx, const uint8_t *aad, - size_t len); - -/* CRYPTO_gcm128_encrypt encrypts |len| bytes from |in| to |out|. It returns - * one on success and zero otherwise. */ -OPENSSL_EXPORT int CRYPTO_gcm128_encrypt(GCM128_CONTEXT *ctx, const uint8_t *in, - uint8_t *out, size_t len); - -/* CRYPTO_gcm128_decrypt decrypts |len| bytes from |in| to |out|. It returns - * one on success and zero otherwise. */ -OPENSSL_EXPORT int CRYPTO_gcm128_decrypt(GCM128_CONTEXT *ctx, const uint8_t *in, - uint8_t *out, size_t len); - -/* CRYPTO_gcm128_encrypt_ctr32 encrypts |len| bytes from |in| to |out| using a - * CTR function that only handles the bottom 32 bits of the nonce, like - * |CRYPTO_ctr128_encrypt_ctr32|. It returns one on success and zero - * otherwise. */ -OPENSSL_EXPORT int CRYPTO_gcm128_encrypt_ctr32(GCM128_CONTEXT *ctx, - const uint8_t *in, uint8_t *out, - size_t len, ctr128_f stream); - -/* CRYPTO_gcm128_decrypt_ctr32 decrypts |len| bytes from |in| to |out| using a - * CTR function that only handles the bottom 32 bits of the nonce, like - * |CRYPTO_ctr128_encrypt_ctr32|. It returns one on success and zero - * otherwise. */ -OPENSSL_EXPORT int CRYPTO_gcm128_decrypt_ctr32(GCM128_CONTEXT *ctx, - const uint8_t *in, uint8_t *out, - size_t len, ctr128_f stream); - -/* CRYPTO_gcm128_finish calculates the authenticator and compares it against - * |len| bytes of |tag|. It returns one on success and zero otherwise. */ -OPENSSL_EXPORT int CRYPTO_gcm128_finish(GCM128_CONTEXT *ctx, const uint8_t *tag, - size_t len); - -/* CRYPTO_gcm128_tag calculates the authenticator and copies it into |tag|. The - * minimum of |len| and 16 bytes are copied into |tag|. */ -OPENSSL_EXPORT void CRYPTO_gcm128_tag(GCM128_CONTEXT *ctx, uint8_t *tag, - size_t len); - -/* CRYPTO_gcm128_release clears and frees |ctx|. */ -OPENSSL_EXPORT void CRYPTO_gcm128_release(GCM128_CONTEXT *ctx); - - -/* CBC. */ - -/* cbc128_f is the type of a function that performs CBC-mode encryption. */ -typedef void (*cbc128_f)(const uint8_t *in, uint8_t *out, size_t len, - const void *key, uint8_t ivec[16], int enc); - -/* CRYPTO_cbc128_encrypt encrypts |len| bytes from |in| to |out| using the - * given IV and block cipher in CBC mode. The input need not be a multiple of - * 128 bits long, but the output will round up to the nearest 128 bit multiple, - * zero padding the input if needed. The IV will be updated on return. */ -void CRYPTO_cbc128_encrypt(const uint8_t *in, uint8_t *out, size_t len, - const void *key, uint8_t ivec[16], block128_f block); - -/* CRYPTO_cbc128_decrypt decrypts |len| bytes from |in| to |out| using the - * given IV and block cipher in CBC mode. If |len| is not a multiple of 128 - * bits then only that many bytes will be written, but a multiple of 128 bits - * is always read from |in|. The IV will be updated on return. */ -void CRYPTO_cbc128_decrypt(const uint8_t *in, uint8_t *out, size_t len, - const void *key, uint8_t ivec[16], block128_f block); - - -/* OFB. */ - -/* CRYPTO_ofb128_encrypt encrypts (or decrypts, it's the same with OFB mode) - * |len| bytes from |in| to |out| using |block| in OFB mode. There's no - * requirement that |len| be a multiple of any value and any partial blocks are - * stored in |ivec| and |*num|, the latter must be zero before the initial - * call. */ -void CRYPTO_ofb128_encrypt(const uint8_t *in, uint8_t *out, - size_t len, const void *key, uint8_t ivec[16], - int *num, block128_f block); - - -/* CFB. */ - -/* CRYPTO_cfb128_encrypt encrypts (or decrypts, if |enc| is zero) |len| bytes - * from |in| to |out| using |block| in CFB mode. There's no requirement that - * |len| be a multiple of any value and any partial blocks are stored in |ivec| - * and |*num|, the latter must be zero before the initial call. */ -void CRYPTO_cfb128_encrypt(const uint8_t *in, uint8_t *out, size_t len, - const void *key, uint8_t ivec[16], int *num, int enc, - block128_f block); - -/* CRYPTO_cfb128_8_encrypt encrypts (or decrypts, if |enc| is zero) |len| bytes - * from |in| to |out| using |block| in CFB-8 mode. Prior to the first call - * |num| should be set to zero. */ -void CRYPTO_cfb128_8_encrypt(const uint8_t *in, uint8_t *out, size_t len, - const void *key, uint8_t ivec[16], int *num, - int enc, block128_f block); - -/* CRYPTO_cfb128_1_encrypt encrypts (or decrypts, if |enc| is zero) |len| bytes - * from |in| to |out| using |block| in CFB-1 mode. Prior to the first call - * |num| should be set to zero. */ -void CRYPTO_cfb128_1_encrypt(const uint8_t *in, uint8_t *out, size_t bits, - const void *key, uint8_t ivec[16], int *num, - int enc, block128_f block); - -size_t CRYPTO_cts128_encrypt_block(const uint8_t *in, uint8_t *out, size_t len, - const void *key, uint8_t ivec[16], - block128_f block); - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_MODES_H */ diff --git a/third_party/boringssl/include/openssl/obj.h b/third_party/boringssl/include/openssl/obj.h deleted file mode 100644 index f476617e18..0000000000 --- a/third_party/boringssl/include/openssl/obj.h +++ /dev/null @@ -1,202 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] */ - -#ifndef OPENSSL_HEADER_OBJECTS_H -#define OPENSSL_HEADER_OBJECTS_H - -#include - -#include -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* The objects library deals with the registration and indexing of ASN.1 object - * identifiers. These values are often written as a dotted sequence of numbers, - * e.g. 1.2.840.113549.1.9.16.3.9. - * - * Internally, OpenSSL likes to deal with these values by numbering them with - * numbers called "nids". OpenSSL has a large, built-in database of common - * object identifiers and also has both short and long names for them. - * - * This library provides functions for translating between object identifiers, - * nids, short names and long names. - * - * The nid values should not be used outside of a single process: they are not - * stable identifiers. */ - - -/* Basic operations. */ - -/* OBJ_dup returns a duplicate copy of |obj| or NULL on allocation failure. */ -OPENSSL_EXPORT ASN1_OBJECT *OBJ_dup(const ASN1_OBJECT *obj); - -/* OBJ_cmp returns a value less than, equal to or greater than zero if |a| is - * less than, equal to or greater than |b|, respectively. */ -OPENSSL_EXPORT int OBJ_cmp(const ASN1_OBJECT *a, const ASN1_OBJECT *b); - - -/* Looking up nids. */ - -/* OBJ_obj2nid returns the nid corresponding to |obj|, or |NID_undef| if no - * such object is known. */ -OPENSSL_EXPORT int OBJ_obj2nid(const ASN1_OBJECT *obj); - -/* OBJ_cbs2nid returns the nid corresponding to the DER data in |cbs|, or - * |NID_undef| if no such object is known. */ -OPENSSL_EXPORT int OBJ_cbs2nid(const CBS *cbs); - -/* OBJ_sn2nid returns the nid corresponding to |short_name|, or |NID_undef| if - * no such short name is known. */ -OPENSSL_EXPORT int OBJ_sn2nid(const char *short_name); - -/* OBJ_ln2nid returns the nid corresponding to |long_name|, or |NID_undef| if - * no such long name is known. */ -OPENSSL_EXPORT int OBJ_ln2nid(const char *long_name); - -/* OBJ_txt2nid returns the nid corresponding to |s|, which may be a short name, - * long name, or an ASCII string containing a dotted sequence of numbers. It - * returns the nid or NID_undef if unknown. */ -OPENSSL_EXPORT int OBJ_txt2nid(const char *s); - - -/* Getting information about nids. */ - -/* OBJ_nid2obj returns the ASN1_OBJECT corresponding to |nid|, or NULL if |nid| - * is unknown. */ -OPENSSL_EXPORT const ASN1_OBJECT *OBJ_nid2obj(int nid); - -/* OBJ_nid2sn returns the short name for |nid|, or NULL if |nid| is unknown. */ -OPENSSL_EXPORT const char *OBJ_nid2sn(int nid); - -/* OBJ_nid2sn returns the long name for |nid|, or NULL if |nid| is unknown. */ -OPENSSL_EXPORT const char *OBJ_nid2ln(int nid); - -/* OBJ_nid2cbs writes |nid| as an ASN.1 OBJECT IDENTIFIER to |out|. It returns - * one on success or zero otherwise. */ -OPENSSL_EXPORT int OBJ_nid2cbb(CBB *out, int nid); - - -/* Dealing with textual representations of object identifiers. */ - -/* OBJ_txt2obj returns an ASN1_OBJECT for the textual respresentation in |s|. - * If |dont_search_names| is zero, then |s| will be matched against the long - * and short names of a known objects to find a match. Otherwise |s| must - * contain an ASCII string with a dotted sequence of numbers. The resulting - * object need not be previously known. It returns a freshly allocated - * |ASN1_OBJECT| or NULL on error. */ -OPENSSL_EXPORT ASN1_OBJECT *OBJ_txt2obj(const char *s, int dont_search_names); - -/* OBJ_obj2txt converts |obj| to a textual representation. If - * |dont_return_name| is zero then |obj| will be matched against known objects - * and the long (preferably) or short name will be used if found. Otherwise - * |obj| will be converted into a dotted sequence of integers. If |out| is not - * NULL, then at most |out_len| bytes of the textual form will be written - * there. If |out_len| is at least one, then string written to |out| will - * always be NUL terminated. It returns the number of characters that could - * have been written, not including the final NUL, or -1 on error. */ -OPENSSL_EXPORT int OBJ_obj2txt(char *out, int out_len, const ASN1_OBJECT *obj, - int dont_return_name); - - -/* Adding objects at runtime. */ - -/* OBJ_create adds a known object and returns the nid of the new object, or - * NID_undef on error. */ -OPENSSL_EXPORT int OBJ_create(const char *oid, const char *short_name, - const char *long_name); - - -/* Handling signature algorithm identifiers. - * - * Some NIDs (e.g. sha256WithRSAEncryption) specify both a digest algorithm and - * a public key algorithm. The following functions map between pairs of digest - * and public-key algorithms and the NIDs that specify their combination. - * - * Sometimes the combination NID leaves the digest unspecified (e.g. - * rsassaPss). In these cases, the digest NID is |NID_undef|. */ - -/* OBJ_find_sigid_algs finds the digest and public-key NIDs that correspond to - * the signing algorithm |sign_nid|. If successful, it sets |*out_digest_nid| - * and |*out_pkey_nid| and returns one. Otherwise it returns zero. Any of - * |out_digest_nid| or |out_pkey_nid| can be NULL if the caller doesn't need - * that output value. */ -OPENSSL_EXPORT int OBJ_find_sigid_algs(int sign_nid, int *out_digest_nid, - int *out_pkey_nid); - -/* OBJ_find_sigid_by_algs finds the signature NID that corresponds to the - * combination of |digest_nid| and |pkey_nid|. If success, it sets - * |*out_sign_nid| and returns one. Otherwise it returns zero. The - * |out_sign_nid| argument can be NULL if the caller only wishes to learn - * whether the combination is valid. */ -OPENSSL_EXPORT int OBJ_find_sigid_by_algs(int *out_sign_nid, int digest_nid, - int pkey_nid); - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#define OBJ_F_OBJ_create 100 -#define OBJ_F_OBJ_dup 101 -#define OBJ_F_OBJ_nid2obj 102 -#define OBJ_F_OBJ_txt2obj 103 -#define OBJ_R_UNKNOWN_NID 100 - -#endif /* OPENSSL_HEADER_OBJECTS_H */ diff --git a/third_party/boringssl/include/openssl/obj_mac.h b/third_party/boringssl/include/openssl/obj_mac.h deleted file mode 100644 index 55e1cba2fe..0000000000 --- a/third_party/boringssl/include/openssl/obj_mac.h +++ /dev/null @@ -1,4140 +0,0 @@ -/* THIS FILE IS GENERATED FROM objects.txt by objects.pl via the - * following command: - * perl objects.pl objects.txt obj_mac.num ../../include/openssl/obj_mac.h */ - -/* Copyright (C) 1995-1997 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] - */ - -#define SN_undef "UNDEF" -#define LN_undef "undefined" -#define NID_undef 0 -#define OBJ_undef 0L - -#define SN_itu_t "ITU-T" -#define LN_itu_t "itu-t" -#define NID_itu_t 645 -#define OBJ_itu_t 0L - -#define NID_ccitt 404 -#define OBJ_ccitt OBJ_itu_t - -#define SN_iso "ISO" -#define LN_iso "iso" -#define NID_iso 181 -#define OBJ_iso 1L - -#define SN_joint_iso_itu_t "JOINT-ISO-ITU-T" -#define LN_joint_iso_itu_t "joint-iso-itu-t" -#define NID_joint_iso_itu_t 646 -#define OBJ_joint_iso_itu_t 2L - -#define NID_joint_iso_ccitt 393 -#define OBJ_joint_iso_ccitt OBJ_joint_iso_itu_t - -#define SN_member_body "member-body" -#define LN_member_body "ISO Member Body" -#define NID_member_body 182 -#define OBJ_member_body OBJ_iso,2L - -#define SN_identified_organization "identified-organization" -#define NID_identified_organization 676 -#define OBJ_identified_organization OBJ_iso,3L - -#define SN_hmac_md5 "HMAC-MD5" -#define LN_hmac_md5 "hmac-md5" -#define NID_hmac_md5 780 -#define OBJ_hmac_md5 OBJ_identified_organization,6L,1L,5L,5L,8L,1L,1L - -#define SN_hmac_sha1 "HMAC-SHA1" -#define LN_hmac_sha1 "hmac-sha1" -#define NID_hmac_sha1 781 -#define OBJ_hmac_sha1 OBJ_identified_organization,6L,1L,5L,5L,8L,1L,2L - -#define SN_certicom_arc "certicom-arc" -#define NID_certicom_arc 677 -#define OBJ_certicom_arc OBJ_identified_organization,132L - -#define SN_international_organizations "international-organizations" -#define LN_international_organizations "International Organizations" -#define NID_international_organizations 647 -#define OBJ_international_organizations OBJ_joint_iso_itu_t,23L - -#define SN_wap "wap" -#define NID_wap 678 -#define OBJ_wap OBJ_international_organizations,43L - -#define SN_wap_wsg "wap-wsg" -#define NID_wap_wsg 679 -#define OBJ_wap_wsg OBJ_wap,1L - -#define SN_selected_attribute_types "selected-attribute-types" -#define LN_selected_attribute_types "Selected Attribute Types" -#define NID_selected_attribute_types 394 -#define OBJ_selected_attribute_types OBJ_joint_iso_itu_t,5L,1L,5L - -#define SN_clearance "clearance" -#define NID_clearance 395 -#define OBJ_clearance OBJ_selected_attribute_types,55L - -#define SN_ISO_US "ISO-US" -#define LN_ISO_US "ISO US Member Body" -#define NID_ISO_US 183 -#define OBJ_ISO_US OBJ_member_body,840L - -#define SN_X9_57 "X9-57" -#define LN_X9_57 "X9.57" -#define NID_X9_57 184 -#define OBJ_X9_57 OBJ_ISO_US,10040L - -#define SN_X9cm "X9cm" -#define LN_X9cm "X9.57 CM ?" -#define NID_X9cm 185 -#define OBJ_X9cm OBJ_X9_57,4L - -#define SN_dsa "DSA" -#define LN_dsa "dsaEncryption" -#define NID_dsa 116 -#define OBJ_dsa OBJ_X9cm,1L - -#define SN_dsaWithSHA1 "DSA-SHA1" -#define LN_dsaWithSHA1 "dsaWithSHA1" -#define NID_dsaWithSHA1 113 -#define OBJ_dsaWithSHA1 OBJ_X9cm,3L - -#define SN_ansi_X9_62 "ansi-X9-62" -#define LN_ansi_X9_62 "ANSI X9.62" -#define NID_ansi_X9_62 405 -#define OBJ_ansi_X9_62 OBJ_ISO_US,10045L - -#define OBJ_X9_62_id_fieldType OBJ_ansi_X9_62,1L - -#define SN_X9_62_prime_field "prime-field" -#define NID_X9_62_prime_field 406 -#define OBJ_X9_62_prime_field OBJ_X9_62_id_fieldType,1L - -#define SN_X9_62_characteristic_two_field "characteristic-two-field" -#define NID_X9_62_characteristic_two_field 407 -#define OBJ_X9_62_characteristic_two_field OBJ_X9_62_id_fieldType,2L - -#define SN_X9_62_id_characteristic_two_basis "id-characteristic-two-basis" -#define NID_X9_62_id_characteristic_two_basis 680 -#define OBJ_X9_62_id_characteristic_two_basis OBJ_X9_62_characteristic_two_field,3L - -#define SN_X9_62_onBasis "onBasis" -#define NID_X9_62_onBasis 681 -#define OBJ_X9_62_onBasis OBJ_X9_62_id_characteristic_two_basis,1L - -#define SN_X9_62_tpBasis "tpBasis" -#define NID_X9_62_tpBasis 682 -#define OBJ_X9_62_tpBasis OBJ_X9_62_id_characteristic_two_basis,2L - -#define SN_X9_62_ppBasis "ppBasis" -#define NID_X9_62_ppBasis 683 -#define OBJ_X9_62_ppBasis OBJ_X9_62_id_characteristic_two_basis,3L - -#define OBJ_X9_62_id_publicKeyType OBJ_ansi_X9_62,2L - -#define SN_X9_62_id_ecPublicKey "id-ecPublicKey" -#define NID_X9_62_id_ecPublicKey 408 -#define OBJ_X9_62_id_ecPublicKey OBJ_X9_62_id_publicKeyType,1L - -#define OBJ_X9_62_ellipticCurve OBJ_ansi_X9_62,3L - -#define OBJ_X9_62_c_TwoCurve OBJ_X9_62_ellipticCurve,0L - -#define SN_X9_62_c2pnb163v1 "c2pnb163v1" -#define NID_X9_62_c2pnb163v1 684 -#define OBJ_X9_62_c2pnb163v1 OBJ_X9_62_c_TwoCurve,1L - -#define SN_X9_62_c2pnb163v2 "c2pnb163v2" -#define NID_X9_62_c2pnb163v2 685 -#define OBJ_X9_62_c2pnb163v2 OBJ_X9_62_c_TwoCurve,2L - -#define SN_X9_62_c2pnb163v3 "c2pnb163v3" -#define NID_X9_62_c2pnb163v3 686 -#define OBJ_X9_62_c2pnb163v3 OBJ_X9_62_c_TwoCurve,3L - -#define SN_X9_62_c2pnb176v1 "c2pnb176v1" -#define NID_X9_62_c2pnb176v1 687 -#define OBJ_X9_62_c2pnb176v1 OBJ_X9_62_c_TwoCurve,4L - -#define SN_X9_62_c2tnb191v1 "c2tnb191v1" -#define NID_X9_62_c2tnb191v1 688 -#define OBJ_X9_62_c2tnb191v1 OBJ_X9_62_c_TwoCurve,5L - -#define SN_X9_62_c2tnb191v2 "c2tnb191v2" -#define NID_X9_62_c2tnb191v2 689 -#define OBJ_X9_62_c2tnb191v2 OBJ_X9_62_c_TwoCurve,6L - -#define SN_X9_62_c2tnb191v3 "c2tnb191v3" -#define NID_X9_62_c2tnb191v3 690 -#define OBJ_X9_62_c2tnb191v3 OBJ_X9_62_c_TwoCurve,7L - -#define SN_X9_62_c2onb191v4 "c2onb191v4" -#define NID_X9_62_c2onb191v4 691 -#define OBJ_X9_62_c2onb191v4 OBJ_X9_62_c_TwoCurve,8L - -#define SN_X9_62_c2onb191v5 "c2onb191v5" -#define NID_X9_62_c2onb191v5 692 -#define OBJ_X9_62_c2onb191v5 OBJ_X9_62_c_TwoCurve,9L - -#define SN_X9_62_c2pnb208w1 "c2pnb208w1" -#define NID_X9_62_c2pnb208w1 693 -#define OBJ_X9_62_c2pnb208w1 OBJ_X9_62_c_TwoCurve,10L - -#define SN_X9_62_c2tnb239v1 "c2tnb239v1" -#define NID_X9_62_c2tnb239v1 694 -#define OBJ_X9_62_c2tnb239v1 OBJ_X9_62_c_TwoCurve,11L - -#define SN_X9_62_c2tnb239v2 "c2tnb239v2" -#define NID_X9_62_c2tnb239v2 695 -#define OBJ_X9_62_c2tnb239v2 OBJ_X9_62_c_TwoCurve,12L - -#define SN_X9_62_c2tnb239v3 "c2tnb239v3" -#define NID_X9_62_c2tnb239v3 696 -#define OBJ_X9_62_c2tnb239v3 OBJ_X9_62_c_TwoCurve,13L - -#define SN_X9_62_c2onb239v4 "c2onb239v4" -#define NID_X9_62_c2onb239v4 697 -#define OBJ_X9_62_c2onb239v4 OBJ_X9_62_c_TwoCurve,14L - -#define SN_X9_62_c2onb239v5 "c2onb239v5" -#define NID_X9_62_c2onb239v5 698 -#define OBJ_X9_62_c2onb239v5 OBJ_X9_62_c_TwoCurve,15L - -#define SN_X9_62_c2pnb272w1 "c2pnb272w1" -#define NID_X9_62_c2pnb272w1 699 -#define OBJ_X9_62_c2pnb272w1 OBJ_X9_62_c_TwoCurve,16L - -#define SN_X9_62_c2pnb304w1 "c2pnb304w1" -#define NID_X9_62_c2pnb304w1 700 -#define OBJ_X9_62_c2pnb304w1 OBJ_X9_62_c_TwoCurve,17L - -#define SN_X9_62_c2tnb359v1 "c2tnb359v1" -#define NID_X9_62_c2tnb359v1 701 -#define OBJ_X9_62_c2tnb359v1 OBJ_X9_62_c_TwoCurve,18L - -#define SN_X9_62_c2pnb368w1 "c2pnb368w1" -#define NID_X9_62_c2pnb368w1 702 -#define OBJ_X9_62_c2pnb368w1 OBJ_X9_62_c_TwoCurve,19L - -#define SN_X9_62_c2tnb431r1 "c2tnb431r1" -#define NID_X9_62_c2tnb431r1 703 -#define OBJ_X9_62_c2tnb431r1 OBJ_X9_62_c_TwoCurve,20L - -#define OBJ_X9_62_primeCurve OBJ_X9_62_ellipticCurve,1L - -#define SN_X9_62_prime192v1 "prime192v1" -#define NID_X9_62_prime192v1 409 -#define OBJ_X9_62_prime192v1 OBJ_X9_62_primeCurve,1L - -#define SN_X9_62_prime192v2 "prime192v2" -#define NID_X9_62_prime192v2 410 -#define OBJ_X9_62_prime192v2 OBJ_X9_62_primeCurve,2L - -#define SN_X9_62_prime192v3 "prime192v3" -#define NID_X9_62_prime192v3 411 -#define OBJ_X9_62_prime192v3 OBJ_X9_62_primeCurve,3L - -#define SN_X9_62_prime239v1 "prime239v1" -#define NID_X9_62_prime239v1 412 -#define OBJ_X9_62_prime239v1 OBJ_X9_62_primeCurve,4L - -#define SN_X9_62_prime239v2 "prime239v2" -#define NID_X9_62_prime239v2 413 -#define OBJ_X9_62_prime239v2 OBJ_X9_62_primeCurve,5L - -#define SN_X9_62_prime239v3 "prime239v3" -#define NID_X9_62_prime239v3 414 -#define OBJ_X9_62_prime239v3 OBJ_X9_62_primeCurve,6L - -#define SN_X9_62_prime256v1 "prime256v1" -#define NID_X9_62_prime256v1 415 -#define OBJ_X9_62_prime256v1 OBJ_X9_62_primeCurve,7L - -#define OBJ_X9_62_id_ecSigType OBJ_ansi_X9_62,4L - -#define SN_ecdsa_with_SHA1 "ecdsa-with-SHA1" -#define NID_ecdsa_with_SHA1 416 -#define OBJ_ecdsa_with_SHA1 OBJ_X9_62_id_ecSigType,1L - -#define SN_ecdsa_with_Recommended "ecdsa-with-Recommended" -#define NID_ecdsa_with_Recommended 791 -#define OBJ_ecdsa_with_Recommended OBJ_X9_62_id_ecSigType,2L - -#define SN_ecdsa_with_Specified "ecdsa-with-Specified" -#define NID_ecdsa_with_Specified 792 -#define OBJ_ecdsa_with_Specified OBJ_X9_62_id_ecSigType,3L - -#define SN_ecdsa_with_SHA224 "ecdsa-with-SHA224" -#define NID_ecdsa_with_SHA224 793 -#define OBJ_ecdsa_with_SHA224 OBJ_ecdsa_with_Specified,1L - -#define SN_ecdsa_with_SHA256 "ecdsa-with-SHA256" -#define NID_ecdsa_with_SHA256 794 -#define OBJ_ecdsa_with_SHA256 OBJ_ecdsa_with_Specified,2L - -#define SN_ecdsa_with_SHA384 "ecdsa-with-SHA384" -#define NID_ecdsa_with_SHA384 795 -#define OBJ_ecdsa_with_SHA384 OBJ_ecdsa_with_Specified,3L - -#define SN_ecdsa_with_SHA512 "ecdsa-with-SHA512" -#define NID_ecdsa_with_SHA512 796 -#define OBJ_ecdsa_with_SHA512 OBJ_ecdsa_with_Specified,4L - -#define OBJ_secg_ellipticCurve OBJ_certicom_arc,0L - -#define SN_secp112r1 "secp112r1" -#define NID_secp112r1 704 -#define OBJ_secp112r1 OBJ_secg_ellipticCurve,6L - -#define SN_secp112r2 "secp112r2" -#define NID_secp112r2 705 -#define OBJ_secp112r2 OBJ_secg_ellipticCurve,7L - -#define SN_secp128r1 "secp128r1" -#define NID_secp128r1 706 -#define OBJ_secp128r1 OBJ_secg_ellipticCurve,28L - -#define SN_secp128r2 "secp128r2" -#define NID_secp128r2 707 -#define OBJ_secp128r2 OBJ_secg_ellipticCurve,29L - -#define SN_secp160k1 "secp160k1" -#define NID_secp160k1 708 -#define OBJ_secp160k1 OBJ_secg_ellipticCurve,9L - -#define SN_secp160r1 "secp160r1" -#define NID_secp160r1 709 -#define OBJ_secp160r1 OBJ_secg_ellipticCurve,8L - -#define SN_secp160r2 "secp160r2" -#define NID_secp160r2 710 -#define OBJ_secp160r2 OBJ_secg_ellipticCurve,30L - -#define SN_secp192k1 "secp192k1" -#define NID_secp192k1 711 -#define OBJ_secp192k1 OBJ_secg_ellipticCurve,31L - -#define SN_secp224k1 "secp224k1" -#define NID_secp224k1 712 -#define OBJ_secp224k1 OBJ_secg_ellipticCurve,32L - -#define SN_secp224r1 "secp224r1" -#define NID_secp224r1 713 -#define OBJ_secp224r1 OBJ_secg_ellipticCurve,33L - -#define SN_secp256k1 "secp256k1" -#define NID_secp256k1 714 -#define OBJ_secp256k1 OBJ_secg_ellipticCurve,10L - -#define SN_secp384r1 "secp384r1" -#define NID_secp384r1 715 -#define OBJ_secp384r1 OBJ_secg_ellipticCurve,34L - -#define SN_secp521r1 "secp521r1" -#define NID_secp521r1 716 -#define OBJ_secp521r1 OBJ_secg_ellipticCurve,35L - -#define SN_sect113r1 "sect113r1" -#define NID_sect113r1 717 -#define OBJ_sect113r1 OBJ_secg_ellipticCurve,4L - -#define SN_sect113r2 "sect113r2" -#define NID_sect113r2 718 -#define OBJ_sect113r2 OBJ_secg_ellipticCurve,5L - -#define SN_sect131r1 "sect131r1" -#define NID_sect131r1 719 -#define OBJ_sect131r1 OBJ_secg_ellipticCurve,22L - -#define SN_sect131r2 "sect131r2" -#define NID_sect131r2 720 -#define OBJ_sect131r2 OBJ_secg_ellipticCurve,23L - -#define SN_sect163k1 "sect163k1" -#define NID_sect163k1 721 -#define OBJ_sect163k1 OBJ_secg_ellipticCurve,1L - -#define SN_sect163r1 "sect163r1" -#define NID_sect163r1 722 -#define OBJ_sect163r1 OBJ_secg_ellipticCurve,2L - -#define SN_sect163r2 "sect163r2" -#define NID_sect163r2 723 -#define OBJ_sect163r2 OBJ_secg_ellipticCurve,15L - -#define SN_sect193r1 "sect193r1" -#define NID_sect193r1 724 -#define OBJ_sect193r1 OBJ_secg_ellipticCurve,24L - -#define SN_sect193r2 "sect193r2" -#define NID_sect193r2 725 -#define OBJ_sect193r2 OBJ_secg_ellipticCurve,25L - -#define SN_sect233k1 "sect233k1" -#define NID_sect233k1 726 -#define OBJ_sect233k1 OBJ_secg_ellipticCurve,26L - -#define SN_sect233r1 "sect233r1" -#define NID_sect233r1 727 -#define OBJ_sect233r1 OBJ_secg_ellipticCurve,27L - -#define SN_sect239k1 "sect239k1" -#define NID_sect239k1 728 -#define OBJ_sect239k1 OBJ_secg_ellipticCurve,3L - -#define SN_sect283k1 "sect283k1" -#define NID_sect283k1 729 -#define OBJ_sect283k1 OBJ_secg_ellipticCurve,16L - -#define SN_sect283r1 "sect283r1" -#define NID_sect283r1 730 -#define OBJ_sect283r1 OBJ_secg_ellipticCurve,17L - -#define SN_sect409k1 "sect409k1" -#define NID_sect409k1 731 -#define OBJ_sect409k1 OBJ_secg_ellipticCurve,36L - -#define SN_sect409r1 "sect409r1" -#define NID_sect409r1 732 -#define OBJ_sect409r1 OBJ_secg_ellipticCurve,37L - -#define SN_sect571k1 "sect571k1" -#define NID_sect571k1 733 -#define OBJ_sect571k1 OBJ_secg_ellipticCurve,38L - -#define SN_sect571r1 "sect571r1" -#define NID_sect571r1 734 -#define OBJ_sect571r1 OBJ_secg_ellipticCurve,39L - -#define OBJ_wap_wsg_idm_ecid OBJ_wap_wsg,4L - -#define SN_wap_wsg_idm_ecid_wtls1 "wap-wsg-idm-ecid-wtls1" -#define NID_wap_wsg_idm_ecid_wtls1 735 -#define OBJ_wap_wsg_idm_ecid_wtls1 OBJ_wap_wsg_idm_ecid,1L - -#define SN_wap_wsg_idm_ecid_wtls3 "wap-wsg-idm-ecid-wtls3" -#define NID_wap_wsg_idm_ecid_wtls3 736 -#define OBJ_wap_wsg_idm_ecid_wtls3 OBJ_wap_wsg_idm_ecid,3L - -#define SN_wap_wsg_idm_ecid_wtls4 "wap-wsg-idm-ecid-wtls4" -#define NID_wap_wsg_idm_ecid_wtls4 737 -#define OBJ_wap_wsg_idm_ecid_wtls4 OBJ_wap_wsg_idm_ecid,4L - -#define SN_wap_wsg_idm_ecid_wtls5 "wap-wsg-idm-ecid-wtls5" -#define NID_wap_wsg_idm_ecid_wtls5 738 -#define OBJ_wap_wsg_idm_ecid_wtls5 OBJ_wap_wsg_idm_ecid,5L - -#define SN_wap_wsg_idm_ecid_wtls6 "wap-wsg-idm-ecid-wtls6" -#define NID_wap_wsg_idm_ecid_wtls6 739 -#define OBJ_wap_wsg_idm_ecid_wtls6 OBJ_wap_wsg_idm_ecid,6L - -#define SN_wap_wsg_idm_ecid_wtls7 "wap-wsg-idm-ecid-wtls7" -#define NID_wap_wsg_idm_ecid_wtls7 740 -#define OBJ_wap_wsg_idm_ecid_wtls7 OBJ_wap_wsg_idm_ecid,7L - -#define SN_wap_wsg_idm_ecid_wtls8 "wap-wsg-idm-ecid-wtls8" -#define NID_wap_wsg_idm_ecid_wtls8 741 -#define OBJ_wap_wsg_idm_ecid_wtls8 OBJ_wap_wsg_idm_ecid,8L - -#define SN_wap_wsg_idm_ecid_wtls9 "wap-wsg-idm-ecid-wtls9" -#define NID_wap_wsg_idm_ecid_wtls9 742 -#define OBJ_wap_wsg_idm_ecid_wtls9 OBJ_wap_wsg_idm_ecid,9L - -#define SN_wap_wsg_idm_ecid_wtls10 "wap-wsg-idm-ecid-wtls10" -#define NID_wap_wsg_idm_ecid_wtls10 743 -#define OBJ_wap_wsg_idm_ecid_wtls10 OBJ_wap_wsg_idm_ecid,10L - -#define SN_wap_wsg_idm_ecid_wtls11 "wap-wsg-idm-ecid-wtls11" -#define NID_wap_wsg_idm_ecid_wtls11 744 -#define OBJ_wap_wsg_idm_ecid_wtls11 OBJ_wap_wsg_idm_ecid,11L - -#define SN_wap_wsg_idm_ecid_wtls12 "wap-wsg-idm-ecid-wtls12" -#define NID_wap_wsg_idm_ecid_wtls12 745 -#define OBJ_wap_wsg_idm_ecid_wtls12 OBJ_wap_wsg_idm_ecid,12L - -#define SN_cast5_cbc "CAST5-CBC" -#define LN_cast5_cbc "cast5-cbc" -#define NID_cast5_cbc 108 -#define OBJ_cast5_cbc OBJ_ISO_US,113533L,7L,66L,10L - -#define SN_cast5_ecb "CAST5-ECB" -#define LN_cast5_ecb "cast5-ecb" -#define NID_cast5_ecb 109 - -#define SN_cast5_cfb64 "CAST5-CFB" -#define LN_cast5_cfb64 "cast5-cfb" -#define NID_cast5_cfb64 110 - -#define SN_cast5_ofb64 "CAST5-OFB" -#define LN_cast5_ofb64 "cast5-ofb" -#define NID_cast5_ofb64 111 - -#define LN_pbeWithMD5AndCast5_CBC "pbeWithMD5AndCast5CBC" -#define NID_pbeWithMD5AndCast5_CBC 112 -#define OBJ_pbeWithMD5AndCast5_CBC OBJ_ISO_US,113533L,7L,66L,12L - -#define SN_id_PasswordBasedMAC "id-PasswordBasedMAC" -#define LN_id_PasswordBasedMAC "password based MAC" -#define NID_id_PasswordBasedMAC 782 -#define OBJ_id_PasswordBasedMAC OBJ_ISO_US,113533L,7L,66L,13L - -#define SN_id_DHBasedMac "id-DHBasedMac" -#define LN_id_DHBasedMac "Diffie-Hellman based MAC" -#define NID_id_DHBasedMac 783 -#define OBJ_id_DHBasedMac OBJ_ISO_US,113533L,7L,66L,30L - -#define SN_rsadsi "rsadsi" -#define LN_rsadsi "RSA Data Security, Inc." -#define NID_rsadsi 1 -#define OBJ_rsadsi OBJ_ISO_US,113549L - -#define SN_pkcs "pkcs" -#define LN_pkcs "RSA Data Security, Inc. PKCS" -#define NID_pkcs 2 -#define OBJ_pkcs OBJ_rsadsi,1L - -#define SN_pkcs1 "pkcs1" -#define NID_pkcs1 186 -#define OBJ_pkcs1 OBJ_pkcs,1L - -#define LN_rsaEncryption "rsaEncryption" -#define NID_rsaEncryption 6 -#define OBJ_rsaEncryption OBJ_pkcs1,1L - -#define SN_md2WithRSAEncryption "RSA-MD2" -#define LN_md2WithRSAEncryption "md2WithRSAEncryption" -#define NID_md2WithRSAEncryption 7 -#define OBJ_md2WithRSAEncryption OBJ_pkcs1,2L - -#define SN_md4WithRSAEncryption "RSA-MD4" -#define LN_md4WithRSAEncryption "md4WithRSAEncryption" -#define NID_md4WithRSAEncryption 396 -#define OBJ_md4WithRSAEncryption OBJ_pkcs1,3L - -#define SN_md5WithRSAEncryption "RSA-MD5" -#define LN_md5WithRSAEncryption "md5WithRSAEncryption" -#define NID_md5WithRSAEncryption 8 -#define OBJ_md5WithRSAEncryption OBJ_pkcs1,4L - -#define SN_sha1WithRSAEncryption "RSA-SHA1" -#define LN_sha1WithRSAEncryption "sha1WithRSAEncryption" -#define NID_sha1WithRSAEncryption 65 -#define OBJ_sha1WithRSAEncryption OBJ_pkcs1,5L - -#define SN_rsaesOaep "RSAES-OAEP" -#define LN_rsaesOaep "rsaesOaep" -#define NID_rsaesOaep 919 -#define OBJ_rsaesOaep OBJ_pkcs1,7L - -#define SN_mgf1 "MGF1" -#define LN_mgf1 "mgf1" -#define NID_mgf1 911 -#define OBJ_mgf1 OBJ_pkcs1,8L - -#define SN_pSpecified "PSPECIFIED" -#define LN_pSpecified "pSpecified" -#define NID_pSpecified 935 -#define OBJ_pSpecified OBJ_pkcs1,9L - -#define SN_rsassaPss "RSASSA-PSS" -#define LN_rsassaPss "rsassaPss" -#define NID_rsassaPss 912 -#define OBJ_rsassaPss OBJ_pkcs1,10L - -#define SN_sha256WithRSAEncryption "RSA-SHA256" -#define LN_sha256WithRSAEncryption "sha256WithRSAEncryption" -#define NID_sha256WithRSAEncryption 668 -#define OBJ_sha256WithRSAEncryption OBJ_pkcs1,11L - -#define SN_sha384WithRSAEncryption "RSA-SHA384" -#define LN_sha384WithRSAEncryption "sha384WithRSAEncryption" -#define NID_sha384WithRSAEncryption 669 -#define OBJ_sha384WithRSAEncryption OBJ_pkcs1,12L - -#define SN_sha512WithRSAEncryption "RSA-SHA512" -#define LN_sha512WithRSAEncryption "sha512WithRSAEncryption" -#define NID_sha512WithRSAEncryption 670 -#define OBJ_sha512WithRSAEncryption OBJ_pkcs1,13L - -#define SN_sha224WithRSAEncryption "RSA-SHA224" -#define LN_sha224WithRSAEncryption "sha224WithRSAEncryption" -#define NID_sha224WithRSAEncryption 671 -#define OBJ_sha224WithRSAEncryption OBJ_pkcs1,14L - -#define SN_pkcs3 "pkcs3" -#define NID_pkcs3 27 -#define OBJ_pkcs3 OBJ_pkcs,3L - -#define LN_dhKeyAgreement "dhKeyAgreement" -#define NID_dhKeyAgreement 28 -#define OBJ_dhKeyAgreement OBJ_pkcs3,1L - -#define SN_pkcs5 "pkcs5" -#define NID_pkcs5 187 -#define OBJ_pkcs5 OBJ_pkcs,5L - -#define SN_pbeWithMD2AndDES_CBC "PBE-MD2-DES" -#define LN_pbeWithMD2AndDES_CBC "pbeWithMD2AndDES-CBC" -#define NID_pbeWithMD2AndDES_CBC 9 -#define OBJ_pbeWithMD2AndDES_CBC OBJ_pkcs5,1L - -#define SN_pbeWithMD5AndDES_CBC "PBE-MD5-DES" -#define LN_pbeWithMD5AndDES_CBC "pbeWithMD5AndDES-CBC" -#define NID_pbeWithMD5AndDES_CBC 10 -#define OBJ_pbeWithMD5AndDES_CBC OBJ_pkcs5,3L - -#define SN_pbeWithMD2AndRC2_CBC "PBE-MD2-RC2-64" -#define LN_pbeWithMD2AndRC2_CBC "pbeWithMD2AndRC2-CBC" -#define NID_pbeWithMD2AndRC2_CBC 168 -#define OBJ_pbeWithMD2AndRC2_CBC OBJ_pkcs5,4L - -#define SN_pbeWithMD5AndRC2_CBC "PBE-MD5-RC2-64" -#define LN_pbeWithMD5AndRC2_CBC "pbeWithMD5AndRC2-CBC" -#define NID_pbeWithMD5AndRC2_CBC 169 -#define OBJ_pbeWithMD5AndRC2_CBC OBJ_pkcs5,6L - -#define SN_pbeWithSHA1AndDES_CBC "PBE-SHA1-DES" -#define LN_pbeWithSHA1AndDES_CBC "pbeWithSHA1AndDES-CBC" -#define NID_pbeWithSHA1AndDES_CBC 170 -#define OBJ_pbeWithSHA1AndDES_CBC OBJ_pkcs5,10L - -#define SN_pbeWithSHA1AndRC2_CBC "PBE-SHA1-RC2-64" -#define LN_pbeWithSHA1AndRC2_CBC "pbeWithSHA1AndRC2-CBC" -#define NID_pbeWithSHA1AndRC2_CBC 68 -#define OBJ_pbeWithSHA1AndRC2_CBC OBJ_pkcs5,11L - -#define LN_id_pbkdf2 "PBKDF2" -#define NID_id_pbkdf2 69 -#define OBJ_id_pbkdf2 OBJ_pkcs5,12L - -#define LN_pbes2 "PBES2" -#define NID_pbes2 161 -#define OBJ_pbes2 OBJ_pkcs5,13L - -#define LN_pbmac1 "PBMAC1" -#define NID_pbmac1 162 -#define OBJ_pbmac1 OBJ_pkcs5,14L - -#define SN_pkcs7 "pkcs7" -#define NID_pkcs7 20 -#define OBJ_pkcs7 OBJ_pkcs,7L - -#define LN_pkcs7_data "pkcs7-data" -#define NID_pkcs7_data 21 -#define OBJ_pkcs7_data OBJ_pkcs7,1L - -#define LN_pkcs7_signed "pkcs7-signedData" -#define NID_pkcs7_signed 22 -#define OBJ_pkcs7_signed OBJ_pkcs7,2L - -#define LN_pkcs7_enveloped "pkcs7-envelopedData" -#define NID_pkcs7_enveloped 23 -#define OBJ_pkcs7_enveloped OBJ_pkcs7,3L - -#define LN_pkcs7_signedAndEnveloped "pkcs7-signedAndEnvelopedData" -#define NID_pkcs7_signedAndEnveloped 24 -#define OBJ_pkcs7_signedAndEnveloped OBJ_pkcs7,4L - -#define LN_pkcs7_digest "pkcs7-digestData" -#define NID_pkcs7_digest 25 -#define OBJ_pkcs7_digest OBJ_pkcs7,5L - -#define LN_pkcs7_encrypted "pkcs7-encryptedData" -#define NID_pkcs7_encrypted 26 -#define OBJ_pkcs7_encrypted OBJ_pkcs7,6L - -#define SN_pkcs9 "pkcs9" -#define NID_pkcs9 47 -#define OBJ_pkcs9 OBJ_pkcs,9L - -#define LN_pkcs9_emailAddress "emailAddress" -#define NID_pkcs9_emailAddress 48 -#define OBJ_pkcs9_emailAddress OBJ_pkcs9,1L - -#define LN_pkcs9_unstructuredName "unstructuredName" -#define NID_pkcs9_unstructuredName 49 -#define OBJ_pkcs9_unstructuredName OBJ_pkcs9,2L - -#define LN_pkcs9_contentType "contentType" -#define NID_pkcs9_contentType 50 -#define OBJ_pkcs9_contentType OBJ_pkcs9,3L - -#define LN_pkcs9_messageDigest "messageDigest" -#define NID_pkcs9_messageDigest 51 -#define OBJ_pkcs9_messageDigest OBJ_pkcs9,4L - -#define LN_pkcs9_signingTime "signingTime" -#define NID_pkcs9_signingTime 52 -#define OBJ_pkcs9_signingTime OBJ_pkcs9,5L - -#define LN_pkcs9_countersignature "countersignature" -#define NID_pkcs9_countersignature 53 -#define OBJ_pkcs9_countersignature OBJ_pkcs9,6L - -#define LN_pkcs9_challengePassword "challengePassword" -#define NID_pkcs9_challengePassword 54 -#define OBJ_pkcs9_challengePassword OBJ_pkcs9,7L - -#define LN_pkcs9_unstructuredAddress "unstructuredAddress" -#define NID_pkcs9_unstructuredAddress 55 -#define OBJ_pkcs9_unstructuredAddress OBJ_pkcs9,8L - -#define LN_pkcs9_extCertAttributes "extendedCertificateAttributes" -#define NID_pkcs9_extCertAttributes 56 -#define OBJ_pkcs9_extCertAttributes OBJ_pkcs9,9L - -#define SN_ext_req "extReq" -#define LN_ext_req "Extension Request" -#define NID_ext_req 172 -#define OBJ_ext_req OBJ_pkcs9,14L - -#define SN_SMIMECapabilities "SMIME-CAPS" -#define LN_SMIMECapabilities "S/MIME Capabilities" -#define NID_SMIMECapabilities 167 -#define OBJ_SMIMECapabilities OBJ_pkcs9,15L - -#define SN_SMIME "SMIME" -#define LN_SMIME "S/MIME" -#define NID_SMIME 188 -#define OBJ_SMIME OBJ_pkcs9,16L - -#define SN_id_smime_mod "id-smime-mod" -#define NID_id_smime_mod 189 -#define OBJ_id_smime_mod OBJ_SMIME,0L - -#define SN_id_smime_ct "id-smime-ct" -#define NID_id_smime_ct 190 -#define OBJ_id_smime_ct OBJ_SMIME,1L - -#define SN_id_smime_aa "id-smime-aa" -#define NID_id_smime_aa 191 -#define OBJ_id_smime_aa OBJ_SMIME,2L - -#define SN_id_smime_alg "id-smime-alg" -#define NID_id_smime_alg 192 -#define OBJ_id_smime_alg OBJ_SMIME,3L - -#define SN_id_smime_cd "id-smime-cd" -#define NID_id_smime_cd 193 -#define OBJ_id_smime_cd OBJ_SMIME,4L - -#define SN_id_smime_spq "id-smime-spq" -#define NID_id_smime_spq 194 -#define OBJ_id_smime_spq OBJ_SMIME,5L - -#define SN_id_smime_cti "id-smime-cti" -#define NID_id_smime_cti 195 -#define OBJ_id_smime_cti OBJ_SMIME,6L - -#define SN_id_smime_mod_cms "id-smime-mod-cms" -#define NID_id_smime_mod_cms 196 -#define OBJ_id_smime_mod_cms OBJ_id_smime_mod,1L - -#define SN_id_smime_mod_ess "id-smime-mod-ess" -#define NID_id_smime_mod_ess 197 -#define OBJ_id_smime_mod_ess OBJ_id_smime_mod,2L - -#define SN_id_smime_mod_oid "id-smime-mod-oid" -#define NID_id_smime_mod_oid 198 -#define OBJ_id_smime_mod_oid OBJ_id_smime_mod,3L - -#define SN_id_smime_mod_msg_v3 "id-smime-mod-msg-v3" -#define NID_id_smime_mod_msg_v3 199 -#define OBJ_id_smime_mod_msg_v3 OBJ_id_smime_mod,4L - -#define SN_id_smime_mod_ets_eSignature_88 "id-smime-mod-ets-eSignature-88" -#define NID_id_smime_mod_ets_eSignature_88 200 -#define OBJ_id_smime_mod_ets_eSignature_88 OBJ_id_smime_mod,5L - -#define SN_id_smime_mod_ets_eSignature_97 "id-smime-mod-ets-eSignature-97" -#define NID_id_smime_mod_ets_eSignature_97 201 -#define OBJ_id_smime_mod_ets_eSignature_97 OBJ_id_smime_mod,6L - -#define SN_id_smime_mod_ets_eSigPolicy_88 "id-smime-mod-ets-eSigPolicy-88" -#define NID_id_smime_mod_ets_eSigPolicy_88 202 -#define OBJ_id_smime_mod_ets_eSigPolicy_88 OBJ_id_smime_mod,7L - -#define SN_id_smime_mod_ets_eSigPolicy_97 "id-smime-mod-ets-eSigPolicy-97" -#define NID_id_smime_mod_ets_eSigPolicy_97 203 -#define OBJ_id_smime_mod_ets_eSigPolicy_97 OBJ_id_smime_mod,8L - -#define SN_id_smime_ct_receipt "id-smime-ct-receipt" -#define NID_id_smime_ct_receipt 204 -#define OBJ_id_smime_ct_receipt OBJ_id_smime_ct,1L - -#define SN_id_smime_ct_authData "id-smime-ct-authData" -#define NID_id_smime_ct_authData 205 -#define OBJ_id_smime_ct_authData OBJ_id_smime_ct,2L - -#define SN_id_smime_ct_publishCert "id-smime-ct-publishCert" -#define NID_id_smime_ct_publishCert 206 -#define OBJ_id_smime_ct_publishCert OBJ_id_smime_ct,3L - -#define SN_id_smime_ct_TSTInfo "id-smime-ct-TSTInfo" -#define NID_id_smime_ct_TSTInfo 207 -#define OBJ_id_smime_ct_TSTInfo OBJ_id_smime_ct,4L - -#define SN_id_smime_ct_TDTInfo "id-smime-ct-TDTInfo" -#define NID_id_smime_ct_TDTInfo 208 -#define OBJ_id_smime_ct_TDTInfo OBJ_id_smime_ct,5L - -#define SN_id_smime_ct_contentInfo "id-smime-ct-contentInfo" -#define NID_id_smime_ct_contentInfo 209 -#define OBJ_id_smime_ct_contentInfo OBJ_id_smime_ct,6L - -#define SN_id_smime_ct_DVCSRequestData "id-smime-ct-DVCSRequestData" -#define NID_id_smime_ct_DVCSRequestData 210 -#define OBJ_id_smime_ct_DVCSRequestData OBJ_id_smime_ct,7L - -#define SN_id_smime_ct_DVCSResponseData "id-smime-ct-DVCSResponseData" -#define NID_id_smime_ct_DVCSResponseData 211 -#define OBJ_id_smime_ct_DVCSResponseData OBJ_id_smime_ct,8L - -#define SN_id_smime_ct_compressedData "id-smime-ct-compressedData" -#define NID_id_smime_ct_compressedData 786 -#define OBJ_id_smime_ct_compressedData OBJ_id_smime_ct,9L - -#define SN_id_ct_asciiTextWithCRLF "id-ct-asciiTextWithCRLF" -#define NID_id_ct_asciiTextWithCRLF 787 -#define OBJ_id_ct_asciiTextWithCRLF OBJ_id_smime_ct,27L - -#define SN_id_smime_aa_receiptRequest "id-smime-aa-receiptRequest" -#define NID_id_smime_aa_receiptRequest 212 -#define OBJ_id_smime_aa_receiptRequest OBJ_id_smime_aa,1L - -#define SN_id_smime_aa_securityLabel "id-smime-aa-securityLabel" -#define NID_id_smime_aa_securityLabel 213 -#define OBJ_id_smime_aa_securityLabel OBJ_id_smime_aa,2L - -#define SN_id_smime_aa_mlExpandHistory "id-smime-aa-mlExpandHistory" -#define NID_id_smime_aa_mlExpandHistory 214 -#define OBJ_id_smime_aa_mlExpandHistory OBJ_id_smime_aa,3L - -#define SN_id_smime_aa_contentHint "id-smime-aa-contentHint" -#define NID_id_smime_aa_contentHint 215 -#define OBJ_id_smime_aa_contentHint OBJ_id_smime_aa,4L - -#define SN_id_smime_aa_msgSigDigest "id-smime-aa-msgSigDigest" -#define NID_id_smime_aa_msgSigDigest 216 -#define OBJ_id_smime_aa_msgSigDigest OBJ_id_smime_aa,5L - -#define SN_id_smime_aa_encapContentType "id-smime-aa-encapContentType" -#define NID_id_smime_aa_encapContentType 217 -#define OBJ_id_smime_aa_encapContentType OBJ_id_smime_aa,6L - -#define SN_id_smime_aa_contentIdentifier "id-smime-aa-contentIdentifier" -#define NID_id_smime_aa_contentIdentifier 218 -#define OBJ_id_smime_aa_contentIdentifier OBJ_id_smime_aa,7L - -#define SN_id_smime_aa_macValue "id-smime-aa-macValue" -#define NID_id_smime_aa_macValue 219 -#define OBJ_id_smime_aa_macValue OBJ_id_smime_aa,8L - -#define SN_id_smime_aa_equivalentLabels "id-smime-aa-equivalentLabels" -#define NID_id_smime_aa_equivalentLabels 220 -#define OBJ_id_smime_aa_equivalentLabels OBJ_id_smime_aa,9L - -#define SN_id_smime_aa_contentReference "id-smime-aa-contentReference" -#define NID_id_smime_aa_contentReference 221 -#define OBJ_id_smime_aa_contentReference OBJ_id_smime_aa,10L - -#define SN_id_smime_aa_encrypKeyPref "id-smime-aa-encrypKeyPref" -#define NID_id_smime_aa_encrypKeyPref 222 -#define OBJ_id_smime_aa_encrypKeyPref OBJ_id_smime_aa,11L - -#define SN_id_smime_aa_signingCertificate "id-smime-aa-signingCertificate" -#define NID_id_smime_aa_signingCertificate 223 -#define OBJ_id_smime_aa_signingCertificate OBJ_id_smime_aa,12L - -#define SN_id_smime_aa_smimeEncryptCerts "id-smime-aa-smimeEncryptCerts" -#define NID_id_smime_aa_smimeEncryptCerts 224 -#define OBJ_id_smime_aa_smimeEncryptCerts OBJ_id_smime_aa,13L - -#define SN_id_smime_aa_timeStampToken "id-smime-aa-timeStampToken" -#define NID_id_smime_aa_timeStampToken 225 -#define OBJ_id_smime_aa_timeStampToken OBJ_id_smime_aa,14L - -#define SN_id_smime_aa_ets_sigPolicyId "id-smime-aa-ets-sigPolicyId" -#define NID_id_smime_aa_ets_sigPolicyId 226 -#define OBJ_id_smime_aa_ets_sigPolicyId OBJ_id_smime_aa,15L - -#define SN_id_smime_aa_ets_commitmentType "id-smime-aa-ets-commitmentType" -#define NID_id_smime_aa_ets_commitmentType 227 -#define OBJ_id_smime_aa_ets_commitmentType OBJ_id_smime_aa,16L - -#define SN_id_smime_aa_ets_signerLocation "id-smime-aa-ets-signerLocation" -#define NID_id_smime_aa_ets_signerLocation 228 -#define OBJ_id_smime_aa_ets_signerLocation OBJ_id_smime_aa,17L - -#define SN_id_smime_aa_ets_signerAttr "id-smime-aa-ets-signerAttr" -#define NID_id_smime_aa_ets_signerAttr 229 -#define OBJ_id_smime_aa_ets_signerAttr OBJ_id_smime_aa,18L - -#define SN_id_smime_aa_ets_otherSigCert "id-smime-aa-ets-otherSigCert" -#define NID_id_smime_aa_ets_otherSigCert 230 -#define OBJ_id_smime_aa_ets_otherSigCert OBJ_id_smime_aa,19L - -#define SN_id_smime_aa_ets_contentTimestamp "id-smime-aa-ets-contentTimestamp" -#define NID_id_smime_aa_ets_contentTimestamp 231 -#define OBJ_id_smime_aa_ets_contentTimestamp OBJ_id_smime_aa,20L - -#define SN_id_smime_aa_ets_CertificateRefs "id-smime-aa-ets-CertificateRefs" -#define NID_id_smime_aa_ets_CertificateRefs 232 -#define OBJ_id_smime_aa_ets_CertificateRefs OBJ_id_smime_aa,21L - -#define SN_id_smime_aa_ets_RevocationRefs "id-smime-aa-ets-RevocationRefs" -#define NID_id_smime_aa_ets_RevocationRefs 233 -#define OBJ_id_smime_aa_ets_RevocationRefs OBJ_id_smime_aa,22L - -#define SN_id_smime_aa_ets_certValues "id-smime-aa-ets-certValues" -#define NID_id_smime_aa_ets_certValues 234 -#define OBJ_id_smime_aa_ets_certValues OBJ_id_smime_aa,23L - -#define SN_id_smime_aa_ets_revocationValues "id-smime-aa-ets-revocationValues" -#define NID_id_smime_aa_ets_revocationValues 235 -#define OBJ_id_smime_aa_ets_revocationValues OBJ_id_smime_aa,24L - -#define SN_id_smime_aa_ets_escTimeStamp "id-smime-aa-ets-escTimeStamp" -#define NID_id_smime_aa_ets_escTimeStamp 236 -#define OBJ_id_smime_aa_ets_escTimeStamp OBJ_id_smime_aa,25L - -#define SN_id_smime_aa_ets_certCRLTimestamp "id-smime-aa-ets-certCRLTimestamp" -#define NID_id_smime_aa_ets_certCRLTimestamp 237 -#define OBJ_id_smime_aa_ets_certCRLTimestamp OBJ_id_smime_aa,26L - -#define SN_id_smime_aa_ets_archiveTimeStamp "id-smime-aa-ets-archiveTimeStamp" -#define NID_id_smime_aa_ets_archiveTimeStamp 238 -#define OBJ_id_smime_aa_ets_archiveTimeStamp OBJ_id_smime_aa,27L - -#define SN_id_smime_aa_signatureType "id-smime-aa-signatureType" -#define NID_id_smime_aa_signatureType 239 -#define OBJ_id_smime_aa_signatureType OBJ_id_smime_aa,28L - -#define SN_id_smime_aa_dvcs_dvc "id-smime-aa-dvcs-dvc" -#define NID_id_smime_aa_dvcs_dvc 240 -#define OBJ_id_smime_aa_dvcs_dvc OBJ_id_smime_aa,29L - -#define SN_id_smime_alg_ESDHwith3DES "id-smime-alg-ESDHwith3DES" -#define NID_id_smime_alg_ESDHwith3DES 241 -#define OBJ_id_smime_alg_ESDHwith3DES OBJ_id_smime_alg,1L - -#define SN_id_smime_alg_ESDHwithRC2 "id-smime-alg-ESDHwithRC2" -#define NID_id_smime_alg_ESDHwithRC2 242 -#define OBJ_id_smime_alg_ESDHwithRC2 OBJ_id_smime_alg,2L - -#define SN_id_smime_alg_3DESwrap "id-smime-alg-3DESwrap" -#define NID_id_smime_alg_3DESwrap 243 -#define OBJ_id_smime_alg_3DESwrap OBJ_id_smime_alg,3L - -#define SN_id_smime_alg_RC2wrap "id-smime-alg-RC2wrap" -#define NID_id_smime_alg_RC2wrap 244 -#define OBJ_id_smime_alg_RC2wrap OBJ_id_smime_alg,4L - -#define SN_id_smime_alg_ESDH "id-smime-alg-ESDH" -#define NID_id_smime_alg_ESDH 245 -#define OBJ_id_smime_alg_ESDH OBJ_id_smime_alg,5L - -#define SN_id_smime_alg_CMS3DESwrap "id-smime-alg-CMS3DESwrap" -#define NID_id_smime_alg_CMS3DESwrap 246 -#define OBJ_id_smime_alg_CMS3DESwrap OBJ_id_smime_alg,6L - -#define SN_id_smime_alg_CMSRC2wrap "id-smime-alg-CMSRC2wrap" -#define NID_id_smime_alg_CMSRC2wrap 247 -#define OBJ_id_smime_alg_CMSRC2wrap OBJ_id_smime_alg,7L - -#define SN_id_alg_PWRI_KEK "id-alg-PWRI-KEK" -#define NID_id_alg_PWRI_KEK 893 -#define OBJ_id_alg_PWRI_KEK OBJ_id_smime_alg,9L - -#define SN_id_smime_cd_ldap "id-smime-cd-ldap" -#define NID_id_smime_cd_ldap 248 -#define OBJ_id_smime_cd_ldap OBJ_id_smime_cd,1L - -#define SN_id_smime_spq_ets_sqt_uri "id-smime-spq-ets-sqt-uri" -#define NID_id_smime_spq_ets_sqt_uri 249 -#define OBJ_id_smime_spq_ets_sqt_uri OBJ_id_smime_spq,1L - -#define SN_id_smime_spq_ets_sqt_unotice "id-smime-spq-ets-sqt-unotice" -#define NID_id_smime_spq_ets_sqt_unotice 250 -#define OBJ_id_smime_spq_ets_sqt_unotice OBJ_id_smime_spq,2L - -#define SN_id_smime_cti_ets_proofOfOrigin "id-smime-cti-ets-proofOfOrigin" -#define NID_id_smime_cti_ets_proofOfOrigin 251 -#define OBJ_id_smime_cti_ets_proofOfOrigin OBJ_id_smime_cti,1L - -#define SN_id_smime_cti_ets_proofOfReceipt "id-smime-cti-ets-proofOfReceipt" -#define NID_id_smime_cti_ets_proofOfReceipt 252 -#define OBJ_id_smime_cti_ets_proofOfReceipt OBJ_id_smime_cti,2L - -#define SN_id_smime_cti_ets_proofOfDelivery "id-smime-cti-ets-proofOfDelivery" -#define NID_id_smime_cti_ets_proofOfDelivery 253 -#define OBJ_id_smime_cti_ets_proofOfDelivery OBJ_id_smime_cti,3L - -#define SN_id_smime_cti_ets_proofOfSender "id-smime-cti-ets-proofOfSender" -#define NID_id_smime_cti_ets_proofOfSender 254 -#define OBJ_id_smime_cti_ets_proofOfSender OBJ_id_smime_cti,4L - -#define SN_id_smime_cti_ets_proofOfApproval "id-smime-cti-ets-proofOfApproval" -#define NID_id_smime_cti_ets_proofOfApproval 255 -#define OBJ_id_smime_cti_ets_proofOfApproval OBJ_id_smime_cti,5L - -#define SN_id_smime_cti_ets_proofOfCreation "id-smime-cti-ets-proofOfCreation" -#define NID_id_smime_cti_ets_proofOfCreation 256 -#define OBJ_id_smime_cti_ets_proofOfCreation OBJ_id_smime_cti,6L - -#define LN_friendlyName "friendlyName" -#define NID_friendlyName 156 -#define OBJ_friendlyName OBJ_pkcs9,20L - -#define LN_localKeyID "localKeyID" -#define NID_localKeyID 157 -#define OBJ_localKeyID OBJ_pkcs9,21L - -#define SN_ms_csp_name "CSPName" -#define LN_ms_csp_name "Microsoft CSP Name" -#define NID_ms_csp_name 417 -#define OBJ_ms_csp_name 1L,3L,6L,1L,4L,1L,311L,17L,1L - -#define SN_LocalKeySet "LocalKeySet" -#define LN_LocalKeySet "Microsoft Local Key set" -#define NID_LocalKeySet 856 -#define OBJ_LocalKeySet 1L,3L,6L,1L,4L,1L,311L,17L,2L - -#define OBJ_certTypes OBJ_pkcs9,22L - -#define LN_x509Certificate "x509Certificate" -#define NID_x509Certificate 158 -#define OBJ_x509Certificate OBJ_certTypes,1L - -#define LN_sdsiCertificate "sdsiCertificate" -#define NID_sdsiCertificate 159 -#define OBJ_sdsiCertificate OBJ_certTypes,2L - -#define OBJ_crlTypes OBJ_pkcs9,23L - -#define LN_x509Crl "x509Crl" -#define NID_x509Crl 160 -#define OBJ_x509Crl OBJ_crlTypes,1L - -#define OBJ_pkcs12 OBJ_pkcs,12L - -#define OBJ_pkcs12_pbeids OBJ_pkcs12,1L - -#define SN_pbe_WithSHA1And128BitRC4 "PBE-SHA1-RC4-128" -#define LN_pbe_WithSHA1And128BitRC4 "pbeWithSHA1And128BitRC4" -#define NID_pbe_WithSHA1And128BitRC4 144 -#define OBJ_pbe_WithSHA1And128BitRC4 OBJ_pkcs12_pbeids,1L - -#define SN_pbe_WithSHA1And40BitRC4 "PBE-SHA1-RC4-40" -#define LN_pbe_WithSHA1And40BitRC4 "pbeWithSHA1And40BitRC4" -#define NID_pbe_WithSHA1And40BitRC4 145 -#define OBJ_pbe_WithSHA1And40BitRC4 OBJ_pkcs12_pbeids,2L - -#define SN_pbe_WithSHA1And3_Key_TripleDES_CBC "PBE-SHA1-3DES" -#define LN_pbe_WithSHA1And3_Key_TripleDES_CBC "pbeWithSHA1And3-KeyTripleDES-CBC" -#define NID_pbe_WithSHA1And3_Key_TripleDES_CBC 146 -#define OBJ_pbe_WithSHA1And3_Key_TripleDES_CBC OBJ_pkcs12_pbeids,3L - -#define SN_pbe_WithSHA1And2_Key_TripleDES_CBC "PBE-SHA1-2DES" -#define LN_pbe_WithSHA1And2_Key_TripleDES_CBC "pbeWithSHA1And2-KeyTripleDES-CBC" -#define NID_pbe_WithSHA1And2_Key_TripleDES_CBC 147 -#define OBJ_pbe_WithSHA1And2_Key_TripleDES_CBC OBJ_pkcs12_pbeids,4L - -#define SN_pbe_WithSHA1And128BitRC2_CBC "PBE-SHA1-RC2-128" -#define LN_pbe_WithSHA1And128BitRC2_CBC "pbeWithSHA1And128BitRC2-CBC" -#define NID_pbe_WithSHA1And128BitRC2_CBC 148 -#define OBJ_pbe_WithSHA1And128BitRC2_CBC OBJ_pkcs12_pbeids,5L - -#define SN_pbe_WithSHA1And40BitRC2_CBC "PBE-SHA1-RC2-40" -#define LN_pbe_WithSHA1And40BitRC2_CBC "pbeWithSHA1And40BitRC2-CBC" -#define NID_pbe_WithSHA1And40BitRC2_CBC 149 -#define OBJ_pbe_WithSHA1And40BitRC2_CBC OBJ_pkcs12_pbeids,6L - -#define OBJ_pkcs12_Version1 OBJ_pkcs12,10L - -#define OBJ_pkcs12_BagIds OBJ_pkcs12_Version1,1L - -#define LN_keyBag "keyBag" -#define NID_keyBag 150 -#define OBJ_keyBag OBJ_pkcs12_BagIds,1L - -#define LN_pkcs8ShroudedKeyBag "pkcs8ShroudedKeyBag" -#define NID_pkcs8ShroudedKeyBag 151 -#define OBJ_pkcs8ShroudedKeyBag OBJ_pkcs12_BagIds,2L - -#define LN_certBag "certBag" -#define NID_certBag 152 -#define OBJ_certBag OBJ_pkcs12_BagIds,3L - -#define LN_crlBag "crlBag" -#define NID_crlBag 153 -#define OBJ_crlBag OBJ_pkcs12_BagIds,4L - -#define LN_secretBag "secretBag" -#define NID_secretBag 154 -#define OBJ_secretBag OBJ_pkcs12_BagIds,5L - -#define LN_safeContentsBag "safeContentsBag" -#define NID_safeContentsBag 155 -#define OBJ_safeContentsBag OBJ_pkcs12_BagIds,6L - -#define SN_md2 "MD2" -#define LN_md2 "md2" -#define NID_md2 3 -#define OBJ_md2 OBJ_rsadsi,2L,2L - -#define SN_md4 "MD4" -#define LN_md4 "md4" -#define NID_md4 257 -#define OBJ_md4 OBJ_rsadsi,2L,4L - -#define SN_md5 "MD5" -#define LN_md5 "md5" -#define NID_md5 4 -#define OBJ_md5 OBJ_rsadsi,2L,5L - -#define SN_md5_sha1 "MD5-SHA1" -#define LN_md5_sha1 "md5-sha1" -#define NID_md5_sha1 114 - -#define LN_hmacWithMD5 "hmacWithMD5" -#define NID_hmacWithMD5 797 -#define OBJ_hmacWithMD5 OBJ_rsadsi,2L,6L - -#define LN_hmacWithSHA1 "hmacWithSHA1" -#define NID_hmacWithSHA1 163 -#define OBJ_hmacWithSHA1 OBJ_rsadsi,2L,7L - -#define LN_hmacWithSHA224 "hmacWithSHA224" -#define NID_hmacWithSHA224 798 -#define OBJ_hmacWithSHA224 OBJ_rsadsi,2L,8L - -#define LN_hmacWithSHA256 "hmacWithSHA256" -#define NID_hmacWithSHA256 799 -#define OBJ_hmacWithSHA256 OBJ_rsadsi,2L,9L - -#define LN_hmacWithSHA384 "hmacWithSHA384" -#define NID_hmacWithSHA384 800 -#define OBJ_hmacWithSHA384 OBJ_rsadsi,2L,10L - -#define LN_hmacWithSHA512 "hmacWithSHA512" -#define NID_hmacWithSHA512 801 -#define OBJ_hmacWithSHA512 OBJ_rsadsi,2L,11L - -#define SN_rc2_cbc "RC2-CBC" -#define LN_rc2_cbc "rc2-cbc" -#define NID_rc2_cbc 37 -#define OBJ_rc2_cbc OBJ_rsadsi,3L,2L - -#define SN_rc2_ecb "RC2-ECB" -#define LN_rc2_ecb "rc2-ecb" -#define NID_rc2_ecb 38 - -#define SN_rc2_cfb64 "RC2-CFB" -#define LN_rc2_cfb64 "rc2-cfb" -#define NID_rc2_cfb64 39 - -#define SN_rc2_ofb64 "RC2-OFB" -#define LN_rc2_ofb64 "rc2-ofb" -#define NID_rc2_ofb64 40 - -#define SN_rc2_40_cbc "RC2-40-CBC" -#define LN_rc2_40_cbc "rc2-40-cbc" -#define NID_rc2_40_cbc 98 - -#define SN_rc2_64_cbc "RC2-64-CBC" -#define LN_rc2_64_cbc "rc2-64-cbc" -#define NID_rc2_64_cbc 166 - -#define SN_rc4 "RC4" -#define LN_rc4 "rc4" -#define NID_rc4 5 -#define OBJ_rc4 OBJ_rsadsi,3L,4L - -#define SN_rc4_40 "RC4-40" -#define LN_rc4_40 "rc4-40" -#define NID_rc4_40 97 - -#define SN_des_ede3_cbc "DES-EDE3-CBC" -#define LN_des_ede3_cbc "des-ede3-cbc" -#define NID_des_ede3_cbc 44 -#define OBJ_des_ede3_cbc OBJ_rsadsi,3L,7L - -#define SN_rc5_cbc "RC5-CBC" -#define LN_rc5_cbc "rc5-cbc" -#define NID_rc5_cbc 120 -#define OBJ_rc5_cbc OBJ_rsadsi,3L,8L - -#define SN_rc5_ecb "RC5-ECB" -#define LN_rc5_ecb "rc5-ecb" -#define NID_rc5_ecb 121 - -#define SN_rc5_cfb64 "RC5-CFB" -#define LN_rc5_cfb64 "rc5-cfb" -#define NID_rc5_cfb64 122 - -#define SN_rc5_ofb64 "RC5-OFB" -#define LN_rc5_ofb64 "rc5-ofb" -#define NID_rc5_ofb64 123 - -#define SN_ms_ext_req "msExtReq" -#define LN_ms_ext_req "Microsoft Extension Request" -#define NID_ms_ext_req 171 -#define OBJ_ms_ext_req 1L,3L,6L,1L,4L,1L,311L,2L,1L,14L - -#define SN_ms_code_ind "msCodeInd" -#define LN_ms_code_ind "Microsoft Individual Code Signing" -#define NID_ms_code_ind 134 -#define OBJ_ms_code_ind 1L,3L,6L,1L,4L,1L,311L,2L,1L,21L - -#define SN_ms_code_com "msCodeCom" -#define LN_ms_code_com "Microsoft Commercial Code Signing" -#define NID_ms_code_com 135 -#define OBJ_ms_code_com 1L,3L,6L,1L,4L,1L,311L,2L,1L,22L - -#define SN_ms_ctl_sign "msCTLSign" -#define LN_ms_ctl_sign "Microsoft Trust List Signing" -#define NID_ms_ctl_sign 136 -#define OBJ_ms_ctl_sign 1L,3L,6L,1L,4L,1L,311L,10L,3L,1L - -#define SN_ms_sgc "msSGC" -#define LN_ms_sgc "Microsoft Server Gated Crypto" -#define NID_ms_sgc 137 -#define OBJ_ms_sgc 1L,3L,6L,1L,4L,1L,311L,10L,3L,3L - -#define SN_ms_efs "msEFS" -#define LN_ms_efs "Microsoft Encrypted File System" -#define NID_ms_efs 138 -#define OBJ_ms_efs 1L,3L,6L,1L,4L,1L,311L,10L,3L,4L - -#define SN_ms_smartcard_login "msSmartcardLogin" -#define LN_ms_smartcard_login "Microsoft Smartcardlogin" -#define NID_ms_smartcard_login 648 -#define OBJ_ms_smartcard_login 1L,3L,6L,1L,4L,1L,311L,20L,2L,2L - -#define SN_ms_upn "msUPN" -#define LN_ms_upn "Microsoft Universal Principal Name" -#define NID_ms_upn 649 -#define OBJ_ms_upn 1L,3L,6L,1L,4L,1L,311L,20L,2L,3L - -#define SN_idea_cbc "IDEA-CBC" -#define LN_idea_cbc "idea-cbc" -#define NID_idea_cbc 34 -#define OBJ_idea_cbc 1L,3L,6L,1L,4L,1L,188L,7L,1L,1L,2L - -#define SN_idea_ecb "IDEA-ECB" -#define LN_idea_ecb "idea-ecb" -#define NID_idea_ecb 36 - -#define SN_idea_cfb64 "IDEA-CFB" -#define LN_idea_cfb64 "idea-cfb" -#define NID_idea_cfb64 35 - -#define SN_idea_ofb64 "IDEA-OFB" -#define LN_idea_ofb64 "idea-ofb" -#define NID_idea_ofb64 46 - -#define SN_bf_cbc "BF-CBC" -#define LN_bf_cbc "bf-cbc" -#define NID_bf_cbc 91 -#define OBJ_bf_cbc 1L,3L,6L,1L,4L,1L,3029L,1L,2L - -#define SN_bf_ecb "BF-ECB" -#define LN_bf_ecb "bf-ecb" -#define NID_bf_ecb 92 - -#define SN_bf_cfb64 "BF-CFB" -#define LN_bf_cfb64 "bf-cfb" -#define NID_bf_cfb64 93 - -#define SN_bf_ofb64 "BF-OFB" -#define LN_bf_ofb64 "bf-ofb" -#define NID_bf_ofb64 94 - -#define SN_id_pkix "PKIX" -#define NID_id_pkix 127 -#define OBJ_id_pkix 1L,3L,6L,1L,5L,5L,7L - -#define SN_id_pkix_mod "id-pkix-mod" -#define NID_id_pkix_mod 258 -#define OBJ_id_pkix_mod OBJ_id_pkix,0L - -#define SN_id_pe "id-pe" -#define NID_id_pe 175 -#define OBJ_id_pe OBJ_id_pkix,1L - -#define SN_id_qt "id-qt" -#define NID_id_qt 259 -#define OBJ_id_qt OBJ_id_pkix,2L - -#define SN_id_kp "id-kp" -#define NID_id_kp 128 -#define OBJ_id_kp OBJ_id_pkix,3L - -#define SN_id_it "id-it" -#define NID_id_it 260 -#define OBJ_id_it OBJ_id_pkix,4L - -#define SN_id_pkip "id-pkip" -#define NID_id_pkip 261 -#define OBJ_id_pkip OBJ_id_pkix,5L - -#define SN_id_alg "id-alg" -#define NID_id_alg 262 -#define OBJ_id_alg OBJ_id_pkix,6L - -#define SN_id_cmc "id-cmc" -#define NID_id_cmc 263 -#define OBJ_id_cmc OBJ_id_pkix,7L - -#define SN_id_on "id-on" -#define NID_id_on 264 -#define OBJ_id_on OBJ_id_pkix,8L - -#define SN_id_pda "id-pda" -#define NID_id_pda 265 -#define OBJ_id_pda OBJ_id_pkix,9L - -#define SN_id_aca "id-aca" -#define NID_id_aca 266 -#define OBJ_id_aca OBJ_id_pkix,10L - -#define SN_id_qcs "id-qcs" -#define NID_id_qcs 267 -#define OBJ_id_qcs OBJ_id_pkix,11L - -#define SN_id_cct "id-cct" -#define NID_id_cct 268 -#define OBJ_id_cct OBJ_id_pkix,12L - -#define SN_id_ppl "id-ppl" -#define NID_id_ppl 662 -#define OBJ_id_ppl OBJ_id_pkix,21L - -#define SN_id_ad "id-ad" -#define NID_id_ad 176 -#define OBJ_id_ad OBJ_id_pkix,48L - -#define SN_id_pkix1_explicit_88 "id-pkix1-explicit-88" -#define NID_id_pkix1_explicit_88 269 -#define OBJ_id_pkix1_explicit_88 OBJ_id_pkix_mod,1L - -#define SN_id_pkix1_implicit_88 "id-pkix1-implicit-88" -#define NID_id_pkix1_implicit_88 270 -#define OBJ_id_pkix1_implicit_88 OBJ_id_pkix_mod,2L - -#define SN_id_pkix1_explicit_93 "id-pkix1-explicit-93" -#define NID_id_pkix1_explicit_93 271 -#define OBJ_id_pkix1_explicit_93 OBJ_id_pkix_mod,3L - -#define SN_id_pkix1_implicit_93 "id-pkix1-implicit-93" -#define NID_id_pkix1_implicit_93 272 -#define OBJ_id_pkix1_implicit_93 OBJ_id_pkix_mod,4L - -#define SN_id_mod_crmf "id-mod-crmf" -#define NID_id_mod_crmf 273 -#define OBJ_id_mod_crmf OBJ_id_pkix_mod,5L - -#define SN_id_mod_cmc "id-mod-cmc" -#define NID_id_mod_cmc 274 -#define OBJ_id_mod_cmc OBJ_id_pkix_mod,6L - -#define SN_id_mod_kea_profile_88 "id-mod-kea-profile-88" -#define NID_id_mod_kea_profile_88 275 -#define OBJ_id_mod_kea_profile_88 OBJ_id_pkix_mod,7L - -#define SN_id_mod_kea_profile_93 "id-mod-kea-profile-93" -#define NID_id_mod_kea_profile_93 276 -#define OBJ_id_mod_kea_profile_93 OBJ_id_pkix_mod,8L - -#define SN_id_mod_cmp "id-mod-cmp" -#define NID_id_mod_cmp 277 -#define OBJ_id_mod_cmp OBJ_id_pkix_mod,9L - -#define SN_id_mod_qualified_cert_88 "id-mod-qualified-cert-88" -#define NID_id_mod_qualified_cert_88 278 -#define OBJ_id_mod_qualified_cert_88 OBJ_id_pkix_mod,10L - -#define SN_id_mod_qualified_cert_93 "id-mod-qualified-cert-93" -#define NID_id_mod_qualified_cert_93 279 -#define OBJ_id_mod_qualified_cert_93 OBJ_id_pkix_mod,11L - -#define SN_id_mod_attribute_cert "id-mod-attribute-cert" -#define NID_id_mod_attribute_cert 280 -#define OBJ_id_mod_attribute_cert OBJ_id_pkix_mod,12L - -#define SN_id_mod_timestamp_protocol "id-mod-timestamp-protocol" -#define NID_id_mod_timestamp_protocol 281 -#define OBJ_id_mod_timestamp_protocol OBJ_id_pkix_mod,13L - -#define SN_id_mod_ocsp "id-mod-ocsp" -#define NID_id_mod_ocsp 282 -#define OBJ_id_mod_ocsp OBJ_id_pkix_mod,14L - -#define SN_id_mod_dvcs "id-mod-dvcs" -#define NID_id_mod_dvcs 283 -#define OBJ_id_mod_dvcs OBJ_id_pkix_mod,15L - -#define SN_id_mod_cmp2000 "id-mod-cmp2000" -#define NID_id_mod_cmp2000 284 -#define OBJ_id_mod_cmp2000 OBJ_id_pkix_mod,16L - -#define SN_info_access "authorityInfoAccess" -#define LN_info_access "Authority Information Access" -#define NID_info_access 177 -#define OBJ_info_access OBJ_id_pe,1L - -#define SN_biometricInfo "biometricInfo" -#define LN_biometricInfo "Biometric Info" -#define NID_biometricInfo 285 -#define OBJ_biometricInfo OBJ_id_pe,2L - -#define SN_qcStatements "qcStatements" -#define NID_qcStatements 286 -#define OBJ_qcStatements OBJ_id_pe,3L - -#define SN_ac_auditEntity "ac-auditEntity" -#define NID_ac_auditEntity 287 -#define OBJ_ac_auditEntity OBJ_id_pe,4L - -#define SN_ac_targeting "ac-targeting" -#define NID_ac_targeting 288 -#define OBJ_ac_targeting OBJ_id_pe,5L - -#define SN_aaControls "aaControls" -#define NID_aaControls 289 -#define OBJ_aaControls OBJ_id_pe,6L - -#define SN_sbgp_ipAddrBlock "sbgp-ipAddrBlock" -#define NID_sbgp_ipAddrBlock 290 -#define OBJ_sbgp_ipAddrBlock OBJ_id_pe,7L - -#define SN_sbgp_autonomousSysNum "sbgp-autonomousSysNum" -#define NID_sbgp_autonomousSysNum 291 -#define OBJ_sbgp_autonomousSysNum OBJ_id_pe,8L - -#define SN_sbgp_routerIdentifier "sbgp-routerIdentifier" -#define NID_sbgp_routerIdentifier 292 -#define OBJ_sbgp_routerIdentifier OBJ_id_pe,9L - -#define SN_ac_proxying "ac-proxying" -#define NID_ac_proxying 397 -#define OBJ_ac_proxying OBJ_id_pe,10L - -#define SN_sinfo_access "subjectInfoAccess" -#define LN_sinfo_access "Subject Information Access" -#define NID_sinfo_access 398 -#define OBJ_sinfo_access OBJ_id_pe,11L - -#define SN_proxyCertInfo "proxyCertInfo" -#define LN_proxyCertInfo "Proxy Certificate Information" -#define NID_proxyCertInfo 663 -#define OBJ_proxyCertInfo OBJ_id_pe,14L - -#define SN_id_qt_cps "id-qt-cps" -#define LN_id_qt_cps "Policy Qualifier CPS" -#define NID_id_qt_cps 164 -#define OBJ_id_qt_cps OBJ_id_qt,1L - -#define SN_id_qt_unotice "id-qt-unotice" -#define LN_id_qt_unotice "Policy Qualifier User Notice" -#define NID_id_qt_unotice 165 -#define OBJ_id_qt_unotice OBJ_id_qt,2L - -#define SN_textNotice "textNotice" -#define NID_textNotice 293 -#define OBJ_textNotice OBJ_id_qt,3L - -#define SN_server_auth "serverAuth" -#define LN_server_auth "TLS Web Server Authentication" -#define NID_server_auth 129 -#define OBJ_server_auth OBJ_id_kp,1L - -#define SN_client_auth "clientAuth" -#define LN_client_auth "TLS Web Client Authentication" -#define NID_client_auth 130 -#define OBJ_client_auth OBJ_id_kp,2L - -#define SN_code_sign "codeSigning" -#define LN_code_sign "Code Signing" -#define NID_code_sign 131 -#define OBJ_code_sign OBJ_id_kp,3L - -#define SN_email_protect "emailProtection" -#define LN_email_protect "E-mail Protection" -#define NID_email_protect 132 -#define OBJ_email_protect OBJ_id_kp,4L - -#define SN_ipsecEndSystem "ipsecEndSystem" -#define LN_ipsecEndSystem "IPSec End System" -#define NID_ipsecEndSystem 294 -#define OBJ_ipsecEndSystem OBJ_id_kp,5L - -#define SN_ipsecTunnel "ipsecTunnel" -#define LN_ipsecTunnel "IPSec Tunnel" -#define NID_ipsecTunnel 295 -#define OBJ_ipsecTunnel OBJ_id_kp,6L - -#define SN_ipsecUser "ipsecUser" -#define LN_ipsecUser "IPSec User" -#define NID_ipsecUser 296 -#define OBJ_ipsecUser OBJ_id_kp,7L - -#define SN_time_stamp "timeStamping" -#define LN_time_stamp "Time Stamping" -#define NID_time_stamp 133 -#define OBJ_time_stamp OBJ_id_kp,8L - -#define SN_OCSP_sign "OCSPSigning" -#define LN_OCSP_sign "OCSP Signing" -#define NID_OCSP_sign 180 -#define OBJ_OCSP_sign OBJ_id_kp,9L - -#define SN_dvcs "DVCS" -#define LN_dvcs "dvcs" -#define NID_dvcs 297 -#define OBJ_dvcs OBJ_id_kp,10L - -#define SN_id_it_caProtEncCert "id-it-caProtEncCert" -#define NID_id_it_caProtEncCert 298 -#define OBJ_id_it_caProtEncCert OBJ_id_it,1L - -#define SN_id_it_signKeyPairTypes "id-it-signKeyPairTypes" -#define NID_id_it_signKeyPairTypes 299 -#define OBJ_id_it_signKeyPairTypes OBJ_id_it,2L - -#define SN_id_it_encKeyPairTypes "id-it-encKeyPairTypes" -#define NID_id_it_encKeyPairTypes 300 -#define OBJ_id_it_encKeyPairTypes OBJ_id_it,3L - -#define SN_id_it_preferredSymmAlg "id-it-preferredSymmAlg" -#define NID_id_it_preferredSymmAlg 301 -#define OBJ_id_it_preferredSymmAlg OBJ_id_it,4L - -#define SN_id_it_caKeyUpdateInfo "id-it-caKeyUpdateInfo" -#define NID_id_it_caKeyUpdateInfo 302 -#define OBJ_id_it_caKeyUpdateInfo OBJ_id_it,5L - -#define SN_id_it_currentCRL "id-it-currentCRL" -#define NID_id_it_currentCRL 303 -#define OBJ_id_it_currentCRL OBJ_id_it,6L - -#define SN_id_it_unsupportedOIDs "id-it-unsupportedOIDs" -#define NID_id_it_unsupportedOIDs 304 -#define OBJ_id_it_unsupportedOIDs OBJ_id_it,7L - -#define SN_id_it_subscriptionRequest "id-it-subscriptionRequest" -#define NID_id_it_subscriptionRequest 305 -#define OBJ_id_it_subscriptionRequest OBJ_id_it,8L - -#define SN_id_it_subscriptionResponse "id-it-subscriptionResponse" -#define NID_id_it_subscriptionResponse 306 -#define OBJ_id_it_subscriptionResponse OBJ_id_it,9L - -#define SN_id_it_keyPairParamReq "id-it-keyPairParamReq" -#define NID_id_it_keyPairParamReq 307 -#define OBJ_id_it_keyPairParamReq OBJ_id_it,10L - -#define SN_id_it_keyPairParamRep "id-it-keyPairParamRep" -#define NID_id_it_keyPairParamRep 308 -#define OBJ_id_it_keyPairParamRep OBJ_id_it,11L - -#define SN_id_it_revPassphrase "id-it-revPassphrase" -#define NID_id_it_revPassphrase 309 -#define OBJ_id_it_revPassphrase OBJ_id_it,12L - -#define SN_id_it_implicitConfirm "id-it-implicitConfirm" -#define NID_id_it_implicitConfirm 310 -#define OBJ_id_it_implicitConfirm OBJ_id_it,13L - -#define SN_id_it_confirmWaitTime "id-it-confirmWaitTime" -#define NID_id_it_confirmWaitTime 311 -#define OBJ_id_it_confirmWaitTime OBJ_id_it,14L - -#define SN_id_it_origPKIMessage "id-it-origPKIMessage" -#define NID_id_it_origPKIMessage 312 -#define OBJ_id_it_origPKIMessage OBJ_id_it,15L - -#define SN_id_it_suppLangTags "id-it-suppLangTags" -#define NID_id_it_suppLangTags 784 -#define OBJ_id_it_suppLangTags OBJ_id_it,16L - -#define SN_id_regCtrl "id-regCtrl" -#define NID_id_regCtrl 313 -#define OBJ_id_regCtrl OBJ_id_pkip,1L - -#define SN_id_regInfo "id-regInfo" -#define NID_id_regInfo 314 -#define OBJ_id_regInfo OBJ_id_pkip,2L - -#define SN_id_regCtrl_regToken "id-regCtrl-regToken" -#define NID_id_regCtrl_regToken 315 -#define OBJ_id_regCtrl_regToken OBJ_id_regCtrl,1L - -#define SN_id_regCtrl_authenticator "id-regCtrl-authenticator" -#define NID_id_regCtrl_authenticator 316 -#define OBJ_id_regCtrl_authenticator OBJ_id_regCtrl,2L - -#define SN_id_regCtrl_pkiPublicationInfo "id-regCtrl-pkiPublicationInfo" -#define NID_id_regCtrl_pkiPublicationInfo 317 -#define OBJ_id_regCtrl_pkiPublicationInfo OBJ_id_regCtrl,3L - -#define SN_id_regCtrl_pkiArchiveOptions "id-regCtrl-pkiArchiveOptions" -#define NID_id_regCtrl_pkiArchiveOptions 318 -#define OBJ_id_regCtrl_pkiArchiveOptions OBJ_id_regCtrl,4L - -#define SN_id_regCtrl_oldCertID "id-regCtrl-oldCertID" -#define NID_id_regCtrl_oldCertID 319 -#define OBJ_id_regCtrl_oldCertID OBJ_id_regCtrl,5L - -#define SN_id_regCtrl_protocolEncrKey "id-regCtrl-protocolEncrKey" -#define NID_id_regCtrl_protocolEncrKey 320 -#define OBJ_id_regCtrl_protocolEncrKey OBJ_id_regCtrl,6L - -#define SN_id_regInfo_utf8Pairs "id-regInfo-utf8Pairs" -#define NID_id_regInfo_utf8Pairs 321 -#define OBJ_id_regInfo_utf8Pairs OBJ_id_regInfo,1L - -#define SN_id_regInfo_certReq "id-regInfo-certReq" -#define NID_id_regInfo_certReq 322 -#define OBJ_id_regInfo_certReq OBJ_id_regInfo,2L - -#define SN_id_alg_des40 "id-alg-des40" -#define NID_id_alg_des40 323 -#define OBJ_id_alg_des40 OBJ_id_alg,1L - -#define SN_id_alg_noSignature "id-alg-noSignature" -#define NID_id_alg_noSignature 324 -#define OBJ_id_alg_noSignature OBJ_id_alg,2L - -#define SN_id_alg_dh_sig_hmac_sha1 "id-alg-dh-sig-hmac-sha1" -#define NID_id_alg_dh_sig_hmac_sha1 325 -#define OBJ_id_alg_dh_sig_hmac_sha1 OBJ_id_alg,3L - -#define SN_id_alg_dh_pop "id-alg-dh-pop" -#define NID_id_alg_dh_pop 326 -#define OBJ_id_alg_dh_pop OBJ_id_alg,4L - -#define SN_id_cmc_statusInfo "id-cmc-statusInfo" -#define NID_id_cmc_statusInfo 327 -#define OBJ_id_cmc_statusInfo OBJ_id_cmc,1L - -#define SN_id_cmc_identification "id-cmc-identification" -#define NID_id_cmc_identification 328 -#define OBJ_id_cmc_identification OBJ_id_cmc,2L - -#define SN_id_cmc_identityProof "id-cmc-identityProof" -#define NID_id_cmc_identityProof 329 -#define OBJ_id_cmc_identityProof OBJ_id_cmc,3L - -#define SN_id_cmc_dataReturn "id-cmc-dataReturn" -#define NID_id_cmc_dataReturn 330 -#define OBJ_id_cmc_dataReturn OBJ_id_cmc,4L - -#define SN_id_cmc_transactionId "id-cmc-transactionId" -#define NID_id_cmc_transactionId 331 -#define OBJ_id_cmc_transactionId OBJ_id_cmc,5L - -#define SN_id_cmc_senderNonce "id-cmc-senderNonce" -#define NID_id_cmc_senderNonce 332 -#define OBJ_id_cmc_senderNonce OBJ_id_cmc,6L - -#define SN_id_cmc_recipientNonce "id-cmc-recipientNonce" -#define NID_id_cmc_recipientNonce 333 -#define OBJ_id_cmc_recipientNonce OBJ_id_cmc,7L - -#define SN_id_cmc_addExtensions "id-cmc-addExtensions" -#define NID_id_cmc_addExtensions 334 -#define OBJ_id_cmc_addExtensions OBJ_id_cmc,8L - -#define SN_id_cmc_encryptedPOP "id-cmc-encryptedPOP" -#define NID_id_cmc_encryptedPOP 335 -#define OBJ_id_cmc_encryptedPOP OBJ_id_cmc,9L - -#define SN_id_cmc_decryptedPOP "id-cmc-decryptedPOP" -#define NID_id_cmc_decryptedPOP 336 -#define OBJ_id_cmc_decryptedPOP OBJ_id_cmc,10L - -#define SN_id_cmc_lraPOPWitness "id-cmc-lraPOPWitness" -#define NID_id_cmc_lraPOPWitness 337 -#define OBJ_id_cmc_lraPOPWitness OBJ_id_cmc,11L - -#define SN_id_cmc_getCert "id-cmc-getCert" -#define NID_id_cmc_getCert 338 -#define OBJ_id_cmc_getCert OBJ_id_cmc,15L - -#define SN_id_cmc_getCRL "id-cmc-getCRL" -#define NID_id_cmc_getCRL 339 -#define OBJ_id_cmc_getCRL OBJ_id_cmc,16L - -#define SN_id_cmc_revokeRequest "id-cmc-revokeRequest" -#define NID_id_cmc_revokeRequest 340 -#define OBJ_id_cmc_revokeRequest OBJ_id_cmc,17L - -#define SN_id_cmc_regInfo "id-cmc-regInfo" -#define NID_id_cmc_regInfo 341 -#define OBJ_id_cmc_regInfo OBJ_id_cmc,18L - -#define SN_id_cmc_responseInfo "id-cmc-responseInfo" -#define NID_id_cmc_responseInfo 342 -#define OBJ_id_cmc_responseInfo OBJ_id_cmc,19L - -#define SN_id_cmc_queryPending "id-cmc-queryPending" -#define NID_id_cmc_queryPending 343 -#define OBJ_id_cmc_queryPending OBJ_id_cmc,21L - -#define SN_id_cmc_popLinkRandom "id-cmc-popLinkRandom" -#define NID_id_cmc_popLinkRandom 344 -#define OBJ_id_cmc_popLinkRandom OBJ_id_cmc,22L - -#define SN_id_cmc_popLinkWitness "id-cmc-popLinkWitness" -#define NID_id_cmc_popLinkWitness 345 -#define OBJ_id_cmc_popLinkWitness OBJ_id_cmc,23L - -#define SN_id_cmc_confirmCertAcceptance "id-cmc-confirmCertAcceptance" -#define NID_id_cmc_confirmCertAcceptance 346 -#define OBJ_id_cmc_confirmCertAcceptance OBJ_id_cmc,24L - -#define SN_id_on_personalData "id-on-personalData" -#define NID_id_on_personalData 347 -#define OBJ_id_on_personalData OBJ_id_on,1L - -#define SN_id_on_permanentIdentifier "id-on-permanentIdentifier" -#define LN_id_on_permanentIdentifier "Permanent Identifier" -#define NID_id_on_permanentIdentifier 858 -#define OBJ_id_on_permanentIdentifier OBJ_id_on,3L - -#define SN_id_pda_dateOfBirth "id-pda-dateOfBirth" -#define NID_id_pda_dateOfBirth 348 -#define OBJ_id_pda_dateOfBirth OBJ_id_pda,1L - -#define SN_id_pda_placeOfBirth "id-pda-placeOfBirth" -#define NID_id_pda_placeOfBirth 349 -#define OBJ_id_pda_placeOfBirth OBJ_id_pda,2L - -#define SN_id_pda_gender "id-pda-gender" -#define NID_id_pda_gender 351 -#define OBJ_id_pda_gender OBJ_id_pda,3L - -#define SN_id_pda_countryOfCitizenship "id-pda-countryOfCitizenship" -#define NID_id_pda_countryOfCitizenship 352 -#define OBJ_id_pda_countryOfCitizenship OBJ_id_pda,4L - -#define SN_id_pda_countryOfResidence "id-pda-countryOfResidence" -#define NID_id_pda_countryOfResidence 353 -#define OBJ_id_pda_countryOfResidence OBJ_id_pda,5L - -#define SN_id_aca_authenticationInfo "id-aca-authenticationInfo" -#define NID_id_aca_authenticationInfo 354 -#define OBJ_id_aca_authenticationInfo OBJ_id_aca,1L - -#define SN_id_aca_accessIdentity "id-aca-accessIdentity" -#define NID_id_aca_accessIdentity 355 -#define OBJ_id_aca_accessIdentity OBJ_id_aca,2L - -#define SN_id_aca_chargingIdentity "id-aca-chargingIdentity" -#define NID_id_aca_chargingIdentity 356 -#define OBJ_id_aca_chargingIdentity OBJ_id_aca,3L - -#define SN_id_aca_group "id-aca-group" -#define NID_id_aca_group 357 -#define OBJ_id_aca_group OBJ_id_aca,4L - -#define SN_id_aca_role "id-aca-role" -#define NID_id_aca_role 358 -#define OBJ_id_aca_role OBJ_id_aca,5L - -#define SN_id_aca_encAttrs "id-aca-encAttrs" -#define NID_id_aca_encAttrs 399 -#define OBJ_id_aca_encAttrs OBJ_id_aca,6L - -#define SN_id_qcs_pkixQCSyntax_v1 "id-qcs-pkixQCSyntax-v1" -#define NID_id_qcs_pkixQCSyntax_v1 359 -#define OBJ_id_qcs_pkixQCSyntax_v1 OBJ_id_qcs,1L - -#define SN_id_cct_crs "id-cct-crs" -#define NID_id_cct_crs 360 -#define OBJ_id_cct_crs OBJ_id_cct,1L - -#define SN_id_cct_PKIData "id-cct-PKIData" -#define NID_id_cct_PKIData 361 -#define OBJ_id_cct_PKIData OBJ_id_cct,2L - -#define SN_id_cct_PKIResponse "id-cct-PKIResponse" -#define NID_id_cct_PKIResponse 362 -#define OBJ_id_cct_PKIResponse OBJ_id_cct,3L - -#define SN_id_ppl_anyLanguage "id-ppl-anyLanguage" -#define LN_id_ppl_anyLanguage "Any language" -#define NID_id_ppl_anyLanguage 664 -#define OBJ_id_ppl_anyLanguage OBJ_id_ppl,0L - -#define SN_id_ppl_inheritAll "id-ppl-inheritAll" -#define LN_id_ppl_inheritAll "Inherit all" -#define NID_id_ppl_inheritAll 665 -#define OBJ_id_ppl_inheritAll OBJ_id_ppl,1L - -#define SN_Independent "id-ppl-independent" -#define LN_Independent "Independent" -#define NID_Independent 667 -#define OBJ_Independent OBJ_id_ppl,2L - -#define SN_ad_OCSP "OCSP" -#define LN_ad_OCSP "OCSP" -#define NID_ad_OCSP 178 -#define OBJ_ad_OCSP OBJ_id_ad,1L - -#define SN_ad_ca_issuers "caIssuers" -#define LN_ad_ca_issuers "CA Issuers" -#define NID_ad_ca_issuers 179 -#define OBJ_ad_ca_issuers OBJ_id_ad,2L - -#define SN_ad_timeStamping "ad_timestamping" -#define LN_ad_timeStamping "AD Time Stamping" -#define NID_ad_timeStamping 363 -#define OBJ_ad_timeStamping OBJ_id_ad,3L - -#define SN_ad_dvcs "AD_DVCS" -#define LN_ad_dvcs "ad dvcs" -#define NID_ad_dvcs 364 -#define OBJ_ad_dvcs OBJ_id_ad,4L - -#define SN_caRepository "caRepository" -#define LN_caRepository "CA Repository" -#define NID_caRepository 785 -#define OBJ_caRepository OBJ_id_ad,5L - -#define OBJ_id_pkix_OCSP OBJ_ad_OCSP - -#define SN_id_pkix_OCSP_basic "basicOCSPResponse" -#define LN_id_pkix_OCSP_basic "Basic OCSP Response" -#define NID_id_pkix_OCSP_basic 365 -#define OBJ_id_pkix_OCSP_basic OBJ_id_pkix_OCSP,1L - -#define SN_id_pkix_OCSP_Nonce "Nonce" -#define LN_id_pkix_OCSP_Nonce "OCSP Nonce" -#define NID_id_pkix_OCSP_Nonce 366 -#define OBJ_id_pkix_OCSP_Nonce OBJ_id_pkix_OCSP,2L - -#define SN_id_pkix_OCSP_CrlID "CrlID" -#define LN_id_pkix_OCSP_CrlID "OCSP CRL ID" -#define NID_id_pkix_OCSP_CrlID 367 -#define OBJ_id_pkix_OCSP_CrlID OBJ_id_pkix_OCSP,3L - -#define SN_id_pkix_OCSP_acceptableResponses "acceptableResponses" -#define LN_id_pkix_OCSP_acceptableResponses "Acceptable OCSP Responses" -#define NID_id_pkix_OCSP_acceptableResponses 368 -#define OBJ_id_pkix_OCSP_acceptableResponses OBJ_id_pkix_OCSP,4L - -#define SN_id_pkix_OCSP_noCheck "noCheck" -#define LN_id_pkix_OCSP_noCheck "OCSP No Check" -#define NID_id_pkix_OCSP_noCheck 369 -#define OBJ_id_pkix_OCSP_noCheck OBJ_id_pkix_OCSP,5L - -#define SN_id_pkix_OCSP_archiveCutoff "archiveCutoff" -#define LN_id_pkix_OCSP_archiveCutoff "OCSP Archive Cutoff" -#define NID_id_pkix_OCSP_archiveCutoff 370 -#define OBJ_id_pkix_OCSP_archiveCutoff OBJ_id_pkix_OCSP,6L - -#define SN_id_pkix_OCSP_serviceLocator "serviceLocator" -#define LN_id_pkix_OCSP_serviceLocator "OCSP Service Locator" -#define NID_id_pkix_OCSP_serviceLocator 371 -#define OBJ_id_pkix_OCSP_serviceLocator OBJ_id_pkix_OCSP,7L - -#define SN_id_pkix_OCSP_extendedStatus "extendedStatus" -#define LN_id_pkix_OCSP_extendedStatus "Extended OCSP Status" -#define NID_id_pkix_OCSP_extendedStatus 372 -#define OBJ_id_pkix_OCSP_extendedStatus OBJ_id_pkix_OCSP,8L - -#define SN_id_pkix_OCSP_valid "valid" -#define NID_id_pkix_OCSP_valid 373 -#define OBJ_id_pkix_OCSP_valid OBJ_id_pkix_OCSP,9L - -#define SN_id_pkix_OCSP_path "path" -#define NID_id_pkix_OCSP_path 374 -#define OBJ_id_pkix_OCSP_path OBJ_id_pkix_OCSP,10L - -#define SN_id_pkix_OCSP_trustRoot "trustRoot" -#define LN_id_pkix_OCSP_trustRoot "Trust Root" -#define NID_id_pkix_OCSP_trustRoot 375 -#define OBJ_id_pkix_OCSP_trustRoot OBJ_id_pkix_OCSP,11L - -#define SN_algorithm "algorithm" -#define LN_algorithm "algorithm" -#define NID_algorithm 376 -#define OBJ_algorithm 1L,3L,14L,3L,2L - -#define SN_md5WithRSA "RSA-NP-MD5" -#define LN_md5WithRSA "md5WithRSA" -#define NID_md5WithRSA 104 -#define OBJ_md5WithRSA OBJ_algorithm,3L - -#define SN_des_ecb "DES-ECB" -#define LN_des_ecb "des-ecb" -#define NID_des_ecb 29 -#define OBJ_des_ecb OBJ_algorithm,6L - -#define SN_des_cbc "DES-CBC" -#define LN_des_cbc "des-cbc" -#define NID_des_cbc 31 -#define OBJ_des_cbc OBJ_algorithm,7L - -#define SN_des_ofb64 "DES-OFB" -#define LN_des_ofb64 "des-ofb" -#define NID_des_ofb64 45 -#define OBJ_des_ofb64 OBJ_algorithm,8L - -#define SN_des_cfb64 "DES-CFB" -#define LN_des_cfb64 "des-cfb" -#define NID_des_cfb64 30 -#define OBJ_des_cfb64 OBJ_algorithm,9L - -#define SN_rsaSignature "rsaSignature" -#define NID_rsaSignature 377 -#define OBJ_rsaSignature OBJ_algorithm,11L - -#define SN_dsa_2 "DSA-old" -#define LN_dsa_2 "dsaEncryption-old" -#define NID_dsa_2 67 -#define OBJ_dsa_2 OBJ_algorithm,12L - -#define SN_dsaWithSHA "DSA-SHA" -#define LN_dsaWithSHA "dsaWithSHA" -#define NID_dsaWithSHA 66 -#define OBJ_dsaWithSHA OBJ_algorithm,13L - -#define SN_shaWithRSAEncryption "RSA-SHA" -#define LN_shaWithRSAEncryption "shaWithRSAEncryption" -#define NID_shaWithRSAEncryption 42 -#define OBJ_shaWithRSAEncryption OBJ_algorithm,15L - -#define SN_des_ede_ecb "DES-EDE" -#define LN_des_ede_ecb "des-ede" -#define NID_des_ede_ecb 32 -#define OBJ_des_ede_ecb OBJ_algorithm,17L - -#define SN_des_ede3_ecb "DES-EDE3" -#define LN_des_ede3_ecb "des-ede3" -#define NID_des_ede3_ecb 33 - -#define SN_des_ede_cbc "DES-EDE-CBC" -#define LN_des_ede_cbc "des-ede-cbc" -#define NID_des_ede_cbc 43 - -#define SN_des_ede_cfb64 "DES-EDE-CFB" -#define LN_des_ede_cfb64 "des-ede-cfb" -#define NID_des_ede_cfb64 60 - -#define SN_des_ede3_cfb64 "DES-EDE3-CFB" -#define LN_des_ede3_cfb64 "des-ede3-cfb" -#define NID_des_ede3_cfb64 61 - -#define SN_des_ede_ofb64 "DES-EDE-OFB" -#define LN_des_ede_ofb64 "des-ede-ofb" -#define NID_des_ede_ofb64 62 - -#define SN_des_ede3_ofb64 "DES-EDE3-OFB" -#define LN_des_ede3_ofb64 "des-ede3-ofb" -#define NID_des_ede3_ofb64 63 - -#define SN_desx_cbc "DESX-CBC" -#define LN_desx_cbc "desx-cbc" -#define NID_desx_cbc 80 - -#define SN_sha "SHA" -#define LN_sha "sha" -#define NID_sha 41 -#define OBJ_sha OBJ_algorithm,18L - -#define SN_sha1 "SHA1" -#define LN_sha1 "sha1" -#define NID_sha1 64 -#define OBJ_sha1 OBJ_algorithm,26L - -#define SN_dsaWithSHA1_2 "DSA-SHA1-old" -#define LN_dsaWithSHA1_2 "dsaWithSHA1-old" -#define NID_dsaWithSHA1_2 70 -#define OBJ_dsaWithSHA1_2 OBJ_algorithm,27L - -#define SN_sha1WithRSA "RSA-SHA1-2" -#define LN_sha1WithRSA "sha1WithRSA" -#define NID_sha1WithRSA 115 -#define OBJ_sha1WithRSA OBJ_algorithm,29L - -#define SN_ripemd160 "RIPEMD160" -#define LN_ripemd160 "ripemd160" -#define NID_ripemd160 117 -#define OBJ_ripemd160 1L,3L,36L,3L,2L,1L - -#define SN_ripemd160WithRSA "RSA-RIPEMD160" -#define LN_ripemd160WithRSA "ripemd160WithRSA" -#define NID_ripemd160WithRSA 119 -#define OBJ_ripemd160WithRSA 1L,3L,36L,3L,3L,1L,2L - -#define SN_sxnet "SXNetID" -#define LN_sxnet "Strong Extranet ID" -#define NID_sxnet 143 -#define OBJ_sxnet 1L,3L,101L,1L,4L,1L - -#define SN_X500 "X500" -#define LN_X500 "directory services (X.500)" -#define NID_X500 11 -#define OBJ_X500 2L,5L - -#define SN_X509 "X509" -#define NID_X509 12 -#define OBJ_X509 OBJ_X500,4L - -#define SN_commonName "CN" -#define LN_commonName "commonName" -#define NID_commonName 13 -#define OBJ_commonName OBJ_X509,3L - -#define SN_surname "SN" -#define LN_surname "surname" -#define NID_surname 100 -#define OBJ_surname OBJ_X509,4L - -#define LN_serialNumber "serialNumber" -#define NID_serialNumber 105 -#define OBJ_serialNumber OBJ_X509,5L - -#define SN_countryName "C" -#define LN_countryName "countryName" -#define NID_countryName 14 -#define OBJ_countryName OBJ_X509,6L - -#define SN_localityName "L" -#define LN_localityName "localityName" -#define NID_localityName 15 -#define OBJ_localityName OBJ_X509,7L - -#define SN_stateOrProvinceName "ST" -#define LN_stateOrProvinceName "stateOrProvinceName" -#define NID_stateOrProvinceName 16 -#define OBJ_stateOrProvinceName OBJ_X509,8L - -#define SN_streetAddress "street" -#define LN_streetAddress "streetAddress" -#define NID_streetAddress 660 -#define OBJ_streetAddress OBJ_X509,9L - -#define SN_organizationName "O" -#define LN_organizationName "organizationName" -#define NID_organizationName 17 -#define OBJ_organizationName OBJ_X509,10L - -#define SN_organizationalUnitName "OU" -#define LN_organizationalUnitName "organizationalUnitName" -#define NID_organizationalUnitName 18 -#define OBJ_organizationalUnitName OBJ_X509,11L - -#define SN_title "title" -#define LN_title "title" -#define NID_title 106 -#define OBJ_title OBJ_X509,12L - -#define LN_description "description" -#define NID_description 107 -#define OBJ_description OBJ_X509,13L - -#define LN_searchGuide "searchGuide" -#define NID_searchGuide 859 -#define OBJ_searchGuide OBJ_X509,14L - -#define LN_businessCategory "businessCategory" -#define NID_businessCategory 860 -#define OBJ_businessCategory OBJ_X509,15L - -#define LN_postalAddress "postalAddress" -#define NID_postalAddress 861 -#define OBJ_postalAddress OBJ_X509,16L - -#define LN_postalCode "postalCode" -#define NID_postalCode 661 -#define OBJ_postalCode OBJ_X509,17L - -#define LN_postOfficeBox "postOfficeBox" -#define NID_postOfficeBox 862 -#define OBJ_postOfficeBox OBJ_X509,18L - -#define LN_physicalDeliveryOfficeName "physicalDeliveryOfficeName" -#define NID_physicalDeliveryOfficeName 863 -#define OBJ_physicalDeliveryOfficeName OBJ_X509,19L - -#define LN_telephoneNumber "telephoneNumber" -#define NID_telephoneNumber 864 -#define OBJ_telephoneNumber OBJ_X509,20L - -#define LN_telexNumber "telexNumber" -#define NID_telexNumber 865 -#define OBJ_telexNumber OBJ_X509,21L - -#define LN_teletexTerminalIdentifier "teletexTerminalIdentifier" -#define NID_teletexTerminalIdentifier 866 -#define OBJ_teletexTerminalIdentifier OBJ_X509,22L - -#define LN_facsimileTelephoneNumber "facsimileTelephoneNumber" -#define NID_facsimileTelephoneNumber 867 -#define OBJ_facsimileTelephoneNumber OBJ_X509,23L - -#define LN_x121Address "x121Address" -#define NID_x121Address 868 -#define OBJ_x121Address OBJ_X509,24L - -#define LN_internationaliSDNNumber "internationaliSDNNumber" -#define NID_internationaliSDNNumber 869 -#define OBJ_internationaliSDNNumber OBJ_X509,25L - -#define LN_registeredAddress "registeredAddress" -#define NID_registeredAddress 870 -#define OBJ_registeredAddress OBJ_X509,26L - -#define LN_destinationIndicator "destinationIndicator" -#define NID_destinationIndicator 871 -#define OBJ_destinationIndicator OBJ_X509,27L - -#define LN_preferredDeliveryMethod "preferredDeliveryMethod" -#define NID_preferredDeliveryMethod 872 -#define OBJ_preferredDeliveryMethod OBJ_X509,28L - -#define LN_presentationAddress "presentationAddress" -#define NID_presentationAddress 873 -#define OBJ_presentationAddress OBJ_X509,29L - -#define LN_supportedApplicationContext "supportedApplicationContext" -#define NID_supportedApplicationContext 874 -#define OBJ_supportedApplicationContext OBJ_X509,30L - -#define SN_member "member" -#define NID_member 875 -#define OBJ_member OBJ_X509,31L - -#define SN_owner "owner" -#define NID_owner 876 -#define OBJ_owner OBJ_X509,32L - -#define LN_roleOccupant "roleOccupant" -#define NID_roleOccupant 877 -#define OBJ_roleOccupant OBJ_X509,33L - -#define SN_seeAlso "seeAlso" -#define NID_seeAlso 878 -#define OBJ_seeAlso OBJ_X509,34L - -#define LN_userPassword "userPassword" -#define NID_userPassword 879 -#define OBJ_userPassword OBJ_X509,35L - -#define LN_userCertificate "userCertificate" -#define NID_userCertificate 880 -#define OBJ_userCertificate OBJ_X509,36L - -#define LN_cACertificate "cACertificate" -#define NID_cACertificate 881 -#define OBJ_cACertificate OBJ_X509,37L - -#define LN_authorityRevocationList "authorityRevocationList" -#define NID_authorityRevocationList 882 -#define OBJ_authorityRevocationList OBJ_X509,38L - -#define LN_certificateRevocationList "certificateRevocationList" -#define NID_certificateRevocationList 883 -#define OBJ_certificateRevocationList OBJ_X509,39L - -#define LN_crossCertificatePair "crossCertificatePair" -#define NID_crossCertificatePair 884 -#define OBJ_crossCertificatePair OBJ_X509,40L - -#define SN_name "name" -#define LN_name "name" -#define NID_name 173 -#define OBJ_name OBJ_X509,41L - -#define SN_givenName "GN" -#define LN_givenName "givenName" -#define NID_givenName 99 -#define OBJ_givenName OBJ_X509,42L - -#define SN_initials "initials" -#define LN_initials "initials" -#define NID_initials 101 -#define OBJ_initials OBJ_X509,43L - -#define LN_generationQualifier "generationQualifier" -#define NID_generationQualifier 509 -#define OBJ_generationQualifier OBJ_X509,44L - -#define LN_x500UniqueIdentifier "x500UniqueIdentifier" -#define NID_x500UniqueIdentifier 503 -#define OBJ_x500UniqueIdentifier OBJ_X509,45L - -#define SN_dnQualifier "dnQualifier" -#define LN_dnQualifier "dnQualifier" -#define NID_dnQualifier 174 -#define OBJ_dnQualifier OBJ_X509,46L - -#define LN_enhancedSearchGuide "enhancedSearchGuide" -#define NID_enhancedSearchGuide 885 -#define OBJ_enhancedSearchGuide OBJ_X509,47L - -#define LN_protocolInformation "protocolInformation" -#define NID_protocolInformation 886 -#define OBJ_protocolInformation OBJ_X509,48L - -#define LN_distinguishedName "distinguishedName" -#define NID_distinguishedName 887 -#define OBJ_distinguishedName OBJ_X509,49L - -#define LN_uniqueMember "uniqueMember" -#define NID_uniqueMember 888 -#define OBJ_uniqueMember OBJ_X509,50L - -#define LN_houseIdentifier "houseIdentifier" -#define NID_houseIdentifier 889 -#define OBJ_houseIdentifier OBJ_X509,51L - -#define LN_supportedAlgorithms "supportedAlgorithms" -#define NID_supportedAlgorithms 890 -#define OBJ_supportedAlgorithms OBJ_X509,52L - -#define LN_deltaRevocationList "deltaRevocationList" -#define NID_deltaRevocationList 891 -#define OBJ_deltaRevocationList OBJ_X509,53L - -#define SN_dmdName "dmdName" -#define NID_dmdName 892 -#define OBJ_dmdName OBJ_X509,54L - -#define LN_pseudonym "pseudonym" -#define NID_pseudonym 510 -#define OBJ_pseudonym OBJ_X509,65L - -#define SN_role "role" -#define LN_role "role" -#define NID_role 400 -#define OBJ_role OBJ_X509,72L - -#define SN_X500algorithms "X500algorithms" -#define LN_X500algorithms "directory services - algorithms" -#define NID_X500algorithms 378 -#define OBJ_X500algorithms OBJ_X500,8L - -#define SN_rsa "RSA" -#define LN_rsa "rsa" -#define NID_rsa 19 -#define OBJ_rsa OBJ_X500algorithms,1L,1L - -#define SN_mdc2WithRSA "RSA-MDC2" -#define LN_mdc2WithRSA "mdc2WithRSA" -#define NID_mdc2WithRSA 96 -#define OBJ_mdc2WithRSA OBJ_X500algorithms,3L,100L - -#define SN_mdc2 "MDC2" -#define LN_mdc2 "mdc2" -#define NID_mdc2 95 -#define OBJ_mdc2 OBJ_X500algorithms,3L,101L - -#define SN_id_ce "id-ce" -#define NID_id_ce 81 -#define OBJ_id_ce OBJ_X500,29L - -#define SN_subject_directory_attributes "subjectDirectoryAttributes" -#define LN_subject_directory_attributes "X509v3 Subject Directory Attributes" -#define NID_subject_directory_attributes 769 -#define OBJ_subject_directory_attributes OBJ_id_ce,9L - -#define SN_subject_key_identifier "subjectKeyIdentifier" -#define LN_subject_key_identifier "X509v3 Subject Key Identifier" -#define NID_subject_key_identifier 82 -#define OBJ_subject_key_identifier OBJ_id_ce,14L - -#define SN_key_usage "keyUsage" -#define LN_key_usage "X509v3 Key Usage" -#define NID_key_usage 83 -#define OBJ_key_usage OBJ_id_ce,15L - -#define SN_private_key_usage_period "privateKeyUsagePeriod" -#define LN_private_key_usage_period "X509v3 Private Key Usage Period" -#define NID_private_key_usage_period 84 -#define OBJ_private_key_usage_period OBJ_id_ce,16L - -#define SN_subject_alt_name "subjectAltName" -#define LN_subject_alt_name "X509v3 Subject Alternative Name" -#define NID_subject_alt_name 85 -#define OBJ_subject_alt_name OBJ_id_ce,17L - -#define SN_issuer_alt_name "issuerAltName" -#define LN_issuer_alt_name "X509v3 Issuer Alternative Name" -#define NID_issuer_alt_name 86 -#define OBJ_issuer_alt_name OBJ_id_ce,18L - -#define SN_basic_constraints "basicConstraints" -#define LN_basic_constraints "X509v3 Basic Constraints" -#define NID_basic_constraints 87 -#define OBJ_basic_constraints OBJ_id_ce,19L - -#define SN_crl_number "crlNumber" -#define LN_crl_number "X509v3 CRL Number" -#define NID_crl_number 88 -#define OBJ_crl_number OBJ_id_ce,20L - -#define SN_crl_reason "CRLReason" -#define LN_crl_reason "X509v3 CRL Reason Code" -#define NID_crl_reason 141 -#define OBJ_crl_reason OBJ_id_ce,21L - -#define SN_invalidity_date "invalidityDate" -#define LN_invalidity_date "Invalidity Date" -#define NID_invalidity_date 142 -#define OBJ_invalidity_date OBJ_id_ce,24L - -#define SN_delta_crl "deltaCRL" -#define LN_delta_crl "X509v3 Delta CRL Indicator" -#define NID_delta_crl 140 -#define OBJ_delta_crl OBJ_id_ce,27L - -#define SN_issuing_distribution_point "issuingDistributionPoint" -#define LN_issuing_distribution_point "X509v3 Issuing Distribution Point" -#define NID_issuing_distribution_point 770 -#define OBJ_issuing_distribution_point OBJ_id_ce,28L - -#define SN_certificate_issuer "certificateIssuer" -#define LN_certificate_issuer "X509v3 Certificate Issuer" -#define NID_certificate_issuer 771 -#define OBJ_certificate_issuer OBJ_id_ce,29L - -#define SN_name_constraints "nameConstraints" -#define LN_name_constraints "X509v3 Name Constraints" -#define NID_name_constraints 666 -#define OBJ_name_constraints OBJ_id_ce,30L - -#define SN_crl_distribution_points "crlDistributionPoints" -#define LN_crl_distribution_points "X509v3 CRL Distribution Points" -#define NID_crl_distribution_points 103 -#define OBJ_crl_distribution_points OBJ_id_ce,31L - -#define SN_certificate_policies "certificatePolicies" -#define LN_certificate_policies "X509v3 Certificate Policies" -#define NID_certificate_policies 89 -#define OBJ_certificate_policies OBJ_id_ce,32L - -#define SN_any_policy "anyPolicy" -#define LN_any_policy "X509v3 Any Policy" -#define NID_any_policy 746 -#define OBJ_any_policy OBJ_certificate_policies,0L - -#define SN_policy_mappings "policyMappings" -#define LN_policy_mappings "X509v3 Policy Mappings" -#define NID_policy_mappings 747 -#define OBJ_policy_mappings OBJ_id_ce,33L - -#define SN_authority_key_identifier "authorityKeyIdentifier" -#define LN_authority_key_identifier "X509v3 Authority Key Identifier" -#define NID_authority_key_identifier 90 -#define OBJ_authority_key_identifier OBJ_id_ce,35L - -#define SN_policy_constraints "policyConstraints" -#define LN_policy_constraints "X509v3 Policy Constraints" -#define NID_policy_constraints 401 -#define OBJ_policy_constraints OBJ_id_ce,36L - -#define SN_ext_key_usage "extendedKeyUsage" -#define LN_ext_key_usage "X509v3 Extended Key Usage" -#define NID_ext_key_usage 126 -#define OBJ_ext_key_usage OBJ_id_ce,37L - -#define SN_freshest_crl "freshestCRL" -#define LN_freshest_crl "X509v3 Freshest CRL" -#define NID_freshest_crl 857 -#define OBJ_freshest_crl OBJ_id_ce,46L - -#define SN_inhibit_any_policy "inhibitAnyPolicy" -#define LN_inhibit_any_policy "X509v3 Inhibit Any Policy" -#define NID_inhibit_any_policy 748 -#define OBJ_inhibit_any_policy OBJ_id_ce,54L - -#define SN_target_information "targetInformation" -#define LN_target_information "X509v3 AC Targeting" -#define NID_target_information 402 -#define OBJ_target_information OBJ_id_ce,55L - -#define SN_no_rev_avail "noRevAvail" -#define LN_no_rev_avail "X509v3 No Revocation Available" -#define NID_no_rev_avail 403 -#define OBJ_no_rev_avail OBJ_id_ce,56L - -#define SN_anyExtendedKeyUsage "anyExtendedKeyUsage" -#define LN_anyExtendedKeyUsage "Any Extended Key Usage" -#define NID_anyExtendedKeyUsage 910 -#define OBJ_anyExtendedKeyUsage OBJ_ext_key_usage,0L - -#define SN_netscape "Netscape" -#define LN_netscape "Netscape Communications Corp." -#define NID_netscape 57 -#define OBJ_netscape 2L,16L,840L,1L,113730L - -#define SN_netscape_cert_extension "nsCertExt" -#define LN_netscape_cert_extension "Netscape Certificate Extension" -#define NID_netscape_cert_extension 58 -#define OBJ_netscape_cert_extension OBJ_netscape,1L - -#define SN_netscape_data_type "nsDataType" -#define LN_netscape_data_type "Netscape Data Type" -#define NID_netscape_data_type 59 -#define OBJ_netscape_data_type OBJ_netscape,2L - -#define SN_netscape_cert_type "nsCertType" -#define LN_netscape_cert_type "Netscape Cert Type" -#define NID_netscape_cert_type 71 -#define OBJ_netscape_cert_type OBJ_netscape_cert_extension,1L - -#define SN_netscape_base_url "nsBaseUrl" -#define LN_netscape_base_url "Netscape Base Url" -#define NID_netscape_base_url 72 -#define OBJ_netscape_base_url OBJ_netscape_cert_extension,2L - -#define SN_netscape_revocation_url "nsRevocationUrl" -#define LN_netscape_revocation_url "Netscape Revocation Url" -#define NID_netscape_revocation_url 73 -#define OBJ_netscape_revocation_url OBJ_netscape_cert_extension,3L - -#define SN_netscape_ca_revocation_url "nsCaRevocationUrl" -#define LN_netscape_ca_revocation_url "Netscape CA Revocation Url" -#define NID_netscape_ca_revocation_url 74 -#define OBJ_netscape_ca_revocation_url OBJ_netscape_cert_extension,4L - -#define SN_netscape_renewal_url "nsRenewalUrl" -#define LN_netscape_renewal_url "Netscape Renewal Url" -#define NID_netscape_renewal_url 75 -#define OBJ_netscape_renewal_url OBJ_netscape_cert_extension,7L - -#define SN_netscape_ca_policy_url "nsCaPolicyUrl" -#define LN_netscape_ca_policy_url "Netscape CA Policy Url" -#define NID_netscape_ca_policy_url 76 -#define OBJ_netscape_ca_policy_url OBJ_netscape_cert_extension,8L - -#define SN_netscape_ssl_server_name "nsSslServerName" -#define LN_netscape_ssl_server_name "Netscape SSL Server Name" -#define NID_netscape_ssl_server_name 77 -#define OBJ_netscape_ssl_server_name OBJ_netscape_cert_extension,12L - -#define SN_netscape_comment "nsComment" -#define LN_netscape_comment "Netscape Comment" -#define NID_netscape_comment 78 -#define OBJ_netscape_comment OBJ_netscape_cert_extension,13L - -#define SN_netscape_cert_sequence "nsCertSequence" -#define LN_netscape_cert_sequence "Netscape Certificate Sequence" -#define NID_netscape_cert_sequence 79 -#define OBJ_netscape_cert_sequence OBJ_netscape_data_type,5L - -#define SN_ns_sgc "nsSGC" -#define LN_ns_sgc "Netscape Server Gated Crypto" -#define NID_ns_sgc 139 -#define OBJ_ns_sgc OBJ_netscape,4L,1L - -#define SN_org "ORG" -#define LN_org "org" -#define NID_org 379 -#define OBJ_org OBJ_iso,3L - -#define SN_dod "DOD" -#define LN_dod "dod" -#define NID_dod 380 -#define OBJ_dod OBJ_org,6L - -#define SN_iana "IANA" -#define LN_iana "iana" -#define NID_iana 381 -#define OBJ_iana OBJ_dod,1L - -#define OBJ_internet OBJ_iana - -#define SN_Directory "directory" -#define LN_Directory "Directory" -#define NID_Directory 382 -#define OBJ_Directory OBJ_internet,1L - -#define SN_Management "mgmt" -#define LN_Management "Management" -#define NID_Management 383 -#define OBJ_Management OBJ_internet,2L - -#define SN_Experimental "experimental" -#define LN_Experimental "Experimental" -#define NID_Experimental 384 -#define OBJ_Experimental OBJ_internet,3L - -#define SN_Private "private" -#define LN_Private "Private" -#define NID_Private 385 -#define OBJ_Private OBJ_internet,4L - -#define SN_Security "security" -#define LN_Security "Security" -#define NID_Security 386 -#define OBJ_Security OBJ_internet,5L - -#define SN_SNMPv2 "snmpv2" -#define LN_SNMPv2 "SNMPv2" -#define NID_SNMPv2 387 -#define OBJ_SNMPv2 OBJ_internet,6L - -#define LN_Mail "Mail" -#define NID_Mail 388 -#define OBJ_Mail OBJ_internet,7L - -#define SN_Enterprises "enterprises" -#define LN_Enterprises "Enterprises" -#define NID_Enterprises 389 -#define OBJ_Enterprises OBJ_Private,1L - -#define SN_dcObject "dcobject" -#define LN_dcObject "dcObject" -#define NID_dcObject 390 -#define OBJ_dcObject OBJ_Enterprises,1466L,344L - -#define SN_mime_mhs "mime-mhs" -#define LN_mime_mhs "MIME MHS" -#define NID_mime_mhs 504 -#define OBJ_mime_mhs OBJ_Mail,1L - -#define SN_mime_mhs_headings "mime-mhs-headings" -#define LN_mime_mhs_headings "mime-mhs-headings" -#define NID_mime_mhs_headings 505 -#define OBJ_mime_mhs_headings OBJ_mime_mhs,1L - -#define SN_mime_mhs_bodies "mime-mhs-bodies" -#define LN_mime_mhs_bodies "mime-mhs-bodies" -#define NID_mime_mhs_bodies 506 -#define OBJ_mime_mhs_bodies OBJ_mime_mhs,2L - -#define SN_id_hex_partial_message "id-hex-partial-message" -#define LN_id_hex_partial_message "id-hex-partial-message" -#define NID_id_hex_partial_message 507 -#define OBJ_id_hex_partial_message OBJ_mime_mhs_headings,1L - -#define SN_id_hex_multipart_message "id-hex-multipart-message" -#define LN_id_hex_multipart_message "id-hex-multipart-message" -#define NID_id_hex_multipart_message 508 -#define OBJ_id_hex_multipart_message OBJ_mime_mhs_headings,2L - -#define SN_zlib_compression "ZLIB" -#define LN_zlib_compression "zlib compression" -#define NID_zlib_compression 125 -#define OBJ_zlib_compression OBJ_id_smime_alg,8L - -#define OBJ_csor 2L,16L,840L,1L,101L,3L - -#define OBJ_nistAlgorithms OBJ_csor,4L - -#define OBJ_aes OBJ_nistAlgorithms,1L - -#define SN_aes_128_ecb "AES-128-ECB" -#define LN_aes_128_ecb "aes-128-ecb" -#define NID_aes_128_ecb 418 -#define OBJ_aes_128_ecb OBJ_aes,1L - -#define SN_aes_128_cbc "AES-128-CBC" -#define LN_aes_128_cbc "aes-128-cbc" -#define NID_aes_128_cbc 419 -#define OBJ_aes_128_cbc OBJ_aes,2L - -#define SN_aes_128_ofb128 "AES-128-OFB" -#define LN_aes_128_ofb128 "aes-128-ofb" -#define NID_aes_128_ofb128 420 -#define OBJ_aes_128_ofb128 OBJ_aes,3L - -#define SN_aes_128_cfb128 "AES-128-CFB" -#define LN_aes_128_cfb128 "aes-128-cfb" -#define NID_aes_128_cfb128 421 -#define OBJ_aes_128_cfb128 OBJ_aes,4L - -#define SN_id_aes128_wrap "id-aes128-wrap" -#define NID_id_aes128_wrap 788 -#define OBJ_id_aes128_wrap OBJ_aes,5L - -#define SN_aes_128_gcm "id-aes128-GCM" -#define LN_aes_128_gcm "aes-128-gcm" -#define NID_aes_128_gcm 895 -#define OBJ_aes_128_gcm OBJ_aes,6L - -#define SN_aes_128_ccm "id-aes128-CCM" -#define LN_aes_128_ccm "aes-128-ccm" -#define NID_aes_128_ccm 896 -#define OBJ_aes_128_ccm OBJ_aes,7L - -#define SN_id_aes128_wrap_pad "id-aes128-wrap-pad" -#define NID_id_aes128_wrap_pad 897 -#define OBJ_id_aes128_wrap_pad OBJ_aes,8L - -#define SN_aes_192_ecb "AES-192-ECB" -#define LN_aes_192_ecb "aes-192-ecb" -#define NID_aes_192_ecb 422 -#define OBJ_aes_192_ecb OBJ_aes,21L - -#define SN_aes_192_cbc "AES-192-CBC" -#define LN_aes_192_cbc "aes-192-cbc" -#define NID_aes_192_cbc 423 -#define OBJ_aes_192_cbc OBJ_aes,22L - -#define SN_aes_192_ofb128 "AES-192-OFB" -#define LN_aes_192_ofb128 "aes-192-ofb" -#define NID_aes_192_ofb128 424 -#define OBJ_aes_192_ofb128 OBJ_aes,23L - -#define SN_aes_192_cfb128 "AES-192-CFB" -#define LN_aes_192_cfb128 "aes-192-cfb" -#define NID_aes_192_cfb128 425 -#define OBJ_aes_192_cfb128 OBJ_aes,24L - -#define SN_id_aes192_wrap "id-aes192-wrap" -#define NID_id_aes192_wrap 789 -#define OBJ_id_aes192_wrap OBJ_aes,25L - -#define SN_aes_192_gcm "id-aes192-GCM" -#define LN_aes_192_gcm "aes-192-gcm" -#define NID_aes_192_gcm 898 -#define OBJ_aes_192_gcm OBJ_aes,26L - -#define SN_aes_192_ccm "id-aes192-CCM" -#define LN_aes_192_ccm "aes-192-ccm" -#define NID_aes_192_ccm 899 -#define OBJ_aes_192_ccm OBJ_aes,27L - -#define SN_id_aes192_wrap_pad "id-aes192-wrap-pad" -#define NID_id_aes192_wrap_pad 900 -#define OBJ_id_aes192_wrap_pad OBJ_aes,28L - -#define SN_aes_256_ecb "AES-256-ECB" -#define LN_aes_256_ecb "aes-256-ecb" -#define NID_aes_256_ecb 426 -#define OBJ_aes_256_ecb OBJ_aes,41L - -#define SN_aes_256_cbc "AES-256-CBC" -#define LN_aes_256_cbc "aes-256-cbc" -#define NID_aes_256_cbc 427 -#define OBJ_aes_256_cbc OBJ_aes,42L - -#define SN_aes_256_ofb128 "AES-256-OFB" -#define LN_aes_256_ofb128 "aes-256-ofb" -#define NID_aes_256_ofb128 428 -#define OBJ_aes_256_ofb128 OBJ_aes,43L - -#define SN_aes_256_cfb128 "AES-256-CFB" -#define LN_aes_256_cfb128 "aes-256-cfb" -#define NID_aes_256_cfb128 429 -#define OBJ_aes_256_cfb128 OBJ_aes,44L - -#define SN_id_aes256_wrap "id-aes256-wrap" -#define NID_id_aes256_wrap 790 -#define OBJ_id_aes256_wrap OBJ_aes,45L - -#define SN_aes_256_gcm "id-aes256-GCM" -#define LN_aes_256_gcm "aes-256-gcm" -#define NID_aes_256_gcm 901 -#define OBJ_aes_256_gcm OBJ_aes,46L - -#define SN_aes_256_ccm "id-aes256-CCM" -#define LN_aes_256_ccm "aes-256-ccm" -#define NID_aes_256_ccm 902 -#define OBJ_aes_256_ccm OBJ_aes,47L - -#define SN_id_aes256_wrap_pad "id-aes256-wrap-pad" -#define NID_id_aes256_wrap_pad 903 -#define OBJ_id_aes256_wrap_pad OBJ_aes,48L - -#define SN_aes_128_cfb1 "AES-128-CFB1" -#define LN_aes_128_cfb1 "aes-128-cfb1" -#define NID_aes_128_cfb1 650 - -#define SN_aes_192_cfb1 "AES-192-CFB1" -#define LN_aes_192_cfb1 "aes-192-cfb1" -#define NID_aes_192_cfb1 651 - -#define SN_aes_256_cfb1 "AES-256-CFB1" -#define LN_aes_256_cfb1 "aes-256-cfb1" -#define NID_aes_256_cfb1 652 - -#define SN_aes_128_cfb8 "AES-128-CFB8" -#define LN_aes_128_cfb8 "aes-128-cfb8" -#define NID_aes_128_cfb8 653 - -#define SN_aes_192_cfb8 "AES-192-CFB8" -#define LN_aes_192_cfb8 "aes-192-cfb8" -#define NID_aes_192_cfb8 654 - -#define SN_aes_256_cfb8 "AES-256-CFB8" -#define LN_aes_256_cfb8 "aes-256-cfb8" -#define NID_aes_256_cfb8 655 - -#define SN_aes_128_ctr "AES-128-CTR" -#define LN_aes_128_ctr "aes-128-ctr" -#define NID_aes_128_ctr 904 - -#define SN_aes_192_ctr "AES-192-CTR" -#define LN_aes_192_ctr "aes-192-ctr" -#define NID_aes_192_ctr 905 - -#define SN_aes_256_ctr "AES-256-CTR" -#define LN_aes_256_ctr "aes-256-ctr" -#define NID_aes_256_ctr 906 - -#define SN_aes_128_xts "AES-128-XTS" -#define LN_aes_128_xts "aes-128-xts" -#define NID_aes_128_xts 913 - -#define SN_aes_256_xts "AES-256-XTS" -#define LN_aes_256_xts "aes-256-xts" -#define NID_aes_256_xts 914 - -#define SN_des_cfb1 "DES-CFB1" -#define LN_des_cfb1 "des-cfb1" -#define NID_des_cfb1 656 - -#define SN_des_cfb8 "DES-CFB8" -#define LN_des_cfb8 "des-cfb8" -#define NID_des_cfb8 657 - -#define SN_des_ede3_cfb1 "DES-EDE3-CFB1" -#define LN_des_ede3_cfb1 "des-ede3-cfb1" -#define NID_des_ede3_cfb1 658 - -#define SN_des_ede3_cfb8 "DES-EDE3-CFB8" -#define LN_des_ede3_cfb8 "des-ede3-cfb8" -#define NID_des_ede3_cfb8 659 - -#define OBJ_nist_hashalgs OBJ_nistAlgorithms,2L - -#define SN_sha256 "SHA256" -#define LN_sha256 "sha256" -#define NID_sha256 672 -#define OBJ_sha256 OBJ_nist_hashalgs,1L - -#define SN_sha384 "SHA384" -#define LN_sha384 "sha384" -#define NID_sha384 673 -#define OBJ_sha384 OBJ_nist_hashalgs,2L - -#define SN_sha512 "SHA512" -#define LN_sha512 "sha512" -#define NID_sha512 674 -#define OBJ_sha512 OBJ_nist_hashalgs,3L - -#define SN_sha224 "SHA224" -#define LN_sha224 "sha224" -#define NID_sha224 675 -#define OBJ_sha224 OBJ_nist_hashalgs,4L - -#define OBJ_dsa_with_sha2 OBJ_nistAlgorithms,3L - -#define SN_dsa_with_SHA224 "dsa_with_SHA224" -#define NID_dsa_with_SHA224 802 -#define OBJ_dsa_with_SHA224 OBJ_dsa_with_sha2,1L - -#define SN_dsa_with_SHA256 "dsa_with_SHA256" -#define NID_dsa_with_SHA256 803 -#define OBJ_dsa_with_SHA256 OBJ_dsa_with_sha2,2L - -#define SN_hold_instruction_code "holdInstructionCode" -#define LN_hold_instruction_code "Hold Instruction Code" -#define NID_hold_instruction_code 430 -#define OBJ_hold_instruction_code OBJ_id_ce,23L - -#define OBJ_holdInstruction OBJ_X9_57,2L - -#define SN_hold_instruction_none "holdInstructionNone" -#define LN_hold_instruction_none "Hold Instruction None" -#define NID_hold_instruction_none 431 -#define OBJ_hold_instruction_none OBJ_holdInstruction,1L - -#define SN_hold_instruction_call_issuer "holdInstructionCallIssuer" -#define LN_hold_instruction_call_issuer "Hold Instruction Call Issuer" -#define NID_hold_instruction_call_issuer 432 -#define OBJ_hold_instruction_call_issuer OBJ_holdInstruction,2L - -#define SN_hold_instruction_reject "holdInstructionReject" -#define LN_hold_instruction_reject "Hold Instruction Reject" -#define NID_hold_instruction_reject 433 -#define OBJ_hold_instruction_reject OBJ_holdInstruction,3L - -#define SN_data "data" -#define NID_data 434 -#define OBJ_data OBJ_itu_t,9L - -#define SN_pss "pss" -#define NID_pss 435 -#define OBJ_pss OBJ_data,2342L - -#define SN_ucl "ucl" -#define NID_ucl 436 -#define OBJ_ucl OBJ_pss,19200300L - -#define SN_pilot "pilot" -#define NID_pilot 437 -#define OBJ_pilot OBJ_ucl,100L - -#define LN_pilotAttributeType "pilotAttributeType" -#define NID_pilotAttributeType 438 -#define OBJ_pilotAttributeType OBJ_pilot,1L - -#define LN_pilotAttributeSyntax "pilotAttributeSyntax" -#define NID_pilotAttributeSyntax 439 -#define OBJ_pilotAttributeSyntax OBJ_pilot,3L - -#define LN_pilotObjectClass "pilotObjectClass" -#define NID_pilotObjectClass 440 -#define OBJ_pilotObjectClass OBJ_pilot,4L - -#define LN_pilotGroups "pilotGroups" -#define NID_pilotGroups 441 -#define OBJ_pilotGroups OBJ_pilot,10L - -#define LN_iA5StringSyntax "iA5StringSyntax" -#define NID_iA5StringSyntax 442 -#define OBJ_iA5StringSyntax OBJ_pilotAttributeSyntax,4L - -#define LN_caseIgnoreIA5StringSyntax "caseIgnoreIA5StringSyntax" -#define NID_caseIgnoreIA5StringSyntax 443 -#define OBJ_caseIgnoreIA5StringSyntax OBJ_pilotAttributeSyntax,5L - -#define LN_pilotObject "pilotObject" -#define NID_pilotObject 444 -#define OBJ_pilotObject OBJ_pilotObjectClass,3L - -#define LN_pilotPerson "pilotPerson" -#define NID_pilotPerson 445 -#define OBJ_pilotPerson OBJ_pilotObjectClass,4L - -#define SN_account "account" -#define NID_account 446 -#define OBJ_account OBJ_pilotObjectClass,5L - -#define SN_document "document" -#define NID_document 447 -#define OBJ_document OBJ_pilotObjectClass,6L - -#define SN_room "room" -#define NID_room 448 -#define OBJ_room OBJ_pilotObjectClass,7L - -#define LN_documentSeries "documentSeries" -#define NID_documentSeries 449 -#define OBJ_documentSeries OBJ_pilotObjectClass,9L - -#define SN_Domain "domain" -#define LN_Domain "Domain" -#define NID_Domain 392 -#define OBJ_Domain OBJ_pilotObjectClass,13L - -#define LN_rFC822localPart "rFC822localPart" -#define NID_rFC822localPart 450 -#define OBJ_rFC822localPart OBJ_pilotObjectClass,14L - -#define LN_dNSDomain "dNSDomain" -#define NID_dNSDomain 451 -#define OBJ_dNSDomain OBJ_pilotObjectClass,15L - -#define LN_domainRelatedObject "domainRelatedObject" -#define NID_domainRelatedObject 452 -#define OBJ_domainRelatedObject OBJ_pilotObjectClass,17L - -#define LN_friendlyCountry "friendlyCountry" -#define NID_friendlyCountry 453 -#define OBJ_friendlyCountry OBJ_pilotObjectClass,18L - -#define LN_simpleSecurityObject "simpleSecurityObject" -#define NID_simpleSecurityObject 454 -#define OBJ_simpleSecurityObject OBJ_pilotObjectClass,19L - -#define LN_pilotOrganization "pilotOrganization" -#define NID_pilotOrganization 455 -#define OBJ_pilotOrganization OBJ_pilotObjectClass,20L - -#define LN_pilotDSA "pilotDSA" -#define NID_pilotDSA 456 -#define OBJ_pilotDSA OBJ_pilotObjectClass,21L - -#define LN_qualityLabelledData "qualityLabelledData" -#define NID_qualityLabelledData 457 -#define OBJ_qualityLabelledData OBJ_pilotObjectClass,22L - -#define SN_userId "UID" -#define LN_userId "userId" -#define NID_userId 458 -#define OBJ_userId OBJ_pilotAttributeType,1L - -#define LN_textEncodedORAddress "textEncodedORAddress" -#define NID_textEncodedORAddress 459 -#define OBJ_textEncodedORAddress OBJ_pilotAttributeType,2L - -#define SN_rfc822Mailbox "mail" -#define LN_rfc822Mailbox "rfc822Mailbox" -#define NID_rfc822Mailbox 460 -#define OBJ_rfc822Mailbox OBJ_pilotAttributeType,3L - -#define SN_info "info" -#define NID_info 461 -#define OBJ_info OBJ_pilotAttributeType,4L - -#define LN_favouriteDrink "favouriteDrink" -#define NID_favouriteDrink 462 -#define OBJ_favouriteDrink OBJ_pilotAttributeType,5L - -#define LN_roomNumber "roomNumber" -#define NID_roomNumber 463 -#define OBJ_roomNumber OBJ_pilotAttributeType,6L - -#define SN_photo "photo" -#define NID_photo 464 -#define OBJ_photo OBJ_pilotAttributeType,7L - -#define LN_userClass "userClass" -#define NID_userClass 465 -#define OBJ_userClass OBJ_pilotAttributeType,8L - -#define SN_host "host" -#define NID_host 466 -#define OBJ_host OBJ_pilotAttributeType,9L - -#define SN_manager "manager" -#define NID_manager 467 -#define OBJ_manager OBJ_pilotAttributeType,10L - -#define LN_documentIdentifier "documentIdentifier" -#define NID_documentIdentifier 468 -#define OBJ_documentIdentifier OBJ_pilotAttributeType,11L - -#define LN_documentTitle "documentTitle" -#define NID_documentTitle 469 -#define OBJ_documentTitle OBJ_pilotAttributeType,12L - -#define LN_documentVersion "documentVersion" -#define NID_documentVersion 470 -#define OBJ_documentVersion OBJ_pilotAttributeType,13L - -#define LN_documentAuthor "documentAuthor" -#define NID_documentAuthor 471 -#define OBJ_documentAuthor OBJ_pilotAttributeType,14L - -#define LN_documentLocation "documentLocation" -#define NID_documentLocation 472 -#define OBJ_documentLocation OBJ_pilotAttributeType,15L - -#define LN_homeTelephoneNumber "homeTelephoneNumber" -#define NID_homeTelephoneNumber 473 -#define OBJ_homeTelephoneNumber OBJ_pilotAttributeType,20L - -#define SN_secretary "secretary" -#define NID_secretary 474 -#define OBJ_secretary OBJ_pilotAttributeType,21L - -#define LN_otherMailbox "otherMailbox" -#define NID_otherMailbox 475 -#define OBJ_otherMailbox OBJ_pilotAttributeType,22L - -#define LN_lastModifiedTime "lastModifiedTime" -#define NID_lastModifiedTime 476 -#define OBJ_lastModifiedTime OBJ_pilotAttributeType,23L - -#define LN_lastModifiedBy "lastModifiedBy" -#define NID_lastModifiedBy 477 -#define OBJ_lastModifiedBy OBJ_pilotAttributeType,24L - -#define SN_domainComponent "DC" -#define LN_domainComponent "domainComponent" -#define NID_domainComponent 391 -#define OBJ_domainComponent OBJ_pilotAttributeType,25L - -#define LN_aRecord "aRecord" -#define NID_aRecord 478 -#define OBJ_aRecord OBJ_pilotAttributeType,26L - -#define LN_pilotAttributeType27 "pilotAttributeType27" -#define NID_pilotAttributeType27 479 -#define OBJ_pilotAttributeType27 OBJ_pilotAttributeType,27L - -#define LN_mXRecord "mXRecord" -#define NID_mXRecord 480 -#define OBJ_mXRecord OBJ_pilotAttributeType,28L - -#define LN_nSRecord "nSRecord" -#define NID_nSRecord 481 -#define OBJ_nSRecord OBJ_pilotAttributeType,29L - -#define LN_sOARecord "sOARecord" -#define NID_sOARecord 482 -#define OBJ_sOARecord OBJ_pilotAttributeType,30L - -#define LN_cNAMERecord "cNAMERecord" -#define NID_cNAMERecord 483 -#define OBJ_cNAMERecord OBJ_pilotAttributeType,31L - -#define LN_associatedDomain "associatedDomain" -#define NID_associatedDomain 484 -#define OBJ_associatedDomain OBJ_pilotAttributeType,37L - -#define LN_associatedName "associatedName" -#define NID_associatedName 485 -#define OBJ_associatedName OBJ_pilotAttributeType,38L - -#define LN_homePostalAddress "homePostalAddress" -#define NID_homePostalAddress 486 -#define OBJ_homePostalAddress OBJ_pilotAttributeType,39L - -#define LN_personalTitle "personalTitle" -#define NID_personalTitle 487 -#define OBJ_personalTitle OBJ_pilotAttributeType,40L - -#define LN_mobileTelephoneNumber "mobileTelephoneNumber" -#define NID_mobileTelephoneNumber 488 -#define OBJ_mobileTelephoneNumber OBJ_pilotAttributeType,41L - -#define LN_pagerTelephoneNumber "pagerTelephoneNumber" -#define NID_pagerTelephoneNumber 489 -#define OBJ_pagerTelephoneNumber OBJ_pilotAttributeType,42L - -#define LN_friendlyCountryName "friendlyCountryName" -#define NID_friendlyCountryName 490 -#define OBJ_friendlyCountryName OBJ_pilotAttributeType,43L - -#define LN_organizationalStatus "organizationalStatus" -#define NID_organizationalStatus 491 -#define OBJ_organizationalStatus OBJ_pilotAttributeType,45L - -#define LN_janetMailbox "janetMailbox" -#define NID_janetMailbox 492 -#define OBJ_janetMailbox OBJ_pilotAttributeType,46L - -#define LN_mailPreferenceOption "mailPreferenceOption" -#define NID_mailPreferenceOption 493 -#define OBJ_mailPreferenceOption OBJ_pilotAttributeType,47L - -#define LN_buildingName "buildingName" -#define NID_buildingName 494 -#define OBJ_buildingName OBJ_pilotAttributeType,48L - -#define LN_dSAQuality "dSAQuality" -#define NID_dSAQuality 495 -#define OBJ_dSAQuality OBJ_pilotAttributeType,49L - -#define LN_singleLevelQuality "singleLevelQuality" -#define NID_singleLevelQuality 496 -#define OBJ_singleLevelQuality OBJ_pilotAttributeType,50L - -#define LN_subtreeMinimumQuality "subtreeMinimumQuality" -#define NID_subtreeMinimumQuality 497 -#define OBJ_subtreeMinimumQuality OBJ_pilotAttributeType,51L - -#define LN_subtreeMaximumQuality "subtreeMaximumQuality" -#define NID_subtreeMaximumQuality 498 -#define OBJ_subtreeMaximumQuality OBJ_pilotAttributeType,52L - -#define LN_personalSignature "personalSignature" -#define NID_personalSignature 499 -#define OBJ_personalSignature OBJ_pilotAttributeType,53L - -#define LN_dITRedirect "dITRedirect" -#define NID_dITRedirect 500 -#define OBJ_dITRedirect OBJ_pilotAttributeType,54L - -#define SN_audio "audio" -#define NID_audio 501 -#define OBJ_audio OBJ_pilotAttributeType,55L - -#define LN_documentPublisher "documentPublisher" -#define NID_documentPublisher 502 -#define OBJ_documentPublisher OBJ_pilotAttributeType,56L - -#define SN_id_set "id-set" -#define LN_id_set "Secure Electronic Transactions" -#define NID_id_set 512 -#define OBJ_id_set OBJ_international_organizations,42L - -#define SN_set_ctype "set-ctype" -#define LN_set_ctype "content types" -#define NID_set_ctype 513 -#define OBJ_set_ctype OBJ_id_set,0L - -#define SN_set_msgExt "set-msgExt" -#define LN_set_msgExt "message extensions" -#define NID_set_msgExt 514 -#define OBJ_set_msgExt OBJ_id_set,1L - -#define SN_set_attr "set-attr" -#define NID_set_attr 515 -#define OBJ_set_attr OBJ_id_set,3L - -#define SN_set_policy "set-policy" -#define NID_set_policy 516 -#define OBJ_set_policy OBJ_id_set,5L - -#define SN_set_certExt "set-certExt" -#define LN_set_certExt "certificate extensions" -#define NID_set_certExt 517 -#define OBJ_set_certExt OBJ_id_set,7L - -#define SN_set_brand "set-brand" -#define NID_set_brand 518 -#define OBJ_set_brand OBJ_id_set,8L - -#define SN_setct_PANData "setct-PANData" -#define NID_setct_PANData 519 -#define OBJ_setct_PANData OBJ_set_ctype,0L - -#define SN_setct_PANToken "setct-PANToken" -#define NID_setct_PANToken 520 -#define OBJ_setct_PANToken OBJ_set_ctype,1L - -#define SN_setct_PANOnly "setct-PANOnly" -#define NID_setct_PANOnly 521 -#define OBJ_setct_PANOnly OBJ_set_ctype,2L - -#define SN_setct_OIData "setct-OIData" -#define NID_setct_OIData 522 -#define OBJ_setct_OIData OBJ_set_ctype,3L - -#define SN_setct_PI "setct-PI" -#define NID_setct_PI 523 -#define OBJ_setct_PI OBJ_set_ctype,4L - -#define SN_setct_PIData "setct-PIData" -#define NID_setct_PIData 524 -#define OBJ_setct_PIData OBJ_set_ctype,5L - -#define SN_setct_PIDataUnsigned "setct-PIDataUnsigned" -#define NID_setct_PIDataUnsigned 525 -#define OBJ_setct_PIDataUnsigned OBJ_set_ctype,6L - -#define SN_setct_HODInput "setct-HODInput" -#define NID_setct_HODInput 526 -#define OBJ_setct_HODInput OBJ_set_ctype,7L - -#define SN_setct_AuthResBaggage "setct-AuthResBaggage" -#define NID_setct_AuthResBaggage 527 -#define OBJ_setct_AuthResBaggage OBJ_set_ctype,8L - -#define SN_setct_AuthRevReqBaggage "setct-AuthRevReqBaggage" -#define NID_setct_AuthRevReqBaggage 528 -#define OBJ_setct_AuthRevReqBaggage OBJ_set_ctype,9L - -#define SN_setct_AuthRevResBaggage "setct-AuthRevResBaggage" -#define NID_setct_AuthRevResBaggage 529 -#define OBJ_setct_AuthRevResBaggage OBJ_set_ctype,10L - -#define SN_setct_CapTokenSeq "setct-CapTokenSeq" -#define NID_setct_CapTokenSeq 530 -#define OBJ_setct_CapTokenSeq OBJ_set_ctype,11L - -#define SN_setct_PInitResData "setct-PInitResData" -#define NID_setct_PInitResData 531 -#define OBJ_setct_PInitResData OBJ_set_ctype,12L - -#define SN_setct_PI_TBS "setct-PI-TBS" -#define NID_setct_PI_TBS 532 -#define OBJ_setct_PI_TBS OBJ_set_ctype,13L - -#define SN_setct_PResData "setct-PResData" -#define NID_setct_PResData 533 -#define OBJ_setct_PResData OBJ_set_ctype,14L - -#define SN_setct_AuthReqTBS "setct-AuthReqTBS" -#define NID_setct_AuthReqTBS 534 -#define OBJ_setct_AuthReqTBS OBJ_set_ctype,16L - -#define SN_setct_AuthResTBS "setct-AuthResTBS" -#define NID_setct_AuthResTBS 535 -#define OBJ_setct_AuthResTBS OBJ_set_ctype,17L - -#define SN_setct_AuthResTBSX "setct-AuthResTBSX" -#define NID_setct_AuthResTBSX 536 -#define OBJ_setct_AuthResTBSX OBJ_set_ctype,18L - -#define SN_setct_AuthTokenTBS "setct-AuthTokenTBS" -#define NID_setct_AuthTokenTBS 537 -#define OBJ_setct_AuthTokenTBS OBJ_set_ctype,19L - -#define SN_setct_CapTokenData "setct-CapTokenData" -#define NID_setct_CapTokenData 538 -#define OBJ_setct_CapTokenData OBJ_set_ctype,20L - -#define SN_setct_CapTokenTBS "setct-CapTokenTBS" -#define NID_setct_CapTokenTBS 539 -#define OBJ_setct_CapTokenTBS OBJ_set_ctype,21L - -#define SN_setct_AcqCardCodeMsg "setct-AcqCardCodeMsg" -#define NID_setct_AcqCardCodeMsg 540 -#define OBJ_setct_AcqCardCodeMsg OBJ_set_ctype,22L - -#define SN_setct_AuthRevReqTBS "setct-AuthRevReqTBS" -#define NID_setct_AuthRevReqTBS 541 -#define OBJ_setct_AuthRevReqTBS OBJ_set_ctype,23L - -#define SN_setct_AuthRevResData "setct-AuthRevResData" -#define NID_setct_AuthRevResData 542 -#define OBJ_setct_AuthRevResData OBJ_set_ctype,24L - -#define SN_setct_AuthRevResTBS "setct-AuthRevResTBS" -#define NID_setct_AuthRevResTBS 543 -#define OBJ_setct_AuthRevResTBS OBJ_set_ctype,25L - -#define SN_setct_CapReqTBS "setct-CapReqTBS" -#define NID_setct_CapReqTBS 544 -#define OBJ_setct_CapReqTBS OBJ_set_ctype,26L - -#define SN_setct_CapReqTBSX "setct-CapReqTBSX" -#define NID_setct_CapReqTBSX 545 -#define OBJ_setct_CapReqTBSX OBJ_set_ctype,27L - -#define SN_setct_CapResData "setct-CapResData" -#define NID_setct_CapResData 546 -#define OBJ_setct_CapResData OBJ_set_ctype,28L - -#define SN_setct_CapRevReqTBS "setct-CapRevReqTBS" -#define NID_setct_CapRevReqTBS 547 -#define OBJ_setct_CapRevReqTBS OBJ_set_ctype,29L - -#define SN_setct_CapRevReqTBSX "setct-CapRevReqTBSX" -#define NID_setct_CapRevReqTBSX 548 -#define OBJ_setct_CapRevReqTBSX OBJ_set_ctype,30L - -#define SN_setct_CapRevResData "setct-CapRevResData" -#define NID_setct_CapRevResData 549 -#define OBJ_setct_CapRevResData OBJ_set_ctype,31L - -#define SN_setct_CredReqTBS "setct-CredReqTBS" -#define NID_setct_CredReqTBS 550 -#define OBJ_setct_CredReqTBS OBJ_set_ctype,32L - -#define SN_setct_CredReqTBSX "setct-CredReqTBSX" -#define NID_setct_CredReqTBSX 551 -#define OBJ_setct_CredReqTBSX OBJ_set_ctype,33L - -#define SN_setct_CredResData "setct-CredResData" -#define NID_setct_CredResData 552 -#define OBJ_setct_CredResData OBJ_set_ctype,34L - -#define SN_setct_CredRevReqTBS "setct-CredRevReqTBS" -#define NID_setct_CredRevReqTBS 553 -#define OBJ_setct_CredRevReqTBS OBJ_set_ctype,35L - -#define SN_setct_CredRevReqTBSX "setct-CredRevReqTBSX" -#define NID_setct_CredRevReqTBSX 554 -#define OBJ_setct_CredRevReqTBSX OBJ_set_ctype,36L - -#define SN_setct_CredRevResData "setct-CredRevResData" -#define NID_setct_CredRevResData 555 -#define OBJ_setct_CredRevResData OBJ_set_ctype,37L - -#define SN_setct_PCertReqData "setct-PCertReqData" -#define NID_setct_PCertReqData 556 -#define OBJ_setct_PCertReqData OBJ_set_ctype,38L - -#define SN_setct_PCertResTBS "setct-PCertResTBS" -#define NID_setct_PCertResTBS 557 -#define OBJ_setct_PCertResTBS OBJ_set_ctype,39L - -#define SN_setct_BatchAdminReqData "setct-BatchAdminReqData" -#define NID_setct_BatchAdminReqData 558 -#define OBJ_setct_BatchAdminReqData OBJ_set_ctype,40L - -#define SN_setct_BatchAdminResData "setct-BatchAdminResData" -#define NID_setct_BatchAdminResData 559 -#define OBJ_setct_BatchAdminResData OBJ_set_ctype,41L - -#define SN_setct_CardCInitResTBS "setct-CardCInitResTBS" -#define NID_setct_CardCInitResTBS 560 -#define OBJ_setct_CardCInitResTBS OBJ_set_ctype,42L - -#define SN_setct_MeAqCInitResTBS "setct-MeAqCInitResTBS" -#define NID_setct_MeAqCInitResTBS 561 -#define OBJ_setct_MeAqCInitResTBS OBJ_set_ctype,43L - -#define SN_setct_RegFormResTBS "setct-RegFormResTBS" -#define NID_setct_RegFormResTBS 562 -#define OBJ_setct_RegFormResTBS OBJ_set_ctype,44L - -#define SN_setct_CertReqData "setct-CertReqData" -#define NID_setct_CertReqData 563 -#define OBJ_setct_CertReqData OBJ_set_ctype,45L - -#define SN_setct_CertReqTBS "setct-CertReqTBS" -#define NID_setct_CertReqTBS 564 -#define OBJ_setct_CertReqTBS OBJ_set_ctype,46L - -#define SN_setct_CertResData "setct-CertResData" -#define NID_setct_CertResData 565 -#define OBJ_setct_CertResData OBJ_set_ctype,47L - -#define SN_setct_CertInqReqTBS "setct-CertInqReqTBS" -#define NID_setct_CertInqReqTBS 566 -#define OBJ_setct_CertInqReqTBS OBJ_set_ctype,48L - -#define SN_setct_ErrorTBS "setct-ErrorTBS" -#define NID_setct_ErrorTBS 567 -#define OBJ_setct_ErrorTBS OBJ_set_ctype,49L - -#define SN_setct_PIDualSignedTBE "setct-PIDualSignedTBE" -#define NID_setct_PIDualSignedTBE 568 -#define OBJ_setct_PIDualSignedTBE OBJ_set_ctype,50L - -#define SN_setct_PIUnsignedTBE "setct-PIUnsignedTBE" -#define NID_setct_PIUnsignedTBE 569 -#define OBJ_setct_PIUnsignedTBE OBJ_set_ctype,51L - -#define SN_setct_AuthReqTBE "setct-AuthReqTBE" -#define NID_setct_AuthReqTBE 570 -#define OBJ_setct_AuthReqTBE OBJ_set_ctype,52L - -#define SN_setct_AuthResTBE "setct-AuthResTBE" -#define NID_setct_AuthResTBE 571 -#define OBJ_setct_AuthResTBE OBJ_set_ctype,53L - -#define SN_setct_AuthResTBEX "setct-AuthResTBEX" -#define NID_setct_AuthResTBEX 572 -#define OBJ_setct_AuthResTBEX OBJ_set_ctype,54L - -#define SN_setct_AuthTokenTBE "setct-AuthTokenTBE" -#define NID_setct_AuthTokenTBE 573 -#define OBJ_setct_AuthTokenTBE OBJ_set_ctype,55L - -#define SN_setct_CapTokenTBE "setct-CapTokenTBE" -#define NID_setct_CapTokenTBE 574 -#define OBJ_setct_CapTokenTBE OBJ_set_ctype,56L - -#define SN_setct_CapTokenTBEX "setct-CapTokenTBEX" -#define NID_setct_CapTokenTBEX 575 -#define OBJ_setct_CapTokenTBEX OBJ_set_ctype,57L - -#define SN_setct_AcqCardCodeMsgTBE "setct-AcqCardCodeMsgTBE" -#define NID_setct_AcqCardCodeMsgTBE 576 -#define OBJ_setct_AcqCardCodeMsgTBE OBJ_set_ctype,58L - -#define SN_setct_AuthRevReqTBE "setct-AuthRevReqTBE" -#define NID_setct_AuthRevReqTBE 577 -#define OBJ_setct_AuthRevReqTBE OBJ_set_ctype,59L - -#define SN_setct_AuthRevResTBE "setct-AuthRevResTBE" -#define NID_setct_AuthRevResTBE 578 -#define OBJ_setct_AuthRevResTBE OBJ_set_ctype,60L - -#define SN_setct_AuthRevResTBEB "setct-AuthRevResTBEB" -#define NID_setct_AuthRevResTBEB 579 -#define OBJ_setct_AuthRevResTBEB OBJ_set_ctype,61L - -#define SN_setct_CapReqTBE "setct-CapReqTBE" -#define NID_setct_CapReqTBE 580 -#define OBJ_setct_CapReqTBE OBJ_set_ctype,62L - -#define SN_setct_CapReqTBEX "setct-CapReqTBEX" -#define NID_setct_CapReqTBEX 581 -#define OBJ_setct_CapReqTBEX OBJ_set_ctype,63L - -#define SN_setct_CapResTBE "setct-CapResTBE" -#define NID_setct_CapResTBE 582 -#define OBJ_setct_CapResTBE OBJ_set_ctype,64L - -#define SN_setct_CapRevReqTBE "setct-CapRevReqTBE" -#define NID_setct_CapRevReqTBE 583 -#define OBJ_setct_CapRevReqTBE OBJ_set_ctype,65L - -#define SN_setct_CapRevReqTBEX "setct-CapRevReqTBEX" -#define NID_setct_CapRevReqTBEX 584 -#define OBJ_setct_CapRevReqTBEX OBJ_set_ctype,66L - -#define SN_setct_CapRevResTBE "setct-CapRevResTBE" -#define NID_setct_CapRevResTBE 585 -#define OBJ_setct_CapRevResTBE OBJ_set_ctype,67L - -#define SN_setct_CredReqTBE "setct-CredReqTBE" -#define NID_setct_CredReqTBE 586 -#define OBJ_setct_CredReqTBE OBJ_set_ctype,68L - -#define SN_setct_CredReqTBEX "setct-CredReqTBEX" -#define NID_setct_CredReqTBEX 587 -#define OBJ_setct_CredReqTBEX OBJ_set_ctype,69L - -#define SN_setct_CredResTBE "setct-CredResTBE" -#define NID_setct_CredResTBE 588 -#define OBJ_setct_CredResTBE OBJ_set_ctype,70L - -#define SN_setct_CredRevReqTBE "setct-CredRevReqTBE" -#define NID_setct_CredRevReqTBE 589 -#define OBJ_setct_CredRevReqTBE OBJ_set_ctype,71L - -#define SN_setct_CredRevReqTBEX "setct-CredRevReqTBEX" -#define NID_setct_CredRevReqTBEX 590 -#define OBJ_setct_CredRevReqTBEX OBJ_set_ctype,72L - -#define SN_setct_CredRevResTBE "setct-CredRevResTBE" -#define NID_setct_CredRevResTBE 591 -#define OBJ_setct_CredRevResTBE OBJ_set_ctype,73L - -#define SN_setct_BatchAdminReqTBE "setct-BatchAdminReqTBE" -#define NID_setct_BatchAdminReqTBE 592 -#define OBJ_setct_BatchAdminReqTBE OBJ_set_ctype,74L - -#define SN_setct_BatchAdminResTBE "setct-BatchAdminResTBE" -#define NID_setct_BatchAdminResTBE 593 -#define OBJ_setct_BatchAdminResTBE OBJ_set_ctype,75L - -#define SN_setct_RegFormReqTBE "setct-RegFormReqTBE" -#define NID_setct_RegFormReqTBE 594 -#define OBJ_setct_RegFormReqTBE OBJ_set_ctype,76L - -#define SN_setct_CertReqTBE "setct-CertReqTBE" -#define NID_setct_CertReqTBE 595 -#define OBJ_setct_CertReqTBE OBJ_set_ctype,77L - -#define SN_setct_CertReqTBEX "setct-CertReqTBEX" -#define NID_setct_CertReqTBEX 596 -#define OBJ_setct_CertReqTBEX OBJ_set_ctype,78L - -#define SN_setct_CertResTBE "setct-CertResTBE" -#define NID_setct_CertResTBE 597 -#define OBJ_setct_CertResTBE OBJ_set_ctype,79L - -#define SN_setct_CRLNotificationTBS "setct-CRLNotificationTBS" -#define NID_setct_CRLNotificationTBS 598 -#define OBJ_setct_CRLNotificationTBS OBJ_set_ctype,80L - -#define SN_setct_CRLNotificationResTBS "setct-CRLNotificationResTBS" -#define NID_setct_CRLNotificationResTBS 599 -#define OBJ_setct_CRLNotificationResTBS OBJ_set_ctype,81L - -#define SN_setct_BCIDistributionTBS "setct-BCIDistributionTBS" -#define NID_setct_BCIDistributionTBS 600 -#define OBJ_setct_BCIDistributionTBS OBJ_set_ctype,82L - -#define SN_setext_genCrypt "setext-genCrypt" -#define LN_setext_genCrypt "generic cryptogram" -#define NID_setext_genCrypt 601 -#define OBJ_setext_genCrypt OBJ_set_msgExt,1L - -#define SN_setext_miAuth "setext-miAuth" -#define LN_setext_miAuth "merchant initiated auth" -#define NID_setext_miAuth 602 -#define OBJ_setext_miAuth OBJ_set_msgExt,3L - -#define SN_setext_pinSecure "setext-pinSecure" -#define NID_setext_pinSecure 603 -#define OBJ_setext_pinSecure OBJ_set_msgExt,4L - -#define SN_setext_pinAny "setext-pinAny" -#define NID_setext_pinAny 604 -#define OBJ_setext_pinAny OBJ_set_msgExt,5L - -#define SN_setext_track2 "setext-track2" -#define NID_setext_track2 605 -#define OBJ_setext_track2 OBJ_set_msgExt,7L - -#define SN_setext_cv "setext-cv" -#define LN_setext_cv "additional verification" -#define NID_setext_cv 606 -#define OBJ_setext_cv OBJ_set_msgExt,8L - -#define SN_set_policy_root "set-policy-root" -#define NID_set_policy_root 607 -#define OBJ_set_policy_root OBJ_set_policy,0L - -#define SN_setCext_hashedRoot "setCext-hashedRoot" -#define NID_setCext_hashedRoot 608 -#define OBJ_setCext_hashedRoot OBJ_set_certExt,0L - -#define SN_setCext_certType "setCext-certType" -#define NID_setCext_certType 609 -#define OBJ_setCext_certType OBJ_set_certExt,1L - -#define SN_setCext_merchData "setCext-merchData" -#define NID_setCext_merchData 610 -#define OBJ_setCext_merchData OBJ_set_certExt,2L - -#define SN_setCext_cCertRequired "setCext-cCertRequired" -#define NID_setCext_cCertRequired 611 -#define OBJ_setCext_cCertRequired OBJ_set_certExt,3L - -#define SN_setCext_tunneling "setCext-tunneling" -#define NID_setCext_tunneling 612 -#define OBJ_setCext_tunneling OBJ_set_certExt,4L - -#define SN_setCext_setExt "setCext-setExt" -#define NID_setCext_setExt 613 -#define OBJ_setCext_setExt OBJ_set_certExt,5L - -#define SN_setCext_setQualf "setCext-setQualf" -#define NID_setCext_setQualf 614 -#define OBJ_setCext_setQualf OBJ_set_certExt,6L - -#define SN_setCext_PGWYcapabilities "setCext-PGWYcapabilities" -#define NID_setCext_PGWYcapabilities 615 -#define OBJ_setCext_PGWYcapabilities OBJ_set_certExt,7L - -#define SN_setCext_TokenIdentifier "setCext-TokenIdentifier" -#define NID_setCext_TokenIdentifier 616 -#define OBJ_setCext_TokenIdentifier OBJ_set_certExt,8L - -#define SN_setCext_Track2Data "setCext-Track2Data" -#define NID_setCext_Track2Data 617 -#define OBJ_setCext_Track2Data OBJ_set_certExt,9L - -#define SN_setCext_TokenType "setCext-TokenType" -#define NID_setCext_TokenType 618 -#define OBJ_setCext_TokenType OBJ_set_certExt,10L - -#define SN_setCext_IssuerCapabilities "setCext-IssuerCapabilities" -#define NID_setCext_IssuerCapabilities 619 -#define OBJ_setCext_IssuerCapabilities OBJ_set_certExt,11L - -#define SN_setAttr_Cert "setAttr-Cert" -#define NID_setAttr_Cert 620 -#define OBJ_setAttr_Cert OBJ_set_attr,0L - -#define SN_setAttr_PGWYcap "setAttr-PGWYcap" -#define LN_setAttr_PGWYcap "payment gateway capabilities" -#define NID_setAttr_PGWYcap 621 -#define OBJ_setAttr_PGWYcap OBJ_set_attr,1L - -#define SN_setAttr_TokenType "setAttr-TokenType" -#define NID_setAttr_TokenType 622 -#define OBJ_setAttr_TokenType OBJ_set_attr,2L - -#define SN_setAttr_IssCap "setAttr-IssCap" -#define LN_setAttr_IssCap "issuer capabilities" -#define NID_setAttr_IssCap 623 -#define OBJ_setAttr_IssCap OBJ_set_attr,3L - -#define SN_set_rootKeyThumb "set-rootKeyThumb" -#define NID_set_rootKeyThumb 624 -#define OBJ_set_rootKeyThumb OBJ_setAttr_Cert,0L - -#define SN_set_addPolicy "set-addPolicy" -#define NID_set_addPolicy 625 -#define OBJ_set_addPolicy OBJ_setAttr_Cert,1L - -#define SN_setAttr_Token_EMV "setAttr-Token-EMV" -#define NID_setAttr_Token_EMV 626 -#define OBJ_setAttr_Token_EMV OBJ_setAttr_TokenType,1L - -#define SN_setAttr_Token_B0Prime "setAttr-Token-B0Prime" -#define NID_setAttr_Token_B0Prime 627 -#define OBJ_setAttr_Token_B0Prime OBJ_setAttr_TokenType,2L - -#define SN_setAttr_IssCap_CVM "setAttr-IssCap-CVM" -#define NID_setAttr_IssCap_CVM 628 -#define OBJ_setAttr_IssCap_CVM OBJ_setAttr_IssCap,3L - -#define SN_setAttr_IssCap_T2 "setAttr-IssCap-T2" -#define NID_setAttr_IssCap_T2 629 -#define OBJ_setAttr_IssCap_T2 OBJ_setAttr_IssCap,4L - -#define SN_setAttr_IssCap_Sig "setAttr-IssCap-Sig" -#define NID_setAttr_IssCap_Sig 630 -#define OBJ_setAttr_IssCap_Sig OBJ_setAttr_IssCap,5L - -#define SN_setAttr_GenCryptgrm "setAttr-GenCryptgrm" -#define LN_setAttr_GenCryptgrm "generate cryptogram" -#define NID_setAttr_GenCryptgrm 631 -#define OBJ_setAttr_GenCryptgrm OBJ_setAttr_IssCap_CVM,1L - -#define SN_setAttr_T2Enc "setAttr-T2Enc" -#define LN_setAttr_T2Enc "encrypted track 2" -#define NID_setAttr_T2Enc 632 -#define OBJ_setAttr_T2Enc OBJ_setAttr_IssCap_T2,1L - -#define SN_setAttr_T2cleartxt "setAttr-T2cleartxt" -#define LN_setAttr_T2cleartxt "cleartext track 2" -#define NID_setAttr_T2cleartxt 633 -#define OBJ_setAttr_T2cleartxt OBJ_setAttr_IssCap_T2,2L - -#define SN_setAttr_TokICCsig "setAttr-TokICCsig" -#define LN_setAttr_TokICCsig "ICC or token signature" -#define NID_setAttr_TokICCsig 634 -#define OBJ_setAttr_TokICCsig OBJ_setAttr_IssCap_Sig,1L - -#define SN_setAttr_SecDevSig "setAttr-SecDevSig" -#define LN_setAttr_SecDevSig "secure device signature" -#define NID_setAttr_SecDevSig 635 -#define OBJ_setAttr_SecDevSig OBJ_setAttr_IssCap_Sig,2L - -#define SN_set_brand_IATA_ATA "set-brand-IATA-ATA" -#define NID_set_brand_IATA_ATA 636 -#define OBJ_set_brand_IATA_ATA OBJ_set_brand,1L - -#define SN_set_brand_Diners "set-brand-Diners" -#define NID_set_brand_Diners 637 -#define OBJ_set_brand_Diners OBJ_set_brand,30L - -#define SN_set_brand_AmericanExpress "set-brand-AmericanExpress" -#define NID_set_brand_AmericanExpress 638 -#define OBJ_set_brand_AmericanExpress OBJ_set_brand,34L - -#define SN_set_brand_JCB "set-brand-JCB" -#define NID_set_brand_JCB 639 -#define OBJ_set_brand_JCB OBJ_set_brand,35L - -#define SN_set_brand_Visa "set-brand-Visa" -#define NID_set_brand_Visa 640 -#define OBJ_set_brand_Visa OBJ_set_brand,4L - -#define SN_set_brand_MasterCard "set-brand-MasterCard" -#define NID_set_brand_MasterCard 641 -#define OBJ_set_brand_MasterCard OBJ_set_brand,5L - -#define SN_set_brand_Novus "set-brand-Novus" -#define NID_set_brand_Novus 642 -#define OBJ_set_brand_Novus OBJ_set_brand,6011L - -#define SN_des_cdmf "DES-CDMF" -#define LN_des_cdmf "des-cdmf" -#define NID_des_cdmf 643 -#define OBJ_des_cdmf OBJ_rsadsi,3L,10L - -#define SN_rsaOAEPEncryptionSET "rsaOAEPEncryptionSET" -#define NID_rsaOAEPEncryptionSET 644 -#define OBJ_rsaOAEPEncryptionSET OBJ_rsadsi,1L,1L,6L - -#define SN_ipsec3 "Oakley-EC2N-3" -#define LN_ipsec3 "ipsec3" -#define NID_ipsec3 749 - -#define SN_ipsec4 "Oakley-EC2N-4" -#define LN_ipsec4 "ipsec4" -#define NID_ipsec4 750 - -#define SN_whirlpool "whirlpool" -#define NID_whirlpool 804 -#define OBJ_whirlpool OBJ_iso,0L,10118L,3L,0L,55L - -#define SN_cryptopro "cryptopro" -#define NID_cryptopro 805 -#define OBJ_cryptopro OBJ_member_body,643L,2L,2L - -#define SN_cryptocom "cryptocom" -#define NID_cryptocom 806 -#define OBJ_cryptocom OBJ_member_body,643L,2L,9L - -#define SN_id_GostR3411_94_with_GostR3410_2001 "id-GostR3411-94-with-GostR3410-2001" -#define LN_id_GostR3411_94_with_GostR3410_2001 "GOST R 34.11-94 with GOST R 34.10-2001" -#define NID_id_GostR3411_94_with_GostR3410_2001 807 -#define OBJ_id_GostR3411_94_with_GostR3410_2001 OBJ_cryptopro,3L - -#define SN_id_GostR3411_94_with_GostR3410_94 "id-GostR3411-94-with-GostR3410-94" -#define LN_id_GostR3411_94_with_GostR3410_94 "GOST R 34.11-94 with GOST R 34.10-94" -#define NID_id_GostR3411_94_with_GostR3410_94 808 -#define OBJ_id_GostR3411_94_with_GostR3410_94 OBJ_cryptopro,4L - -#define SN_id_GostR3411_94 "md_gost94" -#define LN_id_GostR3411_94 "GOST R 34.11-94" -#define NID_id_GostR3411_94 809 -#define OBJ_id_GostR3411_94 OBJ_cryptopro,9L - -#define SN_id_HMACGostR3411_94 "id-HMACGostR3411-94" -#define LN_id_HMACGostR3411_94 "HMAC GOST 34.11-94" -#define NID_id_HMACGostR3411_94 810 -#define OBJ_id_HMACGostR3411_94 OBJ_cryptopro,10L - -#define SN_id_GostR3410_2001 "gost2001" -#define LN_id_GostR3410_2001 "GOST R 34.10-2001" -#define NID_id_GostR3410_2001 811 -#define OBJ_id_GostR3410_2001 OBJ_cryptopro,19L - -#define SN_id_GostR3410_94 "gost94" -#define LN_id_GostR3410_94 "GOST R 34.10-94" -#define NID_id_GostR3410_94 812 -#define OBJ_id_GostR3410_94 OBJ_cryptopro,20L - -#define SN_id_Gost28147_89 "gost89" -#define LN_id_Gost28147_89 "GOST 28147-89" -#define NID_id_Gost28147_89 813 -#define OBJ_id_Gost28147_89 OBJ_cryptopro,21L - -#define SN_gost89_cnt "gost89-cnt" -#define NID_gost89_cnt 814 - -#define SN_id_Gost28147_89_MAC "gost-mac" -#define LN_id_Gost28147_89_MAC "GOST 28147-89 MAC" -#define NID_id_Gost28147_89_MAC 815 -#define OBJ_id_Gost28147_89_MAC OBJ_cryptopro,22L - -#define SN_id_GostR3411_94_prf "prf-gostr3411-94" -#define LN_id_GostR3411_94_prf "GOST R 34.11-94 PRF" -#define NID_id_GostR3411_94_prf 816 -#define OBJ_id_GostR3411_94_prf OBJ_cryptopro,23L - -#define SN_id_GostR3410_2001DH "id-GostR3410-2001DH" -#define LN_id_GostR3410_2001DH "GOST R 34.10-2001 DH" -#define NID_id_GostR3410_2001DH 817 -#define OBJ_id_GostR3410_2001DH OBJ_cryptopro,98L - -#define SN_id_GostR3410_94DH "id-GostR3410-94DH" -#define LN_id_GostR3410_94DH "GOST R 34.10-94 DH" -#define NID_id_GostR3410_94DH 818 -#define OBJ_id_GostR3410_94DH OBJ_cryptopro,99L - -#define SN_id_Gost28147_89_CryptoPro_KeyMeshing "id-Gost28147-89-CryptoPro-KeyMeshing" -#define NID_id_Gost28147_89_CryptoPro_KeyMeshing 819 -#define OBJ_id_Gost28147_89_CryptoPro_KeyMeshing OBJ_cryptopro,14L,1L - -#define SN_id_Gost28147_89_None_KeyMeshing "id-Gost28147-89-None-KeyMeshing" -#define NID_id_Gost28147_89_None_KeyMeshing 820 -#define OBJ_id_Gost28147_89_None_KeyMeshing OBJ_cryptopro,14L,0L - -#define SN_id_GostR3411_94_TestParamSet "id-GostR3411-94-TestParamSet" -#define NID_id_GostR3411_94_TestParamSet 821 -#define OBJ_id_GostR3411_94_TestParamSet OBJ_cryptopro,30L,0L - -#define SN_id_GostR3411_94_CryptoProParamSet "id-GostR3411-94-CryptoProParamSet" -#define NID_id_GostR3411_94_CryptoProParamSet 822 -#define OBJ_id_GostR3411_94_CryptoProParamSet OBJ_cryptopro,30L,1L - -#define SN_id_Gost28147_89_TestParamSet "id-Gost28147-89-TestParamSet" -#define NID_id_Gost28147_89_TestParamSet 823 -#define OBJ_id_Gost28147_89_TestParamSet OBJ_cryptopro,31L,0L - -#define SN_id_Gost28147_89_CryptoPro_A_ParamSet "id-Gost28147-89-CryptoPro-A-ParamSet" -#define NID_id_Gost28147_89_CryptoPro_A_ParamSet 824 -#define OBJ_id_Gost28147_89_CryptoPro_A_ParamSet OBJ_cryptopro,31L,1L - -#define SN_id_Gost28147_89_CryptoPro_B_ParamSet "id-Gost28147-89-CryptoPro-B-ParamSet" -#define NID_id_Gost28147_89_CryptoPro_B_ParamSet 825 -#define OBJ_id_Gost28147_89_CryptoPro_B_ParamSet OBJ_cryptopro,31L,2L - -#define SN_id_Gost28147_89_CryptoPro_C_ParamSet "id-Gost28147-89-CryptoPro-C-ParamSet" -#define NID_id_Gost28147_89_CryptoPro_C_ParamSet 826 -#define OBJ_id_Gost28147_89_CryptoPro_C_ParamSet OBJ_cryptopro,31L,3L - -#define SN_id_Gost28147_89_CryptoPro_D_ParamSet "id-Gost28147-89-CryptoPro-D-ParamSet" -#define NID_id_Gost28147_89_CryptoPro_D_ParamSet 827 -#define OBJ_id_Gost28147_89_CryptoPro_D_ParamSet OBJ_cryptopro,31L,4L - -#define SN_id_Gost28147_89_CryptoPro_Oscar_1_1_ParamSet "id-Gost28147-89-CryptoPro-Oscar-1-1-ParamSet" -#define NID_id_Gost28147_89_CryptoPro_Oscar_1_1_ParamSet 828 -#define OBJ_id_Gost28147_89_CryptoPro_Oscar_1_1_ParamSet OBJ_cryptopro,31L,5L - -#define SN_id_Gost28147_89_CryptoPro_Oscar_1_0_ParamSet "id-Gost28147-89-CryptoPro-Oscar-1-0-ParamSet" -#define NID_id_Gost28147_89_CryptoPro_Oscar_1_0_ParamSet 829 -#define OBJ_id_Gost28147_89_CryptoPro_Oscar_1_0_ParamSet OBJ_cryptopro,31L,6L - -#define SN_id_Gost28147_89_CryptoPro_RIC_1_ParamSet "id-Gost28147-89-CryptoPro-RIC-1-ParamSet" -#define NID_id_Gost28147_89_CryptoPro_RIC_1_ParamSet 830 -#define OBJ_id_Gost28147_89_CryptoPro_RIC_1_ParamSet OBJ_cryptopro,31L,7L - -#define SN_id_GostR3410_94_TestParamSet "id-GostR3410-94-TestParamSet" -#define NID_id_GostR3410_94_TestParamSet 831 -#define OBJ_id_GostR3410_94_TestParamSet OBJ_cryptopro,32L,0L - -#define SN_id_GostR3410_94_CryptoPro_A_ParamSet "id-GostR3410-94-CryptoPro-A-ParamSet" -#define NID_id_GostR3410_94_CryptoPro_A_ParamSet 832 -#define OBJ_id_GostR3410_94_CryptoPro_A_ParamSet OBJ_cryptopro,32L,2L - -#define SN_id_GostR3410_94_CryptoPro_B_ParamSet "id-GostR3410-94-CryptoPro-B-ParamSet" -#define NID_id_GostR3410_94_CryptoPro_B_ParamSet 833 -#define OBJ_id_GostR3410_94_CryptoPro_B_ParamSet OBJ_cryptopro,32L,3L - -#define SN_id_GostR3410_94_CryptoPro_C_ParamSet "id-GostR3410-94-CryptoPro-C-ParamSet" -#define NID_id_GostR3410_94_CryptoPro_C_ParamSet 834 -#define OBJ_id_GostR3410_94_CryptoPro_C_ParamSet OBJ_cryptopro,32L,4L - -#define SN_id_GostR3410_94_CryptoPro_D_ParamSet "id-GostR3410-94-CryptoPro-D-ParamSet" -#define NID_id_GostR3410_94_CryptoPro_D_ParamSet 835 -#define OBJ_id_GostR3410_94_CryptoPro_D_ParamSet OBJ_cryptopro,32L,5L - -#define SN_id_GostR3410_94_CryptoPro_XchA_ParamSet "id-GostR3410-94-CryptoPro-XchA-ParamSet" -#define NID_id_GostR3410_94_CryptoPro_XchA_ParamSet 836 -#define OBJ_id_GostR3410_94_CryptoPro_XchA_ParamSet OBJ_cryptopro,33L,1L - -#define SN_id_GostR3410_94_CryptoPro_XchB_ParamSet "id-GostR3410-94-CryptoPro-XchB-ParamSet" -#define NID_id_GostR3410_94_CryptoPro_XchB_ParamSet 837 -#define OBJ_id_GostR3410_94_CryptoPro_XchB_ParamSet OBJ_cryptopro,33L,2L - -#define SN_id_GostR3410_94_CryptoPro_XchC_ParamSet "id-GostR3410-94-CryptoPro-XchC-ParamSet" -#define NID_id_GostR3410_94_CryptoPro_XchC_ParamSet 838 -#define OBJ_id_GostR3410_94_CryptoPro_XchC_ParamSet OBJ_cryptopro,33L,3L - -#define SN_id_GostR3410_2001_TestParamSet "id-GostR3410-2001-TestParamSet" -#define NID_id_GostR3410_2001_TestParamSet 839 -#define OBJ_id_GostR3410_2001_TestParamSet OBJ_cryptopro,35L,0L - -#define SN_id_GostR3410_2001_CryptoPro_A_ParamSet "id-GostR3410-2001-CryptoPro-A-ParamSet" -#define NID_id_GostR3410_2001_CryptoPro_A_ParamSet 840 -#define OBJ_id_GostR3410_2001_CryptoPro_A_ParamSet OBJ_cryptopro,35L,1L - -#define SN_id_GostR3410_2001_CryptoPro_B_ParamSet "id-GostR3410-2001-CryptoPro-B-ParamSet" -#define NID_id_GostR3410_2001_CryptoPro_B_ParamSet 841 -#define OBJ_id_GostR3410_2001_CryptoPro_B_ParamSet OBJ_cryptopro,35L,2L - -#define SN_id_GostR3410_2001_CryptoPro_C_ParamSet "id-GostR3410-2001-CryptoPro-C-ParamSet" -#define NID_id_GostR3410_2001_CryptoPro_C_ParamSet 842 -#define OBJ_id_GostR3410_2001_CryptoPro_C_ParamSet OBJ_cryptopro,35L,3L - -#define SN_id_GostR3410_2001_CryptoPro_XchA_ParamSet "id-GostR3410-2001-CryptoPro-XchA-ParamSet" -#define NID_id_GostR3410_2001_CryptoPro_XchA_ParamSet 843 -#define OBJ_id_GostR3410_2001_CryptoPro_XchA_ParamSet OBJ_cryptopro,36L,0L - -#define SN_id_GostR3410_2001_CryptoPro_XchB_ParamSet "id-GostR3410-2001-CryptoPro-XchB-ParamSet" -#define NID_id_GostR3410_2001_CryptoPro_XchB_ParamSet 844 -#define OBJ_id_GostR3410_2001_CryptoPro_XchB_ParamSet OBJ_cryptopro,36L,1L - -#define SN_id_GostR3410_94_a "id-GostR3410-94-a" -#define NID_id_GostR3410_94_a 845 -#define OBJ_id_GostR3410_94_a OBJ_id_GostR3410_94,1L - -#define SN_id_GostR3410_94_aBis "id-GostR3410-94-aBis" -#define NID_id_GostR3410_94_aBis 846 -#define OBJ_id_GostR3410_94_aBis OBJ_id_GostR3410_94,2L - -#define SN_id_GostR3410_94_b "id-GostR3410-94-b" -#define NID_id_GostR3410_94_b 847 -#define OBJ_id_GostR3410_94_b OBJ_id_GostR3410_94,3L - -#define SN_id_GostR3410_94_bBis "id-GostR3410-94-bBis" -#define NID_id_GostR3410_94_bBis 848 -#define OBJ_id_GostR3410_94_bBis OBJ_id_GostR3410_94,4L - -#define SN_id_Gost28147_89_cc "id-Gost28147-89-cc" -#define LN_id_Gost28147_89_cc "GOST 28147-89 Cryptocom ParamSet" -#define NID_id_Gost28147_89_cc 849 -#define OBJ_id_Gost28147_89_cc OBJ_cryptocom,1L,6L,1L - -#define SN_id_GostR3410_94_cc "gost94cc" -#define LN_id_GostR3410_94_cc "GOST 34.10-94 Cryptocom" -#define NID_id_GostR3410_94_cc 850 -#define OBJ_id_GostR3410_94_cc OBJ_cryptocom,1L,5L,3L - -#define SN_id_GostR3410_2001_cc "gost2001cc" -#define LN_id_GostR3410_2001_cc "GOST 34.10-2001 Cryptocom" -#define NID_id_GostR3410_2001_cc 851 -#define OBJ_id_GostR3410_2001_cc OBJ_cryptocom,1L,5L,4L - -#define SN_id_GostR3411_94_with_GostR3410_94_cc "id-GostR3411-94-with-GostR3410-94-cc" -#define LN_id_GostR3411_94_with_GostR3410_94_cc "GOST R 34.11-94 with GOST R 34.10-94 Cryptocom" -#define NID_id_GostR3411_94_with_GostR3410_94_cc 852 -#define OBJ_id_GostR3411_94_with_GostR3410_94_cc OBJ_cryptocom,1L,3L,3L - -#define SN_id_GostR3411_94_with_GostR3410_2001_cc "id-GostR3411-94-with-GostR3410-2001-cc" -#define LN_id_GostR3411_94_with_GostR3410_2001_cc "GOST R 34.11-94 with GOST R 34.10-2001 Cryptocom" -#define NID_id_GostR3411_94_with_GostR3410_2001_cc 853 -#define OBJ_id_GostR3411_94_with_GostR3410_2001_cc OBJ_cryptocom,1L,3L,4L - -#define SN_id_GostR3410_2001_ParamSet_cc "id-GostR3410-2001-ParamSet-cc" -#define LN_id_GostR3410_2001_ParamSet_cc "GOST R 3410-2001 Parameter Set Cryptocom" -#define NID_id_GostR3410_2001_ParamSet_cc 854 -#define OBJ_id_GostR3410_2001_ParamSet_cc OBJ_cryptocom,1L,8L,1L - -#define SN_camellia_128_cbc "CAMELLIA-128-CBC" -#define LN_camellia_128_cbc "camellia-128-cbc" -#define NID_camellia_128_cbc 751 -#define OBJ_camellia_128_cbc 1L,2L,392L,200011L,61L,1L,1L,1L,2L - -#define SN_camellia_192_cbc "CAMELLIA-192-CBC" -#define LN_camellia_192_cbc "camellia-192-cbc" -#define NID_camellia_192_cbc 752 -#define OBJ_camellia_192_cbc 1L,2L,392L,200011L,61L,1L,1L,1L,3L - -#define SN_camellia_256_cbc "CAMELLIA-256-CBC" -#define LN_camellia_256_cbc "camellia-256-cbc" -#define NID_camellia_256_cbc 753 -#define OBJ_camellia_256_cbc 1L,2L,392L,200011L,61L,1L,1L,1L,4L - -#define SN_id_camellia128_wrap "id-camellia128-wrap" -#define NID_id_camellia128_wrap 907 -#define OBJ_id_camellia128_wrap 1L,2L,392L,200011L,61L,1L,1L,3L,2L - -#define SN_id_camellia192_wrap "id-camellia192-wrap" -#define NID_id_camellia192_wrap 908 -#define OBJ_id_camellia192_wrap 1L,2L,392L,200011L,61L,1L,1L,3L,3L - -#define SN_id_camellia256_wrap "id-camellia256-wrap" -#define NID_id_camellia256_wrap 909 -#define OBJ_id_camellia256_wrap 1L,2L,392L,200011L,61L,1L,1L,3L,4L - -#define OBJ_ntt_ds 0L,3L,4401L,5L - -#define OBJ_camellia OBJ_ntt_ds,3L,1L,9L - -#define SN_camellia_128_ecb "CAMELLIA-128-ECB" -#define LN_camellia_128_ecb "camellia-128-ecb" -#define NID_camellia_128_ecb 754 -#define OBJ_camellia_128_ecb OBJ_camellia,1L - -#define SN_camellia_128_ofb128 "CAMELLIA-128-OFB" -#define LN_camellia_128_ofb128 "camellia-128-ofb" -#define NID_camellia_128_ofb128 766 -#define OBJ_camellia_128_ofb128 OBJ_camellia,3L - -#define SN_camellia_128_cfb128 "CAMELLIA-128-CFB" -#define LN_camellia_128_cfb128 "camellia-128-cfb" -#define NID_camellia_128_cfb128 757 -#define OBJ_camellia_128_cfb128 OBJ_camellia,4L - -#define SN_camellia_192_ecb "CAMELLIA-192-ECB" -#define LN_camellia_192_ecb "camellia-192-ecb" -#define NID_camellia_192_ecb 755 -#define OBJ_camellia_192_ecb OBJ_camellia,21L - -#define SN_camellia_192_ofb128 "CAMELLIA-192-OFB" -#define LN_camellia_192_ofb128 "camellia-192-ofb" -#define NID_camellia_192_ofb128 767 -#define OBJ_camellia_192_ofb128 OBJ_camellia,23L - -#define SN_camellia_192_cfb128 "CAMELLIA-192-CFB" -#define LN_camellia_192_cfb128 "camellia-192-cfb" -#define NID_camellia_192_cfb128 758 -#define OBJ_camellia_192_cfb128 OBJ_camellia,24L - -#define SN_camellia_256_ecb "CAMELLIA-256-ECB" -#define LN_camellia_256_ecb "camellia-256-ecb" -#define NID_camellia_256_ecb 756 -#define OBJ_camellia_256_ecb OBJ_camellia,41L - -#define SN_camellia_256_ofb128 "CAMELLIA-256-OFB" -#define LN_camellia_256_ofb128 "camellia-256-ofb" -#define NID_camellia_256_ofb128 768 -#define OBJ_camellia_256_ofb128 OBJ_camellia,43L - -#define SN_camellia_256_cfb128 "CAMELLIA-256-CFB" -#define LN_camellia_256_cfb128 "camellia-256-cfb" -#define NID_camellia_256_cfb128 759 -#define OBJ_camellia_256_cfb128 OBJ_camellia,44L - -#define SN_camellia_128_cfb1 "CAMELLIA-128-CFB1" -#define LN_camellia_128_cfb1 "camellia-128-cfb1" -#define NID_camellia_128_cfb1 760 - -#define SN_camellia_192_cfb1 "CAMELLIA-192-CFB1" -#define LN_camellia_192_cfb1 "camellia-192-cfb1" -#define NID_camellia_192_cfb1 761 - -#define SN_camellia_256_cfb1 "CAMELLIA-256-CFB1" -#define LN_camellia_256_cfb1 "camellia-256-cfb1" -#define NID_camellia_256_cfb1 762 - -#define SN_camellia_128_cfb8 "CAMELLIA-128-CFB8" -#define LN_camellia_128_cfb8 "camellia-128-cfb8" -#define NID_camellia_128_cfb8 763 - -#define SN_camellia_192_cfb8 "CAMELLIA-192-CFB8" -#define LN_camellia_192_cfb8 "camellia-192-cfb8" -#define NID_camellia_192_cfb8 764 - -#define SN_camellia_256_cfb8 "CAMELLIA-256-CFB8" -#define LN_camellia_256_cfb8 "camellia-256-cfb8" -#define NID_camellia_256_cfb8 765 - -#define SN_kisa "KISA" -#define LN_kisa "kisa" -#define NID_kisa 773 -#define OBJ_kisa OBJ_member_body,410L,200004L - -#define SN_seed_ecb "SEED-ECB" -#define LN_seed_ecb "seed-ecb" -#define NID_seed_ecb 776 -#define OBJ_seed_ecb OBJ_kisa,1L,3L - -#define SN_seed_cbc "SEED-CBC" -#define LN_seed_cbc "seed-cbc" -#define NID_seed_cbc 777 -#define OBJ_seed_cbc OBJ_kisa,1L,4L - -#define SN_seed_cfb128 "SEED-CFB" -#define LN_seed_cfb128 "seed-cfb" -#define NID_seed_cfb128 779 -#define OBJ_seed_cfb128 OBJ_kisa,1L,5L - -#define SN_seed_ofb128 "SEED-OFB" -#define LN_seed_ofb128 "seed-ofb" -#define NID_seed_ofb128 778 -#define OBJ_seed_ofb128 OBJ_kisa,1L,6L - -#define SN_hmac "HMAC" -#define LN_hmac "hmac" -#define NID_hmac 855 - -#define SN_cmac "CMAC" -#define LN_cmac "cmac" -#define NID_cmac 894 - -#define SN_rc4_hmac_md5 "RC4-HMAC-MD5" -#define LN_rc4_hmac_md5 "rc4-hmac-md5" -#define NID_rc4_hmac_md5 915 - -#define SN_aes_128_cbc_hmac_sha1 "AES-128-CBC-HMAC-SHA1" -#define LN_aes_128_cbc_hmac_sha1 "aes-128-cbc-hmac-sha1" -#define NID_aes_128_cbc_hmac_sha1 916 - -#define SN_aes_192_cbc_hmac_sha1 "AES-192-CBC-HMAC-SHA1" -#define LN_aes_192_cbc_hmac_sha1 "aes-192-cbc-hmac-sha1" -#define NID_aes_192_cbc_hmac_sha1 917 - -#define SN_aes_256_cbc_hmac_sha1 "AES-256-CBC-HMAC-SHA1" -#define LN_aes_256_cbc_hmac_sha1 "aes-256-cbc-hmac-sha1" -#define NID_aes_256_cbc_hmac_sha1 918 - -#define SN_dhpublicnumber "dhpublicnumber" -#define LN_dhpublicnumber "X9.42 DH" -#define NID_dhpublicnumber 920 -#define OBJ_dhpublicnumber OBJ_ISO_US,10046L,2L,1L - -#define SN_brainpoolP160r1 "brainpoolP160r1" -#define NID_brainpoolP160r1 921 -#define OBJ_brainpoolP160r1 1L,3L,36L,3L,3L,2L,8L,1L,1L,1L - -#define SN_brainpoolP160t1 "brainpoolP160t1" -#define NID_brainpoolP160t1 922 -#define OBJ_brainpoolP160t1 1L,3L,36L,3L,3L,2L,8L,1L,1L,2L - -#define SN_brainpoolP192r1 "brainpoolP192r1" -#define NID_brainpoolP192r1 923 -#define OBJ_brainpoolP192r1 1L,3L,36L,3L,3L,2L,8L,1L,1L,3L - -#define SN_brainpoolP192t1 "brainpoolP192t1" -#define NID_brainpoolP192t1 924 -#define OBJ_brainpoolP192t1 1L,3L,36L,3L,3L,2L,8L,1L,1L,4L - -#define SN_brainpoolP224r1 "brainpoolP224r1" -#define NID_brainpoolP224r1 925 -#define OBJ_brainpoolP224r1 1L,3L,36L,3L,3L,2L,8L,1L,1L,5L - -#define SN_brainpoolP224t1 "brainpoolP224t1" -#define NID_brainpoolP224t1 926 -#define OBJ_brainpoolP224t1 1L,3L,36L,3L,3L,2L,8L,1L,1L,6L - -#define SN_brainpoolP256r1 "brainpoolP256r1" -#define NID_brainpoolP256r1 927 -#define OBJ_brainpoolP256r1 1L,3L,36L,3L,3L,2L,8L,1L,1L,7L - -#define SN_brainpoolP256t1 "brainpoolP256t1" -#define NID_brainpoolP256t1 928 -#define OBJ_brainpoolP256t1 1L,3L,36L,3L,3L,2L,8L,1L,1L,8L - -#define SN_brainpoolP320r1 "brainpoolP320r1" -#define NID_brainpoolP320r1 929 -#define OBJ_brainpoolP320r1 1L,3L,36L,3L,3L,2L,8L,1L,1L,9L - -#define SN_brainpoolP320t1 "brainpoolP320t1" -#define NID_brainpoolP320t1 930 -#define OBJ_brainpoolP320t1 1L,3L,36L,3L,3L,2L,8L,1L,1L,10L - -#define SN_brainpoolP384r1 "brainpoolP384r1" -#define NID_brainpoolP384r1 931 -#define OBJ_brainpoolP384r1 1L,3L,36L,3L,3L,2L,8L,1L,1L,11L - -#define SN_brainpoolP384t1 "brainpoolP384t1" -#define NID_brainpoolP384t1 932 -#define OBJ_brainpoolP384t1 1L,3L,36L,3L,3L,2L,8L,1L,1L,12L - -#define SN_brainpoolP512r1 "brainpoolP512r1" -#define NID_brainpoolP512r1 933 -#define OBJ_brainpoolP512r1 1L,3L,36L,3L,3L,2L,8L,1L,1L,13L - -#define SN_brainpoolP512t1 "brainpoolP512t1" -#define NID_brainpoolP512t1 934 -#define OBJ_brainpoolP512t1 1L,3L,36L,3L,3L,2L,8L,1L,1L,14L - -#define OBJ_x9_63_scheme 1L,3L,133L,16L,840L,63L,0L - -#define OBJ_secg_scheme OBJ_certicom_arc,1L - -#define SN_dhSinglePass_stdDH_sha1kdf_scheme "dhSinglePass-stdDH-sha1kdf-scheme" -#define NID_dhSinglePass_stdDH_sha1kdf_scheme 936 -#define OBJ_dhSinglePass_stdDH_sha1kdf_scheme OBJ_x9_63_scheme,2L - -#define SN_dhSinglePass_stdDH_sha224kdf_scheme "dhSinglePass-stdDH-sha224kdf-scheme" -#define NID_dhSinglePass_stdDH_sha224kdf_scheme 937 -#define OBJ_dhSinglePass_stdDH_sha224kdf_scheme OBJ_secg_scheme,11L,0L - -#define SN_dhSinglePass_stdDH_sha256kdf_scheme "dhSinglePass-stdDH-sha256kdf-scheme" -#define NID_dhSinglePass_stdDH_sha256kdf_scheme 938 -#define OBJ_dhSinglePass_stdDH_sha256kdf_scheme OBJ_secg_scheme,11L,1L - -#define SN_dhSinglePass_stdDH_sha384kdf_scheme "dhSinglePass-stdDH-sha384kdf-scheme" -#define NID_dhSinglePass_stdDH_sha384kdf_scheme 939 -#define OBJ_dhSinglePass_stdDH_sha384kdf_scheme OBJ_secg_scheme,11L,2L - -#define SN_dhSinglePass_stdDH_sha512kdf_scheme "dhSinglePass-stdDH-sha512kdf-scheme" -#define NID_dhSinglePass_stdDH_sha512kdf_scheme 940 -#define OBJ_dhSinglePass_stdDH_sha512kdf_scheme OBJ_secg_scheme,11L,3L - -#define SN_dhSinglePass_cofactorDH_sha1kdf_scheme "dhSinglePass-cofactorDH-sha1kdf-scheme" -#define NID_dhSinglePass_cofactorDH_sha1kdf_scheme 941 -#define OBJ_dhSinglePass_cofactorDH_sha1kdf_scheme OBJ_x9_63_scheme,3L - -#define SN_dhSinglePass_cofactorDH_sha224kdf_scheme "dhSinglePass-cofactorDH-sha224kdf-scheme" -#define NID_dhSinglePass_cofactorDH_sha224kdf_scheme 942 -#define OBJ_dhSinglePass_cofactorDH_sha224kdf_scheme OBJ_secg_scheme,14L,0L - -#define SN_dhSinglePass_cofactorDH_sha256kdf_scheme "dhSinglePass-cofactorDH-sha256kdf-scheme" -#define NID_dhSinglePass_cofactorDH_sha256kdf_scheme 943 -#define OBJ_dhSinglePass_cofactorDH_sha256kdf_scheme OBJ_secg_scheme,14L,1L - -#define SN_dhSinglePass_cofactorDH_sha384kdf_scheme "dhSinglePass-cofactorDH-sha384kdf-scheme" -#define NID_dhSinglePass_cofactorDH_sha384kdf_scheme 944 -#define OBJ_dhSinglePass_cofactorDH_sha384kdf_scheme OBJ_secg_scheme,14L,2L - -#define SN_dhSinglePass_cofactorDH_sha512kdf_scheme "dhSinglePass-cofactorDH-sha512kdf-scheme" -#define NID_dhSinglePass_cofactorDH_sha512kdf_scheme 945 -#define OBJ_dhSinglePass_cofactorDH_sha512kdf_scheme OBJ_secg_scheme,14L,3L - -#define SN_dh_std_kdf "dh-std-kdf" -#define NID_dh_std_kdf 946 - -#define SN_dh_cofactor_kdf "dh-cofactor-kdf" -#define NID_dh_cofactor_kdf 947 - diff --git a/third_party/boringssl/include/openssl/objects.h b/third_party/boringssl/include/openssl/objects.h deleted file mode 100644 index dd6556f264..0000000000 --- a/third_party/boringssl/include/openssl/objects.h +++ /dev/null @@ -1,18 +0,0 @@ -/* Copyright (c) 2014, Google Inc. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -/* This header is provided in order to make compiling against code that expects - OpenSSL easier. */ - -#include "obj.h" diff --git a/third_party/boringssl/include/openssl/opensslfeatures.h b/third_party/boringssl/include/openssl/opensslfeatures.h deleted file mode 100644 index c3f97d5a48..0000000000 --- a/third_party/boringssl/include/openssl/opensslfeatures.h +++ /dev/null @@ -1,60 +0,0 @@ -/* Copyright (c) 2014, Google Inc. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -/* This header is provided in order to make compiling against code that expects - OpenSSL easier. */ - -#ifndef OPENSSL_HEADER_OPENSSLFEATURES_H -#define OPENSSL_HEADER_OPENSSLFEATURES_H - - -#define OPENSSL_NO_BF -#define OPENSSL_NO_BUF_FREELISTS -#define OPENSSL_NO_CAMELLIA -#define OPENSSL_NO_CAPIENG -#define OPENSSL_NO_CAST -#define OPENSSL_NO_CMS -#define OPENSSL_NO_COMP -#define OPENSSL_NO_DANE -#define OPENSSL_NO_DEPRECATED -#define OPENSSL_NO_DYNAMIC_ENGINE -#define OPENSSL_NO_EC_NISTP_64_GCC_128 -#define OPENSSL_NO_EC2M -#define OPENSSL_NO_ENGINE -#define OPENSSL_NO_GMP -#define OPENSSL_NO_GOST -#define OPENSSL_NO_HEARTBEATS -#define OPENSSL_NO_HW -#define OPENSSL_NO_IDEA -#define OPENSSL_NO_JPAKE -#define OPENSSL_NO_KRB5 -#define OPENSSL_NO_MD2 -#define OPENSSL_NO_MDC2 -#define OPENSSL_NO_OCB -#define OPENSSL_NO_OCSP -#define OPENSSL_NO_RC2 -#define OPENSSL_NO_RC5 -#define OPENSSL_NO_RFC3779 -#define OPENSSL_NO_RIPEMD -#define OPENSSL_NO_RMD160 -#define OPENSSL_NO_SCTP -#define OPENSSL_NO_SEED -#define OPENSSL_NO_SRP -#define OPENSSL_NO_SSL2 -#define OPENSSL_NO_STATIC_ENGINE -#define OPENSSL_NO_STORE -#define OPENSSL_NO_WHIRLPOOL - - -#endif /* OPENSSL_HEADER_OPENSSLFEATURES_H */ diff --git a/third_party/boringssl/include/openssl/opensslv.h b/third_party/boringssl/include/openssl/opensslv.h deleted file mode 100644 index a3555d4f8b..0000000000 --- a/third_party/boringssl/include/openssl/opensslv.h +++ /dev/null @@ -1,18 +0,0 @@ -/* Copyright (c) 2014, Google Inc. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -/* This header is provided in order to make compiling against code that expects - OpenSSL easier. */ - -#include "crypto.h" diff --git a/third_party/boringssl/include/openssl/ossl_typ.h b/third_party/boringssl/include/openssl/ossl_typ.h deleted file mode 100644 index c2b3fe7c50..0000000000 --- a/third_party/boringssl/include/openssl/ossl_typ.h +++ /dev/null @@ -1,18 +0,0 @@ -/* Copyright (c) 2014, Google Inc. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -/* This header is provided in order to make compiling against code that expects - OpenSSL easier. */ - -#include "base.h" diff --git a/third_party/boringssl/include/openssl/pem.h b/third_party/boringssl/include/openssl/pem.h deleted file mode 100644 index 7756e45ed3..0000000000 --- a/third_party/boringssl/include/openssl/pem.h +++ /dev/null @@ -1,545 +0,0 @@ -/* Copyright (C) 1995-1997 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] */ - -#ifndef OPENSSL_HEADER_PEM_H -#define OPENSSL_HEADER_PEM_H - -#include -#include -#include -#include -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - - -#define PEM_BUFSIZE 1024 - -#define PEM_OBJ_UNDEF 0 -#define PEM_OBJ_X509 1 -#define PEM_OBJ_X509_REQ 2 -#define PEM_OBJ_CRL 3 -#define PEM_OBJ_SSL_SESSION 4 -#define PEM_OBJ_PRIV_KEY 10 -#define PEM_OBJ_PRIV_RSA 11 -#define PEM_OBJ_PRIV_DSA 12 -#define PEM_OBJ_PRIV_DH 13 -#define PEM_OBJ_PUB_RSA 14 -#define PEM_OBJ_PUB_DSA 15 -#define PEM_OBJ_PUB_DH 16 -#define PEM_OBJ_DHPARAMS 17 -#define PEM_OBJ_DSAPARAMS 18 -#define PEM_OBJ_PRIV_RSA_PUBLIC 19 -#define PEM_OBJ_PRIV_ECDSA 20 -#define PEM_OBJ_PUB_ECDSA 21 -#define PEM_OBJ_ECPARAMETERS 22 - -#define PEM_ERROR 30 -#define PEM_DEK_DES_CBC 40 -#define PEM_DEK_IDEA_CBC 45 -#define PEM_DEK_DES_EDE 50 -#define PEM_DEK_DES_ECB 60 -#define PEM_DEK_RSA 70 -#define PEM_DEK_RSA_MD2 80 -#define PEM_DEK_RSA_MD5 90 - -#define PEM_MD_MD2 NID_md2 -#define PEM_MD_MD5 NID_md5 -#define PEM_MD_SHA NID_sha -#define PEM_MD_MD2_RSA NID_md2WithRSAEncryption -#define PEM_MD_MD5_RSA NID_md5WithRSAEncryption -#define PEM_MD_SHA_RSA NID_sha1WithRSAEncryption - -#define PEM_STRING_X509_OLD "X509 CERTIFICATE" -#define PEM_STRING_X509 "CERTIFICATE" -#define PEM_STRING_X509_PAIR "CERTIFICATE PAIR" -#define PEM_STRING_X509_TRUSTED "TRUSTED CERTIFICATE" -#define PEM_STRING_X509_REQ_OLD "NEW CERTIFICATE REQUEST" -#define PEM_STRING_X509_REQ "CERTIFICATE REQUEST" -#define PEM_STRING_X509_CRL "X509 CRL" -#define PEM_STRING_EVP_PKEY "ANY PRIVATE KEY" -#define PEM_STRING_PUBLIC "PUBLIC KEY" -#define PEM_STRING_RSA "RSA PRIVATE KEY" -#define PEM_STRING_RSA_PUBLIC "RSA PUBLIC KEY" -#define PEM_STRING_DSA "DSA PRIVATE KEY" -#define PEM_STRING_DSA_PUBLIC "DSA PUBLIC KEY" -#define PEM_STRING_PKCS7 "PKCS7" -#define PEM_STRING_PKCS7_SIGNED "PKCS #7 SIGNED DATA" -#define PEM_STRING_PKCS8 "ENCRYPTED PRIVATE KEY" -#define PEM_STRING_PKCS8INF "PRIVATE KEY" -#define PEM_STRING_DHPARAMS "DH PARAMETERS" -#define PEM_STRING_DHXPARAMS "X9.42 DH PARAMETERS" -#define PEM_STRING_SSL_SESSION "SSL SESSION PARAMETERS" -#define PEM_STRING_DSAPARAMS "DSA PARAMETERS" -#define PEM_STRING_ECDSA_PUBLIC "ECDSA PUBLIC KEY" -#define PEM_STRING_ECPARAMETERS "EC PARAMETERS" -#define PEM_STRING_ECPRIVATEKEY "EC PRIVATE KEY" -#define PEM_STRING_PARAMETERS "PARAMETERS" -#define PEM_STRING_CMS "CMS" - - /* Note that this structure is initialised by PEM_SealInit and cleaned up - by PEM_SealFinal (at least for now) */ -typedef struct PEM_Encode_Seal_st - { - EVP_ENCODE_CTX encode; - EVP_MD_CTX md; - EVP_CIPHER_CTX cipher; - } PEM_ENCODE_SEAL_CTX; - -/* enc_type is one off */ -#define PEM_TYPE_ENCRYPTED 10 -#define PEM_TYPE_MIC_ONLY 20 -#define PEM_TYPE_MIC_CLEAR 30 -#define PEM_TYPE_CLEAR 40 - -typedef struct pem_recip_st - { - char *name; - X509_NAME *dn; - - int cipher; - int key_enc; - /* char iv[8]; unused and wrong size */ - } PEM_USER; - -typedef struct pem_ctx_st - { - int type; /* what type of object */ - - struct { - int version; - int mode; - } proc_type; - - char *domain; - - struct { - int cipher; - /* unused, and wrong size - unsigned char iv[8]; */ - } DEK_info; - - PEM_USER *originator; - - int num_recipient; - PEM_USER **recipient; - - EVP_MD *md; /* signature type */ - - int md_enc; /* is the md encrypted or not? */ - int md_len; /* length of md_data */ - char *md_data; /* message digest, could be pkey encrypted */ - - EVP_CIPHER *dec; /* date encryption cipher */ - int key_len; /* key length */ - unsigned char *key; /* key */ - /* unused, and wrong size - unsigned char iv[8]; */ - - - int data_enc; /* is the data encrypted */ - int data_len; - unsigned char *data; - } PEM_CTX; - -/* These macros make the PEM_read/PEM_write functions easier to maintain and - * write. Now they are all implemented with either: - * IMPLEMENT_PEM_rw(...) or IMPLEMENT_PEM_rw_cb(...) - */ - -#ifdef OPENSSL_NO_FP_API - -#define IMPLEMENT_PEM_read_fp(name, type, str, asn1) /**/ -#define IMPLEMENT_PEM_write_fp(name, type, str, asn1) /**/ -#define IMPLEMENT_PEM_write_fp_const(name, type, str, asn1) /**/ -#define IMPLEMENT_PEM_write_cb_fp(name, type, str, asn1) /**/ -#define IMPLEMENT_PEM_write_cb_fp_const(name, type, str, asn1) /**/ - -#else - -#define IMPLEMENT_PEM_read_fp(name, type, str, asn1) \ -OPENSSL_EXPORT type *PEM_read_##name(FILE *fp, type **x, pem_password_cb *cb, void *u)\ -{ \ -return PEM_ASN1_read((d2i_of_void *)d2i_##asn1, str,fp,(void **)x,cb,u); \ -} - -#define IMPLEMENT_PEM_write_fp(name, type, str, asn1) \ -OPENSSL_EXPORT int PEM_write_##name(FILE *fp, type *x) \ -{ \ -return PEM_ASN1_write((i2d_of_void *)i2d_##asn1,str,fp,x,NULL,NULL,0,NULL,NULL); \ -} - -#define IMPLEMENT_PEM_write_fp_const(name, type, str, asn1) \ -OPENSSL_EXPORT int PEM_write_##name(FILE *fp, const type *x) \ -{ \ -return PEM_ASN1_write((i2d_of_void *)i2d_##asn1,str,fp,(void *)x,NULL,NULL,0,NULL,NULL); \ -} - -#define IMPLEMENT_PEM_write_cb_fp(name, type, str, asn1) \ -OPENSSL_EXPORT int PEM_write_##name(FILE *fp, type *x, const EVP_CIPHER *enc, \ - unsigned char *kstr, int klen, pem_password_cb *cb, \ - void *u) \ - { \ - return PEM_ASN1_write((i2d_of_void *)i2d_##asn1,str,fp,x,enc,kstr,klen,cb,u); \ - } - -#define IMPLEMENT_PEM_write_cb_fp_const(name, type, str, asn1) \ -OPENSSL_EXPORT int PEM_write_##name(FILE *fp, type *x, const EVP_CIPHER *enc, \ - unsigned char *kstr, int klen, pem_password_cb *cb, \ - void *u) \ - { \ - return PEM_ASN1_write((i2d_of_void *)i2d_##asn1,str,fp,x,enc,kstr,klen,cb,u); \ - } - -#endif - -#define IMPLEMENT_PEM_read_bio(name, type, str, asn1) \ -OPENSSL_EXPORT type *PEM_read_bio_##name(BIO *bp, type **x, pem_password_cb *cb, void *u)\ -{ \ -return PEM_ASN1_read_bio((d2i_of_void *)d2i_##asn1, str,bp,(void **)x,cb,u); \ -} - -#define IMPLEMENT_PEM_write_bio(name, type, str, asn1) \ -OPENSSL_EXPORT int PEM_write_bio_##name(BIO *bp, type *x) \ -{ \ -return PEM_ASN1_write_bio((i2d_of_void *)i2d_##asn1,str,bp,x,NULL,NULL,0,NULL,NULL); \ -} - -#define IMPLEMENT_PEM_write_bio_const(name, type, str, asn1) \ -OPENSSL_EXPORT int PEM_write_bio_##name(BIO *bp, const type *x) \ -{ \ -return PEM_ASN1_write_bio((i2d_of_void *)i2d_##asn1,str,bp,(void *)x,NULL,NULL,0,NULL,NULL); \ -} - -#define IMPLEMENT_PEM_write_cb_bio(name, type, str, asn1) \ -OPENSSL_EXPORT int PEM_write_bio_##name(BIO *bp, type *x, const EVP_CIPHER *enc, \ - unsigned char *kstr, int klen, pem_password_cb *cb, void *u) \ - { \ - return PEM_ASN1_write_bio((i2d_of_void *)i2d_##asn1,str,bp,x,enc,kstr,klen,cb,u); \ - } - -#define IMPLEMENT_PEM_write_cb_bio_const(name, type, str, asn1) \ -OPENSSL_EXPORT int PEM_write_bio_##name(BIO *bp, type *x, const EVP_CIPHER *enc, \ - unsigned char *kstr, int klen, pem_password_cb *cb, void *u) \ - { \ - return PEM_ASN1_write_bio((i2d_of_void *)i2d_##asn1,str,bp,(void *)x,enc,kstr,klen,cb,u); \ - } - -#define IMPLEMENT_PEM_write(name, type, str, asn1) \ - IMPLEMENT_PEM_write_bio(name, type, str, asn1) \ - IMPLEMENT_PEM_write_fp(name, type, str, asn1) - -#define IMPLEMENT_PEM_write_const(name, type, str, asn1) \ - IMPLEMENT_PEM_write_bio_const(name, type, str, asn1) \ - IMPLEMENT_PEM_write_fp_const(name, type, str, asn1) - -#define IMPLEMENT_PEM_write_cb(name, type, str, asn1) \ - IMPLEMENT_PEM_write_cb_bio(name, type, str, asn1) \ - IMPLEMENT_PEM_write_cb_fp(name, type, str, asn1) - -#define IMPLEMENT_PEM_write_cb_const(name, type, str, asn1) \ - IMPLEMENT_PEM_write_cb_bio_const(name, type, str, asn1) \ - IMPLEMENT_PEM_write_cb_fp_const(name, type, str, asn1) - -#define IMPLEMENT_PEM_read(name, type, str, asn1) \ - IMPLEMENT_PEM_read_bio(name, type, str, asn1) \ - IMPLEMENT_PEM_read_fp(name, type, str, asn1) - -#define IMPLEMENT_PEM_rw(name, type, str, asn1) \ - IMPLEMENT_PEM_read(name, type, str, asn1) \ - IMPLEMENT_PEM_write(name, type, str, asn1) - -#define IMPLEMENT_PEM_rw_const(name, type, str, asn1) \ - IMPLEMENT_PEM_read(name, type, str, asn1) \ - IMPLEMENT_PEM_write_const(name, type, str, asn1) - -#define IMPLEMENT_PEM_rw_cb(name, type, str, asn1) \ - IMPLEMENT_PEM_read(name, type, str, asn1) \ - IMPLEMENT_PEM_write_cb(name, type, str, asn1) - -/* These are the same except they are for the declarations */ - -#if defined(OPENSSL_NO_FP_API) - -#define DECLARE_PEM_read_fp(name, type) /**/ -#define DECLARE_PEM_write_fp(name, type) /**/ -#define DECLARE_PEM_write_cb_fp(name, type) /**/ - -#else - -#define DECLARE_PEM_read_fp(name, type) \ - OPENSSL_EXPORT type *PEM_read_##name(FILE *fp, type **x, pem_password_cb *cb, void *u); - -#define DECLARE_PEM_write_fp(name, type) \ - OPENSSL_EXPORT int PEM_write_##name(FILE *fp, type *x); - -#define DECLARE_PEM_write_fp_const(name, type) \ - OPENSSL_EXPORT int PEM_write_##name(FILE *fp, const type *x); - -#define DECLARE_PEM_write_cb_fp(name, type) \ - OPENSSL_EXPORT int PEM_write_##name(FILE *fp, type *x, const EVP_CIPHER *enc, \ - unsigned char *kstr, int klen, pem_password_cb *cb, void *u); - -#endif - -#define DECLARE_PEM_read_bio(name, type) \ - OPENSSL_EXPORT type *PEM_read_bio_##name(BIO *bp, type **x, pem_password_cb *cb, void *u); - -#define DECLARE_PEM_write_bio(name, type) \ - OPENSSL_EXPORT int PEM_write_bio_##name(BIO *bp, type *x); - -#define DECLARE_PEM_write_bio_const(name, type) \ - OPENSSL_EXPORT int PEM_write_bio_##name(BIO *bp, const type *x); - -#define DECLARE_PEM_write_cb_bio(name, type) \ - OPENSSL_EXPORT int PEM_write_bio_##name(BIO *bp, type *x, const EVP_CIPHER *enc, \ - unsigned char *kstr, int klen, pem_password_cb *cb, void *u); - - -#define DECLARE_PEM_write(name, type) \ - DECLARE_PEM_write_bio(name, type) \ - DECLARE_PEM_write_fp(name, type) - -#define DECLARE_PEM_write_const(name, type) \ - DECLARE_PEM_write_bio_const(name, type) \ - DECLARE_PEM_write_fp_const(name, type) - -#define DECLARE_PEM_write_cb(name, type) \ - DECLARE_PEM_write_cb_bio(name, type) \ - DECLARE_PEM_write_cb_fp(name, type) - -#define DECLARE_PEM_read(name, type) \ - DECLARE_PEM_read_bio(name, type) \ - DECLARE_PEM_read_fp(name, type) - -#define DECLARE_PEM_rw(name, type) \ - DECLARE_PEM_read(name, type) \ - DECLARE_PEM_write(name, type) - -#define DECLARE_PEM_rw_const(name, type) \ - DECLARE_PEM_read(name, type) \ - DECLARE_PEM_write_const(name, type) - -#define DECLARE_PEM_rw_cb(name, type) \ - DECLARE_PEM_read(name, type) \ - DECLARE_PEM_write_cb(name, type) - -/* "userdata": new with OpenSSL 0.9.4 */ -typedef int pem_password_cb(char *buf, int size, int rwflag, void *userdata); - -OPENSSL_EXPORT int PEM_get_EVP_CIPHER_INFO(char *header, EVP_CIPHER_INFO *cipher); -OPENSSL_EXPORT int PEM_do_header (EVP_CIPHER_INFO *cipher, unsigned char *data,long *len, pem_password_cb *callback,void *u); - -OPENSSL_EXPORT int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data,long *len); -OPENSSL_EXPORT int PEM_write_bio(BIO *bp,const char *name, const char *hdr, const unsigned char *data, long len); -OPENSSL_EXPORT int PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm, const char *name, BIO *bp, pem_password_cb *cb, void *u); -OPENSSL_EXPORT void * PEM_ASN1_read_bio(d2i_of_void *d2i, const char *name, BIO *bp, void **x, pem_password_cb *cb, void *u); -OPENSSL_EXPORT int PEM_ASN1_write_bio(i2d_of_void *i2d,const char *name,BIO *bp, void *x, const EVP_CIPHER *enc,unsigned char *kstr,int klen, pem_password_cb *cb, void *u); - -OPENSSL_EXPORT STACK_OF(X509_INFO) * PEM_X509_INFO_read_bio(BIO *bp, STACK_OF(X509_INFO) *sk, pem_password_cb *cb, void *u); -OPENSSL_EXPORT int PEM_X509_INFO_write_bio(BIO *bp,X509_INFO *xi, EVP_CIPHER *enc, unsigned char *kstr, int klen, pem_password_cb *cd, void *u); - -OPENSSL_EXPORT int PEM_read(FILE *fp, char **name, char **header, unsigned char **data,long *len); -OPENSSL_EXPORT int PEM_write(FILE *fp, const char *name, const char *hdr, const unsigned char *data, long len); -OPENSSL_EXPORT void * PEM_ASN1_read(d2i_of_void *d2i, const char *name, FILE *fp, void **x, pem_password_cb *cb, void *u); -OPENSSL_EXPORT int PEM_ASN1_write(i2d_of_void *i2d,const char *name,FILE *fp, void *x,const EVP_CIPHER *enc,unsigned char *kstr, int klen,pem_password_cb *callback, void *u); -OPENSSL_EXPORT STACK_OF(X509_INFO) * PEM_X509_INFO_read(FILE *fp, STACK_OF(X509_INFO) *sk, pem_password_cb *cb, void *u); - -OPENSSL_EXPORT int PEM_SealInit(PEM_ENCODE_SEAL_CTX *ctx, EVP_CIPHER *type, EVP_MD *md_type, unsigned char **ek, int *ekl, unsigned char *iv, EVP_PKEY **pubk, int npubk); -OPENSSL_EXPORT void PEM_SealUpdate(PEM_ENCODE_SEAL_CTX *ctx, unsigned char *out, int *outl, unsigned char *in, int inl); -OPENSSL_EXPORT int PEM_SealFinal(PEM_ENCODE_SEAL_CTX *ctx, unsigned char *sig,int *sigl, unsigned char *out, int *outl, EVP_PKEY *priv); - -OPENSSL_EXPORT void PEM_SignInit(EVP_MD_CTX *ctx, EVP_MD *type); -OPENSSL_EXPORT void PEM_SignUpdate(EVP_MD_CTX *ctx,unsigned char *d,unsigned int cnt); -OPENSSL_EXPORT int PEM_SignFinal(EVP_MD_CTX *ctx, unsigned char *sigret, unsigned int *siglen, EVP_PKEY *pkey); - -/* |PEM_def_callback| treats |userdata| as a string and copies it into |buf|, - * assuming its |size| is sufficient. Returns the length of the string, or 0 - * if there is not enough room. If either |buf| or |userdata| is NULL, 0 is - * returned. Note that this is different from OpenSSL, which prompts for a - * password. */ -OPENSSL_EXPORT int PEM_def_callback(char *buf, int size, int rwflag, void *userdata); -OPENSSL_EXPORT void PEM_proc_type(char *buf, int type); -OPENSSL_EXPORT void PEM_dek_info(char *buf, const char *type, int len, char *str); - - -DECLARE_PEM_rw(X509, X509) - -DECLARE_PEM_rw(X509_AUX, X509) - -DECLARE_PEM_rw(X509_CERT_PAIR, X509_CERT_PAIR) - -DECLARE_PEM_rw(X509_REQ, X509_REQ) -DECLARE_PEM_write(X509_REQ_NEW, X509_REQ) - -DECLARE_PEM_rw(X509_CRL, X509_CRL) - -/* DECLARE_PEM_rw(PKCS7, PKCS7) */ - -DECLARE_PEM_rw(NETSCAPE_CERT_SEQUENCE, NETSCAPE_CERT_SEQUENCE) - -DECLARE_PEM_rw(PKCS8, X509_SIG) - -DECLARE_PEM_rw(PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO) - -DECLARE_PEM_rw_cb(RSAPrivateKey, RSA) - -DECLARE_PEM_rw_const(RSAPublicKey, RSA) -DECLARE_PEM_rw(RSA_PUBKEY, RSA) - -#ifndef OPENSSL_NO_DSA - -DECLARE_PEM_rw_cb(DSAPrivateKey, DSA) - -DECLARE_PEM_rw(DSA_PUBKEY, DSA) - -DECLARE_PEM_rw_const(DSAparams, DSA) - -#endif - -DECLARE_PEM_rw_const(ECPKParameters, EC_GROUP) -DECLARE_PEM_rw_cb(ECPrivateKey, EC_KEY) -DECLARE_PEM_rw(EC_PUBKEY, EC_KEY) - - -DECLARE_PEM_rw_const(DHparams, DH) -DECLARE_PEM_write_const(DHxparams, DH) - - -DECLARE_PEM_rw_cb(PrivateKey, EVP_PKEY) - -DECLARE_PEM_rw(PUBKEY, EVP_PKEY) - -OPENSSL_EXPORT int PEM_write_bio_PKCS8PrivateKey_nid(BIO *bp, EVP_PKEY *x, int nid, char *kstr, int klen, pem_password_cb *cb, void *u); -OPENSSL_EXPORT int PEM_write_bio_PKCS8PrivateKey(BIO *, EVP_PKEY *, const EVP_CIPHER *, char *, int, pem_password_cb *, void *); -OPENSSL_EXPORT int i2d_PKCS8PrivateKey_bio(BIO *bp, EVP_PKEY *x, const EVP_CIPHER *enc, char *kstr, int klen, pem_password_cb *cb, void *u); -OPENSSL_EXPORT int i2d_PKCS8PrivateKey_nid_bio(BIO *bp, EVP_PKEY *x, int nid, char *kstr, int klen, pem_password_cb *cb, void *u); -OPENSSL_EXPORT EVP_PKEY *d2i_PKCS8PrivateKey_bio(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u); - -OPENSSL_EXPORT int i2d_PKCS8PrivateKey_fp(FILE *fp, EVP_PKEY *x, const EVP_CIPHER *enc, char *kstr, int klen, pem_password_cb *cb, void *u); -OPENSSL_EXPORT int i2d_PKCS8PrivateKey_nid_fp(FILE *fp, EVP_PKEY *x, int nid, char *kstr, int klen, pem_password_cb *cb, void *u); -OPENSSL_EXPORT int PEM_write_PKCS8PrivateKey_nid(FILE *fp, EVP_PKEY *x, int nid, char *kstr, int klen, pem_password_cb *cb, void *u); - -OPENSSL_EXPORT EVP_PKEY *d2i_PKCS8PrivateKey_fp(FILE *fp, EVP_PKEY **x, pem_password_cb *cb, void *u); - -OPENSSL_EXPORT int PEM_write_PKCS8PrivateKey(FILE *fp,EVP_PKEY *x,const EVP_CIPHER *enc, char *kstr,int klen, pem_password_cb *cd, void *u); - -OPENSSL_EXPORT EVP_PKEY *PEM_read_bio_Parameters(BIO *bp, EVP_PKEY **x); -OPENSSL_EXPORT int PEM_write_bio_Parameters(BIO *bp, EVP_PKEY *x); - - -OPENSSL_EXPORT EVP_PKEY *b2i_PrivateKey(const unsigned char **in, long length); -OPENSSL_EXPORT EVP_PKEY *b2i_PublicKey(const unsigned char **in, long length); -OPENSSL_EXPORT EVP_PKEY *b2i_PrivateKey_bio(BIO *in); -OPENSSL_EXPORT EVP_PKEY *b2i_PublicKey_bio(BIO *in); -OPENSSL_EXPORT int i2b_PrivateKey_bio(BIO *out, EVP_PKEY *pk); -OPENSSL_EXPORT int i2b_PublicKey_bio(BIO *out, EVP_PKEY *pk); -OPENSSL_EXPORT EVP_PKEY *b2i_PVK_bio(BIO *in, pem_password_cb *cb, void *u); -OPENSSL_EXPORT int i2b_PVK_bio(BIO *out, EVP_PKEY *pk, int enclevel, pem_password_cb *cb, void *u); - - -void ERR_load_PEM_strings(void); - - -#ifdef __cplusplus -} -#endif - -#define PEM_F_PEM_ASN1_read 100 -#define PEM_F_PEM_ASN1_read_bio 101 -#define PEM_F_PEM_ASN1_write 102 -#define PEM_F_PEM_ASN1_write_bio 103 -#define PEM_F_PEM_X509_INFO_read 104 -#define PEM_F_PEM_X509_INFO_read_bio 105 -#define PEM_F_PEM_X509_INFO_write_bio 106 -#define PEM_F_PEM_do_header 107 -#define PEM_F_PEM_get_EVP_CIPHER_INFO 108 -#define PEM_F_PEM_read 109 -#define PEM_F_PEM_read_DHparams 110 -#define PEM_F_PEM_read_PrivateKey 111 -#define PEM_F_PEM_read_bio 112 -#define PEM_F_PEM_read_bio_DHparams 113 -#define PEM_F_PEM_read_bio_Parameters 114 -#define PEM_F_PEM_read_bio_PrivateKey 115 -#define PEM_F_PEM_write 116 -#define PEM_F_PEM_write_PrivateKey 117 -#define PEM_F_PEM_write_bio 118 -#define PEM_F_d2i_PKCS8PrivateKey_bio 119 -#define PEM_F_d2i_PKCS8PrivateKey_fp 120 -#define PEM_F_do_pk8pkey 121 -#define PEM_F_do_pk8pkey_fp 122 -#define PEM_F_load_iv 123 -#define PEM_R_BAD_BASE64_DECODE 100 -#define PEM_R_BAD_DECRYPT 101 -#define PEM_R_BAD_END_LINE 102 -#define PEM_R_BAD_IV_CHARS 103 -#define PEM_R_BAD_PASSWORD_READ 104 -#define PEM_R_CIPHER_IS_NULL 105 -#define PEM_R_ERROR_CONVERTING_PRIVATE_KEY 106 -#define PEM_R_NOT_DEK_INFO 107 -#define PEM_R_NOT_ENCRYPTED 108 -#define PEM_R_NOT_PROC_TYPE 109 -#define PEM_R_NO_START_LINE 110 -#define PEM_R_READ_KEY 111 -#define PEM_R_SHORT_HEADER 112 -#define PEM_R_UNSUPPORTED_CIPHER 113 -#define PEM_R_UNSUPPORTED_ENCRYPTION 114 - -#endif /* OPENSSL_HEADER_PEM_H */ diff --git a/third_party/boringssl/include/openssl/pkcs12.h b/third_party/boringssl/include/openssl/pkcs12.h deleted file mode 100644 index b5e9516382..0000000000 --- a/third_party/boringssl/include/openssl/pkcs12.h +++ /dev/null @@ -1,18 +0,0 @@ -/* Copyright (c) 2014, Google Inc. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -/* This header is provided in order to make compiling against code that expects - OpenSSL easier. */ - -#include "pkcs8.h" diff --git a/third_party/boringssl/include/openssl/pkcs7.h b/third_party/boringssl/include/openssl/pkcs7.h deleted file mode 100644 index 6e5e433074..0000000000 --- a/third_party/boringssl/include/openssl/pkcs7.h +++ /dev/null @@ -1,16 +0,0 @@ -/* Copyright (c) 2014, Google Inc. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -/* This header is provided in order to make compiling against code that expects - OpenSSL easier. */ diff --git a/third_party/boringssl/include/openssl/pkcs8.h b/third_party/boringssl/include/openssl/pkcs8.h deleted file mode 100644 index 8dc7731bf5..0000000000 --- a/third_party/boringssl/include/openssl/pkcs8.h +++ /dev/null @@ -1,217 +0,0 @@ -/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL - * project 1999. - */ -/* ==================================================================== - * Copyright (c) 1999 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * licensing@OpenSSL.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS 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. - * ==================================================================== - * - * This product includes cryptographic software written by Eric Young - * (eay@cryptsoft.com). This product includes software written by Tim - * Hudson (tjh@cryptsoft.com). */ - - -#ifndef OPENSSL_HEADER_PKCS8_H -#define OPENSSL_HEADER_PKCS8_H - -#include -#include - - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* PKCS8_encrypt_pbe serializes and encrypts a PKCS8_PRIV_KEY_INFO with PBES1 as - * defined in PKCS #5. Only pbeWithSHAAnd128BitRC4, - * pbeWithSHAAnd3-KeyTripleDES-CBC and pbeWithSHA1And40BitRC2, defined in PKCS - * #12, are supported. The |pass_raw_len| bytes pointed to by |pass_raw| are - * used as the password. Note that any conversions from the password as - * supplied in a text string (such as those specified in B.1 of PKCS #12) must - * be performed by the caller. - * - * If |salt| is NULL, a random salt of |salt_len| bytes is generated. If - * |salt_len| is zero, a default salt length is used instead. - * - * The resulting structure is stored in an X509_SIG which must be freed by the - * caller. - * - * TODO(davidben): Really? An X509_SIG? OpenSSL probably did that because it has - * the same structure as EncryptedPrivateKeyInfo. */ -OPENSSL_EXPORT X509_SIG *PKCS8_encrypt_pbe(int pbe_nid, - const uint8_t *pass_raw, - size_t pass_raw_len, - uint8_t *salt, size_t salt_len, - int iterations, - PKCS8_PRIV_KEY_INFO *p8inf); - -/* PKCS8_decrypt_pbe decrypts and decodes a PKCS8_PRIV_KEY_INFO with PBES1 as - * defined in PKCS #5. Only pbeWithSHAAnd128BitRC4, - * pbeWithSHAAnd3-KeyTripleDES-CBC and pbeWithSHA1And40BitRC2, defined in PKCS - * #12, are supported. The |pass_raw_len| bytes pointed to by |pass_raw| are - * used as the password. Note that any conversions from the password as - * supplied in a text string (such as those specified in B.1 of PKCS #12) must - * be performed by the caller. - * - * The resulting structure must be freed by the caller. */ -OPENSSL_EXPORT PKCS8_PRIV_KEY_INFO *PKCS8_decrypt_pbe(X509_SIG *pkcs8, - const uint8_t *pass_raw, - size_t pass_raw_len); - - -/* Deprecated functions. */ - -/* PKCS8_encrypt calls PKCS8_encrypt_pbe after treating |pass| as an ASCII - * string, appending U+0000, and converting to UCS-2. (So the empty password - * encodes as two NUL bytes.) The |cipher| argument is ignored. */ -OPENSSL_EXPORT X509_SIG *PKCS8_encrypt(int pbe_nid, const EVP_CIPHER *cipher, - const char *pass, int pass_len, - uint8_t *salt, size_t salt_len, - int iterations, - PKCS8_PRIV_KEY_INFO *p8inf); - -/* PKCS8_decrypt calls PKCS8_decrypt_pbe after treating |pass| as an ASCII - * string, appending U+0000, and converting to UCS-2. (So the empty password - * encodes as two NUL bytes.) */ -OPENSSL_EXPORT PKCS8_PRIV_KEY_INFO *PKCS8_decrypt(X509_SIG *pkcs8, - const char *pass, - int pass_len); - -/* PKCS12_get_key_and_certs parses a PKCS#12 structure from |in|, authenticates - * and decrypts it using |password|, sets |*out_key| to the included private - * key and appends the included certificates to |out_certs|. It returns one on - * success and zero on error. The caller takes ownership of the outputs. */ -OPENSSL_EXPORT int PKCS12_get_key_and_certs(EVP_PKEY **out_key, - STACK_OF(X509) *out_certs, - CBS *in, const char *password); - - -/* Deprecated functions. */ - -/* PKCS12_PBE_add does nothing. It exists for compatibility with OpenSSL. */ -OPENSSL_EXPORT void PKCS12_PBE_add(void); - -/* d2i_PKCS12 is a dummy function that copies |*ber_bytes| into a - * |PKCS12| structure. The |out_p12| argument must be NULL. On exit, - * |*ber_bytes| will be advanced by |ber_len|. It returns a fresh |PKCS12| - * structure or NULL on error. - * - * Note: unlike other d2i functions, |d2i_PKCS12| will always consume |ber_len| - * bytes.*/ -OPENSSL_EXPORT PKCS12 *d2i_PKCS12(PKCS12 **out_p12, const uint8_t **ber_bytes, - size_t ber_len); - -/* d2i_PKCS12_bio acts like |d2i_PKCS12| but reads from a |BIO|. */ -OPENSSL_EXPORT PKCS12* d2i_PKCS12_bio(BIO *bio, PKCS12 **out_p12); - -/* d2i_PKCS12_fp acts like |d2i_PKCS12| but reads from a |FILE|. */ -OPENSSL_EXPORT PKCS12* d2i_PKCS12_fp(FILE *fp, PKCS12 **out_p12); - -/* PKCS12_parse calls |PKCS12_get_key_and_certs| on the ASN.1 data stored in - * |p12|. The |out_pkey| and |out_cert| arguments must not be NULL and, on - * successful exit, the private key and first certificate will be stored in - * them. The |out_ca_certs| argument may be NULL but, if not, then any extra - * certificates will be appended to |*out_ca_certs|. If |*out_ca_certs| is NULL - * then it will be set to a freshly allocated stack containing the extra certs. - * - * It returns one on success and zero on error. */ -OPENSSL_EXPORT int PKCS12_parse(const PKCS12 *p12, const char *password, - EVP_PKEY **out_pkey, X509 **out_cert, - STACK_OF(X509) **out_ca_certs); - -/* PKCS12_free frees |p12| and its contents. */ -OPENSSL_EXPORT void PKCS12_free(PKCS12 *p12); - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#define PKCS8_F_EVP_PKCS82PKEY 100 -#define PKCS8_F_EVP_PKEY2PKCS8 101 -#define PKCS8_F_PKCS12_get_key_and_certs 102 -#define PKCS8_F_PKCS12_handle_content_info 103 -#define PKCS8_F_PKCS12_handle_content_infos 104 -#define PKCS8_F_PKCS5_pbe2_set_iv 105 -#define PKCS8_F_PKCS5_pbe_set 106 -#define PKCS8_F_PKCS5_pbe_set0_algor 107 -#define PKCS8_F_PKCS5_pbkdf2_set 108 -#define PKCS8_F_PKCS8_decrypt 109 -#define PKCS8_F_PKCS8_encrypt 110 -#define PKCS8_F_PKCS8_encrypt_pbe 111 -#define PKCS8_F_pbe_cipher_init 112 -#define PKCS8_F_pbe_crypt 113 -#define PKCS8_F_pkcs12_item_decrypt_d2i 114 -#define PKCS8_F_pkcs12_item_i2d_encrypt 115 -#define PKCS8_F_pkcs12_key_gen_raw 116 -#define PKCS8_F_pkcs12_pbe_keyivgen 117 -#define PKCS8_R_BAD_PKCS12_DATA 100 -#define PKCS8_R_BAD_PKCS12_VERSION 101 -#define PKCS8_R_CIPHER_HAS_NO_OBJECT_IDENTIFIER 102 -#define PKCS8_R_CRYPT_ERROR 103 -#define PKCS8_R_DECODE_ERROR 104 -#define PKCS8_R_ENCODE_ERROR 105 -#define PKCS8_R_ENCRYPT_ERROR 106 -#define PKCS8_R_ERROR_SETTING_CIPHER_PARAMS 107 -#define PKCS8_R_INCORRECT_PASSWORD 108 -#define PKCS8_R_KEYGEN_FAILURE 109 -#define PKCS8_R_KEY_GEN_ERROR 110 -#define PKCS8_R_METHOD_NOT_SUPPORTED 111 -#define PKCS8_R_MISSING_MAC 112 -#define PKCS8_R_MULTIPLE_PRIVATE_KEYS_IN_PKCS12 113 -#define PKCS8_R_PKCS12_PUBLIC_KEY_INTEGRITY_NOT_SUPPORTED 114 -#define PKCS8_R_PKCS12_TOO_DEEPLY_NESTED 115 -#define PKCS8_R_PRIVATE_KEY_DECODE_ERROR 116 -#define PKCS8_R_PRIVATE_KEY_ENCODE_ERROR 117 -#define PKCS8_R_TOO_LONG 118 -#define PKCS8_R_UNKNOWN_ALGORITHM 119 -#define PKCS8_R_UNKNOWN_CIPHER 120 -#define PKCS8_R_UNKNOWN_CIPHER_ALGORITHM 121 -#define PKCS8_R_UNKNOWN_DIGEST 122 -#define PKCS8_R_UNKNOWN_HASH 123 -#define PKCS8_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM 124 - -#endif /* OPENSSL_HEADER_PKCS8_H */ diff --git a/third_party/boringssl/include/openssl/poly1305.h b/third_party/boringssl/include/openssl/poly1305.h deleted file mode 100644 index aa904869ce..0000000000 --- a/third_party/boringssl/include/openssl/poly1305.h +++ /dev/null @@ -1,47 +0,0 @@ -/* Copyright (c) 2014, Google Inc. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -#ifndef OPENSSL_HEADER_POLY1305_H -#define OPENSSL_HEADER_POLY1305_H - -#include - -#ifdef __cplusplus -extern "C" { -#endif - - -typedef unsigned char poly1305_state[512]; - -/* poly1305_init sets up |state| so that it can be used to calculate an - * authentication tag with the one-time key |key|. Note that |key| is a - * one-time key and therefore there is no `reset' method because that would - * enable several messages to be authenticated with the same key. */ -extern void CRYPTO_poly1305_init(poly1305_state* state, const uint8_t key[32]); - -/* poly1305_update processes |in_len| bytes from |in|. It can be called zero or - * more times after poly1305_init. */ -extern void CRYPTO_poly1305_update(poly1305_state* state, const uint8_t* in, - size_t in_len); - -/* poly1305_finish completes the poly1305 calculation and writes a 16 byte - * authentication tag to |mac|. The |mac| address must be 16-byte aligned. */ -extern void CRYPTO_poly1305_finish(poly1305_state* state, uint8_t mac[16]); - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_POLY1305_H */ diff --git a/third_party/boringssl/include/openssl/pqueue.h b/third_party/boringssl/include/openssl/pqueue.h deleted file mode 100644 index ceb1fa2a74..0000000000 --- a/third_party/boringssl/include/openssl/pqueue.h +++ /dev/null @@ -1,146 +0,0 @@ -/* - * DTLS implementation written by Nagendra Modadugu - * (nagendra@cs.stanford.edu) for the OpenSSL project 2005. - */ -/* ==================================================================== - * Copyright (c) 1999-2005 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * openssl-core@OpenSSL.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS 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. - * ==================================================================== - * - * This product includes cryptographic software written by Eric Young - * (eay@cryptsoft.com). This product includes software written by Tim - * Hudson (tjh@cryptsoft.com). */ - -#ifndef OPENSSL_HEADER_PQUEUE_H -#define OPENSSL_HEADER_PQUEUE_H - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* Priority queue. - * - * The priority queue maintains a linked-list of nodes, each with a unique, - * 64-bit priority, in ascending priority order. */ - -typedef struct _pqueue *pqueue; - -typedef struct _pitem { - uint8_t priority[8]; /* 64-bit value in big-endian encoding */ - void *data; - struct _pitem *next; -} pitem; - -typedef struct _pitem *piterator; - - -/* Creating and freeing queues. */ - -/* pqueue_new allocates a fresh, empty priority queue object and returns it, or - * NULL on error. */ -OPENSSL_EXPORT pqueue pqueue_new(void); - -/* pqueue_free frees |pq| but not any of the items it points to. Thus |pq| must - * be empty or a memory leak will occur. */ -OPENSSL_EXPORT void pqueue_free(pqueue pq); - - -/* Creating and freeing items. */ - -/* pitem_new allocates a fresh priority queue item that points at |data| and - * has a priority given by |prio64be|, which is a 64-bit, unsigned number - * expressed in big-endian form. It returns the fresh item, or NULL on - * error. */ -OPENSSL_EXPORT pitem *pitem_new(uint8_t prio64be[8], void *data); - -/* pitem_free frees |item|, but not any data that it points to. */ -OPENSSL_EXPORT void pitem_free(pitem *item); - - -/* Queue accessor functions */ - -/* pqueue_peek returns the item with the smallest priority from |pq|, or NULL - * if empty. */ -OPENSSL_EXPORT pitem *pqueue_peek(pqueue pq); - -/* pqueue_find returns the item whose priority matches |prio64be| or NULL if no - * such item exists. */ -OPENSSL_EXPORT pitem *pqueue_find(pqueue pq, uint8_t *prio64be); - - -/* Queue mutation functions */ - -/* pqueue_insert inserts |item| into |pq| and returns item. */ -OPENSSL_EXPORT pitem *pqueue_insert(pqueue pq, pitem *item); - -/* pqueue_pop takes the item with the least priority from |pq| and returns it, - * or NULL if |pq| is empty. */ -OPENSSL_EXPORT pitem *pqueue_pop(pqueue pq); - -/* pqueue_size returns the number of items in |pq|. */ -OPENSSL_EXPORT size_t pqueue_size(pqueue pq); - - -/* Iterating */ - -/* pqueue_iterator returns an iterator that can be used to iterate over the - * contents of the queue. */ -OPENSSL_EXPORT piterator pqueue_iterator(pqueue pq); - -/* pqueue_next returns the current value of |iter| and advances it to the next - * position. If the iterator has advanced over all the elements, it returns - * NULL. */ -OPENSSL_EXPORT pitem *pqueue_next(piterator *iter); - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_PQUEUE_H */ diff --git a/third_party/boringssl/include/openssl/rand.h b/third_party/boringssl/include/openssl/rand.h deleted file mode 100644 index 300bf42287..0000000000 --- a/third_party/boringssl/include/openssl/rand.h +++ /dev/null @@ -1,61 +0,0 @@ -/* Copyright (c) 2014, Google Inc. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -#ifndef OPENSSL_HEADER_RAND_H -#define OPENSSL_HEADER_RAND_H - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* Random number generation. */ - - -/* RAND_bytes writes |len| bytes of random data to |buf| and returns one. */ -OPENSSL_EXPORT int RAND_bytes(uint8_t *buf, size_t len); - -/* RAND_cleanup frees any resources used by the RNG. This is not safe if other - * threads might still be calling |RAND_bytes|. */ -OPENSSL_EXPORT void RAND_cleanup(void); - - -/* Deprecated functions */ - -/* RAND_pseudo_bytes is a wrapper around |RAND_bytes|. */ -OPENSSL_EXPORT int RAND_pseudo_bytes(uint8_t *buf, size_t len); - -/* RAND_seed does nothing. */ -OPENSSL_EXPORT void RAND_seed(const void *buf, int num); - -/* RAND_load_file returns a nonnegative number. */ -OPENSSL_EXPORT int RAND_load_file(const char *path, long num); - -/* RAND_add does nothing. */ -OPENSSL_EXPORT void RAND_add(const void *buf, int num, double entropy); - -/* RAND_poll returns one. */ -OPENSSL_EXPORT int RAND_poll(void); - -/* RAND_status returns one. */ -OPENSSL_EXPORT int RAND_status(void); - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_RAND_H */ diff --git a/third_party/boringssl/include/openssl/rc4.h b/third_party/boringssl/include/openssl/rc4.h deleted file mode 100644 index 0619cac355..0000000000 --- a/third_party/boringssl/include/openssl/rc4.h +++ /dev/null @@ -1,90 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] */ - -#ifndef OPENSSL_HEADER_RC4_H -#define OPENSSL_HEADER_RC4_H - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* RC4. */ - - -struct rc4_key_st { - uint32_t x, y; - uint32_t data[256]; -} /* RC4_KEY */; - -/* RC4_set_key performs an RC4 key schedule and initialises |rc4key| with |len| - * bytes of key material from |key|. */ -OPENSSL_EXPORT void RC4_set_key(RC4_KEY *rc4key, unsigned len, - const uint8_t *key); - -/* RC4 encrypts (or decrypts, it's the same with RC4) |len| bytes from |in| to - * |out|. */ -OPENSSL_EXPORT void RC4(RC4_KEY *key, size_t len, const uint8_t *in, - uint8_t *out); - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_RC4_H */ diff --git a/third_party/boringssl/include/openssl/rsa.h b/third_party/boringssl/include/openssl/rsa.h deleted file mode 100644 index 9b415d75e1..0000000000 --- a/third_party/boringssl/include/openssl/rsa.h +++ /dev/null @@ -1,575 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] */ - -#ifndef OPENSSL_HEADER_RSA_H -#define OPENSSL_HEADER_RSA_H - -#include - -#include -#include -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* rsa.h contains functions for handling encryption and signature using RSA. */ - - -/* Allocation and destruction. */ - -/* RSA_new returns a new, empty RSA object or NULL on error. */ -OPENSSL_EXPORT RSA *RSA_new(void); - -/* RSA_new_method acts the same as |RSA_new| but takes an explicit |ENGINE|. */ -OPENSSL_EXPORT RSA *RSA_new_method(const ENGINE *engine); - -/* RSA_free decrements the reference count of |rsa| and frees it if the - * reference count drops to zero. */ -OPENSSL_EXPORT void RSA_free(RSA *rsa); - -/* RSA_up_ref increments the reference count of |rsa|. */ -OPENSSL_EXPORT int RSA_up_ref(RSA *rsa); - - -/* Key generation. */ - -/* RSA_generate_key_ex generates a new RSA key where the modulus has size - * |bits| and the public exponent is |e|. If unsure, |RSA_F4| is a good value - * for |e|. If |cb| is not NULL then it is called during the key generation - * process. In addition to the calls documented for |BN_generate_prime_ex|, it - * is called with event=2 when the n'th prime is rejected as unsuitable and - * with event=3 when a suitable value for |p| is found. - * - * It returns one on success or zero on error. */ -OPENSSL_EXPORT int RSA_generate_key_ex(RSA *rsa, int bits, BIGNUM *e, - BN_GENCB *cb); - - -/* Encryption / Decryption */ - -/* Padding types for encryption. */ -#define RSA_PKCS1_PADDING 1 -#define RSA_NO_PADDING 3 -#define RSA_PKCS1_OAEP_PADDING 4 -/* RSA_PKCS1_PSS_PADDING can only be used via the EVP interface. */ -#define RSA_PKCS1_PSS_PADDING 6 - -/* RSA_encrypt encrypts |in_len| bytes from |in| to the public key from |rsa| - * and writes, at most, |max_out| bytes of encrypted data to |out|. The - * |max_out| argument must be, at least, |RSA_size| in order to ensure success. - * - * It returns 1 on success or zero on error. - * - * The |padding| argument must be one of the |RSA_*_PADDING| values. If in - * doubt, |RSA_PKCS1_PADDING| is the most common but |RSA_PKCS1_OAEP_PADDING| - * is the most secure. */ -OPENSSL_EXPORT int RSA_encrypt(RSA *rsa, size_t *out_len, uint8_t *out, - size_t max_out, const uint8_t *in, size_t in_len, - int padding); - -/* RSA_decrypt decrypts |in_len| bytes from |in| with the private key from - * |rsa| and writes, at most, |max_out| bytes of plaintext to |out|. The - * |max_out| argument must be, at least, |RSA_size| in order to ensure success. - * - * It returns 1 on success or zero on error. - * - * The |padding| argument must be one of the |RSA_*_PADDING| values. If in - * doubt, |RSA_PKCS1_PADDING| is the most common but |RSA_PKCS1_OAEP_PADDING| - * is the most secure. */ -OPENSSL_EXPORT int RSA_decrypt(RSA *rsa, size_t *out_len, uint8_t *out, - size_t max_out, const uint8_t *in, size_t in_len, - int padding); - -/* RSA_public_encrypt encrypts |flen| bytes from |from| to the public key in - * |rsa| and writes the encrypted data to |to|. The |to| buffer must have at - * least |RSA_size| bytes of space. It returns the number of bytes written, or - * -1 on error. The |padding| argument must be one of the |RSA_*_PADDING| - * values. If in doubt, |RSA_PKCS1_PADDING| is the most common but - * |RSA_PKCS1_OAEP_PADDING| is the most secure. - * - * WARNING: this function is dangerous because it breaks the usual return value - * convention. Use |RSA_encrypt| instead. */ -OPENSSL_EXPORT int RSA_public_encrypt(int flen, const uint8_t *from, - uint8_t *to, RSA *rsa, int padding); - -/* RSA_private_decrypt decrypts |flen| bytes from |from| with the public key in - * |rsa| and writes the plaintext to |to|. The |to| buffer must have at - * least |RSA_size| bytes of space. It returns the number of bytes written, or - * -1 on error. The |padding| argument must be one of the |RSA_*_PADDING| - * values. If in doubt, |RSA_PKCS1_PADDING| is the most common but - * |RSA_PKCS1_OAEP_PADDING| is the most secure. - * - * WARNING: this function is dangerous because it breaks the usual return value - * convention. Use |RSA_decrypt| instead. */ -OPENSSL_EXPORT int RSA_private_decrypt(int flen, const uint8_t *from, - uint8_t *to, RSA *rsa, int padding); - -/* RSA_message_index_PKCS1_type_2 performs the first step of a PKCS #1 padding - * check for decryption. If the |from_len| bytes pointed to at |from| are a - * valid PKCS #1 message, it returns one and sets |*out_index| to the start of - * the unpadded message. The unpadded message is a suffix of the input and has - * length |from_len - *out_index|. Otherwise, it returns zero and sets - * |*out_index| to zero. This function runs in time independent of the input - * data and is intended to be used directly to avoid Bleichenbacher's attack. - * - * WARNING: This function behaves differently from the usual OpenSSL convention - * in that it does NOT put an error on the queue in the error case. */ -OPENSSL_EXPORT int RSA_message_index_PKCS1_type_2(const uint8_t *from, - size_t from_len, - size_t *out_index); - - -/* Signing / Verification */ - -/* RSA_sign signs |in_len| bytes of digest from |in| with |rsa| and writes, at - * most, |RSA_size(rsa)| bytes to |out|. On successful return, the actual - * number of bytes written is written to |*out_len|. - * - * The |hash_nid| argument identifies the hash function used to calculate |in| - * and is embedded in the resulting signature. For example, it might be - * |NID_sha256|. - * - * It returns 1 on success and zero on error. */ -OPENSSL_EXPORT int RSA_sign(int hash_nid, const uint8_t *in, - unsigned int in_len, uint8_t *out, - unsigned int *out_len, RSA *rsa); - -/* RSA_sign_raw signs |in_len| bytes from |in| with the public key from |rsa| - * and writes, at most, |max_out| bytes of signature data to |out|. The - * |max_out| argument must be, at least, |RSA_size| in order to ensure success. - * - * It returns 1 on success or zero on error. - * - * The |padding| argument must be one of the |RSA_*_PADDING| values. If in - * doubt, |RSA_PKCS1_PADDING| is the most common. */ -OPENSSL_EXPORT int RSA_sign_raw(RSA *rsa, size_t *out_len, uint8_t *out, - size_t max_out, const uint8_t *in, - size_t in_len, int padding); - -/* RSA_verify verifies that |sig_len| bytes from |sig| are a valid, PKCS#1 - * signature of |msg_len| bytes at |msg| by |rsa|. - * - * The |hash_nid| argument identifies the hash function used to calculate |in| - * and is embedded in the resulting signature in order to prevent hash - * confusion attacks. For example, it might be |NID_sha256|. - * - * It returns one if the signature is valid and zero otherwise. - * - * WARNING: this differs from the original, OpenSSL function which additionally - * returned -1 on error. */ -OPENSSL_EXPORT int RSA_verify(int hash_nid, const uint8_t *msg, size_t msg_len, - const uint8_t *sig, size_t sig_len, RSA *rsa); - -/* RSA_verify_raw verifies |in_len| bytes of signature from |in| using the - * public key from |rsa| and writes, at most, |max_out| bytes of plaintext to - * |out|. The |max_out| argument must be, at least, |RSA_size| in order to - * ensure success. - * - * It returns 1 on success or zero on error. - * - * The |padding| argument must be one of the |RSA_*_PADDING| values. If in - * doubt, |RSA_PKCS1_PADDING| is the most common. */ -OPENSSL_EXPORT int RSA_verify_raw(RSA *rsa, size_t *out_len, uint8_t *out, - size_t max_out, const uint8_t *in, - size_t in_len, int padding); - -/* RSA_private_encrypt encrypts |flen| bytes from |from| with the private key in - * |rsa| and writes the encrypted data to |to|. The |to| buffer must have at - * least |RSA_size| bytes of space. It returns the number of bytes written, or - * -1 on error. The |padding| argument must be one of the |RSA_*_PADDING| - * values. If in doubt, |RSA_PKCS1_PADDING| is the most common. - * - * WARNING: this function is dangerous because it breaks the usual return value - * convention. Use |RSA_sign_raw| instead. */ -OPENSSL_EXPORT int RSA_private_encrypt(int flen, const uint8_t *from, - uint8_t *to, RSA *rsa, int padding); - -/* RSA_private_encrypt verifies |flen| bytes of signature from |from| using the - * public key in |rsa| and writes the plaintext to |to|. The |to| buffer must - * have at least |RSA_size| bytes of space. It returns the number of bytes - * written, or -1 on error. The |padding| argument must be one of the - * |RSA_*_PADDING| values. If in doubt, |RSA_PKCS1_PADDING| is the most common. - * - * WARNING: this function is dangerous because it breaks the usual return value - * convention. Use |RSA_verify_raw| instead. */ -OPENSSL_EXPORT int RSA_public_decrypt(int flen, const uint8_t *from, - uint8_t *to, RSA *rsa, int padding); - - -/* Utility functions. */ - -/* RSA_size returns the number of bytes in the modulus, which is also the size - * of a signature or encrypted value using |rsa|. */ -OPENSSL_EXPORT unsigned RSA_size(const RSA *rsa); - -/* RSA_is_opaque returns one if |rsa| is opaque and doesn't expose its key - * material. Otherwise it returns zero. */ -OPENSSL_EXPORT int RSA_is_opaque(const RSA *rsa); - -/* RSA_supports_digest returns one if |rsa| supports signing digests - * of type |md|. Otherwise it returns zero. */ -OPENSSL_EXPORT int RSA_supports_digest(const RSA *rsa, const EVP_MD *md); - -/* RSAPublicKey_dup allocates a fresh |RSA| and copies the private key from - * |rsa| into it. It returns the fresh |RSA| object, or NULL on error. */ -OPENSSL_EXPORT RSA *RSAPublicKey_dup(const RSA *rsa); - -/* RSAPrivateKey_dup allocates a fresh |RSA| and copies the private key from - * |rsa| into it. It returns the fresh |RSA| object, or NULL on error. */ -OPENSSL_EXPORT RSA *RSAPrivateKey_dup(const RSA *rsa); - -/* RSA_check_key performs basic validatity tests on |rsa|. It returns one if - * they pass and zero otherwise. Opaque keys and public keys always pass. If it - * returns zero then a more detailed error is available on the error queue. */ -OPENSSL_EXPORT int RSA_check_key(const RSA *rsa); - -/* RSA_recover_crt_params uses |rsa->n|, |rsa->d| and |rsa->e| in order to - * calculate the two primes used and thus the precomputed, CRT values. These - * values are set in the |p|, |q|, |dmp1|, |dmq1| and |iqmp| members of |rsa|, - * which must be |NULL| on entry. It returns one on success and zero - * otherwise. */ -OPENSSL_EXPORT int RSA_recover_crt_params(RSA *rsa); - -/* RSA_verify_PKCS1_PSS_mgf1 verifies that |EM| is a correct PSS padding of - * |mHash|, where |mHash| is a digest produced by |Hash|. |EM| must point to - * exactly |RSA_size(rsa)| bytes of data. The |mgf1Hash| argument specifies the - * hash function for generating the mask. If NULL, |Hash| is used. The |sLen| - * argument specifies the expected salt length in bytes. If |sLen| is -1 then - * the salt length is the same as the hash length. If -2, then the salt length - * is maximal and is taken from the size of |EM|. - * - * It returns one on success or zero on error. */ -OPENSSL_EXPORT int RSA_verify_PKCS1_PSS_mgf1(RSA *rsa, const uint8_t *mHash, - const EVP_MD *Hash, - const EVP_MD *mgf1Hash, - const uint8_t *EM, int sLen); - -/* RSA_padding_add_PKCS1_PSS_mgf1 writes a PSS padding of |mHash| to |EM|, - * where |mHash| is a digest produced by |Hash|. |RSA_size(rsa)| bytes of - * output will be written to |EM|. The |mgf1Hash| argument specifies the hash - * function for generating the mask. If NULL, |Hash| is used. The |sLen| - * argument specifies the expected salt length in bytes. If |sLen| is -1 then - * the salt length is the same as the hash length. If -2, then the salt length - * is maximal given the space in |EM|. - * - * It returns one on success or zero on error. */ -OPENSSL_EXPORT int RSA_padding_add_PKCS1_PSS_mgf1(RSA *rsa, uint8_t *EM, - const uint8_t *mHash, - const EVP_MD *Hash, - const EVP_MD *mgf1Hash, - int sLen); - - -/* ASN.1 functions. */ - -/* d2i_RSAPublicKey parses an ASN.1, DER-encoded, RSA public key from |len| - * bytes at |*inp|. If |out| is not NULL then, on exit, a pointer to the result - * is in |*out|. If |*out| is already non-NULL on entry then the result is - * written directly into |*out|, otherwise a fresh |RSA| is allocated. On - * successful exit, |*inp| is advanced past the DER structure. It returns the - * result or NULL on error. */ -OPENSSL_EXPORT RSA *d2i_RSAPublicKey(RSA **out, const uint8_t **inp, long len); - -/* i2d_RSAPublicKey marshals |in| to an ASN.1, DER structure. If |outp| is not - * NULL then the result is written to |*outp| and |*outp| is advanced just past - * the output. It returns the number of bytes in the result, whether written or - * not, or a negative value on error. */ -OPENSSL_EXPORT int i2d_RSAPublicKey(const RSA *in, uint8_t **outp); - -/* d2i_RSAPrivateKey parses an ASN.1, DER-encoded, RSA private key from |len| - * bytes at |*inp|. If |out| is not NULL then, on exit, a pointer to the result - * is in |*out|. If |*out| is already non-NULL on entry then the result is - * written directly into |*out|, otherwise a fresh |RSA| is allocated. On - * successful exit, |*inp| is advanced past the DER structure. It returns the - * result or NULL on error. */ -OPENSSL_EXPORT RSA *d2i_RSAPrivateKey(RSA **out, const uint8_t **inp, long len); - -/* i2d_RSAPrivateKey marshals |in| to an ASN.1, DER structure. If |outp| is not - * NULL then the result is written to |*outp| and |*outp| is advanced just past - * the output. It returns the number of bytes in the result, whether written or - * not, or a negative value on error. */ -OPENSSL_EXPORT int i2d_RSAPrivateKey(const RSA *in, uint8_t **outp); - - -/* ex_data functions. - * - * See |ex_data.h| for details. */ - -OPENSSL_EXPORT int RSA_get_ex_new_index(long argl, void *argp, - CRYPTO_EX_new *new_func, - CRYPTO_EX_dup *dup_func, - CRYPTO_EX_free *free_func); -OPENSSL_EXPORT int RSA_set_ex_data(RSA *r, int idx, void *arg); -OPENSSL_EXPORT void *RSA_get_ex_data(const RSA *r, int idx); - -/* RSA_FLAG_OPAQUE specifies that this RSA_METHOD does not expose its key - * material. This may be set if, for instance, it is wrapping some other crypto - * API, like a platform key store. */ -#define RSA_FLAG_OPAQUE 1 - -/* RSA_FLAG_CACHE_PUBLIC causes a precomputed Montgomery context to be created, - * on demand, for the public key operations. */ -#define RSA_FLAG_CACHE_PUBLIC 2 - -/* RSA_FLAG_CACHE_PRIVATE causes a precomputed Montgomery context to be - * created, on demand, for the private key operations. */ -#define RSA_FLAG_CACHE_PRIVATE 4 - -/* RSA_FLAG_NO_BLINDING disables blinding of private operations. */ -#define RSA_FLAG_NO_BLINDING 8 - -/* RSA_FLAG_EXT_PKEY means that private key operations will be handled by - * |mod_exp| and that they do not depend on the private key components being - * present: for example a key stored in external hardware. */ -#define RSA_FLAG_EXT_PKEY 0x20 - -/* RSA_FLAG_SIGN_VER causes the |sign| and |verify| functions of |rsa_meth_st| - * to be called when set. */ -#define RSA_FLAG_SIGN_VER 0x40 - - -/* RSA public exponent values. */ - -#define RSA_3 0x3 -#define RSA_F4 0x10001 - - -/* Deprecated functions. */ - -/* RSA_blinding_on returns one. */ -OPENSSL_EXPORT int RSA_blinding_on(RSA *rsa, BN_CTX *ctx); - - -struct rsa_meth_st { - struct openssl_method_common_st common; - - void *app_data; - - int (*init)(RSA *rsa); - int (*finish)(RSA *rsa); - - /* size returns the size of the RSA modulus in bytes. */ - size_t (*size)(const RSA *rsa); - - int (*sign)(int type, const uint8_t *m, unsigned int m_length, - uint8_t *sigret, unsigned int *siglen, const RSA *rsa); - - int (*verify)(int dtype, const uint8_t *m, unsigned int m_length, - const uint8_t *sigbuf, unsigned int siglen, const RSA *rsa); - - - /* These functions mirror the |RSA_*| functions of the same name. */ - int (*encrypt)(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out, - const uint8_t *in, size_t in_len, int padding); - int (*sign_raw)(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out, - const uint8_t *in, size_t in_len, int padding); - - int (*decrypt)(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out, - const uint8_t *in, size_t in_len, int padding); - int (*verify_raw)(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out, - const uint8_t *in, size_t in_len, int padding); - - /* private_transform takes a big-endian integer from |in|, calculates the - * d'th power of it, modulo the RSA modulus and writes the result as a - * big-endian integer to |out|. Both |in| and |out| are |len| bytes long and - * |len| is always equal to |RSA_size(rsa)|. If the result of the transform - * can be represented in fewer than |len| bytes, then |out| must be zero - * padded on the left. - * - * It returns one on success and zero otherwise. - * - * RSA decrypt and sign operations will call this, thus an ENGINE might wish - * to override it in order to avoid having to implement the padding - * functionality demanded by those, higher level, operations. */ - int (*private_transform)(RSA *rsa, uint8_t *out, const uint8_t *in, - size_t len); - - int (*mod_exp)(BIGNUM *r0, const BIGNUM *I, RSA *rsa, - BN_CTX *ctx); /* Can be null */ - int (*bn_mod_exp)(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, - const BIGNUM *m, BN_CTX *ctx, - BN_MONT_CTX *m_ctx); - - int flags; - - int (*keygen)(RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb); - - /* supports_digest returns one if |rsa| supports digests of type - * |md|. If null, it is assumed that all digests are supported. */ - int (*supports_digest)(const RSA *rsa, const EVP_MD *md); -}; - - -/* Private functions. */ - -typedef struct bn_blinding_st BN_BLINDING; - -struct rsa_st { - /* version is only used during ASN.1 (de)serialisation. */ - long version; - RSA_METHOD *meth; - - BIGNUM *n; - BIGNUM *e; - BIGNUM *d; - BIGNUM *p; - BIGNUM *q; - BIGNUM *dmp1; - BIGNUM *dmq1; - BIGNUM *iqmp; - /* be careful using this if the RSA structure is shared */ - CRYPTO_EX_DATA ex_data; - CRYPTO_refcount_t references; - int flags; - - CRYPTO_MUTEX lock; - - /* Used to cache montgomery values. The creation of these values is protected - * by |lock|. */ - BN_MONT_CTX *_method_mod_n; - BN_MONT_CTX *_method_mod_p; - BN_MONT_CTX *_method_mod_q; - - /* num_blindings contains the size of the |blindings| and |blindings_inuse| - * arrays. This member and the |blindings_inuse| array are protected by - * |lock|. */ - unsigned num_blindings; - /* blindings is an array of BN_BLINDING structures that can be reserved by a - * thread by locking |lock| and changing the corresponding element in - * |blindings_inuse| from 0 to 1. */ - BN_BLINDING **blindings; - unsigned char *blindings_inuse; -}; - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#define RSA_F_BN_BLINDING_convert_ex 100 -#define RSA_F_BN_BLINDING_create_param 101 -#define RSA_F_BN_BLINDING_invert_ex 102 -#define RSA_F_BN_BLINDING_new 103 -#define RSA_F_BN_BLINDING_update 104 -#define RSA_F_RSA_check_key 105 -#define RSA_F_RSA_new_method 106 -#define RSA_F_RSA_padding_add_PKCS1_OAEP_mgf1 107 -#define RSA_F_RSA_padding_add_PKCS1_PSS_mgf1 108 -#define RSA_F_RSA_padding_add_PKCS1_type_1 109 -#define RSA_F_RSA_padding_add_PKCS1_type_2 110 -#define RSA_F_RSA_padding_add_none 111 -#define RSA_F_RSA_padding_check_PKCS1_OAEP_mgf1 112 -#define RSA_F_RSA_padding_check_PKCS1_type_1 113 -#define RSA_F_RSA_padding_check_PKCS1_type_2 114 -#define RSA_F_RSA_padding_check_none 115 -#define RSA_F_RSA_recover_crt_params 116 -#define RSA_F_RSA_sign 117 -#define RSA_F_RSA_verify 118 -#define RSA_F_RSA_verify_PKCS1_PSS_mgf1 119 -#define RSA_F_decrypt 120 -#define RSA_F_encrypt 121 -#define RSA_F_keygen 122 -#define RSA_F_pkcs1_prefixed_msg 123 -#define RSA_F_private_transform 124 -#define RSA_F_rsa_setup_blinding 125 -#define RSA_F_sign_raw 126 -#define RSA_F_verify_raw 127 -#define RSA_R_BAD_E_VALUE 100 -#define RSA_R_BAD_FIXED_HEADER_DECRYPT 101 -#define RSA_R_BAD_PAD_BYTE_COUNT 102 -#define RSA_R_BAD_RSA_PARAMETERS 103 -#define RSA_R_BAD_SIGNATURE 104 -#define RSA_R_BLOCK_TYPE_IS_NOT_01 105 -#define RSA_R_BN_NOT_INITIALIZED 106 -#define RSA_R_CRT_PARAMS_ALREADY_GIVEN 107 -#define RSA_R_CRT_VALUES_INCORRECT 108 -#define RSA_R_DATA_LEN_NOT_EQUAL_TO_MOD_LEN 109 -#define RSA_R_DATA_TOO_LARGE 110 -#define RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE 111 -#define RSA_R_DATA_TOO_LARGE_FOR_MODULUS 112 -#define RSA_R_DATA_TOO_SMALL 113 -#define RSA_R_DATA_TOO_SMALL_FOR_KEY_SIZE 114 -#define RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY 115 -#define RSA_R_D_E_NOT_CONGRUENT_TO_1 116 -#define RSA_R_EMPTY_PUBLIC_KEY 117 -#define RSA_R_FIRST_OCTET_INVALID 118 -#define RSA_R_INCONSISTENT_SET_OF_CRT_VALUES 119 -#define RSA_R_INTERNAL_ERROR 120 -#define RSA_R_INVALID_MESSAGE_LENGTH 121 -#define RSA_R_KEY_SIZE_TOO_SMALL 122 -#define RSA_R_LAST_OCTET_INVALID 123 -#define RSA_R_MODULUS_TOO_LARGE 124 -#define RSA_R_NO_PUBLIC_EXPONENT 125 -#define RSA_R_NULL_BEFORE_BLOCK_MISSING 126 -#define RSA_R_N_NOT_EQUAL_P_Q 127 -#define RSA_R_OAEP_DECODING_ERROR 128 -#define RSA_R_ONLY_ONE_OF_P_Q_GIVEN 129 -#define RSA_R_OUTPUT_BUFFER_TOO_SMALL 130 -#define RSA_R_PADDING_CHECK_FAILED 131 -#define RSA_R_PKCS_DECODING_ERROR 132 -#define RSA_R_SLEN_CHECK_FAILED 133 -#define RSA_R_SLEN_RECOVERY_FAILED 134 -#define RSA_R_TOO_LONG 135 -#define RSA_R_TOO_MANY_ITERATIONS 136 -#define RSA_R_UNKNOWN_ALGORITHM_TYPE 137 -#define RSA_R_UNKNOWN_PADDING_TYPE 138 -#define RSA_R_VALUE_MISSING 139 -#define RSA_R_WRONG_SIGNATURE_LENGTH 140 - -#endif /* OPENSSL_HEADER_RSA_H */ diff --git a/third_party/boringssl/include/openssl/safestack.h b/third_party/boringssl/include/openssl/safestack.h deleted file mode 100644 index 6e5e433074..0000000000 --- a/third_party/boringssl/include/openssl/safestack.h +++ /dev/null @@ -1,16 +0,0 @@ -/* Copyright (c) 2014, Google Inc. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -/* This header is provided in order to make compiling against code that expects - OpenSSL easier. */ diff --git a/third_party/boringssl/include/openssl/sha.h b/third_party/boringssl/include/openssl/sha.h deleted file mode 100644 index ac2ab758b4..0000000000 --- a/third_party/boringssl/include/openssl/sha.h +++ /dev/null @@ -1,241 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] */ - -#ifndef OPENSSL_HEADER_SHA_H -#define OPENSSL_HEADER_SHA_H - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* The SHA family of hash functions (SHA-1 and SHA-2). */ - - -/* SHA_CBLOCK is the block size of SHA-1. */ -#define SHA_CBLOCK 64 - -/* SHA_DIGEST_LENGTH is the length of a SHA-1 digest. */ -#define SHA_DIGEST_LENGTH 20 - -/* TODO(fork): remove */ -#define SHA_LBLOCK 16 -#define SHA_LONG uint32_t - -/* SHA1_Init initialises |sha| and returns one. */ -OPENSSL_EXPORT int SHA1_Init(SHA_CTX *sha); - -/* SHA1_Update adds |len| bytes from |data| to |sha| and returns one. */ -OPENSSL_EXPORT int SHA1_Update(SHA_CTX *sha, const void *data, size_t len); - -/* SHA1_Final adds the final padding to |sha| and writes the resulting digest - * to |md|, which must have at least |SHA_DIGEST_LENGTH| bytes of space. It - * returns one. */ -OPENSSL_EXPORT int SHA1_Final(uint8_t *md, SHA_CTX *sha); - -/* SHA1 writes the digest of |len| bytes from |data| to |out| and returns - * |out|. There must be at least |SHA_DIGEST_LENGTH| bytes of space in - * |out|. */ -OPENSSL_EXPORT uint8_t *SHA1(const uint8_t *data, size_t len, uint8_t *out); - -/* SHA1_Transform is a low-level function that performs a single, SHA-1 block - * transformation using the state from |sha| and 64 bytes from |block|. */ -OPENSSL_EXPORT void SHA1_Transform(SHA_CTX *sha, const uint8_t *block); - -struct sha_state_st { - uint32_t h0, h1, h2, h3, h4; - uint32_t Nl, Nh; - uint32_t data[16]; - unsigned int num; -}; - - -/* SHA-224. */ - -/* SHA224_CBLOCK is the block size of SHA-224. */ -#define SHA224_CBLOCK 64 - -/* SHA224_DIGEST_LENGTH is the length of a SHA-224 digest. */ -#define SHA224_DIGEST_LENGTH 28 - -/* SHA224_Init initialises |sha| and returns 1. */ -OPENSSL_EXPORT int SHA224_Init(SHA256_CTX *sha); - -/* SHA224_Update adds |len| bytes from |data| to |sha| and returns 1. */ -OPENSSL_EXPORT int SHA224_Update(SHA256_CTX *sha, const void *data, size_t len); - -/* SHA224_Final adds the final padding to |sha| and writes the resulting digest - * to |md|, which must have at least |SHA224_DIGEST_LENGTH| bytes of space. It - * returns one on success and zero on programmer error. */ -OPENSSL_EXPORT int SHA224_Final(uint8_t *md, SHA256_CTX *sha); - -/* SHA224 writes the digest of |len| bytes from |data| to |out| and returns - * |out|. There must be at least |SHA224_DIGEST_LENGTH| bytes of space in - * |out|. */ -OPENSSL_EXPORT uint8_t *SHA224(const uint8_t *data, size_t len, uint8_t *out); - - -/* SHA-256. */ - -/* SHA256_CBLOCK is the block size of SHA-256. */ -#define SHA256_CBLOCK 64 - -/* SHA256_DIGEST_LENGTH is the length of a SHA-256 digest. */ -#define SHA256_DIGEST_LENGTH 32 - -/* SHA256_Init initialises |sha| and returns 1. */ -OPENSSL_EXPORT int SHA256_Init(SHA256_CTX *sha); - -/* SHA256_Update adds |len| bytes from |data| to |sha| and returns 1. */ -OPENSSL_EXPORT int SHA256_Update(SHA256_CTX *sha, const void *data, size_t len); - -/* SHA256_Final adds the final padding to |sha| and writes the resulting digest - * to |md|, which must have at least |SHA256_DIGEST_LENGTH| bytes of space. It - * returns one on success and zero on programmer error. */ -OPENSSL_EXPORT int SHA256_Final(uint8_t *md, SHA256_CTX *sha); - -/* SHA256 writes the digest of |len| bytes from |data| to |out| and returns - * |out|. There must be at least |SHA256_DIGEST_LENGTH| bytes of space in - * |out|. */ -OPENSSL_EXPORT uint8_t *SHA256(const uint8_t *data, size_t len, uint8_t *out); - -/* SHA256_Transform is a low-level function that performs a single, SHA-1 block - * transformation using the state from |sha| and 64 bytes from |block|. */ -OPENSSL_EXPORT void SHA256_Transform(SHA256_CTX *sha, const uint8_t *data); - -struct sha256_state_st { - uint32_t h[8]; - uint32_t Nl, Nh; - uint32_t data[16]; - unsigned int num, md_len; -}; - - -/* SHA-384. */ - -/* SHA384_CBLOCK is the block size of SHA-384. */ -#define SHA384_CBLOCK 128 - -/* SHA384_DIGEST_LENGTH is the length of a SHA-384 digest. */ -#define SHA384_DIGEST_LENGTH 48 - -/* SHA384_Init initialises |sha| and returns 1. */ -OPENSSL_EXPORT int SHA384_Init(SHA512_CTX *sha); - -/* SHA384_Update adds |len| bytes from |data| to |sha| and returns 1. */ -OPENSSL_EXPORT int SHA384_Update(SHA512_CTX *sha, const void *data, size_t len); - -/* SHA384_Final adds the final padding to |sha| and writes the resulting digest - * to |md|, which must have at least |SHA384_DIGEST_LENGTH| bytes of space. It - * returns one on success and zero on programmer error. */ -OPENSSL_EXPORT int SHA384_Final(uint8_t *md, SHA512_CTX *sha); - -/* SHA384 writes the digest of |len| bytes from |data| to |out| and returns - * |out|. There must be at least |SHA384_DIGEST_LENGTH| bytes of space in - * |out|. */ -OPENSSL_EXPORT uint8_t *SHA384(const uint8_t *data, size_t len, uint8_t *out); - -/* SHA384_Transform is a low-level function that performs a single, SHA-1 block - * transformation using the state from |sha| and 64 bytes from |block|. */ -OPENSSL_EXPORT void SHA384_Transform(SHA512_CTX *sha, const uint8_t *data); - - -/* SHA-512. */ - -/* SHA512_CBLOCK is the block size of SHA-512. */ -#define SHA512_CBLOCK 128 - -/* SHA512_DIGEST_LENGTH is the length of a SHA-512 digest. */ -#define SHA512_DIGEST_LENGTH 64 - -/* SHA512_Init initialises |sha| and returns 1. */ -OPENSSL_EXPORT int SHA512_Init(SHA512_CTX *sha); - -/* SHA512_Update adds |len| bytes from |data| to |sha| and returns 1. */ -OPENSSL_EXPORT int SHA512_Update(SHA512_CTX *sha, const void *data, size_t len); - -/* SHA512_Final adds the final padding to |sha| and writes the resulting digest - * to |md|, which must have at least |SHA512_DIGEST_LENGTH| bytes of space. It - * returns one on success and zero on programmer error. */ -OPENSSL_EXPORT int SHA512_Final(uint8_t *md, SHA512_CTX *sha); - -/* SHA512 writes the digest of |len| bytes from |data| to |out| and returns - * |out|. There must be at least |SHA512_DIGEST_LENGTH| bytes of space in - * |out|. */ -OPENSSL_EXPORT uint8_t *SHA512(const uint8_t *data, size_t len, uint8_t *out); - -/* SHA512_Transform is a low-level function that performs a single, SHA-1 block - * transformation using the state from |sha| and 64 bytes from |block|. */ -OPENSSL_EXPORT void SHA512_Transform(SHA512_CTX *sha, const uint8_t *data); - -struct sha512_state_st { - uint64_t h[8]; - uint64_t Nl, Nh; - union { - uint64_t d[16]; - uint8_t p[128]; - } u; - unsigned int num, md_len; -}; - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_SHA_H */ diff --git a/third_party/boringssl/include/openssl/srtp.h b/third_party/boringssl/include/openssl/srtp.h deleted file mode 100644 index 3f5a53e2c1..0000000000 --- a/third_party/boringssl/include/openssl/srtp.h +++ /dev/null @@ -1,178 +0,0 @@ -/* ssl/tls1.h */ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] - */ -/* ==================================================================== - * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * openssl-core@openssl.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.openssl.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS 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. - * ==================================================================== - * - * This product includes cryptographic software written by Eric Young - * (eay@cryptsoft.com). This product includes software written by Tim - * Hudson (tjh@cryptsoft.com). - * - */ -/* - DTLS code by Eric Rescorla - - Copyright (C) 2006, Network Resonance, Inc. - Copyright (C) 2011, RTFM, Inc. -*/ - -#ifndef OPENSSL_HEADER_SRTP_H -#define OPENSSL_HEADER_SRTP_H - -#ifdef __cplusplus -extern "C" { -#endif - - -/* Constants for SRTP profiles */ -#define SRTP_AES128_CM_SHA1_80 0x0001 -#define SRTP_AES128_CM_SHA1_32 0x0002 -#define SRTP_AES128_F8_SHA1_80 0x0003 -#define SRTP_AES128_F8_SHA1_32 0x0004 -#define SRTP_NULL_SHA1_80 0x0005 -#define SRTP_NULL_SHA1_32 0x0006 - -/* SSL_CTX_set_srtp_profiles enables SRTP for all SSL objects created from - * |ctx|. |profile| contains a colon-separated list of profile names. It returns - * one on success and zero on failure. */ -OPENSSL_EXPORT int SSL_CTX_set_srtp_profiles(SSL_CTX *ctx, - const char *profiles); - -/* SSL_set_srtp_profiles enables SRTP for |ssl|. |profile| contains a - * colon-separated list of profile names. It returns one on success and zero on - * failure. */ -OPENSSL_EXPORT int SSL_set_srtp_profiles(SSL *ctx, const char *profiles); - -/* SSL_get_srtp_profiles returns the SRTP profiles supported by |ssl|. */ -OPENSSL_EXPORT STACK_OF(SRTP_PROTECTION_PROFILE) *SSL_get_srtp_profiles( - SSL *ssl); - -/* SSL_get_selected_srtp_profile returns the selected SRTP profile, or NULL if - * SRTP was not negotiated. */ -OPENSSL_EXPORT const SRTP_PROTECTION_PROFILE *SSL_get_selected_srtp_profile( - SSL *s); - - -/* Deprecated functions */ - -/* SSL_CTX_set_tlsext_use_srtp calls SSL_CTX_set_srtp_profiles. It returns zero - * on success and one on failure. - * - * WARNING: this function is dangerous because it breaks the usual return value - * convention. Use SSL_CTX_set_srtp_profiles instead. */ -OPENSSL_EXPORT int SSL_CTX_set_tlsext_use_srtp(SSL_CTX *ctx, - const char *profiles); - -/* SSL_set_tlsext_use_srtp calls SSL_set_srtp_profiles. It returns zero on - * success and one on failure. - * - * WARNING: this function is dangerous because it breaks the usual return value - * convention. Use SSL_set_srtp_profiles instead. */ -OPENSSL_EXPORT int SSL_set_tlsext_use_srtp(SSL *ctx, const char *profiles); - - -#ifdef __cplusplus -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_SRTP_H */ - diff --git a/third_party/boringssl/include/openssl/ssl.h b/third_party/boringssl/include/openssl/ssl.h deleted file mode 100644 index 217dbaf2f4..0000000000 --- a/third_party/boringssl/include/openssl/ssl.h +++ /dev/null @@ -1,2959 +0,0 @@ -/* ssl/ssl.h */ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] - */ -/* ==================================================================== - * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * openssl-core@openssl.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.openssl.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS 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. - * ==================================================================== - * - * This product includes cryptographic software written by Eric Young - * (eay@cryptsoft.com). This product includes software written by Tim - * Hudson (tjh@cryptsoft.com). - * - */ -/* ==================================================================== - * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. - * ECC cipher suite support in OpenSSL originally developed by - * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. - */ -/* ==================================================================== - * Copyright 2005 Nokia. All rights reserved. - * - * The portions of the attached software ("Contribution") is developed by - * Nokia Corporation and is licensed pursuant to the OpenSSL open source - * license. - * - * The Contribution, originally written by Mika Kousa and Pasi Eronen of - * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites - * support (see RFC 4279) to OpenSSL. - * - * No patent licenses or other rights except those expressly stated in - * the OpenSSL open source license shall be deemed granted or received - * expressly, by implication, estoppel, or otherwise. - * - * No assurances are provided by Nokia that the Contribution does not - * infringe the patent or other intellectual property rights of any third - * party or that the license provides you with all the necessary rights - * to make use of the Contribution. - * - * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN - * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA - * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY - * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR - * OTHERWISE. - */ - -#ifndef OPENSSL_HEADER_SSL_H -#define OPENSSL_HEADER_SSL_H - -#include - -#include -#include -#include -#include -#include -#include -#include - -#if !defined(OPENSSL_WINDOWS) -#include -#endif - -/* wpa_supplicant expects to get the version functions from ssl.h */ -#include - -/* Forward-declare struct timeval. On Windows, it is defined in winsock2.h and - * Windows headers define too many macros to be included in public headers. - * However, only a forward declaration is needed. */ -struct timeval; - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* SSL implementation. */ - - -/* Initialization. */ - -/* SSL_library_init initializes the crypto and SSL libraries and returns one. */ -OPENSSL_EXPORT int SSL_library_init(void); - - -/* Cipher suites. */ - -/* An SSL_CIPHER represents a cipher suite. */ -typedef struct ssl_cipher_st { - /* name is the OpenSSL name for the cipher. */ - const char *name; - /* id is the cipher suite value bitwise OR-d with 0x03000000. */ - uint32_t id; - - /* The following are internal fields. See ssl/internal.h for their values. */ - - uint32_t algorithm_mkey; - uint32_t algorithm_auth; - uint32_t algorithm_enc; - uint32_t algorithm_mac; - uint32_t algorithm_ssl; - uint32_t algo_strength; - - /* algorithm2 contains extra flags. See ssl/internal.h. */ - uint32_t algorithm2; - - /* strength_bits is the strength of the cipher in bits. */ - int strength_bits; - /* alg_bits is the number of bits of key material used by the algorithm. */ - int alg_bits; -} SSL_CIPHER; - -DECLARE_STACK_OF(SSL_CIPHER) - -/* SSL_get_cipher_by_value returns the structure representing a TLS cipher - * suite based on its assigned number, or NULL if unknown. See - * https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-4. */ -OPENSSL_EXPORT const SSL_CIPHER *SSL_get_cipher_by_value(uint16_t value); - -/* SSL_CIPHER_get_id returns |cipher|'s id. It may be cast to a |uint16_t| to - * get the cipher suite value. */ -OPENSSL_EXPORT uint32_t SSL_CIPHER_get_id(const SSL_CIPHER *cipher); - -/* SSL_CIPHER_is_AES returns one if |cipher| uses AES (either GCM or CBC - * mode). */ -OPENSSL_EXPORT int SSL_CIPHER_is_AES(const SSL_CIPHER *cipher); - -/* SSL_CIPHER_has_MD5_HMAC returns one if |cipher| uses HMAC-MD5. */ -OPENSSL_EXPORT int SSL_CIPHER_has_MD5_HMAC(const SSL_CIPHER *cipher); - -/* SSL_CIPHER_is_AESGCM returns one if |cipher| uses AES-GCM. */ -OPENSSL_EXPORT int SSL_CIPHER_is_AESGCM(const SSL_CIPHER *cipher); - -/* SSL_CIPHER_is_CHACHA20POLY1305 returns one if |cipher| uses - * CHACHA20_POLY1305. */ -OPENSSL_EXPORT int SSL_CIPHER_is_CHACHA20POLY1305(const SSL_CIPHER *cipher); - -/* SSL_CIPHER_get_name returns the OpenSSL name of |cipher|. */ -OPENSSL_EXPORT const char *SSL_CIPHER_get_name(const SSL_CIPHER *cipher); - -/* SSL_CIPHER_get_kx_name returns a string that describes the key-exchange - * method used by |cipher|. For example, "ECDHE_ECDSA". */ -OPENSSL_EXPORT const char *SSL_CIPHER_get_kx_name(const SSL_CIPHER *cipher); - -/* SSL_CIPHER_get_rfc_name returns a newly-allocated string with the standard - * name for |cipher| or NULL on error. For example, - * "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256". The caller is responsible for - * calling |OPENSSL_free| on the result. */ -OPENSSL_EXPORT char *SSL_CIPHER_get_rfc_name(const SSL_CIPHER *cipher); - -/* SSL_CIPHER_get_bits returns the strength, in bits, of |cipher|. If - * |out_alg_bits| is not NULL, it writes the number of bits consumed by the - * symmetric algorithm to |*out_alg_bits|. */ -OPENSSL_EXPORT int SSL_CIPHER_get_bits(const SSL_CIPHER *cipher, - int *out_alg_bits); - - -/* SSL contexts. */ - -/* An SSL_METHOD selects whether to use TLS or DTLS. */ -typedef struct ssl_method_st SSL_METHOD; - -/* TLS_method is the |SSL_METHOD| used for TLS (and SSLv3) connections. */ -OPENSSL_EXPORT const SSL_METHOD *TLS_method(void); - -/* DTLS_method is the |SSL_METHOD| used for DTLS connections. */ -OPENSSL_EXPORT const SSL_METHOD *DTLS_method(void); - -/* SSL_CTX_new returns a newly-allocated |SSL_CTX| with default settings or NULL - * on error. An |SSL_CTX| manages shared state and configuration between - * multiple TLS or DTLS connections. */ -OPENSSL_EXPORT SSL_CTX *SSL_CTX_new(const SSL_METHOD *method); - -/* SSL_CTX_free releases memory associated with |ctx|. */ -OPENSSL_EXPORT void SSL_CTX_free(SSL_CTX *ctx); - - -/* SSL connections. */ - -/* SSL_new returns a newly-allocated |SSL| using |ctx| or NULL on error. An - * |SSL| object represents a single TLS or DTLS connection. It inherits settings - * from |ctx| at the time of creation. Settings may also be individually - * configured on the connection. - * - * On creation, an |SSL| is not configured to be either a client or server. Call - * |SSL_set_connect_state| or |SSL_set_accept_state| to set this. */ -OPENSSL_EXPORT SSL *SSL_new(SSL_CTX *ctx); - -/* SSL_free releases memory associated with |ssl|. */ -OPENSSL_EXPORT void SSL_free(SSL *ssl); - -/* SSL_set_connect_state configures |ssl| to be a client. */ -OPENSSL_EXPORT void SSL_set_connect_state(SSL *ssl); - -/* SSL_set_accept_state configures |ssl| to be a server. */ -OPENSSL_EXPORT void SSL_set_accept_state(SSL *ssl); - - -/* Protocol versions. */ - -#define SSL3_VERSION_MAJOR 0x03 - -#define SSL3_VERSION 0x0300 -#define TLS1_VERSION 0x0301 -#define TLS1_1_VERSION 0x0302 -#define TLS1_2_VERSION 0x0303 - -#define DTLS1_VERSION 0xfeff -#define DTLS1_2_VERSION 0xfefd - -/* SSL_CTX_set_min_version sets the minimum protocol version for |ctx| to - * |version|. */ -OPENSSL_EXPORT void SSL_CTX_set_min_version(SSL_CTX *ctx, uint16_t version); - -/* SSL_CTX_set_max_version sets the maximum protocol version for |ctx| to - * |version|. */ -OPENSSL_EXPORT void SSL_CTX_set_max_version(SSL_CTX *ctx, uint16_t version); - -/* SSL_set_min_version sets the minimum protocol version for |ssl| to - * |version|. */ -OPENSSL_EXPORT void SSL_set_min_version(SSL *ssl, uint16_t version); - -/* SSL_set_max_version sets the maximum protocol version for |ssl| to - * |version|. */ -OPENSSL_EXPORT void SSL_set_max_version(SSL *ssl, uint16_t version); - - -/* Options. - * - * Options configure protocol behavior. */ - -/* SSL_OP_LEGACY_SERVER_CONNECT allows initial connections to servers that don't - * support the renegotiation_info extension (RFC 5746). It is on by default. */ -#define SSL_OP_LEGACY_SERVER_CONNECT 0x00000004L - -/* SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER allows for record sizes |SSL3_RT_MAX_EXTRA| - * bytes above the maximum record size. */ -#define SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER 0x00000020L - -/* SSL_OP_TLS_D5_BUG accepts an RSAClientKeyExchange in TLS encoded as in SSL3 - * (i.e. without a length prefix). */ -#define SSL_OP_TLS_D5_BUG 0x00000100L - -/* SSL_OP_ALL enables the above bug workarounds that are enabled by many - * consumers. - * TODO(davidben): Determine which of the remaining may be removed now. */ -#define SSL_OP_ALL 0x00000BFFL - -/* SSL_OP_NO_QUERY_MTU, in DTLS, disables querying the MTU from the underlying - * |BIO|. Instead, the MTU is configured with |SSL_set_mtu|. */ -#define SSL_OP_NO_QUERY_MTU 0x00001000L - -/* SSL_OP_NO_TICKET disables session ticket support (RFC 4507). */ -#define SSL_OP_NO_TICKET 0x00004000L - -/* SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION permits unsafe legacy renegotiation - * without renegotiation_info (RFC 5746) support. */ -#define SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x00040000L - -/* SSL_OP_CIPHER_SERVER_PREFERENCE configures servers to select ciphers and - * ECDHE curves according to the server's preferences instead of the - * client's. */ -#define SSL_OP_CIPHER_SERVER_PREFERENCE 0x00400000L - -/* The following flags toggle individual protocol versions. This is deprecated. - * Use |SSL_CTX_set_min_version| and |SSL_CTX_set_max_version| instead. */ -#define SSL_OP_NO_SSLv3 0x02000000L -#define SSL_OP_NO_TLSv1 0x04000000L -#define SSL_OP_NO_TLSv1_2 0x08000000L -#define SSL_OP_NO_TLSv1_1 0x10000000L -#define SSL_OP_NO_DTLSv1 SSL_OP_NO_TLSv1 -#define SSL_OP_NO_DTLSv1_2 SSL_OP_NO_TLSv1_2 - -/* The following flags do nothing and are included only to make it easier to - * compile code with BoringSSL. */ -#define SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS 0 -#define SSL_OP_MICROSOFT_SESS_ID_BUG 0 -#define SSL_OP_NETSCAPE_CHALLENGE_BUG 0 -#define SSL_OP_NO_COMPRESSION 0 -#define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION 0 -#define SSL_OP_NO_SSLv2 0 -#define SSL_OP_SINGLE_DH_USE 0 -#define SSL_OP_SINGLE_ECDH_USE 0 -#define SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG 0 -#define SSL_OP_TLS_BLOCK_PADDING_BUG 0 -#define SSL_OP_TLS_ROLLBACK_BUG 0 - -/* SSL_CTX_set_options enables all options set in |options| (which should be one - * or more of the |SSL_OP_*| values, ORed together) in |ctx|. It returns a - * bitmask representing the resulting enabled options. */ -OPENSSL_EXPORT uint32_t SSL_CTX_set_options(SSL_CTX *ctx, uint32_t options); - -/* SSL_CTX_clear_options disables all options set in |options| (which should be - * one or more of the |SSL_OP_*| values, ORed together) in |ctx|. It returns a - * bitmask representing the resulting enabled options. */ -OPENSSL_EXPORT uint32_t SSL_CTX_clear_options(SSL_CTX *ctx, uint32_t options); - -/* SSL_CTX_get_options returns a bitmask of |SSL_OP_*| values that represent all - * the options enabled for |ctx|. */ -OPENSSL_EXPORT uint32_t SSL_CTX_get_options(const SSL_CTX *ctx); - -/* SSL_set_options enables all options set in |options| (which should be one or - * more of the |SSL_OP_*| values, ORed together) in |ssl|. It returns a bitmask - * representing the resulting enabled options. */ -OPENSSL_EXPORT uint32_t SSL_set_options(SSL *ssl, uint32_t options); - -/* SSL_clear_options disables all options set in |options| (which should be one - * or more of the |SSL_OP_*| values, ORed together) in |ssl|. It returns a - * bitmask representing the resulting enabled options. */ -OPENSSL_EXPORT uint32_t SSL_clear_options(SSL *ssl, uint32_t options); - -/* SSL_get_options returns a bitmask of |SSL_OP_*| values that represent all the - * options enabled for |ssl|. */ -OPENSSL_EXPORT uint32_t SSL_get_options(const SSL *ssl); - - -/* Modes. - * - * Modes configure API behavior. */ - -/* SSL_MODE_ENABLE_PARTIAL_WRITE allows |SSL_write| to complete with a partial - * result when the only part of the input was written in a single record. */ -#define SSL_MODE_ENABLE_PARTIAL_WRITE 0x00000001L - -/* SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER allows retrying an incomplete |SSL_write| - * with a different buffer. However, |SSL_write| still assumes the buffer - * contents are unchanged. This is not the default to avoid the misconception - * that non-blocking |SSL_write| behaves like non-blocking |write|. */ -#define SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER 0x00000002L - -/* SSL_MODE_NO_AUTO_CHAIN disables automatically building a certificate chain - * before sending certificates to the peer. - * TODO(davidben): Remove this behavior. https://crbug.com/486295. */ -#define SSL_MODE_NO_AUTO_CHAIN 0x00000008L - -/* SSL_MODE_ENABLE_FALSE_START allows clients to send application data before - * receipt of CCS and Finished. This mode enables full-handshakes to 'complete' - * in one RTT. See draft-bmoeller-tls-falsestart-01. */ -#define SSL_MODE_ENABLE_FALSE_START 0x00000080L - -/* Deprecated: SSL_MODE_HANDSHAKE_CUTTHROUGH is the same as - * SSL_MODE_ENABLE_FALSE_START. */ -#define SSL_MODE_HANDSHAKE_CUTTHROUGH SSL_MODE_ENABLE_FALSE_START - -/* SSL_MODE_CBC_RECORD_SPLITTING causes multi-byte CBC records in SSL 3.0 and - * TLS 1.0 to be split in two: the first record will contain a single byte and - * the second will contain the remainder. This effectively randomises the IV and - * prevents BEAST attacks. */ -#define SSL_MODE_CBC_RECORD_SPLITTING 0x00000100L - -/* SSL_MODE_NO_SESSION_CREATION will cause any attempts to create a session to - * fail with SSL_R_SESSION_MAY_NOT_BE_CREATED. This can be used to enforce that - * session resumption is used for a given SSL*. */ -#define SSL_MODE_NO_SESSION_CREATION 0x00000200L - -/* SSL_MODE_SEND_FALLBACK_SCSV sends TLS_FALLBACK_SCSV in the ClientHello. - * To be set only by applications that reconnect with a downgraded protocol - * version; see https://tools.ietf.org/html/draft-ietf-tls-downgrade-scsv-05 - * for details. - * - * DO NOT ENABLE THIS if your application attempts a normal handshake. Only use - * this in explicit fallback retries, following the guidance in - * draft-ietf-tls-downgrade-scsv-05. */ -#define SSL_MODE_SEND_FALLBACK_SCSV 0x00000400L - -/* The following flags do nothing and are included only to make it easier to - * compile code with BoringSSL. */ -#define SSL_MODE_AUTO_RETRY 0 -#define SSL_MODE_RELEASE_BUFFERS 0 -#define SSL_MODE_SEND_CLIENTHELLO_TIME 0 -#define SSL_MODE_SEND_SERVERHELLO_TIME 0 - -/* SSL_CTX_set_mode enables all modes set in |mode| (which should be one or more - * of the |SSL_MODE_*| values, ORed together) in |ctx|. It returns a bitmask - * representing the resulting enabled modes. */ -OPENSSL_EXPORT uint32_t SSL_CTX_set_mode(SSL_CTX *ctx, uint32_t mode); - -/* SSL_CTX_clear_mode disables all modes set in |mode| (which should be one or - * more of the |SSL_MODE_*| values, ORed together) in |ctx|. It returns a - * bitmask representing the resulting enabled modes. */ -OPENSSL_EXPORT uint32_t SSL_CTX_clear_mode(SSL_CTX *ctx, uint32_t mode); - -/* SSL_CTX_get_mode returns a bitmask of |SSL_MODE_*| values that represent all - * the modes enabled for |ssl|. */ -OPENSSL_EXPORT uint32_t SSL_CTX_get_mode(const SSL_CTX *ctx); - -/* SSL_set_mode enables all modes set in |mode| (which should be one or more of - * the |SSL_MODE_*| values, ORed together) in |ssl|. It returns a bitmask - * representing the resulting enabled modes. */ -OPENSSL_EXPORT uint32_t SSL_set_mode(SSL *ssl, uint32_t mode); - -/* SSL_clear_mode disables all modes set in |mode| (which should be one or more - * of the |SSL_MODE_*| values, ORed together) in |ssl|. It returns a bitmask - * representing the resulting enabled modes. */ -OPENSSL_EXPORT uint32_t SSL_clear_mode(SSL *ssl, uint32_t mode); - -/* SSL_get_mode returns a bitmask of |SSL_MODE_*| values that represent all the - * modes enabled for |ssl|. */ -OPENSSL_EXPORT uint32_t SSL_get_mode(const SSL *ssl); - - -/* Connection information. */ - -/* SSL_get_tls_unique writes at most |max_out| bytes of the tls-unique value - * for |ssl| to |out| and sets |*out_len| to the number of bytes written. It - * returns one on success or zero on error. In general |max_out| should be at - * least 12. - * - * This function will always fail if the initial handshake has not completed. - * The tls-unique value will change after a renegotiation but, since - * renegotiations can be initiated by the server at any point, the higher-level - * protocol must either leave them disabled or define states in which the - * tls-unique value can be read. - * - * The tls-unique value is defined by - * https://tools.ietf.org/html/rfc5929#section-3.1. Due to a weakness in the - * TLS protocol, tls-unique is broken for resumed connections unless the - * Extended Master Secret extension is negotiated. Thus this function will - * return zero if |ssl| performed session resumption unless EMS was used when - * negotiating the original session. */ -OPENSSL_EXPORT int SSL_get_tls_unique(const SSL *ssl, uint8_t *out, - size_t *out_len, size_t max_out); - - -/* Underdocumented functions. - * - * Functions below here haven't been touched up and may be underdocumented. */ - -/* SSLeay version number for ASN.1 encoding of the session information */ -/* Version 0 - initial version - * Version 1 - added the optional peer certificate. */ -#define SSL_SESSION_ASN1_VERSION 0x0001 - -#define SSL_MAX_SSL_SESSION_ID_LENGTH 32 -#define SSL_MAX_SID_CTX_LENGTH 32 -#define SSL_MAX_MASTER_KEY_LENGTH 48 - -/* These are used to specify which ciphers to use and not to use */ - -#define SSL_TXT_MEDIUM "MEDIUM" -#define SSL_TXT_HIGH "HIGH" -#define SSL_TXT_FIPS "FIPS" - -#define SSL_TXT_kRSA "kRSA" -#define SSL_TXT_kDHE "kDHE" -#define SSL_TXT_kEDH "kEDH" /* same as "kDHE" */ -#define SSL_TXT_kECDHE "kECDHE" -#define SSL_TXT_kEECDH "kEECDH" /* same as "kECDHE" */ -#define SSL_TXT_kPSK "kPSK" - -#define SSL_TXT_aRSA "aRSA" -#define SSL_TXT_aECDSA "aECDSA" -#define SSL_TXT_aPSK "aPSK" - -#define SSL_TXT_DH "DH" -#define SSL_TXT_DHE "DHE" /* same as "kDHE" */ -#define SSL_TXT_EDH "EDH" /* same as "DHE" */ -#define SSL_TXT_RSA "RSA" -#define SSL_TXT_ECDH "ECDH" -#define SSL_TXT_ECDHE "ECDHE" /* same as "kECDHE" */ -#define SSL_TXT_EECDH "EECDH" /* same as "ECDHE" */ -#define SSL_TXT_ECDSA "ECDSA" -#define SSL_TXT_PSK "PSK" - -#define SSL_TXT_3DES "3DES" -#define SSL_TXT_RC4 "RC4" -#define SSL_TXT_AES128 "AES128" -#define SSL_TXT_AES256 "AES256" -#define SSL_TXT_AES "AES" -#define SSL_TXT_AES_GCM "AESGCM" -#define SSL_TXT_CHACHA20 "CHACHA20" - -#define SSL_TXT_MD5 "MD5" -#define SSL_TXT_SHA1 "SHA1" -#define SSL_TXT_SHA "SHA" /* same as "SHA1" */ -#define SSL_TXT_SHA256 "SHA256" -#define SSL_TXT_SHA384 "SHA384" - -#define SSL_TXT_SSLV3 "SSLv3" -#define SSL_TXT_TLSV1 "TLSv1" -#define SSL_TXT_TLSV1_1 "TLSv1.1" -#define SSL_TXT_TLSV1_2 "TLSv1.2" - -#define SSL_TXT_ALL "ALL" - -/* COMPLEMENTOF* definitions. These identifiers are used to (de-select) ciphers - * normally not being used. - * - * Example: "RC4" will activate all ciphers using RC4 including ciphers without - * authentication, which would normally disabled by DEFAULT (due the "!ADH" - * being part of default). Therefore "RC4:!COMPLEMENTOFDEFAULT" will make sure - * that it is also disabled in the specific selection. COMPLEMENTOF* - * identifiers are portable between version, as adjustments to the default - * cipher setup will also be included here. - * - * COMPLEMENTOFDEFAULT does not experience the same special treatment that - * DEFAULT gets, as only selection is being done and no sorting as needed for - * DEFAULT. */ -#define SSL_TXT_CMPDEF "COMPLEMENTOFDEFAULT" - -/* The following cipher list is used by default. It also is substituted when an - * application-defined cipher list string starts with 'DEFAULT'. */ -#define SSL_DEFAULT_CIPHER_LIST "ALL" - -/* As of OpenSSL 1.0.0, ssl_create_cipher_list() in ssl/ssl_ciph.c always - * starts with a reasonable order, and all we have to do for DEFAULT is - * throwing out anonymous and unencrypted ciphersuites! (The latter are not - * actually enabled by ALL, but "ALL:RSA" would enable some of them.) */ - -/* Used in SSL_set_shutdown()/SSL_get_shutdown(); */ -#define SSL_SENT_SHUTDOWN 1 -#define SSL_RECEIVED_SHUTDOWN 2 - -#define SSL_FILETYPE_ASN1 X509_FILETYPE_ASN1 -#define SSL_FILETYPE_PEM X509_FILETYPE_PEM - -typedef struct ssl_protocol_method_st SSL_PROTOCOL_METHOD; -typedef struct ssl_session_st SSL_SESSION; -typedef struct tls_sigalgs_st TLS_SIGALGS; -typedef struct ssl_conf_ctx_st SSL_CONF_CTX; -typedef struct ssl3_enc_method SSL3_ENC_METHOD; - -/* SRTP protection profiles for use with the use_srtp extension (RFC 5764). */ -typedef struct srtp_protection_profile_st { - const char *name; - unsigned long id; -} SRTP_PROTECTION_PROFILE; - -DECLARE_STACK_OF(SRTP_PROTECTION_PROFILE) - -/* An SSL_SESSION represents an SSL session that may be resumed in an - * abbreviated handshake. */ -struct ssl_session_st { - int ssl_version; /* what ssl version session info is being kept in here? */ - - int master_key_length; - uint8_t master_key[SSL_MAX_MASTER_KEY_LENGTH]; - /* session_id - valid? */ - unsigned int session_id_length; - uint8_t session_id[SSL_MAX_SSL_SESSION_ID_LENGTH]; - /* this is used to determine whether the session is being reused in - * the appropriate context. It is up to the application to set this, - * via SSL_new */ - unsigned int sid_ctx_length; - uint8_t sid_ctx[SSL_MAX_SID_CTX_LENGTH]; - - char *psk_identity; - /* Used to indicate that session resumption is not allowed. Applications can - * also set this bit for a new session via not_resumable_session_cb to - * disable session caching and tickets. */ - int not_resumable; - - /* The cert is the certificate used to establish this connection */ - struct sess_cert_st /* SESS_CERT */ *sess_cert; - - /* This is the cert for the other end. On clients, it will be the same as - * sess_cert->peer_key->x509 (the latter is not enough as sess_cert is not - * retained in the external representation of sessions, see ssl_asn1.c). */ - X509 *peer; - /* when app_verify_callback accepts a session where the peer's certificate is - * not ok, we must remember the error for session reuse: */ - long verify_result; /* only for servers */ - - CRYPTO_refcount_t references; - long timeout; - long time; - - const SSL_CIPHER *cipher; - - CRYPTO_EX_DATA ex_data; /* application specific data */ - - /* These are used to make removal of session-ids more efficient and to - * implement a maximum cache size. */ - SSL_SESSION *prev, *next; - char *tlsext_hostname; - /* RFC4507 info */ - uint8_t *tlsext_tick; /* Session ticket */ - size_t tlsext_ticklen; /* Session ticket length */ - uint32_t tlsext_tick_lifetime_hint; /* Session lifetime hint in seconds */ - - size_t tlsext_signed_cert_timestamp_list_length; - uint8_t *tlsext_signed_cert_timestamp_list; /* Server's list. */ - - /* The OCSP response that came with the session. */ - size_t ocsp_response_length; - uint8_t *ocsp_response; - - char peer_sha256_valid; /* Non-zero if peer_sha256 is valid */ - uint8_t - peer_sha256[SHA256_DIGEST_LENGTH]; /* SHA256 of peer certificate */ - - /* original_handshake_hash contains the handshake hash (either SHA-1+MD5 or - * SHA-2, depending on TLS version) for the original, full handshake that - * created a session. This is used by Channel IDs during resumption. */ - uint8_t original_handshake_hash[EVP_MAX_MD_SIZE]; - unsigned int original_handshake_hash_len; - - /* extended_master_secret is true if the master secret in this session was - * generated using EMS and thus isn't vulnerable to the Triple Handshake - * attack. */ - char extended_master_secret; -}; - - -/* Cert related flags */ -/* Many implementations ignore some aspects of the TLS standards such as - * enforcing certifcate chain algorithms. When this is set we enforce them. */ -#define SSL_CERT_FLAG_TLS_STRICT 0x00000001L - -/* Flags for building certificate chains */ -/* Treat any existing certificates as untrusted CAs */ -#define SSL_BUILD_CHAIN_FLAG_UNTRUSTED 0x1 -/* Don't include root CA in chain */ -#define SSL_BUILD_CHAIN_FLAG_NO_ROOT 0x2 -/* Just check certificates already there */ -#define SSL_BUILD_CHAIN_FLAG_CHECK 0x4 -/* Ignore verification errors */ -#define SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR 0x8 -/* Clear verification errors from queue */ -#define SSL_BUILD_CHAIN_FLAG_CLEAR_ERROR 0x10 - -/* SSL_set_mtu sets the |ssl|'s MTU in DTLS to |mtu|. It returns one on success - * and zero on failure. */ -OPENSSL_EXPORT int SSL_set_mtu(SSL *ssl, unsigned mtu); - -/* SSL_get_secure_renegotiation_support returns one if the peer supports secure - * renegotiation (RFC 5746) and zero otherwise. */ -OPENSSL_EXPORT int SSL_get_secure_renegotiation_support(const SSL *ssl); - -/* SSL_CTX_set_msg_callback installs |cb| as the message callback for |ctx|. - * This callback will be called when sending or receiving low-level record - * headers, complete handshake messages, ChangeCipherSpec, and alerts. - * |write_p| is one for outgoing messages and zero for incoming messages. - * - * For each record header, |cb| is called with |version| = 0 and |content_type| - * = |SSL3_RT_HEADER|. The |len| bytes from |buf| contain the header. Note that - * this does not include the record body. If the record is sealed, the length - * in the header is the length of the ciphertext. - * - * For each handshake message, ChangeCipherSpec, and alert, |version| is the - * protocol version and |content_type| is the corresponding record type. The - * |len| bytes from |buf| contain the handshake message, one-byte - * ChangeCipherSpec body, and two-byte alert, respectively. */ -OPENSSL_EXPORT void SSL_CTX_set_msg_callback( - SSL_CTX *ctx, void (*cb)(int write_p, int version, int content_type, - const void *buf, size_t len, SSL *ssl, void *arg)); - -/* SSL_CTX_set_msg_callback_arg sets the |arg| parameter of the message - * callback. */ -OPENSSL_EXPORT void SSL_CTX_set_msg_callback_arg(SSL_CTX *ctx, void *arg); - -/* SSL_set_msg_callback installs |cb| as the message callback of |ssl|. See - * |SSL_CTX_set_msg_callback| for when this callback is called. */ -OPENSSL_EXPORT void SSL_set_msg_callback( - SSL *ssl, void (*cb)(int write_p, int version, int content_type, - const void *buf, size_t len, SSL *ssl, void *arg)); - -/* SSL_set_msg_callback_arg sets the |arg| parameter of the message callback. */ -OPENSSL_EXPORT void SSL_set_msg_callback_arg(SSL *ssl, void *arg); - -/* SSL_CTX_set_keylog_bio sets configures all SSL objects attached to |ctx| to - * log session material to |keylog_bio|. This is intended for debugging use - * with tools like Wireshark. |ctx| takes ownership of |keylog_bio|. - * - * The format is described in - * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format. */ -OPENSSL_EXPORT void SSL_CTX_set_keylog_bio(SSL_CTX *ctx, BIO *keylog_bio); - - -struct ssl_aead_ctx_st; -typedef struct ssl_aead_ctx_st SSL_AEAD_CTX; - -#define SSL_MAX_CERT_LIST_DEFAULT 1024 * 100 /* 100k max cert list */ - -#define SSL_SESSION_CACHE_MAX_SIZE_DEFAULT (1024 * 20) - -#define SSL_DEFAULT_SESSION_TIMEOUT (2 * 60 * 60) - -/* This callback type is used inside SSL_CTX, SSL, and in the functions that - * set them. It is used to override the generation of SSL/TLS session IDs in a - * server. Return value should be zero on an error, non-zero to proceed. Also, - * callbacks should themselves check if the id they generate is unique - * otherwise the SSL handshake will fail with an error - callbacks can do this - * using the 'ssl' value they're passed by; - * SSL_has_matching_session_id(ssl, id, *id_len) - * The length value passed in is set at the maximum size the session ID can be. - * In SSLv2 this is 16 bytes, whereas SSLv3/TLSv1 it is 32 bytes. The callback - * can alter this length to be less if desired, but under SSLv2 session IDs are - * supposed to be fixed at 16 bytes so the id will be padded after the callback - * returns in this case. It is also an error for the callback to set the size - * to zero. */ -typedef int (*GEN_SESSION_CB)(const SSL *ssl, uint8_t *id, - unsigned int *id_len); - -/* ssl_early_callback_ctx is passed to certain callbacks that are called very - * early on during the server handshake. At this point, much of the SSL* hasn't - * been filled out and only the ClientHello can be depended on. */ -struct ssl_early_callback_ctx { - SSL *ssl; - const uint8_t *client_hello; - size_t client_hello_len; - const uint8_t *session_id; - size_t session_id_len; - const uint8_t *cipher_suites; - size_t cipher_suites_len; - const uint8_t *compression_methods; - size_t compression_methods_len; - const uint8_t *extensions; - size_t extensions_len; -}; - -/* SSL_early_callback_ctx_extension_get searches the extensions in |ctx| for an - * extension of the given type. If not found, it returns zero. Otherwise it - * sets |out_data| to point to the extension contents (not including the type - * and length bytes), sets |out_len| to the length of the extension contents - * and returns one. */ -OPENSSL_EXPORT char SSL_early_callback_ctx_extension_get( - const struct ssl_early_callback_ctx *ctx, uint16_t extension_type, - const uint8_t **out_data, size_t *out_len); - -typedef struct ssl_comp_st SSL_COMP; - -struct ssl_comp_st { - int id; - const char *name; - char *method; -}; - -DECLARE_STACK_OF(SSL_COMP) -DECLARE_LHASH_OF(SSL_SESSION) - -/* ssl_cipher_preference_list_st contains a list of SSL_CIPHERs with - * equal-preference groups. For TLS clients, the groups are moot because the - * server picks the cipher and groups cannot be expressed on the wire. However, - * for servers, the equal-preference groups allow the client's preferences to - * be partially respected. (This only has an effect with - * SSL_OP_CIPHER_SERVER_PREFERENCE). - * - * The equal-preference groups are expressed by grouping SSL_CIPHERs together. - * All elements of a group have the same priority: no ordering is expressed - * within a group. - * - * The values in |ciphers| are in one-to-one correspondence with - * |in_group_flags|. (That is, sk_SSL_CIPHER_num(ciphers) is the number of - * bytes in |in_group_flags|.) The bytes in |in_group_flags| are either 1, to - * indicate that the corresponding SSL_CIPHER is not the last element of a - * group, or 0 to indicate that it is. - * - * For example, if |in_group_flags| contains all zeros then that indicates a - * traditional, fully-ordered preference. Every SSL_CIPHER is the last element - * of the group (i.e. they are all in a one-element group). - * - * For a more complex example, consider: - * ciphers: A B C D E F - * in_group_flags: 1 1 0 0 1 0 - * - * That would express the following, order: - * - * A E - * B -> D -> F - * C - */ -struct ssl_cipher_preference_list_st { - STACK_OF(SSL_CIPHER) *ciphers; - uint8_t *in_group_flags; -}; - -struct ssl_ctx_st { - const SSL_PROTOCOL_METHOD *method; - - /* lock is used to protect various operations on this object. */ - CRYPTO_MUTEX lock; - - /* max_version is the maximum acceptable protocol version. If zero, the - * maximum supported version, currently (D)TLS 1.2, is used. */ - uint16_t max_version; - - /* min_version is the minimum acceptable protocl version. If zero, the - * minimum supported version, currently SSL 3.0 and DTLS 1.0, is used */ - uint16_t min_version; - - struct ssl_cipher_preference_list_st *cipher_list; - /* same as above but sorted for lookup */ - STACK_OF(SSL_CIPHER) *cipher_list_by_id; - /* cipher_list_tls11 is the list of ciphers when TLS 1.1 or greater is in - * use. This only applies to server connections as, for clients, the version - * number is known at connect time and so the cipher list can be set then. */ - struct ssl_cipher_preference_list_st *cipher_list_tls11; - - X509_STORE *cert_store; - LHASH_OF(SSL_SESSION) *sessions; - /* Most session-ids that will be cached, default is - * SSL_SESSION_CACHE_MAX_SIZE_DEFAULT. 0 is unlimited. */ - unsigned long session_cache_size; - SSL_SESSION *session_cache_head; - SSL_SESSION *session_cache_tail; - - /* handshakes_since_cache_flush is the number of successful handshakes since - * the last cache flush. */ - int handshakes_since_cache_flush; - - /* This can have one of 2 values, ored together, - * SSL_SESS_CACHE_CLIENT, - * SSL_SESS_CACHE_SERVER, - * Default is SSL_SESSION_CACHE_SERVER, which means only - * SSL_accept which cache SSL_SESSIONS. */ - int session_cache_mode; - - /* If timeout is not 0, it is the default timeout value set when SSL_new() is - * called. This has been put in to make life easier to set things up */ - long session_timeout; - - /* If this callback is not null, it will be called each time a session id is - * added to the cache. If this function returns 1, it means that the - * callback will do a SSL_SESSION_free() when it has finished using it. - * Otherwise, on 0, it means the callback has finished with it. If - * remove_session_cb is not null, it will be called when a session-id is - * removed from the cache. After the call, OpenSSL will SSL_SESSION_free() - * it. */ - int (*new_session_cb)(SSL *ssl, SSL_SESSION *sess); - void (*remove_session_cb)(SSL_CTX *ctx, SSL_SESSION *sess); - SSL_SESSION *(*get_session_cb)(SSL *ssl, uint8_t *data, int len, - int *copy); - - CRYPTO_refcount_t references; - - /* if defined, these override the X509_verify_cert() calls */ - int (*app_verify_callback)(X509_STORE_CTX *, void *); - void *app_verify_arg; - /* before OpenSSL 0.9.7, 'app_verify_arg' was ignored ('app_verify_callback' - * was called with just one argument) */ - - /* Default password callback. */ - pem_password_cb *default_passwd_callback; - - /* Default password callback user data. */ - void *default_passwd_callback_userdata; - - /* get client cert callback */ - int (*client_cert_cb)(SSL *ssl, X509 **x509, EVP_PKEY **pkey); - - /* get channel id callback */ - void (*channel_id_cb)(SSL *ssl, EVP_PKEY **pkey); - - CRYPTO_EX_DATA ex_data; - - STACK_OF(X509) *extra_certs; - - - /* Default values used when no per-SSL value is defined follow */ - - void (*info_callback)(const SSL *ssl, int type, - int val); /* used if SSL's info_callback is NULL */ - - /* what we put in client cert requests */ - STACK_OF(X509_NAME) *client_CA; - - - /* Default values to use in SSL structures follow (these are copied by - * SSL_new) */ - - uint32_t options; - uint32_t mode; - uint32_t max_cert_list; - - struct cert_st /* CERT */ *cert; - - /* callback that allows applications to peek at protocol messages */ - void (*msg_callback)(int write_p, int version, int content_type, - const void *buf, size_t len, SSL *ssl, void *arg); - void *msg_callback_arg; - - int verify_mode; - unsigned int sid_ctx_length; - uint8_t sid_ctx[SSL_MAX_SID_CTX_LENGTH]; - int (*default_verify_callback)( - int ok, X509_STORE_CTX *ctx); /* called 'verify_callback' in the SSL */ - - /* Default generate session ID callback. */ - GEN_SESSION_CB generate_session_id; - - X509_VERIFY_PARAM *param; - - /* select_certificate_cb is called before most ClientHello processing and - * before the decision whether to resume a session is made. It may return one - * to continue the handshake or zero to cause the handshake loop to return - * with an error and cause SSL_get_error to return - * SSL_ERROR_PENDING_CERTIFICATE. Note: when the handshake loop is resumed, it - * will not call the callback a second time. */ - int (*select_certificate_cb)(const struct ssl_early_callback_ctx *); - - /* dos_protection_cb is called once the resumption decision for a ClientHello - * has been made. It returns one to continue the handshake or zero to - * abort. */ - int (*dos_protection_cb) (const struct ssl_early_callback_ctx *); - - /* quiet_shutdown is true if the connection should not send a close_notify on - * shutdown. */ - int quiet_shutdown; - - /* Maximum amount of data to send in one fragment. actual record size can be - * more than this due to padding and MAC overheads. */ - uint16_t max_send_fragment; - - /* TLS extensions servername callback */ - int (*tlsext_servername_callback)(SSL *, int *, void *); - void *tlsext_servername_arg; - /* RFC 4507 session ticket keys */ - uint8_t tlsext_tick_key_name[16]; - uint8_t tlsext_tick_hmac_key[16]; - uint8_t tlsext_tick_aes_key[16]; - /* Callback to support customisation of ticket key setting */ - int (*tlsext_ticket_key_cb)(SSL *ssl, uint8_t *name, uint8_t *iv, - EVP_CIPHER_CTX *ectx, HMAC_CTX *hctx, int enc); - - /* Server-only: psk_identity_hint is the default identity hint to send in - * PSK-based key exchanges. */ - char *psk_identity_hint; - - unsigned int (*psk_client_callback)(SSL *ssl, const char *hint, - char *identity, - unsigned int max_identity_len, - uint8_t *psk, unsigned int max_psk_len); - unsigned int (*psk_server_callback)(SSL *ssl, const char *identity, - uint8_t *psk, unsigned int max_psk_len); - - - /* retain_only_sha256_of_client_certs is true if we should compute the SHA256 - * hash of the peer's certifiate and then discard it to save memory and - * session space. Only effective on the server side. */ - char retain_only_sha256_of_client_certs; - - /* Next protocol negotiation information */ - /* (for experimental NPN extension). */ - - /* For a server, this contains a callback function by which the set of - * advertised protocols can be provided. */ - int (*next_protos_advertised_cb)(SSL *s, const uint8_t **buf, - unsigned int *len, void *arg); - void *next_protos_advertised_cb_arg; - /* For a client, this contains a callback function that selects the - * next protocol from the list provided by the server. */ - int (*next_proto_select_cb)(SSL *s, uint8_t **out, uint8_t *outlen, - const uint8_t *in, unsigned int inlen, void *arg); - void *next_proto_select_cb_arg; - - /* ALPN information - * (we are in the process of transitioning from NPN to ALPN.) */ - - /* For a server, this contains a callback function that allows the - * server to select the protocol for the connection. - * out: on successful return, this must point to the raw protocol - * name (without the length prefix). - * outlen: on successful return, this contains the length of |*out|. - * in: points to the client's list of supported protocols in - * wire-format. - * inlen: the length of |in|. */ - int (*alpn_select_cb)(SSL *s, const uint8_t **out, uint8_t *outlen, - const uint8_t *in, unsigned int inlen, void *arg); - void *alpn_select_cb_arg; - - /* For a client, this contains the list of supported protocols in wire - * format. */ - uint8_t *alpn_client_proto_list; - unsigned alpn_client_proto_list_len; - - /* SRTP profiles we are willing to do from RFC 5764 */ - STACK_OF(SRTP_PROTECTION_PROFILE) *srtp_profiles; - - /* EC extension values inherited by SSL structure */ - size_t tlsext_ecpointformatlist_length; - uint8_t *tlsext_ecpointformatlist; - size_t tlsext_ellipticcurvelist_length; - uint16_t *tlsext_ellipticcurvelist; - - /* If true, a client will advertise the Channel ID extension and a server - * will echo it. */ - char tlsext_channel_id_enabled; - /* tlsext_channel_id_enabled_new is a hack to support both old and new - * ChannelID signatures. It indicates that a client should advertise the new - * ChannelID extension number. */ - char tlsext_channel_id_enabled_new; - /* The client's Channel ID private key. */ - EVP_PKEY *tlsext_channel_id_private; - - /* If true, a client will request certificate timestamps. */ - char signed_cert_timestamps_enabled; - - /* If true, a client will request a stapled OCSP response. */ - char ocsp_stapling_enabled; - - /* If not NULL, session key material will be logged to this BIO for debugging - * purposes. The format matches NSS's and is readable by Wireshark. */ - BIO *keylog_bio; - - /* current_time_cb, if not NULL, is the function to use to get the current - * time. It sets |*out_clock| to the current time. */ - void (*current_time_cb)(const SSL *ssl, struct timeval *out_clock); -}; - -OPENSSL_EXPORT LHASH_OF(SSL_SESSION) *SSL_CTX_sessions(SSL_CTX *ctx); - -/* SSL_CTX_sess_number returns the number of sessions in |ctx|'s internal - * session cache. */ -OPENSSL_EXPORT size_t SSL_CTX_sess_number(const SSL_CTX *ctx); - -OPENSSL_EXPORT void SSL_CTX_sess_set_new_cb( - SSL_CTX *ctx, int (*new_session_cb)(SSL *ssl, SSL_SESSION *sess)); -OPENSSL_EXPORT int (*SSL_CTX_sess_get_new_cb(SSL_CTX *ctx))(SSL *ssl, - SSL_SESSION *sess); -OPENSSL_EXPORT void SSL_CTX_sess_set_remove_cb( - SSL_CTX *ctx, - void (*remove_session_cb)(SSL_CTX *ctx, SSL_SESSION *sess)); -OPENSSL_EXPORT void (*SSL_CTX_sess_get_remove_cb(SSL_CTX *ctx))( - SSL_CTX *ctx, SSL_SESSION *sess); -OPENSSL_EXPORT void SSL_CTX_sess_set_get_cb( - SSL_CTX *ctx, - SSL_SESSION *(*get_session_cb)(SSL *ssl, uint8_t *data, int len, - int *copy)); -OPENSSL_EXPORT SSL_SESSION *(*SSL_CTX_sess_get_get_cb(SSL_CTX *ctx))( - SSL *ssl, uint8_t *data, int len, int *copy); -/* SSL_magic_pending_session_ptr returns a magic SSL_SESSION* which indicates - * that the session isn't currently unavailable. SSL_get_error will then return - * SSL_ERROR_PENDING_SESSION and the handshake can be retried later when the - * lookup has completed. */ -OPENSSL_EXPORT SSL_SESSION *SSL_magic_pending_session_ptr(void); -OPENSSL_EXPORT void SSL_CTX_set_info_callback(SSL_CTX *ctx, - void (*cb)(const SSL *ssl, - int type, int val)); -OPENSSL_EXPORT void (*SSL_CTX_get_info_callback(SSL_CTX *ctx))(const SSL *ssl, - int type, - int val); -OPENSSL_EXPORT void SSL_CTX_set_client_cert_cb( - SSL_CTX *ctx, - int (*client_cert_cb)(SSL *ssl, X509 **x509, EVP_PKEY **pkey)); -OPENSSL_EXPORT int (*SSL_CTX_get_client_cert_cb(SSL_CTX *ctx))(SSL *ssl, - X509 **x509, - EVP_PKEY **pkey); -OPENSSL_EXPORT void SSL_CTX_set_channel_id_cb( - SSL_CTX *ctx, void (*channel_id_cb)(SSL *ssl, EVP_PKEY **pkey)); -OPENSSL_EXPORT void (*SSL_CTX_get_channel_id_cb(SSL_CTX *ctx))(SSL *ssl, - EVP_PKEY **pkey); - -/* SSL_enable_signed_cert_timestamps causes |ssl| (which must be the client end - * of a connection) to request SCTs from the server. See - * https://tools.ietf.org/html/rfc6962. It returns one. */ -OPENSSL_EXPORT int SSL_enable_signed_cert_timestamps(SSL *ssl); - -/* SSL_CTX_enable_signed_cert_timestamps enables SCT requests on all client SSL - * objects created from |ctx|. */ -OPENSSL_EXPORT void SSL_CTX_enable_signed_cert_timestamps(SSL_CTX *ctx); - -/* SSL_enable_ocsp_stapling causes |ssl| (which must be the client end of a - * connection) to request a stapled OCSP response from the server. It returns - * one. */ -OPENSSL_EXPORT int SSL_enable_ocsp_stapling(SSL *ssl); - -/* SSL_CTX_enable_ocsp_stapling enables OCSP stapling on all client SSL objects - * created from |ctx|. */ -OPENSSL_EXPORT void SSL_CTX_enable_ocsp_stapling(SSL_CTX *ctx); - -/* SSL_get0_signed_cert_timestamp_list sets |*out| and |*out_len| to point to - * |*out_len| bytes of SCT information from the server. This is only valid if - * |ssl| is a client. The SCT information is a SignedCertificateTimestampList - * (including the two leading length bytes). - * See https://tools.ietf.org/html/rfc6962#section-3.3 - * If no SCT was received then |*out_len| will be zero on return. - * - * WARNING: the returned data is not guaranteed to be well formed. */ -OPENSSL_EXPORT void SSL_get0_signed_cert_timestamp_list(const SSL *ssl, - const uint8_t **out, - size_t *out_len); - -/* SSL_get0_ocsp_response sets |*out| and |*out_len| to point to |*out_len| - * bytes of an OCSP response from the server. This is the DER encoding of an - * OCSPResponse type as defined in RFC 2560. - * - * WARNING: the returned data is not guaranteed to be well formed. */ -OPENSSL_EXPORT void SSL_get0_ocsp_response(const SSL *ssl, const uint8_t **out, - size_t *out_len); - -OPENSSL_EXPORT void SSL_CTX_set_next_protos_advertised_cb( - SSL_CTX *s, - int (*cb)(SSL *ssl, const uint8_t **out, unsigned int *outlen, void *arg), - void *arg); -OPENSSL_EXPORT void SSL_CTX_set_next_proto_select_cb( - SSL_CTX *s, int (*cb)(SSL *ssl, uint8_t **out, uint8_t *outlen, - const uint8_t *in, unsigned int inlen, void *arg), - void *arg); -OPENSSL_EXPORT void SSL_get0_next_proto_negotiated(const SSL *s, - const uint8_t **data, - unsigned *len); - -OPENSSL_EXPORT int SSL_select_next_proto(uint8_t **out, uint8_t *outlen, - const uint8_t *in, unsigned int inlen, - const uint8_t *client, - unsigned int client_len); - -#define OPENSSL_NPN_UNSUPPORTED 0 -#define OPENSSL_NPN_NEGOTIATED 1 -#define OPENSSL_NPN_NO_OVERLAP 2 - -/* SSL_CTX_set_alpn_protos sets the ALPN protocol list on |ctx| to |protos|. - * |protos| must be in wire-format (i.e. a series of non-empty, 8-bit - * length-prefixed strings). It returns zero on success and one on failure. - * - * WARNING: this function is dangerous because it breaks the usual return value - * convention. */ -OPENSSL_EXPORT int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const uint8_t *protos, - unsigned protos_len); - -/* SSL_set_alpn_protos sets the ALPN protocol list on |ssl| to |protos|. - * |protos| must be in wire-format (i.e. a series of non-empty, 8-bit - * length-prefixed strings). It returns zero on success and one on failure. - * - * WARNING: this function is dangerous because it breaks the usual return value - * convention. */ -OPENSSL_EXPORT int SSL_set_alpn_protos(SSL *ssl, const uint8_t *protos, - unsigned protos_len); - -OPENSSL_EXPORT void SSL_CTX_set_alpn_select_cb( - SSL_CTX *ctx, int (*cb)(SSL *ssl, const uint8_t **out, uint8_t *outlen, - const uint8_t *in, unsigned int inlen, void *arg), - void *arg); -OPENSSL_EXPORT void SSL_get0_alpn_selected(const SSL *ssl, const uint8_t **data, - unsigned *len); - -/* SSL_enable_fastradio_padding controls whether fastradio padding is enabled - * on |ssl|. If it is, ClientHello messages are padded to 1024 bytes. This - * causes 3G radios to switch to DCH mode (high data rate). */ -OPENSSL_EXPORT void SSL_enable_fastradio_padding(SSL *ssl, char on_off); - -/* SSL_set_reject_peer_renegotiations controls whether renegotiation attempts by - * the peer are rejected. It may be set at any point in a connection's lifetime - * to control future renegotiations programmatically. By default, renegotiations - * are rejected. (Renegotiations requested by a client are always rejected.) */ -OPENSSL_EXPORT void SSL_set_reject_peer_renegotiations(SSL *ssl, int reject); - -/* the maximum length of the buffer given to callbacks containing the resulting - * identity/psk */ -#define PSK_MAX_IDENTITY_LEN 128 -#define PSK_MAX_PSK_LEN 256 -OPENSSL_EXPORT void SSL_CTX_set_psk_client_callback( - SSL_CTX *ctx, - unsigned int (*psk_client_callback)( - SSL *ssl, const char *hint, char *identity, - unsigned int max_identity_len, uint8_t *psk, unsigned int max_psk_len)); -OPENSSL_EXPORT void SSL_set_psk_client_callback( - SSL *ssl, unsigned int (*psk_client_callback)(SSL *ssl, const char *hint, - char *identity, - unsigned int max_identity_len, - uint8_t *psk, - unsigned int max_psk_len)); -OPENSSL_EXPORT void SSL_CTX_set_psk_server_callback( - SSL_CTX *ctx, - unsigned int (*psk_server_callback)(SSL *ssl, const char *identity, - uint8_t *psk, - unsigned int max_psk_len)); -OPENSSL_EXPORT void SSL_set_psk_server_callback( - SSL *ssl, - unsigned int (*psk_server_callback)(SSL *ssl, const char *identity, - uint8_t *psk, - unsigned int max_psk_len)); -OPENSSL_EXPORT int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, - const char *identity_hint); -OPENSSL_EXPORT int SSL_use_psk_identity_hint(SSL *s, const char *identity_hint); -OPENSSL_EXPORT const char *SSL_get_psk_identity_hint(const SSL *s); -OPENSSL_EXPORT const char *SSL_get_psk_identity(const SSL *s); - -#define SSL_NOTHING 1 -#define SSL_WRITING 2 -#define SSL_READING 3 -#define SSL_X509_LOOKUP 4 -#define SSL_CHANNEL_ID_LOOKUP 5 -#define SSL_PENDING_SESSION 7 -#define SSL_CERTIFICATE_SELECTION_PENDING 8 - -/* These will only be used when doing non-blocking IO */ -#define SSL_want_nothing(s) (SSL_want(s) == SSL_NOTHING) -#define SSL_want_read(s) (SSL_want(s) == SSL_READING) -#define SSL_want_write(s) (SSL_want(s) == SSL_WRITING) -#define SSL_want_x509_lookup(s) (SSL_want(s) == SSL_X509_LOOKUP) -#define SSL_want_channel_id_lookup(s) (SSL_want(s) == SSL_CHANNEL_ID_LOOKUP) -#define SSL_want_session(s) (SSL_want(s) == SSL_PENDING_SESSION) -#define SSL_want_certificate(s) \ - (SSL_want(s) == SSL_CERTIFICATE_SELECTION_PENDING) - -struct ssl_st { - /* version is the protocol version. */ - int version; - - /* method is the method table corresponding to the current protocol (DTLS or - * TLS). */ - const SSL_PROTOCOL_METHOD *method; - - /* enc_method is the method table corresponding to the current protocol - * version. */ - const SSL3_ENC_METHOD *enc_method; - - /* max_version is the maximum acceptable protocol version. If zero, the - * maximum supported version, currently (D)TLS 1.2, is used. */ - uint16_t max_version; - - /* min_version is the minimum acceptable protocl version. If zero, the - * minimum supported version, currently SSL 3.0 and DTLS 1.0, is used */ - uint16_t min_version; - - /* There are 2 BIO's even though they are normally both the same. This is so - * data can be read and written to different handlers */ - - BIO *rbio; /* used by SSL_read */ - BIO *wbio; /* used by SSL_write */ - BIO *bbio; /* used during session-id reuse to concatenate - * messages */ - - /* This holds a variable that indicates what we were doing when a 0 or -1 is - * returned. This is needed for non-blocking IO so we know what request - * needs re-doing when in SSL_accept or SSL_connect */ - int rwstate; - - /* true when we are actually in SSL_accept() or SSL_connect() */ - int in_handshake; - int (*handshake_func)(SSL *); - - /* Imagine that here's a boolean member "init" that is switched as soon as - * SSL_set_{accept/connect}_state is called for the first time, so that - * "state" and "handshake_func" are properly initialized. But as - * handshake_func is == 0 until then, we use this test instead of an "init" - * member. */ - - /* server is true iff the this SSL* is the server half. Note: before the SSL* - * is initialized by either SSL_set_accept_state or SSL_set_connect_state, - * the side is not determined. In this state, server is always false. */ - int server; - - /* quiet_shutdown is true if the connection should not send a close_notify on - * shutdown. */ - int quiet_shutdown; - - int shutdown; /* we have shut things down, 0x01 sent, 0x02 - * for received */ - int state; /* where we are */ - int rstate; /* where we are when reading */ - - BUF_MEM *init_buf; /* buffer used during init */ - uint8_t *init_msg; /* pointer to handshake message body, set by - ssl3_get_message() */ - int init_num; /* amount read/written */ - int init_off; /* amount read/written */ - - /* used internally to point at a raw packet */ - uint8_t *packet; - unsigned int packet_length; - - struct ssl3_state_st *s3; /* SSLv3 variables */ - struct dtls1_state_st *d1; /* DTLSv1 variables */ - - /* callback that allows applications to peek at protocol messages */ - void (*msg_callback)(int write_p, int version, int content_type, - const void *buf, size_t len, SSL *ssl, void *arg); - void *msg_callback_arg; - - int hit; /* reusing a previous session */ - - X509_VERIFY_PARAM *param; - - /* crypto */ - struct ssl_cipher_preference_list_st *cipher_list; - STACK_OF(SSL_CIPHER) *cipher_list_by_id; - - SSL_AEAD_CTX *aead_read_ctx; - SSL_AEAD_CTX *aead_write_ctx; - - /* session info */ - - /* client cert? */ - /* This is used to hold the server certificate used */ - struct cert_st /* CERT */ *cert; - - /* the session_id_context is used to ensure sessions are only reused - * in the appropriate context */ - unsigned int sid_ctx_length; - uint8_t sid_ctx[SSL_MAX_SID_CTX_LENGTH]; - - /* This can also be in the session once a session is established */ - SSL_SESSION *session; - - /* Default generate session ID callback. */ - GEN_SESSION_CB generate_session_id; - - /* Used in SSL2 and SSL3 */ - int verify_mode; /* 0 don't care about verify failure. - * 1 fail if verify fails */ - int (*verify_callback)(int ok, - X509_STORE_CTX *ctx); /* fail if callback returns 0 */ - - void (*info_callback)(const SSL *ssl, int type, - int val); /* optional informational callback */ - - /* Server-only: psk_identity_hint is the identity hint to send in - * PSK-based key exchanges. */ - char *psk_identity_hint; - - unsigned int (*psk_client_callback)(SSL *ssl, const char *hint, - char *identity, - unsigned int max_identity_len, - uint8_t *psk, unsigned int max_psk_len); - unsigned int (*psk_server_callback)(SSL *ssl, const char *identity, - uint8_t *psk, unsigned int max_psk_len); - - SSL_CTX *ctx; - - /* extra application data */ - long verify_result; - CRYPTO_EX_DATA ex_data; - - /* for server side, keep the list of CA_dn we can use */ - STACK_OF(X509_NAME) *client_CA; - - uint32_t options; /* protocol behaviour */ - uint32_t mode; /* API behaviour */ - uint32_t max_cert_list; - int client_version; /* what was passed, used for - * SSLv3/TLS rollback check */ - uint16_t max_send_fragment; - char *tlsext_hostname; - /* should_ack_sni is true if the SNI extension should be acked. This is - * only used by a server. */ - char should_ack_sni; - /* RFC4507 session ticket expected to be received or sent */ - int tlsext_ticket_expected; - size_t tlsext_ecpointformatlist_length; - uint8_t *tlsext_ecpointformatlist; /* our list */ - size_t tlsext_ellipticcurvelist_length; - uint16_t *tlsext_ellipticcurvelist; /* our list */ - - SSL_CTX *initial_ctx; /* initial ctx, used to store sessions */ - - /* Next protocol negotiation. For the client, this is the protocol that we - * sent in NextProtocol and is set when handling ServerHello extensions. - * - * For a server, this is the client's selected_protocol from NextProtocol and - * is set when handling the NextProtocol message, before the Finished - * message. */ - uint8_t *next_proto_negotiated; - size_t next_proto_negotiated_len; - - /* srtp_profiles is the list of configured SRTP protection profiles for - * DTLS-SRTP. */ - STACK_OF(SRTP_PROTECTION_PROFILE) *srtp_profiles; - - /* srtp_profile is the selected SRTP protection profile for - * DTLS-SRTP. */ - const SRTP_PROTECTION_PROFILE *srtp_profile; - - /* Copied from the SSL_CTX. For a server, means that we'll accept Channel IDs - * from clients. For a client, means that we'll advertise support. */ - char tlsext_channel_id_enabled; - /* The client's Channel ID private key. */ - EVP_PKEY *tlsext_channel_id_private; - - /* Enable signed certificate time stamps. Currently client only. */ - char signed_cert_timestamps_enabled; - - /* Enable OCSP stapling. Currently client only. - * TODO(davidben): Add a server-side implementation when it becomes - * necesary. */ - char ocsp_stapling_enabled; - - /* For a client, this contains the list of supported protocols in wire - * format. */ - uint8_t *alpn_client_proto_list; - unsigned alpn_client_proto_list_len; - - /* fastradio_padding, if true, causes ClientHellos to be padded to 1024 - * bytes. This ensures that the cellular radio is fast forwarded to DCH (high - * data rate) state in 3G networks. */ - char fastradio_padding; - - /* accept_peer_renegotiations, if one, accepts renegotiation attempts from the - * peer. Otherwise, they will be rejected with a fatal error. */ - char accept_peer_renegotiations; - - /* These fields are always NULL and exist only to keep wpa_supplicant happy - * about the change to EVP_AEAD. They are only needed for EAP-FAST, which we - * don't support. */ - EVP_CIPHER_CTX *enc_read_ctx; - EVP_MD_CTX *read_hash; -}; - -/* compatibility */ -#define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg)) -#define SSL_get_app_data(s) (SSL_get_ex_data(s, 0)) -#define SSL_SESSION_set_app_data(s, a) \ - (SSL_SESSION_set_ex_data(s, 0, (char *)a)) -#define SSL_SESSION_get_app_data(s) (SSL_SESSION_get_ex_data(s, 0)) -#define SSL_CTX_get_app_data(ctx) (SSL_CTX_get_ex_data(ctx, 0)) -#define SSL_CTX_set_app_data(ctx, arg) \ - (SSL_CTX_set_ex_data(ctx, 0, (char *)arg)) - -/* The following are the possible values for ssl->state are are used to - * indicate where we are up to in the SSL connection establishment. The macros - * that follow are about the only things you should need to use and even then, - * only when using non-blocking IO. It can also be useful to work out where you - * were when the connection failed */ - -#define SSL_ST_CONNECT 0x1000 -#define SSL_ST_ACCEPT 0x2000 -#define SSL_ST_MASK 0x0FFF -#define SSL_ST_INIT (SSL_ST_CONNECT | SSL_ST_ACCEPT) -#define SSL_ST_OK 0x03 -#define SSL_ST_RENEGOTIATE (0x04 | SSL_ST_INIT) - -#define SSL_CB_LOOP 0x01 -#define SSL_CB_EXIT 0x02 -#define SSL_CB_READ 0x04 -#define SSL_CB_WRITE 0x08 -#define SSL_CB_ALERT 0x4000 /* used in callback */ -#define SSL_CB_READ_ALERT (SSL_CB_ALERT | SSL_CB_READ) -#define SSL_CB_WRITE_ALERT (SSL_CB_ALERT | SSL_CB_WRITE) -#define SSL_CB_ACCEPT_LOOP (SSL_ST_ACCEPT | SSL_CB_LOOP) -#define SSL_CB_ACCEPT_EXIT (SSL_ST_ACCEPT | SSL_CB_EXIT) -#define SSL_CB_CONNECT_LOOP (SSL_ST_CONNECT | SSL_CB_LOOP) -#define SSL_CB_CONNECT_EXIT (SSL_ST_CONNECT | SSL_CB_EXIT) -#define SSL_CB_HANDSHAKE_START 0x10 -#define SSL_CB_HANDSHAKE_DONE 0x20 - -/* Is the SSL_connection established? */ -#define SSL_get_state(a) SSL_state(a) -#define SSL_is_init_finished(a) (SSL_state(a) == SSL_ST_OK) -#define SSL_in_init(a) (SSL_state(a) & SSL_ST_INIT) -#define SSL_in_connect_init(a) (SSL_state(a) & SSL_ST_CONNECT) -#define SSL_in_accept_init(a) (SSL_state(a) & SSL_ST_ACCEPT) - -/* SSL_in_false_start returns one if |s| has a pending unfinished handshake that - * is in False Start. |SSL_write| may be called at this point without waiting - * for the peer, but |SSL_read| will require the handshake to be completed. */ -OPENSSL_EXPORT int SSL_in_false_start(const SSL *s); - -/* The following 2 states are kept in ssl->rstate when reads fail, - * you should not need these */ -#define SSL_ST_READ_HEADER 0xF0 -#define SSL_ST_READ_BODY 0xF1 -#define SSL_ST_READ_DONE 0xF2 - -/* Obtain latest Finished message - * -- that we sent (SSL_get_finished) - * -- that we expected from peer (SSL_get_peer_finished). - * Returns length (0 == no Finished so far), copies up to 'count' bytes. */ -OPENSSL_EXPORT size_t SSL_get_finished(const SSL *s, void *buf, size_t count); -OPENSSL_EXPORT size_t SSL_get_peer_finished(const SSL *s, void *buf, size_t count); - -/* use either SSL_VERIFY_NONE or SSL_VERIFY_PEER, the last 3 options - * are 'ored' with SSL_VERIFY_PEER if they are desired */ -#define SSL_VERIFY_NONE 0x00 -#define SSL_VERIFY_PEER 0x01 -#define SSL_VERIFY_FAIL_IF_NO_PEER_CERT 0x02 -/* SSL_VERIFY_CLIENT_ONCE does nothing. */ -#define SSL_VERIFY_CLIENT_ONCE 0x04 -#define SSL_VERIFY_PEER_IF_NO_OBC 0x08 - -#define OpenSSL_add_ssl_algorithms() SSL_library_init() -#define SSLeay_add_ssl_algorithms() SSL_library_init() - -/* For backward compatibility */ -#define SSL_get_cipher(s) SSL_CIPHER_get_name(SSL_get_current_cipher(s)) -#define SSL_get_cipher_bits(s, np) \ - SSL_CIPHER_get_bits(SSL_get_current_cipher(s), np) -#define SSL_get_cipher_version(s) \ - SSL_CIPHER_get_version(SSL_get_current_cipher(s)) -#define SSL_get_cipher_name(s) SSL_CIPHER_get_name(SSL_get_current_cipher(s)) -#define SSL_get_time(a) SSL_SESSION_get_time(a) -#define SSL_set_time(a, b) SSL_SESSION_set_time((a), (b)) -#define SSL_get_timeout(a) SSL_SESSION_get_timeout(a) -#define SSL_set_timeout(a, b) SSL_SESSION_set_timeout((a), (b)) - -#define d2i_SSL_SESSION_bio(bp, s_id) \ - ASN1_d2i_bio_of(SSL_SESSION, SSL_SESSION_new, d2i_SSL_SESSION, bp, s_id) -#define i2d_SSL_SESSION_bio(bp, s_id) \ - ASN1_i2d_bio_of(SSL_SESSION, i2d_SSL_SESSION, bp, s_id) - -DECLARE_PEM_rw(SSL_SESSION, SSL_SESSION) - -/* make_errors.go reserves error codes above 1000 for manually-assigned errors. - * This value must be kept in sync with reservedReasonCode in make_errors.h */ -#define SSL_AD_REASON_OFFSET \ - 1000 /* offset to get SSL_R_... value from SSL_AD_... */ - -/* These alert types are for SSLv3 and TLSv1 */ -#define SSL_AD_CLOSE_NOTIFY SSL3_AD_CLOSE_NOTIFY -#define SSL_AD_UNEXPECTED_MESSAGE SSL3_AD_UNEXPECTED_MESSAGE /* fatal */ -#define SSL_AD_BAD_RECORD_MAC SSL3_AD_BAD_RECORD_MAC /* fatal */ -#define SSL_AD_DECRYPTION_FAILED TLS1_AD_DECRYPTION_FAILED -#define SSL_AD_RECORD_OVERFLOW TLS1_AD_RECORD_OVERFLOW -#define SSL_AD_DECOMPRESSION_FAILURE SSL3_AD_DECOMPRESSION_FAILURE /* fatal */ -#define SSL_AD_HANDSHAKE_FAILURE SSL3_AD_HANDSHAKE_FAILURE /* fatal */ -#define SSL_AD_NO_CERTIFICATE SSL3_AD_NO_CERTIFICATE /* Not for TLS */ -#define SSL_AD_BAD_CERTIFICATE SSL3_AD_BAD_CERTIFICATE -#define SSL_AD_UNSUPPORTED_CERTIFICATE SSL3_AD_UNSUPPORTED_CERTIFICATE -#define SSL_AD_CERTIFICATE_REVOKED SSL3_AD_CERTIFICATE_REVOKED -#define SSL_AD_CERTIFICATE_EXPIRED SSL3_AD_CERTIFICATE_EXPIRED -#define SSL_AD_CERTIFICATE_UNKNOWN SSL3_AD_CERTIFICATE_UNKNOWN -#define SSL_AD_ILLEGAL_PARAMETER SSL3_AD_ILLEGAL_PARAMETER /* fatal */ -#define SSL_AD_UNKNOWN_CA TLS1_AD_UNKNOWN_CA /* fatal */ -#define SSL_AD_ACCESS_DENIED TLS1_AD_ACCESS_DENIED /* fatal */ -#define SSL_AD_DECODE_ERROR TLS1_AD_DECODE_ERROR /* fatal */ -#define SSL_AD_DECRYPT_ERROR TLS1_AD_DECRYPT_ERROR -#define SSL_AD_EXPORT_RESTRICTION TLS1_AD_EXPORT_RESTRICTION /* fatal */ -#define SSL_AD_PROTOCOL_VERSION TLS1_AD_PROTOCOL_VERSION /* fatal */ -#define SSL_AD_INSUFFICIENT_SECURITY TLS1_AD_INSUFFICIENT_SECURITY /* fatal */ -#define SSL_AD_INTERNAL_ERROR TLS1_AD_INTERNAL_ERROR /* fatal */ -#define SSL_AD_USER_CANCELLED TLS1_AD_USER_CANCELLED -#define SSL_AD_NO_RENEGOTIATION TLS1_AD_NO_RENEGOTIATION -#define SSL_AD_UNSUPPORTED_EXTENSION TLS1_AD_UNSUPPORTED_EXTENSION -#define SSL_AD_CERTIFICATE_UNOBTAINABLE TLS1_AD_CERTIFICATE_UNOBTAINABLE -#define SSL_AD_UNRECOGNIZED_NAME TLS1_AD_UNRECOGNIZED_NAME -#define SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE \ - TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE -#define SSL_AD_BAD_CERTIFICATE_HASH_VALUE TLS1_AD_BAD_CERTIFICATE_HASH_VALUE -#define SSL_AD_UNKNOWN_PSK_IDENTITY TLS1_AD_UNKNOWN_PSK_IDENTITY /* fatal */ -#define SSL_AD_INAPPROPRIATE_FALLBACK SSL3_AD_INAPPROPRIATE_FALLBACK /* fatal */ - -#define SSL_ERROR_NONE 0 -#define SSL_ERROR_SSL 1 -#define SSL_ERROR_WANT_READ 2 -#define SSL_ERROR_WANT_WRITE 3 -#define SSL_ERROR_WANT_X509_LOOKUP 4 -#define SSL_ERROR_SYSCALL 5 /* look at error stack/return value/errno */ -#define SSL_ERROR_ZERO_RETURN 6 -#define SSL_ERROR_WANT_CONNECT 7 -#define SSL_ERROR_WANT_ACCEPT 8 -#define SSL_ERROR_WANT_CHANNEL_ID_LOOKUP 9 -#define SSL_ERROR_PENDING_SESSION 11 -#define SSL_ERROR_PENDING_CERTIFICATE 12 - -#define SSL_CTRL_EXTRA_CHAIN_CERT 14 - -/* see tls1.h for macros based on these */ -#define SSL_CTRL_GET_TLSEXT_TICKET_KEYS 58 -#define SSL_CTRL_SET_TLSEXT_TICKET_KEYS 59 - -#define SSL_CTRL_SET_SRP_ARG 78 -#define SSL_CTRL_SET_TLS_EXT_SRP_USERNAME 79 -#define SSL_CTRL_SET_TLS_EXT_SRP_STRENGTH 80 -#define SSL_CTRL_SET_TLS_EXT_SRP_PASSWORD 81 - -#define SSL_CTRL_GET_EXTRA_CHAIN_CERTS 82 -#define SSL_CTRL_CLEAR_EXTRA_CHAIN_CERTS 83 - -#define SSL_CTRL_CHAIN 88 -#define SSL_CTRL_CHAIN_CERT 89 - -#define SSL_CTRL_GET_CURVES 90 -#define SSL_CTRL_SET_CURVES 91 -#define SSL_CTRL_SET_CURVES_LIST 92 -#define SSL_CTRL_SET_SIGALGS 97 -#define SSL_CTRL_SET_SIGALGS_LIST 98 -#define SSL_CTRL_SET_CLIENT_SIGALGS 101 -#define SSL_CTRL_SET_CLIENT_SIGALGS_LIST 102 -#define SSL_CTRL_GET_CLIENT_CERT_TYPES 103 -#define SSL_CTRL_SET_CLIENT_CERT_TYPES 104 -#define SSL_CTRL_BUILD_CERT_CHAIN 105 -#define SSL_CTRL_SET_VERIFY_CERT_STORE 106 -#define SSL_CTRL_SET_CHAIN_CERT_STORE 107 -#define SSL_CTRL_GET_SERVER_TMP_KEY 109 -#define SSL_CTRL_GET_EC_POINT_FORMATS 111 - -#define SSL_CTRL_GET_CHAIN_CERTS 115 -#define SSL_CTRL_SELECT_CURRENT_CERT 116 - -/* DTLSv1_get_timeout queries the next DTLS handshake timeout. If there is a - * timeout in progress, it sets |*out| to the time remaining and returns one. - * Otherwise, it returns zero. - * - * When the timeout expires, call |DTLSv1_handle_timeout| to handle the - * retransmit behavior. - * - * NOTE: This function must be queried again whenever the handshake state - * machine changes, including when |DTLSv1_handle_timeout| is called. */ -OPENSSL_EXPORT int DTLSv1_get_timeout(const SSL *ssl, struct timeval *out); - -/* DTLSv1_handle_timeout is called when a DTLS handshake timeout expires. If no - * timeout had expired, it returns 0. Otherwise, it retransmits the previous - * flight of handshake messages and returns 1. If too many timeouts had expired - * without progress or an error occurs, it returns -1. - * - * NOTE: The caller's external timer should be compatible with the one |ssl| - * queries within some fudge factor. Otherwise, the call will be a no-op, but - * |DTLSv1_get_timeout| will return an updated timeout. - * - * WARNING: This function breaks the usual return value convention. */ -OPENSSL_EXPORT int DTLSv1_handle_timeout(SSL *ssl); - -/* SSL_session_reused returns one if |ssl| performed an abbreviated handshake - * and zero otherwise. - * - * TODO(davidben): Hammer down the semantics of this API while a handshake, - * initial or renego, is in progress. */ -OPENSSL_EXPORT int SSL_session_reused(const SSL *ssl); - -/* SSL_total_renegotiations returns the total number of renegotiation handshakes - * peformed by |ssl|. This includes the pending renegotiation, if any. */ -OPENSSL_EXPORT int SSL_total_renegotiations(const SSL *ssl); - -/* SSL_CTX_set_tmp_dh configures |ctx| to use the group from |dh| as the group - * for DHE. Only the group is used, so |dh| needn't have a keypair. It returns - * one on success and zero on error. */ -OPENSSL_EXPORT int SSL_CTX_set_tmp_dh(SSL_CTX *ctx, const DH *dh); - -/* SSL_set_tmp_dh configures |ssl| to use the group from |dh| as the group for - * DHE. Only the group is used, so |dh| needn't have a keypair. It returns one - * on success and zero on error. */ -OPENSSL_EXPORT int SSL_set_tmp_dh(SSL *ssl, const DH *dh); - -/* SSL_CTX_set_tmp_ecdh configures |ctx| to use the curve from |ecdh| as the - * curve for ephemeral ECDH keys. For historical reasons, this API expects an - * |EC_KEY|, but only the curve is used. It returns one on success and zero on - * error. If unset, an appropriate curve will be chosen automatically. (This is - * recommended.) */ -OPENSSL_EXPORT int SSL_CTX_set_tmp_ecdh(SSL_CTX *ctx, const EC_KEY *ec_key); - -/* SSL_set_tmp_ecdh configures |ssl| to use the curve from |ecdh| as the curve - * for ephemeral ECDH keys. For historical reasons, this API expects an - * |EC_KEY|, but only the curve is used. It returns one on success and zero on - * error. If unset, an appropriate curve will be chosen automatically. (This is - * recommended.) */ -OPENSSL_EXPORT int SSL_set_tmp_ecdh(SSL *ssl, const EC_KEY *ec_key); - -/* SSL_CTX_enable_tls_channel_id either configures a TLS server to accept TLS - * client IDs from clients, or configures a client to send TLS client IDs to - * a server. It returns one. */ -OPENSSL_EXPORT int SSL_CTX_enable_tls_channel_id(SSL_CTX *ctx); - -/* SSL_enable_tls_channel_id either configures a TLS server to accept TLS - * client IDs from clients, or configure a client to send TLS client IDs to - * server. It returns one. */ -OPENSSL_EXPORT int SSL_enable_tls_channel_id(SSL *ssl); - -/* SSL_CTX_set1_tls_channel_id configures a TLS client to send a TLS Channel ID - * to compatible servers. |private_key| must be a P-256 EC key. It returns one - * on success and zero on error. */ -OPENSSL_EXPORT int SSL_CTX_set1_tls_channel_id(SSL_CTX *ctx, - EVP_PKEY *private_key); - -/* SSL_set1_tls_channel_id configures a TLS client to send a TLS Channel ID to - * compatible servers. |private_key| must be a P-256 EC key. It returns one on - * success and zero on error. */ -OPENSSL_EXPORT int SSL_set1_tls_channel_id(SSL *ssl, EVP_PKEY *private_key); - -/* SSL_get_tls_channel_id gets the client's TLS Channel ID from a server SSL* - * and copies up to the first |max_out| bytes into |out|. The Channel ID - * consists of the client's P-256 public key as an (x,y) pair where each is a - * 32-byte, big-endian field element. It returns 0 if the client didn't offer a - * Channel ID and the length of the complete Channel ID otherwise. */ -OPENSSL_EXPORT size_t SSL_get_tls_channel_id(SSL *ssl, uint8_t *out, - size_t max_out); - -#define SSL_CTX_add_extra_chain_cert(ctx, x509) \ - SSL_CTX_ctrl(ctx, SSL_CTRL_EXTRA_CHAIN_CERT, 0, (char *)x509) -#define SSL_CTX_get_extra_chain_certs(ctx, px509) \ - SSL_CTX_ctrl(ctx, SSL_CTRL_GET_EXTRA_CHAIN_CERTS, 0, px509) -#define SSL_CTX_get_extra_chain_certs_only(ctx, px509) \ - SSL_CTX_ctrl(ctx, SSL_CTRL_GET_EXTRA_CHAIN_CERTS, 1, px509) -#define SSL_CTX_clear_extra_chain_certs(ctx) \ - SSL_CTX_ctrl(ctx, SSL_CTRL_CLEAR_EXTRA_CHAIN_CERTS, 0, NULL) - -#define SSL_CTX_set0_chain(ctx, sk) \ - SSL_CTX_ctrl(ctx, SSL_CTRL_CHAIN, 0, (char *)sk) -#define SSL_CTX_set1_chain(ctx, sk) \ - SSL_CTX_ctrl(ctx, SSL_CTRL_CHAIN, 1, (char *)sk) -#define SSL_CTX_add0_chain_cert(ctx, x509) \ - SSL_CTX_ctrl(ctx, SSL_CTRL_CHAIN_CERT, 0, (char *)x509) -#define SSL_CTX_add1_chain_cert(ctx, x509) \ - SSL_CTX_ctrl(ctx, SSL_CTRL_CHAIN_CERT, 1, (char *)x509) -#define SSL_CTX_get0_chain_certs(ctx, px509) \ - SSL_CTX_ctrl(ctx, SSL_CTRL_GET_CHAIN_CERTS, 0, px509) -#define SSL_CTX_clear_chain_certs(ctx) SSL_CTX_set0_chain(ctx, NULL) -#define SSL_CTX_build_cert_chain(ctx, flags) \ - SSL_CTX_ctrl(ctx, SSL_CTRL_BUILD_CERT_CHAIN, flags, NULL) -#define SSL_CTX_select_current_cert(ctx, x509) \ - SSL_CTX_ctrl(ctx, SSL_CTRL_SELECT_CURRENT_CERT, 0, (char *)x509) - -#define SSL_CTX_set0_verify_cert_store(ctx, st) \ - SSL_CTX_ctrl(ctx, SSL_CTRL_SET_VERIFY_CERT_STORE, 0, (char *)st) -#define SSL_CTX_set1_verify_cert_store(ctx, st) \ - SSL_CTX_ctrl(ctx, SSL_CTRL_SET_VERIFY_CERT_STORE, 1, (char *)st) -#define SSL_CTX_set0_chain_cert_store(ctx, st) \ - SSL_CTX_ctrl(ctx, SSL_CTRL_SET_CHAIN_CERT_STORE, 0, (char *)st) -#define SSL_CTX_set1_chain_cert_store(ctx, st) \ - SSL_CTX_ctrl(ctx, SSL_CTRL_SET_CHAIN_CERT_STORE, 1, (char *)st) - -#define SSL_set0_chain(ctx, sk) SSL_ctrl(ctx, SSL_CTRL_CHAIN, 0, (char *)sk) -#define SSL_set1_chain(ctx, sk) SSL_ctrl(ctx, SSL_CTRL_CHAIN, 1, (char *)sk) -#define SSL_add0_chain_cert(ctx, x509) \ - SSL_ctrl(ctx, SSL_CTRL_CHAIN_CERT, 0, (char *)x509) -#define SSL_add1_chain_cert(ctx, x509) \ - SSL_ctrl(ctx, SSL_CTRL_CHAIN_CERT, 1, (char *)x509) -#define SSL_get0_chain_certs(ctx, px509) \ - SSL_ctrl(ctx, SSL_CTRL_GET_CHAIN_CERTS, 0, px509) -#define SSL_clear_chain_certs(ctx) SSL_set0_chain(ctx, NULL) -#define SSL_build_cert_chain(s, flags) \ - SSL_ctrl(s, SSL_CTRL_BUILD_CERT_CHAIN, flags, NULL) -#define SSL_select_current_cert(ctx, x509) \ - SSL_ctrl(ctx, SSL_CTRL_SELECT_CURRENT_CERT, 0, (char *)x509) - -#define SSL_set0_verify_cert_store(s, st) \ - SSL_ctrl(s, SSL_CTRL_SET_VERIFY_CERT_STORE, 0, (char *)st) -#define SSL_set1_verify_cert_store(s, st) \ - SSL_ctrl(s, SSL_CTRL_SET_VERIFY_CERT_STORE, 1, (char *)st) -#define SSL_set0_chain_cert_store(s, st) \ - SSL_ctrl(s, SSL_CTRL_SET_CHAIN_CERT_STORE, 0, (char *)st) -#define SSL_set1_chain_cert_store(s, st) \ - SSL_ctrl(s, SSL_CTRL_SET_CHAIN_CERT_STORE, 1, (char *)st) - -#define SSL_get1_curves(ctx, s) SSL_ctrl(ctx, SSL_CTRL_GET_CURVES, 0, (char *)s) -#define SSL_CTX_set1_curves(ctx, clist, clistlen) \ - SSL_CTX_ctrl(ctx, SSL_CTRL_SET_CURVES, clistlen, (char *)clist) -#define SSL_CTX_set1_curves_list(ctx, s) \ - SSL_CTX_ctrl(ctx, SSL_CTRL_SET_CURVES_LIST, 0, (char *)s) -#define SSL_set1_curves(ctx, clist, clistlen) \ - SSL_ctrl(ctx, SSL_CTRL_SET_CURVES, clistlen, (char *)clist) -#define SSL_set1_curves_list(ctx, s) \ - SSL_ctrl(ctx, SSL_CTRL_SET_CURVES_LIST, 0, (char *)s) - -#define SSL_CTX_set1_sigalgs(ctx, slist, slistlen) \ - SSL_CTX_ctrl(ctx, SSL_CTRL_SET_SIGALGS, slistlen, (int *)slist) -#define SSL_CTX_set1_sigalgs_list(ctx, s) \ - SSL_CTX_ctrl(ctx, SSL_CTRL_SET_SIGALGS_LIST, 0, (char *)s) -#define SSL_set1_sigalgs(ctx, slist, slistlen) \ - SSL_ctrl(ctx, SSL_CTRL_SET_SIGALGS, clistlen, (int *)slist) -#define SSL_set1_sigalgs_list(ctx, s) \ - SSL_ctrl(ctx, SSL_CTRL_SET_SIGALGS_LIST, 0, (char *)s) - -#define SSL_CTX_set1_client_sigalgs(ctx, slist, slistlen) \ - SSL_CTX_ctrl(ctx, SSL_CTRL_SET_CLIENT_SIGALGS, slistlen, (int *)slist) -#define SSL_CTX_set1_client_sigalgs_list(ctx, s) \ - SSL_CTX_ctrl(ctx, SSL_CTRL_SET_CLIENT_SIGALGS_LIST, 0, (char *)s) -#define SSL_set1_client_sigalgs(ctx, slist, slistlen) \ - SSL_ctrl(ctx, SSL_CTRL_SET_CLIENT_SIGALGS, clistlen, (int *)slist) -#define SSL_set1_client_sigalgs_list(ctx, s) \ - SSL_ctrl(ctx, SSL_CTRL_SET_CLIENT_SIGALGS_LIST, 0, (char *)s) - -#define SSL_get0_certificate_types(s, clist) \ - SSL_ctrl(s, SSL_CTRL_GET_CLIENT_CERT_TYPES, 0, (char *)clist) - -#define SSL_CTX_set1_client_certificate_types(ctx, clist, clistlen) \ - SSL_CTX_ctrl(ctx, SSL_CTRL_SET_CLIENT_CERT_TYPES, clistlen, (char *)clist) -#define SSL_set1_client_certificate_types(s, clist, clistlen) \ - SSL_ctrl(s, SSL_CTRL_SET_CLIENT_CERT_TYPES, clistlen, (char *)clist) - -#define SSL_get_server_tmp_key(s, pk) \ - SSL_ctrl(s, SSL_CTRL_GET_SERVER_TMP_KEY, 0, pk) - -#define SSL_get0_ec_point_formats(s, plst) \ - SSL_ctrl(s, SSL_CTRL_GET_EC_POINT_FORMATS, 0, (char *)plst) - -OPENSSL_EXPORT int SSL_CTX_set_cipher_list(SSL_CTX *, const char *str); -OPENSSL_EXPORT int SSL_CTX_set_cipher_list_tls11(SSL_CTX *, const char *str); -OPENSSL_EXPORT long SSL_CTX_set_timeout(SSL_CTX *ctx, long t); -OPENSSL_EXPORT long SSL_CTX_get_timeout(const SSL_CTX *ctx); -OPENSSL_EXPORT X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *); -OPENSSL_EXPORT void SSL_CTX_set_cert_store(SSL_CTX *, X509_STORE *); -OPENSSL_EXPORT int SSL_want(const SSL *s); - -OPENSSL_EXPORT void SSL_CTX_flush_sessions(SSL_CTX *ctx, long tm); - -/* SSL_get_current_cipher returns the cipher used in the current outgoing - * connection state, or NULL if the null cipher is active. */ -OPENSSL_EXPORT const SSL_CIPHER *SSL_get_current_cipher(const SSL *s); - -OPENSSL_EXPORT int SSL_get_fd(const SSL *s); -OPENSSL_EXPORT int SSL_get_rfd(const SSL *s); -OPENSSL_EXPORT int SSL_get_wfd(const SSL *s); -OPENSSL_EXPORT const char *SSL_get_cipher_list(const SSL *s, int n); -OPENSSL_EXPORT int SSL_pending(const SSL *s); -OPENSSL_EXPORT int SSL_set_fd(SSL *s, int fd); -OPENSSL_EXPORT int SSL_set_rfd(SSL *s, int fd); -OPENSSL_EXPORT int SSL_set_wfd(SSL *s, int fd); -OPENSSL_EXPORT void SSL_set_bio(SSL *s, BIO *rbio, BIO *wbio); -OPENSSL_EXPORT BIO *SSL_get_rbio(const SSL *s); -OPENSSL_EXPORT BIO *SSL_get_wbio(const SSL *s); -OPENSSL_EXPORT int SSL_set_cipher_list(SSL *s, const char *str); -OPENSSL_EXPORT int SSL_get_verify_mode(const SSL *s); -OPENSSL_EXPORT int SSL_get_verify_depth(const SSL *s); -OPENSSL_EXPORT int (*SSL_get_verify_callback(const SSL *s))(int, - X509_STORE_CTX *); -OPENSSL_EXPORT void SSL_set_verify(SSL *s, int mode, - int (*callback)(int ok, - X509_STORE_CTX *ctx)); -OPENSSL_EXPORT void SSL_set_verify_depth(SSL *s, int depth); -OPENSSL_EXPORT void SSL_set_cert_cb(SSL *s, int (*cb)(SSL *ssl, void *arg), - void *arg); -OPENSSL_EXPORT int SSL_use_RSAPrivateKey(SSL *ssl, RSA *rsa); -OPENSSL_EXPORT int SSL_use_RSAPrivateKey_ASN1(SSL *ssl, uint8_t *d, long len); -OPENSSL_EXPORT int SSL_use_PrivateKey(SSL *ssl, EVP_PKEY *pkey); -OPENSSL_EXPORT int SSL_use_PrivateKey_ASN1(int pk, SSL *ssl, const uint8_t *d, - long len); -OPENSSL_EXPORT int SSL_use_certificate(SSL *ssl, X509 *x); -OPENSSL_EXPORT int SSL_use_certificate_ASN1(SSL *ssl, const uint8_t *d, - int len); - -OPENSSL_EXPORT int SSL_use_RSAPrivateKey_file(SSL *ssl, const char *file, - int type); -OPENSSL_EXPORT int SSL_use_PrivateKey_file(SSL *ssl, const char *file, - int type); -OPENSSL_EXPORT int SSL_use_certificate_file(SSL *ssl, const char *file, - int type); -OPENSSL_EXPORT int SSL_CTX_use_RSAPrivateKey_file(SSL_CTX *ctx, - const char *file, int type); -OPENSSL_EXPORT int SSL_CTX_use_PrivateKey_file(SSL_CTX *ctx, const char *file, - int type); -OPENSSL_EXPORT int SSL_CTX_use_certificate_file(SSL_CTX *ctx, const char *file, - int type); -OPENSSL_EXPORT int SSL_CTX_use_certificate_chain_file( - SSL_CTX *ctx, const char *file); /* PEM type */ -OPENSSL_EXPORT STACK_OF(X509_NAME) *SSL_load_client_CA_file(const char *file); -OPENSSL_EXPORT int SSL_add_file_cert_subjects_to_stack(STACK_OF(X509_NAME) * - stackCAs, - const char *file); -OPENSSL_EXPORT int SSL_add_dir_cert_subjects_to_stack(STACK_OF(X509_NAME) * - stackCAs, - const char *dir); - -/* SSL_load_error_strings does nothing. */ -OPENSSL_EXPORT void SSL_load_error_strings(void); - -OPENSSL_EXPORT const char *SSL_state_string(const SSL *s); -OPENSSL_EXPORT const char *SSL_rstate_string(const SSL *s); -OPENSSL_EXPORT const char *SSL_state_string_long(const SSL *s); -OPENSSL_EXPORT const char *SSL_rstate_string_long(const SSL *s); -OPENSSL_EXPORT long SSL_SESSION_get_time(const SSL_SESSION *s); -OPENSSL_EXPORT long SSL_SESSION_set_time(SSL_SESSION *s, long t); -OPENSSL_EXPORT long SSL_SESSION_get_timeout(const SSL_SESSION *s); -OPENSSL_EXPORT long SSL_SESSION_set_timeout(SSL_SESSION *s, long t); -OPENSSL_EXPORT X509 *SSL_SESSION_get0_peer(SSL_SESSION *s); -OPENSSL_EXPORT int SSL_SESSION_set1_id_context(SSL_SESSION *s, - const uint8_t *sid_ctx, - unsigned int sid_ctx_len); - -OPENSSL_EXPORT SSL_SESSION *SSL_SESSION_new(void); -OPENSSL_EXPORT const uint8_t *SSL_SESSION_get_id(const SSL_SESSION *s, - unsigned int *len); -OPENSSL_EXPORT int SSL_SESSION_print_fp(FILE *fp, const SSL_SESSION *ses); -OPENSSL_EXPORT int SSL_SESSION_print(BIO *fp, const SSL_SESSION *ses); - -/* SSL_SESSION_up_ref, if |session| is not NULL, increments the reference count - * of |session|. It then returns |session|. */ -OPENSSL_EXPORT SSL_SESSION *SSL_SESSION_up_ref(SSL_SESSION *session); - -/* SSL_SESSION_free decrements the reference count of |session|. If it reaches - * zero, all data referenced by |session| and |session| itself are released. */ -OPENSSL_EXPORT void SSL_SESSION_free(SSL_SESSION *session); - -OPENSSL_EXPORT int SSL_set_session(SSL *to, SSL_SESSION *session); -OPENSSL_EXPORT int SSL_CTX_add_session(SSL_CTX *s, SSL_SESSION *c); -OPENSSL_EXPORT int SSL_CTX_remove_session(SSL_CTX *, SSL_SESSION *c); -OPENSSL_EXPORT int SSL_CTX_set_generate_session_id(SSL_CTX *, GEN_SESSION_CB); -OPENSSL_EXPORT int SSL_set_generate_session_id(SSL *, GEN_SESSION_CB); -OPENSSL_EXPORT int SSL_has_matching_session_id(const SSL *ssl, - const uint8_t *id, - unsigned int id_len); - -/* SSL_SESSION_to_bytes serializes |in| into a newly allocated buffer and sets - * |*out_data| to that buffer and |*out_len| to its length. The caller takes - * ownership of the buffer and must call |OPENSSL_free| when done. It returns - * one on success and zero on error. */ -OPENSSL_EXPORT int SSL_SESSION_to_bytes(SSL_SESSION *in, uint8_t **out_data, - size_t *out_len); - -/* SSL_SESSION_to_bytes_for_ticket serializes |in|, but excludes the session ID - * which is not necessary in a session ticket. */ -OPENSSL_EXPORT int SSL_SESSION_to_bytes_for_ticket(SSL_SESSION *in, - uint8_t **out_data, - size_t *out_len); - -/* Deprecated: i2d_SSL_SESSION serializes |in| to the bytes pointed to by - * |*pp|. On success, it returns the number of bytes written and advances |*pp| - * by that many bytes. On failure, it returns -1. If |pp| is NULL, no bytes are - * written and only the length is returned. - * - * Use SSL_SESSION_to_bytes instead. */ -OPENSSL_EXPORT int i2d_SSL_SESSION(SSL_SESSION *in, uint8_t **pp); - -/* d2i_SSL_SESSION deserializes a serialized buffer contained in the |length| - * bytes pointed to by |*pp|. It returns the new SSL_SESSION and advances |*pp| - * by the number of bytes consumed on success and NULL on failure. If |a| is - * NULL, the caller takes ownership of the new session and must call - * |SSL_SESSION_free| when done. - * - * If |a| and |*a| are not NULL, the SSL_SESSION at |*a| is overridden with the - * deserialized session rather than allocating a new one. In addition, |a| is - * not NULL, but |*a| is, |*a| is set to the new SSL_SESSION. - * - * Passing a value other than NULL to |a| is deprecated. */ -OPENSSL_EXPORT SSL_SESSION *d2i_SSL_SESSION(SSL_SESSION **a, const uint8_t **pp, - long length); - -OPENSSL_EXPORT X509 *SSL_get_peer_certificate(const SSL *s); - -OPENSSL_EXPORT STACK_OF(X509) *SSL_get_peer_cert_chain(const SSL *s); - -OPENSSL_EXPORT int SSL_CTX_get_verify_mode(const SSL_CTX *ctx); -OPENSSL_EXPORT int SSL_CTX_get_verify_depth(const SSL_CTX *ctx); -OPENSSL_EXPORT int (*SSL_CTX_get_verify_callback(const SSL_CTX *ctx))( - int, X509_STORE_CTX *); -OPENSSL_EXPORT void SSL_CTX_set_verify(SSL_CTX *ctx, int mode, - int (*callback)(int, X509_STORE_CTX *)); -OPENSSL_EXPORT void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth); -OPENSSL_EXPORT void SSL_CTX_set_cert_verify_callback( - SSL_CTX *ctx, int (*cb)(X509_STORE_CTX *, void *), void *arg); -OPENSSL_EXPORT void SSL_CTX_set_cert_cb(SSL_CTX *c, - int (*cb)(SSL *ssl, void *arg), - void *arg); -OPENSSL_EXPORT int SSL_CTX_use_RSAPrivateKey(SSL_CTX *ctx, RSA *rsa); -OPENSSL_EXPORT int SSL_CTX_use_RSAPrivateKey_ASN1(SSL_CTX *ctx, - const uint8_t *d, long len); -OPENSSL_EXPORT int SSL_CTX_use_PrivateKey(SSL_CTX *ctx, EVP_PKEY *pkey); -OPENSSL_EXPORT int SSL_CTX_use_PrivateKey_ASN1(int pk, SSL_CTX *ctx, - const uint8_t *d, long len); -OPENSSL_EXPORT int SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x); -OPENSSL_EXPORT int SSL_CTX_use_certificate_ASN1(SSL_CTX *ctx, int len, - const uint8_t *d); - -OPENSSL_EXPORT void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, - pem_password_cb *cb); -OPENSSL_EXPORT void SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, - void *u); - -OPENSSL_EXPORT int SSL_CTX_check_private_key(const SSL_CTX *ctx); -OPENSSL_EXPORT int SSL_check_private_key(const SSL *ctx); - -OPENSSL_EXPORT int SSL_CTX_set_session_id_context(SSL_CTX *ctx, - const uint8_t *sid_ctx, - unsigned int sid_ctx_len); - -OPENSSL_EXPORT int SSL_set_session_id_context(SSL *ssl, const uint8_t *sid_ctx, - unsigned int sid_ctx_len); - -OPENSSL_EXPORT int SSL_CTX_set_purpose(SSL_CTX *s, int purpose); -OPENSSL_EXPORT int SSL_set_purpose(SSL *s, int purpose); -OPENSSL_EXPORT int SSL_CTX_set_trust(SSL_CTX *s, int trust); -OPENSSL_EXPORT int SSL_set_trust(SSL *s, int trust); - -OPENSSL_EXPORT int SSL_CTX_set1_param(SSL_CTX *ctx, X509_VERIFY_PARAM *vpm); -OPENSSL_EXPORT int SSL_set1_param(SSL *ssl, X509_VERIFY_PARAM *vpm); - -OPENSSL_EXPORT X509_VERIFY_PARAM *SSL_CTX_get0_param(SSL_CTX *ctx); -OPENSSL_EXPORT X509_VERIFY_PARAM *SSL_get0_param(SSL *ssl); - -OPENSSL_EXPORT void SSL_certs_clear(SSL *s); -OPENSSL_EXPORT int SSL_accept(SSL *ssl); -OPENSSL_EXPORT int SSL_connect(SSL *ssl); -OPENSSL_EXPORT int SSL_read(SSL *ssl, void *buf, int num); -OPENSSL_EXPORT int SSL_peek(SSL *ssl, void *buf, int num); -OPENSSL_EXPORT int SSL_write(SSL *ssl, const void *buf, int num); -OPENSSL_EXPORT long SSL_ctrl(SSL *ssl, int cmd, long larg, void *parg); -OPENSSL_EXPORT long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg); - -OPENSSL_EXPORT int SSL_get_error(const SSL *s, int ret_code); -/* SSL_get_version returns a string describing the TLS version used by |s|. For - * example, "TLSv1.2" or "SSLv3". */ -OPENSSL_EXPORT const char *SSL_get_version(const SSL *s); -/* SSL_SESSION_get_version returns a string describing the TLS version used by - * |sess|. For example, "TLSv1.2" or "SSLv3". */ -OPENSSL_EXPORT const char *SSL_SESSION_get_version(const SSL_SESSION *sess); - -OPENSSL_EXPORT STACK_OF(SSL_CIPHER) *SSL_get_ciphers(const SSL *s); - -OPENSSL_EXPORT int SSL_do_handshake(SSL *s); - -/* SSL_renegotiate_pending returns one if |ssl| is in the middle of a - * renegotiation. */ -OPENSSL_EXPORT int SSL_renegotiate_pending(SSL *ssl); - -OPENSSL_EXPORT int SSL_shutdown(SSL *s); - -OPENSSL_EXPORT const char *SSL_alert_type_string_long(int value); -OPENSSL_EXPORT const char *SSL_alert_type_string(int value); -OPENSSL_EXPORT const char *SSL_alert_desc_string_long(int value); -OPENSSL_EXPORT const char *SSL_alert_desc_string(int value); - -OPENSSL_EXPORT void SSL_set_client_CA_list(SSL *s, - STACK_OF(X509_NAME) *name_list); -OPENSSL_EXPORT void SSL_CTX_set_client_CA_list(SSL_CTX *ctx, - STACK_OF(X509_NAME) *name_list); -OPENSSL_EXPORT STACK_OF(X509_NAME) *SSL_get_client_CA_list(const SSL *s); -OPENSSL_EXPORT STACK_OF(X509_NAME) * - SSL_CTX_get_client_CA_list(const SSL_CTX *s); -OPENSSL_EXPORT int SSL_add_client_CA(SSL *ssl, X509 *x); -OPENSSL_EXPORT int SSL_CTX_add_client_CA(SSL_CTX *ctx, X509 *x); - -OPENSSL_EXPORT long SSL_get_default_timeout(const SSL *s); - -OPENSSL_EXPORT STACK_OF(X509_NAME) *SSL_dup_CA_list(STACK_OF(X509_NAME) *sk); - -OPENSSL_EXPORT X509 *SSL_get_certificate(const SSL *ssl); -OPENSSL_EXPORT EVP_PKEY *SSL_get_privatekey(const SSL *ssl); - -OPENSSL_EXPORT X509 *SSL_CTX_get0_certificate(const SSL_CTX *ctx); -OPENSSL_EXPORT EVP_PKEY *SSL_CTX_get0_privatekey(const SSL_CTX *ctx); - -OPENSSL_EXPORT void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode); -OPENSSL_EXPORT int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx); -OPENSSL_EXPORT void SSL_set_quiet_shutdown(SSL *ssl, int mode); -OPENSSL_EXPORT int SSL_get_quiet_shutdown(const SSL *ssl); -OPENSSL_EXPORT void SSL_set_shutdown(SSL *ssl, int mode); -OPENSSL_EXPORT int SSL_get_shutdown(const SSL *ssl); -OPENSSL_EXPORT int SSL_version(const SSL *ssl); -OPENSSL_EXPORT int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx); -OPENSSL_EXPORT int SSL_CTX_load_verify_locations(SSL_CTX *ctx, - const char *CAfile, - const char *CApath); -#define SSL_get0_session SSL_get_session /* just peek at pointer */ -OPENSSL_EXPORT SSL_SESSION *SSL_get_session(const SSL *ssl); -OPENSSL_EXPORT SSL_SESSION *SSL_get1_session( - SSL *ssl); /* obtain a reference count */ -OPENSSL_EXPORT SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl); -OPENSSL_EXPORT SSL_CTX *SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx); -OPENSSL_EXPORT void SSL_set_info_callback(SSL *ssl, - void (*cb)(const SSL *ssl, int type, - int val)); -OPENSSL_EXPORT void (*SSL_get_info_callback(const SSL *ssl))(const SSL *ssl, - int type, int val); -OPENSSL_EXPORT int SSL_state(const SSL *ssl); - -OPENSSL_EXPORT void SSL_set_verify_result(SSL *ssl, long v); -OPENSSL_EXPORT long SSL_get_verify_result(const SSL *ssl); - -OPENSSL_EXPORT int SSL_set_ex_data(SSL *ssl, int idx, void *data); -OPENSSL_EXPORT void *SSL_get_ex_data(const SSL *ssl, int idx); -OPENSSL_EXPORT int SSL_get_ex_new_index(long argl, void *argp, - CRYPTO_EX_new *new_func, - CRYPTO_EX_dup *dup_func, - CRYPTO_EX_free *free_func); - -OPENSSL_EXPORT int SSL_SESSION_set_ex_data(SSL_SESSION *ss, int idx, - void *data); -OPENSSL_EXPORT void *SSL_SESSION_get_ex_data(const SSL_SESSION *ss, int idx); -OPENSSL_EXPORT int SSL_SESSION_get_ex_new_index(long argl, void *argp, - CRYPTO_EX_new *new_func, - CRYPTO_EX_dup *dup_func, - CRYPTO_EX_free *free_func); - -OPENSSL_EXPORT int SSL_CTX_set_ex_data(SSL_CTX *ssl, int idx, void *data); -OPENSSL_EXPORT void *SSL_CTX_get_ex_data(const SSL_CTX *ssl, int idx); -OPENSSL_EXPORT int SSL_CTX_get_ex_new_index(long argl, void *argp, - CRYPTO_EX_new *new_func, - CRYPTO_EX_dup *dup_func, - CRYPTO_EX_free *free_func); - -OPENSSL_EXPORT int SSL_get_ex_data_X509_STORE_CTX_idx(void); - -/* SSL_CTX_sess_set_cache_size sets the maximum size of |ctx|'s session cache to - * |size|. It returns the previous value. */ -OPENSSL_EXPORT unsigned long SSL_CTX_sess_set_cache_size(SSL_CTX *ctx, - unsigned long size); - -/* SSL_CTX_sess_get_cache_size returns the maximum size of |ctx|'s session - * cache. */ -OPENSSL_EXPORT unsigned long SSL_CTX_sess_get_cache_size(const SSL_CTX *ctx); - -/* SSL_SESS_CACHE_* are the possible session cache mode bits. - * TODO(davidben): Document. */ -#define SSL_SESS_CACHE_OFF 0x0000 -#define SSL_SESS_CACHE_CLIENT 0x0001 -#define SSL_SESS_CACHE_SERVER 0x0002 -#define SSL_SESS_CACHE_BOTH (SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_SERVER) -#define SSL_SESS_CACHE_NO_AUTO_CLEAR 0x0080 -#define SSL_SESS_CACHE_NO_INTERNAL_LOOKUP 0x0100 -#define SSL_SESS_CACHE_NO_INTERNAL_STORE 0x0200 -#define SSL_SESS_CACHE_NO_INTERNAL \ - (SSL_SESS_CACHE_NO_INTERNAL_LOOKUP | SSL_SESS_CACHE_NO_INTERNAL_STORE) - -/* SSL_CTX_set_session_cache_mode sets the session cache mode bits for |ctx| to - * |mode|. It returns the previous value. */ -OPENSSL_EXPORT int SSL_CTX_set_session_cache_mode(SSL_CTX *ctx, int mode); - -/* SSL_CTX_get_session_cache_mode returns the session cache mode bits for - * |ctx| */ -OPENSSL_EXPORT int SSL_CTX_get_session_cache_mode(const SSL_CTX *ctx); - -/* SSL_CTX_get_max_cert_list returns the maximum length, in bytes, of a peer - * certificate chain accepted by |ctx|. */ -OPENSSL_EXPORT size_t SSL_CTX_get_max_cert_list(const SSL_CTX *ctx); - -/* SSL_CTX_set_max_cert_list sets the maximum length, in bytes, of a peer - * certificate chain to |max_cert_list|. This affects how much memory may be - * consumed during the handshake. */ -OPENSSL_EXPORT void SSL_CTX_set_max_cert_list(SSL_CTX *ctx, - size_t max_cert_list); - -/* SSL_get_max_cert_list returns the maximum length, in bytes, of a peer - * certificate chain accepted by |ssl|. */ -OPENSSL_EXPORT size_t SSL_get_max_cert_list(const SSL *ssl); - -/* SSL_set_max_cert_list sets the maximum length, in bytes, of a peer - * certificate chain to |max_cert_list|. This affects how much memory may be - * consumed during the handshake. */ -OPENSSL_EXPORT void SSL_set_max_cert_list(SSL *ssl, size_t max_cert_list); - -/* SSL_CTX_set_max_send_fragment sets the maximum length, in bytes, of records - * sent by |ctx|. Beyond this length, handshake messages and application data - * will be split into multiple records. */ -OPENSSL_EXPORT void SSL_CTX_set_max_send_fragment(SSL_CTX *ctx, - size_t max_send_fragment); - -/* SSL_set_max_send_fragment sets the maximum length, in bytes, of records - * sent by |ssl|. Beyond this length, handshake messages and application data - * will be split into multiple records. */ -OPENSSL_EXPORT void SSL_set_max_send_fragment(SSL *ssl, - size_t max_send_fragment); - -/* SSL_CTX_set_tmp_dh_callback configures |ctx| to use |callback| to determine - * the group for DHE ciphers. |callback| should ignore |is_export| and - * |keylength| and return a |DH| of the selected group or NULL on error. Only - * the parameters are used, so the |DH| needn't have a generated keypair. - * - * WARNING: The caller does not take ownership of the resulting |DH|, so - * |callback| must save and release the object elsewhere. */ -OPENSSL_EXPORT void SSL_CTX_set_tmp_dh_callback( - SSL_CTX *ctx, DH *(*callback)(SSL *ssl, int is_export, int keylength)); - -/* SSL_set_tmp_dh_callback configures |ssl| to use |callback| to determine the - * group for DHE ciphers. |callback| should ignore |is_export| and |keylength| - * and return a |DH| of the selected group or NULL on error. Only the - * parameters are used, so the |DH| needn't have a generated keypair. - * - * WARNING: The caller does not take ownership of the resulting |DH|, so - * |callback| must save and release the object elsewhere. */ -OPENSSL_EXPORT void SSL_set_tmp_dh_callback(SSL *ssl, - DH *(*dh)(SSL *ssl, int is_export, - int keylength)); - -/* SSL_CTX_set_tmp_ecdh_callback configures |ctx| to use |callback| to determine - * the curve for ephemeral ECDH keys. |callback| should ignore |is_export| and - * |keylength| and return an |EC_KEY| of the selected curve or NULL on - * error. Only the curve is used, so the |EC_KEY| needn't have a generated - * keypair. - * - * If the callback is unset, an appropriate curve will be chosen automatically. - * (This is recommended.) - * - * WARNING: The caller does not take ownership of the resulting |EC_KEY|, so - * |callback| must save and release the object elsewhere. */ -OPENSSL_EXPORT void SSL_CTX_set_tmp_ecdh_callback( - SSL_CTX *ctx, EC_KEY *(*callback)(SSL *ssl, int is_export, int keylength)); - -/* SSL_set_tmp_ecdh_callback configures |ssl| to use |callback| to determine the - * curve for ephemeral ECDH keys. |callback| should ignore |is_export| and - * |keylength| and return an |EC_KEY| of the selected curve or NULL on - * error. Only the curve is used, so the |EC_KEY| needn't have a generated - * keypair. - * - * If the callback is unset, an appropriate curve will be chosen automatically. - * (This is recommended.) - * - * WARNING: The caller does not take ownership of the resulting |EC_KEY|, so - * |callback| must save and release the object elsewhere. */ -OPENSSL_EXPORT void SSL_set_tmp_ecdh_callback( - SSL *ssl, EC_KEY *(*callback)(SSL *ssl, int is_export, int keylength)); - -OPENSSL_EXPORT const void *SSL_get_current_compression(SSL *s); -OPENSSL_EXPORT const void *SSL_get_current_expansion(SSL *s); - -OPENSSL_EXPORT int SSL_cache_hit(SSL *s); -OPENSSL_EXPORT int SSL_is_server(SSL *s); - -/* SSL_CTX_set_dos_protection_cb sets a callback that is called once the - * resumption decision for a ClientHello has been made. It can return 1 to - * allow the handshake to continue or zero to cause the handshake to abort. */ -OPENSSL_EXPORT void SSL_CTX_set_dos_protection_cb( - SSL_CTX *ctx, int (*cb)(const struct ssl_early_callback_ctx *)); - -/* SSL_get_structure_sizes returns the sizes of the SSL, SSL_CTX and - * SSL_SESSION structures so that a test can ensure that outside code agrees on - * these values. */ -OPENSSL_EXPORT void SSL_get_structure_sizes(size_t *ssl_size, - size_t *ssl_ctx_size, - size_t *ssl_session_size); - -OPENSSL_EXPORT void ERR_load_SSL_strings(void); - -/* SSL_get_rc4_state sets |*read_key| and |*write_key| to the RC4 states for - * the read and write directions. It returns one on success or zero if |ssl| - * isn't using an RC4-based cipher suite. */ -OPENSSL_EXPORT int SSL_get_rc4_state(const SSL *ssl, const RC4_KEY **read_key, - const RC4_KEY **write_key); - - -/* Deprecated functions. */ - -/* SSL_CIPHER_description writes a description of |cipher| into |buf| and - * returns |buf|. If |buf| is NULL, it returns a newly allocated string, to be - * freed with |OPENSSL_free|, or NULL on error. - * - * The description includes a trailing newline and has the form: - * AES128-SHA SSLv3 Kx=RSA Au=RSA Enc=AES(128) Mac=SHA1 - * - * Consider |SSL_CIPHER_get_name| or |SSL_CIPHER_get_rfc_name| instead. */ -OPENSSL_EXPORT const char *SSL_CIPHER_description(const SSL_CIPHER *cipher, - char *buf, int len); - -/* SSL_CIPHER_get_version returns the string "TLSv1/SSLv3". */ -OPENSSL_EXPORT const char *SSL_CIPHER_get_version(const SSL_CIPHER *cipher); - -/* SSL_COMP_get_compression_methods returns NULL. */ -OPENSSL_EXPORT void *SSL_COMP_get_compression_methods(void); - -/* SSL_COMP_add_compression_method returns one. */ -OPENSSL_EXPORT int SSL_COMP_add_compression_method(int id, void *cm); - -/* SSL_COMP_get_name returns NULL. */ -OPENSSL_EXPORT const char *SSL_COMP_get_name(const void *comp); - -/* SSLv23_method calls |TLS_method|. */ -OPENSSL_EXPORT const SSL_METHOD *SSLv23_method(void); - -/* Version-specific methods behave exactly like |TLS_method| and |DTLS_method| - * except they also call |SSL_CTX_set_min_version| and |SSL_CTX_set_max_version| - * to lock connections to that protocol version. */ -OPENSSL_EXPORT const SSL_METHOD *SSLv3_method(void); -OPENSSL_EXPORT const SSL_METHOD *TLSv1_method(void); -OPENSSL_EXPORT const SSL_METHOD *TLSv1_1_method(void); -OPENSSL_EXPORT const SSL_METHOD *TLSv1_2_method(void); -OPENSSL_EXPORT const SSL_METHOD *DTLSv1_method(void); -OPENSSL_EXPORT const SSL_METHOD *DTLSv1_2_method(void); - -/* Client- and server-specific methods call their corresponding generic - * methods. */ -OPENSSL_EXPORT const SSL_METHOD *SSLv23_server_method(void); -OPENSSL_EXPORT const SSL_METHOD *SSLv23_client_method(void); -OPENSSL_EXPORT const SSL_METHOD *SSLv3_server_method(void); -OPENSSL_EXPORT const SSL_METHOD *SSLv3_client_method(void); -OPENSSL_EXPORT const SSL_METHOD *TLSv1_server_method(void); -OPENSSL_EXPORT const SSL_METHOD *TLSv1_client_method(void); -OPENSSL_EXPORT const SSL_METHOD *TLSv1_1_server_method(void); -OPENSSL_EXPORT const SSL_METHOD *TLSv1_1_client_method(void); -OPENSSL_EXPORT const SSL_METHOD *TLSv1_2_server_method(void); -OPENSSL_EXPORT const SSL_METHOD *TLSv1_2_client_method(void); -OPENSSL_EXPORT const SSL_METHOD *DTLS_server_method(void); -OPENSSL_EXPORT const SSL_METHOD *DTLS_client_method(void); -OPENSSL_EXPORT const SSL_METHOD *DTLSv1_server_method(void); -OPENSSL_EXPORT const SSL_METHOD *DTLSv1_client_method(void); -OPENSSL_EXPORT const SSL_METHOD *DTLSv1_2_server_method(void); -OPENSSL_EXPORT const SSL_METHOD *DTLSv1_2_client_method(void); - -/* SSL_clear resets |ssl| to allow another connection and returns one on success - * or zero on failure. It returns most configuration state but releases memory - * associated with the current connection. - * - * Free |ssl| and create a new one instead. */ -OPENSSL_EXPORT int SSL_clear(SSL *ssl); - -/* SSL_CTX_set_tmp_rsa_callback does nothing. */ -OPENSSL_EXPORT void SSL_CTX_set_tmp_rsa_callback( - SSL_CTX *ctx, RSA *(*cb)(SSL *ssl, int is_export, int keylength)); - -/* SSL_set_tmp_rsa_callback does nothing. */ -OPENSSL_EXPORT void SSL_set_tmp_rsa_callback(SSL *ssl, - RSA *(*cb)(SSL *ssl, int is_export, - int keylength)); - -/* SSL_CTX_sess_connect returns zero. */ -OPENSSL_EXPORT int SSL_CTX_sess_connect(const SSL_CTX *ctx); - -/* SSL_CTX_sess_connect_good returns zero. */ -OPENSSL_EXPORT int SSL_CTX_sess_connect_good(const SSL_CTX *ctx); - -/* SSL_CTX_sess_connect_renegotiate returns zero. */ -OPENSSL_EXPORT int SSL_CTX_sess_connect_renegotiate(const SSL_CTX *ctx); - -/* SSL_CTX_sess_accept returns zero. */ -OPENSSL_EXPORT int SSL_CTX_sess_accept(const SSL_CTX *ctx); - -/* SSL_CTX_sess_accept_renegotiate returns zero. */ -OPENSSL_EXPORT int SSL_CTX_sess_accept_renegotiate(const SSL_CTX *ctx); - -/* SSL_CTX_sess_accept_good returns zero. */ -OPENSSL_EXPORT int SSL_CTX_sess_accept_good(const SSL_CTX *ctx); - -/* SSL_CTX_sess_hits returns zero. */ -OPENSSL_EXPORT int SSL_CTX_sess_hits(const SSL_CTX *ctx); - -/* SSL_CTX_sess_cb_hits returns zero. */ -OPENSSL_EXPORT int SSL_CTX_sess_cb_hits(const SSL_CTX *ctx); - -/* SSL_CTX_sess_misses returns zero. */ -OPENSSL_EXPORT int SSL_CTX_sess_misses(const SSL_CTX *ctx); - -/* SSL_CTX_sess_timeouts returns zero. */ -OPENSSL_EXPORT int SSL_CTX_sess_timeouts(const SSL_CTX *ctx); - -/* SSL_CTX_sess_cache_full returns zero. */ -OPENSSL_EXPORT int SSL_CTX_sess_cache_full(const SSL_CTX *ctx); - -/* SSL_cutthrough_complete calls |SSL_in_false_start|. */ -OPENSSL_EXPORT int SSL_cutthrough_complete(const SSL *s); - -/* SSL_num_renegotiations calls |SSL_total_renegotiations|. */ -OPENSSL_EXPORT int SSL_num_renegotiations(const SSL *ssl); - -/* SSL_CTX_need_tmp_RSA returns zero. */ -OPENSSL_EXPORT int SSL_CTX_need_tmp_RSA(const SSL_CTX *ctx); - -/* SSL_need_tmp_RSA returns zero. */ -OPENSSL_EXPORT int SSL_need_tmp_RSA(const SSL *ssl); - -/* SSL_CTX_set_tmp_rsa returns one. */ -OPENSSL_EXPORT int SSL_CTX_set_tmp_rsa(SSL_CTX *ctx, const RSA *rsa); - -/* SSL_set_tmp_rsa returns one. */ -OPENSSL_EXPORT int SSL_set_tmp_rsa(SSL *ssl, const RSA *rsa); - -/* SSL_CTX_get_read_head returns zero. */ -OPENSSL_EXPORT int SSL_CTX_get_read_ahead(const SSL_CTX *ctx); - -/* SSL_CTX_set_read_ahead does nothing. */ -OPENSSL_EXPORT void SSL_CTX_set_read_ahead(SSL_CTX *ctx, int yes); - -/* SSL_get_read_head returns zero. */ -OPENSSL_EXPORT int SSL_get_read_ahead(const SSL *s); - -/* SSL_set_read_ahead does nothing. */ -OPENSSL_EXPORT void SSL_set_read_ahead(SSL *s, int yes); - -/* SSL_renegotiate put an error on the error queue and returns zero. */ -OPENSSL_EXPORT int SSL_renegotiate(SSL *ssl); - -/* SSL_set_state does nothing. */ -OPENSSL_EXPORT void SSL_set_state(SSL *ssl, int state); - - -/* Android compatibility section. - * - * These functions are declared, temporarily, for Android because - * wpa_supplicant will take a little time to sync with upstream. Outside of - * Android they'll have no definition. */ - -#define SSL_F_SSL_SET_SESSION_TICKET_EXT doesnt_exist - -OPENSSL_EXPORT int SSL_set_session_ticket_ext(SSL *s, void *ext_data, - int ext_len); -OPENSSL_EXPORT int SSL_set_session_secret_cb(SSL *s, void *cb, void *arg); -OPENSSL_EXPORT int SSL_set_session_ticket_ext_cb(SSL *s, void *cb, void *arg); -OPENSSL_EXPORT int SSL_set_ssl_method(SSL *s, const SSL_METHOD *method); - -#define OPENSSL_VERSION_TEXT "BoringSSL" - -#define SSLEAY_VERSION 0 - -/* SSLeay_version is a compatibility function that returns the string - * "BoringSSL". */ -OPENSSL_EXPORT const char *SSLeay_version(int unused); - - -/* Preprocessor compatibility section. - * - * Historically, a number of APIs were implemented in OpenSSL as macros and - * constants to 'ctrl' functions. To avoid breaking #ifdefs in consumers, this - * section defines a number of legacy macros. */ - -#define SSL_CTRL_NEED_TMP_RSA doesnt_exist -#define SSL_CTRL_SET_TMP_RSA doesnt_exist -#define SSL_CTRL_SET_TMP_DH doesnt_exist -#define SSL_CTRL_SET_TMP_ECDH doesnt_exist -#define SSL_CTRL_SET_TMP_RSA_CB doesnt_exist -#define SSL_CTRL_SET_TMP_DH_CB doesnt_exist -#define SSL_CTRL_SET_TMP_ECDH_CB doesnt_exist -#define SSL_CTRL_GET_SESSION_REUSED doesnt_exist -#define SSL_CTRL_GET_NUM_RENEGOTIATIONS doesnt_exist -#define SSL_CTRL_GET_TOTAL_RENEGOTIATIONS doesnt_exist -#define SSL_CTRL_SET_MSG_CALLBACK doesnt_exist -#define SSL_CTRL_SET_MSG_CALLBACK_ARG doesnt_exist -#define SSL_CTRL_SET_MTU doesnt_exist -#define SSL_CTRL_SESS_NUMBER doesnt_exist -#define SSL_CTRL_OPTIONS doesnt_exist -#define SSL_CTRL_MODE doesnt_exist -#define SSL_CTRL_GET_READ_AHEAD doesnt_exist -#define SSL_CTRL_SET_READ_AHEAD doesnt_exist -#define SSL_CTRL_SET_SESS_CACHE_SIZE doesnt_exist -#define SSL_CTRL_GET_SESS_CACHE_SIZE doesnt_exist -#define SSL_CTRL_SET_SESS_CACHE_MODE doesnt_exist -#define SSL_CTRL_GET_SESS_CACHE_MODE doesnt_exist -#define SSL_CTRL_GET_MAX_CERT_LIST doesnt_exist -#define SSL_CTRL_SET_MAX_CERT_LIST doesnt_exist -#define SSL_CTRL_SET_MAX_SEND_FRAGMENT doesnt_exist -#define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB doesnt_exist -#define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG doesnt_exist -#define SSL_CTRL_SET_TLSEXT_HOSTNAME doesnt_exist -#define SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB doesnt_exist -#define DTLS_CTRL_GET_TIMEOUT doesnt_exist -#define DTLS_CTRL_HANDLE_TIMEOUT doesnt_exist -#define SSL_CTRL_GET_RI_SUPPORT doesnt_exist -#define SSL_CTRL_CLEAR_OPTIONS doesnt_exist -#define SSL_CTRL_CLEAR_MODE doesnt_exist -#define SSL_CTRL_CHANNEL_ID doesnt_exist -#define SSL_CTRL_GET_CHANNEL_ID doesnt_exist -#define SSL_CTRL_SET_CHANNEL_ID doesnt_exist - -#define SSL_CTX_need_tmp_RSA SSL_CTX_need_tmp_RSA -#define SSL_need_tmp_RSA SSL_need_tmp_RSA -#define SSL_CTX_set_tmp_rsa SSL_CTX_set_tmp_rsa -#define SSL_set_tmp_rsa SSL_set_tmp_rsa -#define SSL_CTX_set_tmp_dh SSL_CTX_set_tmp_dh -#define SSL_set_tmp_dh SSL_set_tmp_dh -#define SSL_CTX_set_tmp_ecdh SSL_CTX_set_tmp_ecdh -#define SSL_set_tmp_ecdh SSL_set_tmp_ecdh -#define SSL_session_reused SSL_session_reused -#define SSL_num_renegotiations SSL_num_renegotiations -#define SSL_total_renegotiations SSL_total_renegotiations -#define SSL_CTX_set_msg_callback_arg SSL_CTX_set_msg_callback_arg -#define SSL_set_msg_callback_arg SSL_set_msg_callback_arg -#define SSL_set_mtu SSL_set_mtu -#define SSL_CTX_sess_number SSL_CTX_sess_number -#define SSL_CTX_get_options SSL_CTX_get_options -#define SSL_CTX_set_options SSL_CTX_set_options -#define SSL_get_options SSL_get_options -#define SSL_set_options SSL_set_options -#define SSL_CTX_get_mode SSL_CTX_get_mode -#define SSL_CTX_set_mode SSL_CTX_set_mode -#define SSL_get_mode SSL_get_mode -#define SSL_set_mode SSL_set_mode -#define SSL_CTX_get_read_ahead SSL_CTX_get_read_ahead -#define SSL_CTX_set_read_ahead SSL_CTX_set_read_ahead -#define SSL_CTX_sess_set_cache_size SSL_CTX_sess_set_cache_size -#define SSL_CTX_sess_get_cache_size SSL_CTX_sess_get_cache_size -#define SSL_CTX_set_session_cache_mode SSL_CTX_set_session_cache_mode -#define SSL_CTX_get_session_cache_mode SSL_CTX_get_session_cache_mode -#define SSL_CTX_get_max_cert_list SSL_CTX_get_max_cert_list -#define SSL_get_max_cert_list SSL_get_max_cert_list -#define SSL_CTX_set_max_cert_list SSL_CTX_set_max_cert_list -#define SSL_set_max_cert_list SSL_set_max_cert_list -#define SSL_CTX_set_max_send_fragment SSL_CTX_set_max_send_fragment -#define SSL_set_max_send_fragment SSL_set_max_send_fragment -#define SSL_CTX_set_tlsext_servername_callback \ - SSL_CTX_set_tlsext_servername_callback -#define SSL_CTX_set_tlsext_servername_arg SSL_CTX_set_tlsext_servername_arg -#define SSL_set_tlsext_host_name SSL_set_tlsext_host_name -#define SSL_CTX_set_tlsext_ticket_key_cb SSL_CTX_set_tlsext_ticket_key_cb -#define DTLSv1_get_timeout DTLSv1_get_timeout -#define DTLSv1_handle_timeout DTLSv1_handle_timeout -#define SSL_get_secure_renegotiation_support \ - SSL_get_secure_renegotiation_support -#define SSL_CTX_clear_options SSL_CTX_clear_options -#define SSL_clear_options SSL_clear_options -#define SSL_CTX_clear_mode SSL_CTX_clear_mode -#define SSL_clear_mode SSL_clear_mode -#define SSL_CTX_enable_tls_channel_id SSL_CTX_enable_tls_channel_id -#define SSL_enable_tls_channel_id SSL_enable_tls_channel_id -#define SSL_set1_tls_channel_id SSL_set1_tls_channel_id -#define SSL_CTX_set1_tls_channel_id SSL_CTX_set1_tls_channel_id -#define SSL_get_tls_channel_id SSL_get_tls_channel_id - - -#if defined(__cplusplus) -} /* extern C */ -#endif - - -/* Library consumers assume these headers are included by ssl.h, but they depend - * on ssl.h, so include them after all declarations. - * - * TODO(davidben): The separation between ssl.h and these version-specific - * headers introduces circular dependencies and is inconsistent. The function - * declarations should move to ssl.h. Many of the constants can probably be - * pruned or unexported. */ -#include -#include -#include /* This is mostly sslv3 with a few tweaks */ -#include -#include /* Support for the use_srtp extension */ - - -/* BEGIN ERROR CODES */ -/* The following lines are auto generated by the script make_errors.go. Any - * changes made after this point may be overwritten when the script is next run. - */ -#define SSL_F_SSL_CTX_check_private_key 100 -#define SSL_F_SSL_CTX_new 101 -#define SSL_F_SSL_CTX_set_cipher_list 102 -#define SSL_F_SSL_CTX_set_cipher_list_tls11 103 -#define SSL_F_SSL_CTX_set_session_id_context 104 -#define SSL_F_SSL_CTX_use_PrivateKey 105 -#define SSL_F_SSL_CTX_use_PrivateKey_ASN1 106 -#define SSL_F_SSL_CTX_use_PrivateKey_file 107 -#define SSL_F_SSL_CTX_use_RSAPrivateKey 108 -#define SSL_F_SSL_CTX_use_RSAPrivateKey_ASN1 109 -#define SSL_F_SSL_CTX_use_RSAPrivateKey_file 110 -#define SSL_F_SSL_CTX_use_certificate 111 -#define SSL_F_SSL_CTX_use_certificate_ASN1 112 -#define SSL_F_SSL_CTX_use_certificate_chain_file 113 -#define SSL_F_SSL_CTX_use_certificate_file 114 -#define SSL_F_SSL_CTX_use_psk_identity_hint 115 -#define SSL_F_SSL_SESSION_new 116 -#define SSL_F_SSL_SESSION_print_fp 117 -#define SSL_F_SSL_SESSION_set1_id_context 118 -#define SSL_F_SSL_SESSION_to_bytes_full 119 -#define SSL_F_SSL_accept 120 -#define SSL_F_SSL_add_dir_cert_subjects_to_stack 121 -#define SSL_F_SSL_add_file_cert_subjects_to_stack 122 -#define SSL_F_SSL_check_private_key 123 -#define SSL_F_SSL_clear 124 -#define SSL_F_SSL_connect 125 -#define SSL_F_SSL_do_handshake 126 -#define SSL_F_SSL_load_client_CA_file 127 -#define SSL_F_SSL_new 128 -#define SSL_F_SSL_peek 129 -#define SSL_F_SSL_read 130 -#define SSL_F_SSL_renegotiate 131 -#define SSL_F_SSL_set_cipher_list 132 -#define SSL_F_SSL_set_fd 133 -#define SSL_F_SSL_set_rfd 134 -#define SSL_F_SSL_set_session_id_context 135 -#define SSL_F_SSL_set_wfd 136 -#define SSL_F_SSL_shutdown 137 -#define SSL_F_SSL_use_PrivateKey 138 -#define SSL_F_SSL_use_PrivateKey_ASN1 139 -#define SSL_F_SSL_use_PrivateKey_file 140 -#define SSL_F_SSL_use_RSAPrivateKey 141 -#define SSL_F_SSL_use_RSAPrivateKey_ASN1 142 -#define SSL_F_SSL_use_RSAPrivateKey_file 143 -#define SSL_F_SSL_use_certificate 144 -#define SSL_F_SSL_use_certificate_ASN1 145 -#define SSL_F_SSL_use_certificate_file 146 -#define SSL_F_SSL_use_psk_identity_hint 147 -#define SSL_F_SSL_write 148 -#define SSL_F_d2i_SSL_SESSION 149 -#define SSL_F_d2i_SSL_SESSION_get_octet_string 150 -#define SSL_F_d2i_SSL_SESSION_get_string 151 -#define SSL_F_do_ssl3_write 152 -#define SSL_F_dtls1_accept 153 -#define SSL_F_dtls1_buffer_record 154 -#define SSL_F_dtls1_check_timeout_num 155 -#define SSL_F_dtls1_connect 156 -#define SSL_F_dtls1_do_write 157 -#define SSL_F_dtls1_get_hello_verify 158 -#define SSL_F_dtls1_get_message 159 -#define SSL_F_dtls1_get_message_fragment 160 -#define SSL_F_dtls1_preprocess_fragment 161 -#define SSL_F_dtls1_process_record 162 -#define SSL_F_dtls1_read_bytes 163 -#define SSL_F_dtls1_send_hello_verify_request 164 -#define SSL_F_dtls1_write_app_data 165 -#define SSL_F_i2d_SSL_SESSION 166 -#define SSL_F_ssl3_accept 167 -#define SSL_F_ssl3_cert_verify_hash 169 -#define SSL_F_ssl3_check_cert_and_algorithm 170 -#define SSL_F_ssl3_connect 171 -#define SSL_F_ssl3_ctrl 172 -#define SSL_F_ssl3_ctx_ctrl 173 -#define SSL_F_ssl3_digest_cached_records 174 -#define SSL_F_ssl3_do_change_cipher_spec 175 -#define SSL_F_ssl3_expect_change_cipher_spec 176 -#define SSL_F_ssl3_get_cert_status 177 -#define SSL_F_ssl3_get_cert_verify 178 -#define SSL_F_ssl3_get_certificate_request 179 -#define SSL_F_ssl3_get_channel_id 180 -#define SSL_F_ssl3_get_client_certificate 181 -#define SSL_F_ssl3_get_client_hello 182 -#define SSL_F_ssl3_get_client_key_exchange 183 -#define SSL_F_ssl3_get_finished 184 -#define SSL_F_ssl3_get_initial_bytes 185 -#define SSL_F_ssl3_get_message 186 -#define SSL_F_ssl3_get_new_session_ticket 187 -#define SSL_F_ssl3_get_next_proto 188 -#define SSL_F_ssl3_get_record 189 -#define SSL_F_ssl3_get_server_certificate 190 -#define SSL_F_ssl3_get_server_done 191 -#define SSL_F_ssl3_get_server_hello 192 -#define SSL_F_ssl3_get_server_key_exchange 193 -#define SSL_F_ssl3_get_v2_client_hello 194 -#define SSL_F_ssl3_handshake_mac 195 -#define SSL_F_ssl3_prf 196 -#define SSL_F_ssl3_read_bytes 197 -#define SSL_F_ssl3_read_n 198 -#define SSL_F_ssl3_send_cert_verify 199 -#define SSL_F_ssl3_send_certificate_request 200 -#define SSL_F_ssl3_send_channel_id 201 -#define SSL_F_ssl3_send_client_certificate 202 -#define SSL_F_ssl3_send_client_hello 203 -#define SSL_F_ssl3_send_client_key_exchange 204 -#define SSL_F_ssl3_send_server_certificate 205 -#define SSL_F_ssl3_send_server_hello 206 -#define SSL_F_ssl3_send_server_key_exchange 207 -#define SSL_F_ssl3_setup_read_buffer 208 -#define SSL_F_ssl3_setup_write_buffer 209 -#define SSL_F_ssl3_write_bytes 210 -#define SSL_F_ssl3_write_pending 211 -#define SSL_F_ssl_add_cert_chain 212 -#define SSL_F_ssl_add_cert_to_buf 213 -#define SSL_F_ssl_add_clienthello_renegotiate_ext 214 -#define SSL_F_ssl_add_clienthello_tlsext 215 -#define SSL_F_ssl_add_clienthello_use_srtp_ext 216 -#define SSL_F_ssl_add_serverhello_renegotiate_ext 217 -#define SSL_F_ssl_add_serverhello_tlsext 218 -#define SSL_F_ssl_add_serverhello_use_srtp_ext 219 -#define SSL_F_ssl_build_cert_chain 220 -#define SSL_F_ssl_bytes_to_cipher_list 221 -#define SSL_F_ssl_cert_dup 222 -#define SSL_F_ssl_cert_inst 223 -#define SSL_F_ssl_cert_new 224 -#define SSL_F_ssl_check_serverhello_tlsext 225 -#define SSL_F_ssl_check_srvr_ecc_cert_and_alg 226 -#define SSL_F_ssl_cipher_process_rulestr 227 -#define SSL_F_ssl_cipher_strength_sort 228 -#define SSL_F_ssl_create_cipher_list 229 -#define SSL_F_ssl_ctx_log_master_secret 230 -#define SSL_F_ssl_ctx_log_rsa_client_key_exchange 231 -#define SSL_F_ssl_ctx_make_profiles 232 -#define SSL_F_ssl_get_new_session 233 -#define SSL_F_ssl_get_prev_session 234 -#define SSL_F_ssl_get_server_cert_index 235 -#define SSL_F_ssl_get_sign_pkey 236 -#define SSL_F_ssl_init_wbio_buffer 237 -#define SSL_F_ssl_parse_clienthello_renegotiate_ext 238 -#define SSL_F_ssl_parse_clienthello_tlsext 239 -#define SSL_F_ssl_parse_clienthello_use_srtp_ext 240 -#define SSL_F_ssl_parse_serverhello_renegotiate_ext 241 -#define SSL_F_ssl_parse_serverhello_tlsext 242 -#define SSL_F_ssl_parse_serverhello_use_srtp_ext 243 -#define SSL_F_ssl_scan_clienthello_tlsext 244 -#define SSL_F_ssl_scan_serverhello_tlsext 245 -#define SSL_F_ssl_sess_cert_new 246 -#define SSL_F_ssl_set_cert 247 -#define SSL_F_ssl_set_pkey 248 -#define SSL_F_ssl_verify_cert_chain 252 -#define SSL_F_tls12_check_peer_sigalg 253 -#define SSL_F_tls1_aead_ctx_init 254 -#define SSL_F_tls1_cert_verify_mac 255 -#define SSL_F_tls1_change_cipher_state 256 -#define SSL_F_tls1_change_cipher_state_aead 257 -#define SSL_F_tls1_check_duplicate_extensions 258 -#define SSL_F_tls1_enc 259 -#define SSL_F_tls1_export_keying_material 260 -#define SSL_F_tls1_prf 261 -#define SSL_F_tls1_setup_key_block 262 -#define SSL_F_dtls1_get_buffered_message 263 -#define SSL_F_dtls1_process_fragment 264 -#define SSL_F_dtls1_hm_fragment_new 265 -#define SSL_F_ssl3_seal_record 266 -#define SSL_F_ssl3_record_sequence_update 267 -#define SSL_F_SSL_CTX_set_tmp_dh 268 -#define SSL_F_SSL_CTX_set_tmp_ecdh 269 -#define SSL_F_SSL_set_tmp_dh 270 -#define SSL_F_SSL_set_tmp_ecdh 271 -#define SSL_F_SSL_CTX_set1_tls_channel_id 272 -#define SSL_F_SSL_set1_tls_channel_id 273 -#define SSL_F_SSL_set_tlsext_host_name 274 -#define SSL_F_ssl3_output_cert_chain 275 -#define SSL_F_SSL_AEAD_CTX_new 276 -#define SSL_F_SSL_AEAD_CTX_open 277 -#define SSL_F_SSL_AEAD_CTX_seal 278 -#define SSL_F_dtls1_seal_record 279 -#define SSL_R_APP_DATA_IN_HANDSHAKE 100 -#define SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT 101 -#define SSL_R_BAD_ALERT 102 -#define SSL_R_BAD_CHANGE_CIPHER_SPEC 103 -#define SSL_R_BAD_DATA_RETURNED_BY_CALLBACK 104 -#define SSL_R_BAD_DH_P_LENGTH 105 -#define SSL_R_BAD_DIGEST_LENGTH 106 -#define SSL_R_BAD_ECC_CERT 107 -#define SSL_R_BAD_ECPOINT 108 -#define SSL_R_BAD_HANDSHAKE_LENGTH 109 -#define SSL_R_BAD_HANDSHAKE_RECORD 110 -#define SSL_R_BAD_HELLO_REQUEST 111 -#define SSL_R_BAD_LENGTH 112 -#define SSL_R_BAD_PACKET_LENGTH 113 -#define SSL_R_BAD_RSA_ENCRYPT 114 -#define SSL_R_BAD_SIGNATURE 115 -#define SSL_R_BAD_SRTP_MKI_VALUE 116 -#define SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST 117 -#define SSL_R_BAD_SSL_FILETYPE 118 -#define SSL_R_BAD_WRITE_RETRY 119 -#define SSL_R_BIO_NOT_SET 120 -#define SSL_R_BN_LIB 121 -#define SSL_R_CANNOT_SERIALIZE_PUBLIC_KEY 122 -#define SSL_R_CA_DN_LENGTH_MISMATCH 123 -#define SSL_R_CA_DN_TOO_LONG 124 -#define SSL_R_CCS_RECEIVED_EARLY 125 -#define SSL_R_CERTIFICATE_VERIFY_FAILED 126 -#define SSL_R_CERT_CB_ERROR 127 -#define SSL_R_CERT_LENGTH_MISMATCH 128 -#define SSL_R_CHANNEL_ID_NOT_P256 129 -#define SSL_R_CHANNEL_ID_SIGNATURE_INVALID 130 -#define SSL_R_CIPHER_CODE_WRONG_LENGTH 131 -#define SSL_R_CIPHER_OR_HASH_UNAVAILABLE 132 -#define SSL_R_CLIENTHELLO_PARSE_FAILED 133 -#define SSL_R_CLIENTHELLO_TLSEXT 134 -#define SSL_R_CONNECTION_REJECTED 135 -#define SSL_R_CONNECTION_TYPE_NOT_SET 136 -#define SSL_R_COOKIE_MISMATCH 137 -#define SSL_R_D2I_ECDSA_SIG 138 -#define SSL_R_DATA_BETWEEN_CCS_AND_FINISHED 139 -#define SSL_R_DATA_LENGTH_TOO_LONG 140 -#define SSL_R_DECODE_ERROR 141 -#define SSL_R_DECRYPTION_FAILED 142 -#define SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC 143 -#define SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG 144 -#define SSL_R_DIGEST_CHECK_FAILED 145 -#define SSL_R_DTLS_MESSAGE_TOO_BIG 146 -#define SSL_R_ECC_CERT_NOT_FOR_SIGNING 147 -#define SSL_R_EMPTY_SRTP_PROTECTION_PROFILE_LIST 148 -#define SSL_R_ENCRYPTED_LENGTH_TOO_LONG 149 -#define SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST 150 -#define SSL_R_EVP_DIGESTSIGNFINAL_FAILED 151 -#define SSL_R_EVP_DIGESTSIGNINIT_FAILED 152 -#define SSL_R_EXCESSIVE_MESSAGE_SIZE 153 -#define SSL_R_EXTRA_DATA_IN_MESSAGE 154 -#define SSL_R_GOT_A_FIN_BEFORE_A_CCS 155 -#define SSL_R_GOT_CHANNEL_ID_BEFORE_A_CCS 156 -#define SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS 157 -#define SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION 158 -#define SSL_R_HANDSHAKE_FAILURE_ON_CLIENT_HELLO 159 -#define SSL_R_HANDSHAKE_RECORD_BEFORE_CCS 160 -#define SSL_R_HTTPS_PROXY_REQUEST 161 -#define SSL_R_HTTP_REQUEST 162 -#define SSL_R_INAPPROPRIATE_FALLBACK 163 -#define SSL_R_INVALID_COMMAND 164 -#define SSL_R_INVALID_MESSAGE 165 -#define SSL_R_INVALID_SSL_SESSION 166 -#define SSL_R_INVALID_TICKET_KEYS_LENGTH 167 -#define SSL_R_LENGTH_MISMATCH 168 -#define SSL_R_LIBRARY_HAS_NO_CIPHERS 169 -#define SSL_R_MISSING_DH_KEY 170 -#define SSL_R_MISSING_ECDSA_SIGNING_CERT 171 -#define SSL_R_MISSING_RSA_CERTIFICATE 172 -#define SSL_R_MISSING_RSA_ENCRYPTING_CERT 173 -#define SSL_R_MISSING_RSA_SIGNING_CERT 174 -#define SSL_R_MISSING_TMP_DH_KEY 175 -#define SSL_R_MISSING_TMP_ECDH_KEY 176 -#define SSL_R_MIXED_SPECIAL_OPERATOR_WITH_GROUPS 177 -#define SSL_R_MTU_TOO_SMALL 178 -#define SSL_R_NESTED_GROUP 179 -#define SSL_R_NO_CERTIFICATES_RETURNED 180 -#define SSL_R_NO_CERTIFICATE_ASSIGNED 181 -#define SSL_R_NO_CERTIFICATE_SET 182 -#define SSL_R_NO_CIPHERS_AVAILABLE 183 -#define SSL_R_NO_CIPHERS_PASSED 184 -#define SSL_R_NO_CIPHERS_SPECIFIED 185 -#define SSL_R_NO_CIPHER_MATCH 186 -#define SSL_R_NO_COMPRESSION_SPECIFIED 187 -#define SSL_R_NO_METHOD_SPECIFIED 188 -#define SSL_R_NO_P256_SUPPORT 189 -#define SSL_R_NO_PRIVATE_KEY_ASSIGNED 190 -#define SSL_R_NO_RENEGOTIATION 191 -#define SSL_R_NO_REQUIRED_DIGEST 192 -#define SSL_R_NO_SHARED_CIPHER 193 -#define SSL_R_NO_SHARED_SIGATURE_ALGORITHMS 194 -#define SSL_R_NO_SRTP_PROFILES 195 -#define SSL_R_NULL_SSL_CTX 196 -#define SSL_R_NULL_SSL_METHOD_PASSED 197 -#define SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED 198 -#define SSL_R_PACKET_LENGTH_TOO_LONG 199 -#define SSL_R_PARSE_TLSEXT 200 -#define SSL_R_PATH_TOO_LONG 201 -#define SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE 202 -#define SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE 203 -#define SSL_R_PROTOCOL_IS_SHUTDOWN 204 -#define SSL_R_PSK_IDENTITY_NOT_FOUND 205 -#define SSL_R_PSK_NO_CLIENT_CB 206 -#define SSL_R_PSK_NO_SERVER_CB 207 -#define SSL_R_READ_BIO_NOT_SET 208 -#define SSL_R_READ_TIMEOUT_EXPIRED 209 -#define SSL_R_RECORD_LENGTH_MISMATCH 210 -#define SSL_R_RECORD_TOO_LARGE 211 -#define SSL_R_RENEGOTIATE_EXT_TOO_LONG 212 -#define SSL_R_RENEGOTIATION_ENCODING_ERR 213 -#define SSL_R_RENEGOTIATION_MISMATCH 214 -#define SSL_R_REQUIRED_CIPHER_MISSING 215 -#define SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING 216 -#define SSL_R_SERVERHELLO_TLSEXT 217 -#define SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED 218 -#define SSL_R_SESSION_MAY_NOT_BE_CREATED 219 -#define SSL_R_SIGNATURE_ALGORITHMS_ERROR 220 -#define SSL_R_SRTP_COULD_NOT_ALLOCATE_PROFILES 221 -#define SSL_R_SRTP_PROTECTION_PROFILE_LIST_TOO_LONG 222 -#define SSL_R_SRTP_UNKNOWN_PROTECTION_PROFILE 223 -#define SSL_R_SSL3_EXT_INVALID_SERVERNAME 224 -#define SSL_R_SSL3_EXT_INVALID_SERVERNAME_TYPE 225 -#define SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION 226 -#define SSL_R_SSL_HANDSHAKE_FAILURE 227 -#define SSL_R_SSL_SESSION_ID_CALLBACK_FAILED 228 -#define SSL_R_SSL_SESSION_ID_CONFLICT 229 -#define SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG 230 -#define SSL_R_SSL_SESSION_ID_HAS_BAD_LENGTH 231 -#define SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER 232 -#define SSL_R_TLS_ILLEGAL_EXPORTER_LABEL 233 -#define SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST 234 -#define SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST 235 -#define SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG 236 -#define SSL_R_TOO_MANY_EMPTY_FRAGMENTS 237 -#define SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS 238 -#define SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS 239 -#define SSL_R_UNEXPECTED_GROUP_CLOSE 240 -#define SSL_R_UNEXPECTED_MESSAGE 241 -#define SSL_R_UNEXPECTED_OPERATOR_IN_GROUP 242 -#define SSL_R_UNEXPECTED_RECORD 243 -#define SSL_R_UNINITIALIZED 244 -#define SSL_R_UNKNOWN_ALERT_TYPE 245 -#define SSL_R_UNKNOWN_CERTIFICATE_TYPE 246 -#define SSL_R_UNKNOWN_CIPHER_RETURNED 247 -#define SSL_R_UNKNOWN_CIPHER_TYPE 248 -#define SSL_R_UNKNOWN_DIGEST 249 -#define SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE 250 -#define SSL_R_UNKNOWN_PROTOCOL 251 -#define SSL_R_UNKNOWN_SSL_VERSION 252 -#define SSL_R_UNKNOWN_STATE 253 -#define SSL_R_UNPROCESSED_HANDSHAKE_DATA 254 -#define SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED 255 -#define SSL_R_UNSUPPORTED_CIPHER 256 -#define SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM 257 -#define SSL_R_UNSUPPORTED_ELLIPTIC_CURVE 258 -#define SSL_R_UNSUPPORTED_PROTOCOL 259 -#define SSL_R_UNSUPPORTED_SSL_VERSION 260 -#define SSL_R_USE_SRTP_NOT_NEGOTIATED 261 -#define SSL_R_WRONG_CERTIFICATE_TYPE 262 -#define SSL_R_WRONG_CIPHER_RETURNED 263 -#define SSL_R_WRONG_CURVE 264 -#define SSL_R_WRONG_MESSAGE_TYPE 265 -#define SSL_R_WRONG_SIGNATURE_TYPE 266 -#define SSL_R_WRONG_SSL_VERSION 267 -#define SSL_R_WRONG_VERSION_NUMBER 268 -#define SSL_R_X509_LIB 269 -#define SSL_R_X509_VERIFICATION_SETUP_PROBLEMS 270 -#define SSL_R_FRAGMENT_MISMATCH 271 -#define SSL_R_BUFFER_TOO_SMALL 272 -#define SSL_R_OLD_SESSION_VERSION_NOT_RETURNED 273 -#define SSL_R_OUTPUT_ALIASES_INPUT 274 -#define SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION 275 -#define SSL_R_EMS_STATE_INCONSISTENT 276 -#define SSL_R_RESUMED_NON_EMS_SESSION_WITH_EMS_EXTENSION 277 -#define SSL_R_SSLV3_ALERT_CLOSE_NOTIFY 1000 -#define SSL_R_SSLV3_ALERT_UNEXPECTED_MESSAGE 1010 -#define SSL_R_SSLV3_ALERT_BAD_RECORD_MAC 1020 -#define SSL_R_TLSV1_ALERT_DECRYPTION_FAILED 1021 -#define SSL_R_TLSV1_ALERT_RECORD_OVERFLOW 1022 -#define SSL_R_SSLV3_ALERT_DECOMPRESSION_FAILURE 1030 -#define SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE 1040 -#define SSL_R_SSLV3_ALERT_NO_CERTIFICATE 1041 -#define SSL_R_SSLV3_ALERT_BAD_CERTIFICATE 1042 -#define SSL_R_SSLV3_ALERT_UNSUPPORTED_CERTIFICATE 1043 -#define SSL_R_SSLV3_ALERT_CERTIFICATE_REVOKED 1044 -#define SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED 1045 -#define SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN 1046 -#define SSL_R_SSLV3_ALERT_ILLEGAL_PARAMETER 1047 -#define SSL_R_TLSV1_ALERT_UNKNOWN_CA 1048 -#define SSL_R_TLSV1_ALERT_ACCESS_DENIED 1049 -#define SSL_R_TLSV1_ALERT_DECODE_ERROR 1050 -#define SSL_R_TLSV1_ALERT_DECRYPT_ERROR 1051 -#define SSL_R_TLSV1_ALERT_EXPORT_RESTRICTION 1060 -#define SSL_R_TLSV1_ALERT_PROTOCOL_VERSION 1070 -#define SSL_R_TLSV1_ALERT_INSUFFICIENT_SECURITY 1071 -#define SSL_R_TLSV1_ALERT_INTERNAL_ERROR 1080 -#define SSL_R_TLSV1_ALERT_INAPPROPRIATE_FALLBACK 1086 -#define SSL_R_TLSV1_ALERT_USER_CANCELLED 1090 -#define SSL_R_TLSV1_ALERT_NO_RENEGOTIATION 1100 -#define SSL_R_TLSV1_UNSUPPORTED_EXTENSION 1110 -#define SSL_R_TLSV1_CERTIFICATE_UNOBTAINABLE 1111 -#define SSL_R_TLSV1_UNRECOGNIZED_NAME 1112 -#define SSL_R_TLSV1_BAD_CERTIFICATE_STATUS_RESPONSE 1113 -#define SSL_R_TLSV1_BAD_CERTIFICATE_HASH_VALUE 1114 - -#endif /* OPENSSL_HEADER_SSL_H */ diff --git a/third_party/boringssl/include/openssl/ssl2.h b/third_party/boringssl/include/openssl/ssl2.h deleted file mode 100644 index b8401faaf6..0000000000 --- a/third_party/boringssl/include/openssl/ssl2.h +++ /dev/null @@ -1,268 +0,0 @@ -/* ssl/ssl2.h */ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] - */ - -#ifndef HEADER_SSL2_H -#define HEADER_SSL2_H - -#ifdef __cplusplus -extern "C" { -#endif - -/* Protocol Version Codes */ -#define SSL2_VERSION 0x0002 -#define SSL2_VERSION_MAJOR 0x00 -#define SSL2_VERSION_MINOR 0x02 -/* #define SSL2_CLIENT_VERSION 0x0002 */ -/* #define SSL2_SERVER_VERSION 0x0002 */ - -/* Protocol Message Codes */ -#define SSL2_MT_ERROR 0 -#define SSL2_MT_CLIENT_HELLO 1 -#define SSL2_MT_CLIENT_MASTER_KEY 2 -#define SSL2_MT_CLIENT_FINISHED 3 -#define SSL2_MT_SERVER_HELLO 4 -#define SSL2_MT_SERVER_VERIFY 5 -#define SSL2_MT_SERVER_FINISHED 6 -#define SSL2_MT_REQUEST_CERTIFICATE 7 -#define SSL2_MT_CLIENT_CERTIFICATE 8 - -/* Error Message Codes */ -#define SSL2_PE_UNDEFINED_ERROR 0x0000 -#define SSL2_PE_NO_CIPHER 0x0001 -#define SSL2_PE_NO_CERTIFICATE 0x0002 -#define SSL2_PE_BAD_CERTIFICATE 0x0004 -#define SSL2_PE_UNSUPPORTED_CERTIFICATE_TYPE 0x0006 - -/* Cipher Kind Values */ -#define SSL2_CK_NULL_WITH_MD5 0x02000000 /* v3 */ -#define SSL2_CK_RC4_128_WITH_MD5 0x02010080 -#define SSL2_CK_RC4_128_EXPORT40_WITH_MD5 0x02020080 -#define SSL2_CK_RC2_128_CBC_WITH_MD5 0x02030080 -#define SSL2_CK_RC2_128_CBC_EXPORT40_WITH_MD5 0x02040080 -#define SSL2_CK_IDEA_128_CBC_WITH_MD5 0x02050080 -#define SSL2_CK_DES_64_CBC_WITH_MD5 0x02060040 -#define SSL2_CK_DES_64_CBC_WITH_SHA 0x02060140 /* v3 */ -#define SSL2_CK_DES_192_EDE3_CBC_WITH_MD5 0x020700c0 -#define SSL2_CK_DES_192_EDE3_CBC_WITH_SHA 0x020701c0 /* v3 */ -#define SSL2_CK_RC4_64_WITH_MD5 0x02080080 /* MS hack */ - -#define SSL2_CK_DES_64_CFB64_WITH_MD5_1 0x02ff0800 /* SSLeay */ -#define SSL2_CK_NULL 0x02ff0810 /* SSLeay */ - -#define SSL2_TXT_DES_64_CFB64_WITH_MD5_1 "DES-CFB-M1" -#define SSL2_TXT_NULL_WITH_MD5 "NULL-MD5" -#define SSL2_TXT_RC4_128_WITH_MD5 "RC4-MD5" -#define SSL2_TXT_RC4_128_EXPORT40_WITH_MD5 "EXP-RC4-MD5" -#define SSL2_TXT_RC2_128_CBC_WITH_MD5 "RC2-CBC-MD5" -#define SSL2_TXT_RC2_128_CBC_EXPORT40_WITH_MD5 "EXP-RC2-CBC-MD5" -#define SSL2_TXT_IDEA_128_CBC_WITH_MD5 "IDEA-CBC-MD5" -#define SSL2_TXT_DES_64_CBC_WITH_MD5 "DES-CBC-MD5" -#define SSL2_TXT_DES_64_CBC_WITH_SHA "DES-CBC-SHA" -#define SSL2_TXT_DES_192_EDE3_CBC_WITH_MD5 "DES-CBC3-MD5" -#define SSL2_TXT_DES_192_EDE3_CBC_WITH_SHA "DES-CBC3-SHA" -#define SSL2_TXT_RC4_64_WITH_MD5 "RC4-64-MD5" - -#define SSL2_TXT_NULL "NULL" - -/* Flags for the SSL_CIPHER.algorithm2 field */ -#define SSL2_CF_5_BYTE_ENC 0x01 -#define SSL2_CF_8_BYTE_ENC 0x02 - -/* Certificate Type Codes */ -#define SSL2_CT_X509_CERTIFICATE 0x01 - -/* Authentication Type Code */ -#define SSL2_AT_MD5_WITH_RSA_ENCRYPTION 0x01 - -#define SSL2_MAX_SSL_SESSION_ID_LENGTH 32 - -/* Upper/Lower Bounds */ -#define SSL2_MAX_MASTER_KEY_LENGTH_IN_BITS 256 -#ifdef OPENSSL_SYS_MPE -#define SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER 29998u -#else -#define SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER 32767u /* 2^15-1 */ -#endif -#define SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER 16383 /* 2^14-1 */ - -#define SSL2_CHALLENGE_LENGTH 16 -/*#define SSL2_CHALLENGE_LENGTH 32 */ -#define SSL2_MIN_CHALLENGE_LENGTH 16 -#define SSL2_MAX_CHALLENGE_LENGTH 32 -#define SSL2_CONNECTION_ID_LENGTH 16 -#define SSL2_MAX_CONNECTION_ID_LENGTH 16 -#define SSL2_SSL_SESSION_ID_LENGTH 16 -#define SSL2_MAX_CERT_CHALLENGE_LENGTH 32 -#define SSL2_MIN_CERT_CHALLENGE_LENGTH 16 -#define SSL2_MAX_KEY_MATERIAL_LENGTH 24 - -#ifndef OPENSSL_NO_SSL_INTERN - -typedef struct ssl2_state_st - { - int three_byte_header; - int clear_text; /* clear text */ - int escape; /* not used in SSLv2 */ - int ssl2_rollback; /* used if SSLv23 rolled back to SSLv2 */ - - /* non-blocking io info, used to make sure the same - * args were passwd */ - unsigned int wnum; /* number of bytes sent so far */ - int wpend_tot; - const unsigned char *wpend_buf; - - int wpend_off; /* offset to data to write */ - int wpend_len; /* number of bytes passwd to write */ - int wpend_ret; /* number of bytes to return to caller */ - - /* buffer raw data */ - int rbuf_left; - int rbuf_offs; - unsigned char *rbuf; - unsigned char *wbuf; - - unsigned char *write_ptr;/* used to point to the start due to - * 2/3 byte header. */ - - unsigned int padding; - unsigned int rlength; /* passed to ssl2_enc */ - int ract_data_length; /* Set when things are encrypted. */ - unsigned int wlength; /* passed to ssl2_enc */ - int wact_data_length; /* Set when things are decrypted. */ - unsigned char *ract_data; - unsigned char *wact_data; - unsigned char *mac_data; - - unsigned char *read_key; - unsigned char *write_key; - - /* Stuff specifically to do with this SSL session */ - unsigned int challenge_length; - unsigned char challenge[SSL2_MAX_CHALLENGE_LENGTH]; - unsigned int conn_id_length; - unsigned char conn_id[SSL2_MAX_CONNECTION_ID_LENGTH]; - unsigned int key_material_length; - unsigned char key_material[SSL2_MAX_KEY_MATERIAL_LENGTH*2]; - - unsigned long read_sequence; - unsigned long write_sequence; - - struct { - unsigned int conn_id_length; - unsigned int cert_type; - unsigned int cert_length; - unsigned int csl; - unsigned int clear; - unsigned int enc; - unsigned char ccl[SSL2_MAX_CERT_CHALLENGE_LENGTH]; - unsigned int cipher_spec_length; - unsigned int session_id_length; - unsigned int clen; - unsigned int rlen; - } tmp; - } SSL2_STATE; - -#endif - -/* SSLv2 */ -/* client */ -#define SSL2_ST_SEND_CLIENT_HELLO_A (0x10|SSL_ST_CONNECT) -#define SSL2_ST_SEND_CLIENT_HELLO_B (0x11|SSL_ST_CONNECT) -#define SSL2_ST_GET_SERVER_HELLO_A (0x20|SSL_ST_CONNECT) -#define SSL2_ST_GET_SERVER_HELLO_B (0x21|SSL_ST_CONNECT) -#define SSL2_ST_SEND_CLIENT_MASTER_KEY_A (0x30|SSL_ST_CONNECT) -#define SSL2_ST_SEND_CLIENT_MASTER_KEY_B (0x31|SSL_ST_CONNECT) -#define SSL2_ST_SEND_CLIENT_FINISHED_A (0x40|SSL_ST_CONNECT) -#define SSL2_ST_SEND_CLIENT_FINISHED_B (0x41|SSL_ST_CONNECT) -#define SSL2_ST_SEND_CLIENT_CERTIFICATE_A (0x50|SSL_ST_CONNECT) -#define SSL2_ST_SEND_CLIENT_CERTIFICATE_B (0x51|SSL_ST_CONNECT) -#define SSL2_ST_SEND_CLIENT_CERTIFICATE_C (0x52|SSL_ST_CONNECT) -#define SSL2_ST_SEND_CLIENT_CERTIFICATE_D (0x53|SSL_ST_CONNECT) -#define SSL2_ST_GET_SERVER_VERIFY_A (0x60|SSL_ST_CONNECT) -#define SSL2_ST_GET_SERVER_VERIFY_B (0x61|SSL_ST_CONNECT) -#define SSL2_ST_GET_SERVER_FINISHED_A (0x70|SSL_ST_CONNECT) -#define SSL2_ST_GET_SERVER_FINISHED_B (0x71|SSL_ST_CONNECT) -#define SSL2_ST_CLIENT_START_ENCRYPTION (0x80|SSL_ST_CONNECT) -#define SSL2_ST_X509_GET_CLIENT_CERTIFICATE (0x90|SSL_ST_CONNECT) -/* server */ -#define SSL2_ST_GET_CLIENT_HELLO_A (0x10|SSL_ST_ACCEPT) -#define SSL2_ST_GET_CLIENT_HELLO_B (0x11|SSL_ST_ACCEPT) -#define SSL2_ST_GET_CLIENT_HELLO_C (0x12|SSL_ST_ACCEPT) -#define SSL2_ST_SEND_SERVER_HELLO_A (0x20|SSL_ST_ACCEPT) -#define SSL2_ST_SEND_SERVER_HELLO_B (0x21|SSL_ST_ACCEPT) -#define SSL2_ST_GET_CLIENT_MASTER_KEY_A (0x30|SSL_ST_ACCEPT) -#define SSL2_ST_GET_CLIENT_MASTER_KEY_B (0x31|SSL_ST_ACCEPT) -#define SSL2_ST_SEND_SERVER_VERIFY_A (0x40|SSL_ST_ACCEPT) -#define SSL2_ST_SEND_SERVER_VERIFY_B (0x41|SSL_ST_ACCEPT) -#define SSL2_ST_SEND_SERVER_VERIFY_C (0x42|SSL_ST_ACCEPT) -#define SSL2_ST_GET_CLIENT_FINISHED_A (0x50|SSL_ST_ACCEPT) -#define SSL2_ST_GET_CLIENT_FINISHED_B (0x51|SSL_ST_ACCEPT) -#define SSL2_ST_SEND_SERVER_FINISHED_A (0x60|SSL_ST_ACCEPT) -#define SSL2_ST_SEND_SERVER_FINISHED_B (0x61|SSL_ST_ACCEPT) -#define SSL2_ST_SEND_REQUEST_CERTIFICATE_A (0x70|SSL_ST_ACCEPT) -#define SSL2_ST_SEND_REQUEST_CERTIFICATE_B (0x71|SSL_ST_ACCEPT) -#define SSL2_ST_SEND_REQUEST_CERTIFICATE_C (0x72|SSL_ST_ACCEPT) -#define SSL2_ST_SEND_REQUEST_CERTIFICATE_D (0x73|SSL_ST_ACCEPT) -#define SSL2_ST_SERVER_START_ENCRYPTION (0x80|SSL_ST_ACCEPT) -#define SSL2_ST_X509_GET_SERVER_CERTIFICATE (0x90|SSL_ST_ACCEPT) - -#ifdef __cplusplus -} -#endif -#endif - diff --git a/third_party/boringssl/include/openssl/ssl23.h b/third_party/boringssl/include/openssl/ssl23.h deleted file mode 100644 index df395a8e97..0000000000 --- a/third_party/boringssl/include/openssl/ssl23.h +++ /dev/null @@ -1,85 +0,0 @@ -/* ssl/ssl23.h */ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] - */ - -#ifndef HEADER_SSL23_H -#define HEADER_SSL23_H - -#ifdef __cplusplus -extern "C" { -#endif - - -/*client */ -/* write to server */ -#define SSL23_ST_CW_CLNT_HELLO_A (0x210 | SSL_ST_CONNECT) -#define SSL23_ST_CW_CLNT_HELLO_B (0x211 | SSL_ST_CONNECT) -/* read from server */ -#define SSL23_ST_CR_SRVR_HELLO_A (0x220 | SSL_ST_CONNECT) -#define SSL23_ST_CR_SRVR_HELLO_B (0x221 | SSL_ST_CONNECT) - -/* server */ -/* read from client */ -#define SSL23_ST_SR_CLNT_HELLO (0x210 | SSL_ST_ACCEPT) -#define SSL23_ST_SR_V2_CLNT_HELLO (0x220 | SSL_ST_ACCEPT) -#define SSL23_ST_SR_SWITCH_VERSION (0x230 | SSL_ST_ACCEPT) - - -#ifdef __cplusplus -} -#endif -#endif diff --git a/third_party/boringssl/include/openssl/ssl3.h b/third_party/boringssl/include/openssl/ssl3.h deleted file mode 100644 index 640a22826e..0000000000 --- a/third_party/boringssl/include/openssl/ssl3.h +++ /dev/null @@ -1,681 +0,0 @@ -/* ssl/ssl3.h */ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] - */ -/* ==================================================================== - * Copyright (c) 1998-2002 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * openssl-core@openssl.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.openssl.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS 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. - * ==================================================================== - * - * This product includes cryptographic software written by Eric Young - * (eay@cryptsoft.com). This product includes software written by Tim - * Hudson (tjh@cryptsoft.com). - * - */ -/* ==================================================================== - * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. - * ECC cipher suite support in OpenSSL originally developed by - * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. - */ - -#ifndef HEADER_SSL3_H -#define HEADER_SSL3_H - -#include -#include -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - - -/* Signalling cipher suite value: from RFC5746 */ -#define SSL3_CK_SCSV 0x030000FF -/* Fallback signalling cipher suite value: not IANA assigned. - * See https://tools.ietf.org/html/draft-bmoeller-tls-downgrade-scsv-01 */ -#define SSL3_CK_FALLBACK_SCSV 0x03005600 - -#define SSL3_CK_RSA_NULL_MD5 0x03000001 -#define SSL3_CK_RSA_NULL_SHA 0x03000002 -#define SSL3_CK_RSA_RC4_40_MD5 0x03000003 -#define SSL3_CK_RSA_RC4_128_MD5 0x03000004 -#define SSL3_CK_RSA_RC4_128_SHA 0x03000005 -#define SSL3_CK_RSA_RC2_40_MD5 0x03000006 -#define SSL3_CK_RSA_IDEA_128_SHA 0x03000007 -#define SSL3_CK_RSA_DES_40_CBC_SHA 0x03000008 -#define SSL3_CK_RSA_DES_64_CBC_SHA 0x03000009 -#define SSL3_CK_RSA_DES_192_CBC3_SHA 0x0300000A - -#define SSL3_CK_DH_DSS_DES_40_CBC_SHA 0x0300000B -#define SSL3_CK_DH_DSS_DES_64_CBC_SHA 0x0300000C -#define SSL3_CK_DH_DSS_DES_192_CBC3_SHA 0x0300000D -#define SSL3_CK_DH_RSA_DES_40_CBC_SHA 0x0300000E -#define SSL3_CK_DH_RSA_DES_64_CBC_SHA 0x0300000F -#define SSL3_CK_DH_RSA_DES_192_CBC3_SHA 0x03000010 - -#define SSL3_CK_EDH_DSS_DES_40_CBC_SHA 0x03000011 -#define SSL3_CK_EDH_DSS_DES_64_CBC_SHA 0x03000012 -#define SSL3_CK_EDH_DSS_DES_192_CBC3_SHA 0x03000013 -#define SSL3_CK_EDH_RSA_DES_40_CBC_SHA 0x03000014 -#define SSL3_CK_EDH_RSA_DES_64_CBC_SHA 0x03000015 -#define SSL3_CK_EDH_RSA_DES_192_CBC3_SHA 0x03000016 - -#define SSL3_CK_ADH_RC4_40_MD5 0x03000017 -#define SSL3_CK_ADH_RC4_128_MD5 0x03000018 -#define SSL3_CK_ADH_DES_40_CBC_SHA 0x03000019 -#define SSL3_CK_ADH_DES_64_CBC_SHA 0x0300001A -#define SSL3_CK_ADH_DES_192_CBC_SHA 0x0300001B - -#define SSL3_TXT_RSA_NULL_MD5 "NULL-MD5" -#define SSL3_TXT_RSA_NULL_SHA "NULL-SHA" -#define SSL3_TXT_RSA_RC4_40_MD5 "EXP-RC4-MD5" -#define SSL3_TXT_RSA_RC4_128_MD5 "RC4-MD5" -#define SSL3_TXT_RSA_RC4_128_SHA "RC4-SHA" -#define SSL3_TXT_RSA_RC2_40_MD5 "EXP-RC2-CBC-MD5" -#define SSL3_TXT_RSA_IDEA_128_SHA "IDEA-CBC-SHA" -#define SSL3_TXT_RSA_DES_40_CBC_SHA "EXP-DES-CBC-SHA" -#define SSL3_TXT_RSA_DES_64_CBC_SHA "DES-CBC-SHA" -#define SSL3_TXT_RSA_DES_192_CBC3_SHA "DES-CBC3-SHA" - -#define SSL3_TXT_DH_DSS_DES_40_CBC_SHA "EXP-DH-DSS-DES-CBC-SHA" -#define SSL3_TXT_DH_DSS_DES_64_CBC_SHA "DH-DSS-DES-CBC-SHA" -#define SSL3_TXT_DH_DSS_DES_192_CBC3_SHA "DH-DSS-DES-CBC3-SHA" -#define SSL3_TXT_DH_RSA_DES_40_CBC_SHA "EXP-DH-RSA-DES-CBC-SHA" -#define SSL3_TXT_DH_RSA_DES_64_CBC_SHA "DH-RSA-DES-CBC-SHA" -#define SSL3_TXT_DH_RSA_DES_192_CBC3_SHA "DH-RSA-DES-CBC3-SHA" - -#define SSL3_TXT_EDH_DSS_DES_40_CBC_SHA "EXP-EDH-DSS-DES-CBC-SHA" -#define SSL3_TXT_EDH_DSS_DES_64_CBC_SHA "EDH-DSS-DES-CBC-SHA" -#define SSL3_TXT_EDH_DSS_DES_192_CBC3_SHA "EDH-DSS-DES-CBC3-SHA" -#define SSL3_TXT_EDH_RSA_DES_40_CBC_SHA "EXP-EDH-RSA-DES-CBC-SHA" -#define SSL3_TXT_EDH_RSA_DES_64_CBC_SHA "EDH-RSA-DES-CBC-SHA" -#define SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA "EDH-RSA-DES-CBC3-SHA" - -#define SSL3_TXT_ADH_RC4_40_MD5 "EXP-ADH-RC4-MD5" -#define SSL3_TXT_ADH_RC4_128_MD5 "ADH-RC4-MD5" -#define SSL3_TXT_ADH_DES_40_CBC_SHA "EXP-ADH-DES-CBC-SHA" -#define SSL3_TXT_ADH_DES_64_CBC_SHA "ADH-DES-CBC-SHA" -#define SSL3_TXT_ADH_DES_192_CBC_SHA "ADH-DES-CBC3-SHA" - -#define SSL3_SSL_SESSION_ID_LENGTH 32 -#define SSL3_MAX_SSL_SESSION_ID_LENGTH 32 - -#define SSL3_MASTER_SECRET_SIZE 48 -#define SSL3_RANDOM_SIZE 32 -#define SSL3_SESSION_ID_SIZE 32 -#define SSL3_RT_HEADER_LENGTH 5 - -#define SSL3_HM_HEADER_LENGTH 4 - -#ifndef SSL3_ALIGN_PAYLOAD -/* Some will argue that this increases memory footprint, but it's not actually - * true. Point is that malloc has to return at least 64-bit aligned pointers, - * meaning that allocating 5 bytes wastes 3 bytes in either case. Suggested - * pre-gaping simply moves these wasted bytes from the end of allocated region - * to its front, but makes data payload aligned, which improves performance. */ -#define SSL3_ALIGN_PAYLOAD 8 -#else -#if (SSL3_ALIGN_PAYLOAD & (SSL3_ALIGN_PAYLOAD - 1)) != 0 -#error "insane SSL3_ALIGN_PAYLOAD" -#undef SSL3_ALIGN_PAYLOAD -#endif -#endif - -/* This is the maximum MAC (digest) size used by the SSL library. Currently - * maximum of 20 is used by SHA1, but we reserve for future extension for - * 512-bit hashes. */ - -#define SSL3_RT_MAX_MD_SIZE 64 - -/* Maximum block size used in all ciphersuites. Currently 16 for AES. */ - -#define SSL_RT_MAX_CIPHER_BLOCK_SIZE 16 - -#define SSL3_RT_MAX_EXTRA (16384) - -/* Maximum plaintext length: defined by SSL/TLS standards */ -#define SSL3_RT_MAX_PLAIN_LENGTH 16384 -/* Maximum compression overhead: defined by SSL/TLS standards */ -#define SSL3_RT_MAX_COMPRESSED_OVERHEAD 1024 - -/* The standards give a maximum encryption overhead of 1024 bytes. In practice - * the value is lower than this. The overhead is the maximum number of padding - * bytes (256) plus the mac size. - * - * TODO(davidben): This derivation doesn't take AEADs into account, or TLS 1.1 - * explicit nonces. It happens to work because |SSL3_RT_MAX_MD_SIZE| is larger - * than necessary and no true AEAD has variable overhead in TLS 1.2. */ -#define SSL3_RT_MAX_ENCRYPTED_OVERHEAD (256 + SSL3_RT_MAX_MD_SIZE) - -/* SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD is the maximum overhead in encrypting a - * record. This does not include the record header. Some ciphers use explicit - * nonces, so it includes both the AEAD overhead as well as the nonce. */ -#define SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD \ - (EVP_AEAD_MAX_OVERHEAD + EVP_AEAD_MAX_NONCE_LENGTH) - -OPENSSL_COMPILE_ASSERT( - SSL3_RT_MAX_ENCRYPTED_OVERHEAD >= SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD, - max_overheads_are_consistent); - -/* SSL3_RT_MAX_COMPRESSED_LENGTH is an alias for - * |SSL3_RT_MAX_PLAIN_LENGTH|. Compression is gone, so don't include the - * compression overhead. */ -#define SSL3_RT_MAX_COMPRESSED_LENGTH SSL3_RT_MAX_PLAIN_LENGTH - -#define SSL3_RT_MAX_ENCRYPTED_LENGTH \ - (SSL3_RT_MAX_ENCRYPTED_OVERHEAD + SSL3_RT_MAX_COMPRESSED_LENGTH) -#define SSL3_RT_MAX_PACKET_SIZE \ - (SSL3_RT_MAX_ENCRYPTED_LENGTH + SSL3_RT_HEADER_LENGTH) - -#define SSL3_MD_CLIENT_FINISHED_CONST "\x43\x4C\x4E\x54" -#define SSL3_MD_SERVER_FINISHED_CONST "\x53\x52\x56\x52" - -#define SSL3_VERSION 0x0300 -#define SSL3_VERSION_MAJOR 0x03 -#define SSL3_VERSION_MINOR 0x00 - -#define SSL3_RT_CHANGE_CIPHER_SPEC 20 -#define SSL3_RT_ALERT 21 -#define SSL3_RT_HANDSHAKE 22 -#define SSL3_RT_APPLICATION_DATA 23 - -/* Pseudo content types to indicate additional parameters */ -#define TLS1_RT_CRYPTO 0x1000 -#define TLS1_RT_CRYPTO_PREMASTER (TLS1_RT_CRYPTO | 0x1) -#define TLS1_RT_CRYPTO_CLIENT_RANDOM (TLS1_RT_CRYPTO | 0x2) -#define TLS1_RT_CRYPTO_SERVER_RANDOM (TLS1_RT_CRYPTO | 0x3) -#define TLS1_RT_CRYPTO_MASTER (TLS1_RT_CRYPTO | 0x4) - -#define TLS1_RT_CRYPTO_READ 0x0000 -#define TLS1_RT_CRYPTO_WRITE 0x0100 -#define TLS1_RT_CRYPTO_MAC (TLS1_RT_CRYPTO | 0x5) -#define TLS1_RT_CRYPTO_KEY (TLS1_RT_CRYPTO | 0x6) -#define TLS1_RT_CRYPTO_IV (TLS1_RT_CRYPTO | 0x7) -#define TLS1_RT_CRYPTO_FIXED_IV (TLS1_RT_CRYPTO | 0x8) - -/* Pseudo content type for SSL/TLS header info */ -#define SSL3_RT_HEADER 0x100 - -#define SSL3_AL_WARNING 1 -#define SSL3_AL_FATAL 2 - -#define SSL3_AD_CLOSE_NOTIFY 0 -#define SSL3_AD_UNEXPECTED_MESSAGE 10 /* fatal */ -#define SSL3_AD_BAD_RECORD_MAC 20 /* fatal */ -#define SSL3_AD_DECOMPRESSION_FAILURE 30 /* fatal */ -#define SSL3_AD_HANDSHAKE_FAILURE 40 /* fatal */ -#define SSL3_AD_NO_CERTIFICATE 41 -#define SSL3_AD_BAD_CERTIFICATE 42 -#define SSL3_AD_UNSUPPORTED_CERTIFICATE 43 -#define SSL3_AD_CERTIFICATE_REVOKED 44 -#define SSL3_AD_CERTIFICATE_EXPIRED 45 -#define SSL3_AD_CERTIFICATE_UNKNOWN 46 -#define SSL3_AD_ILLEGAL_PARAMETER 47 /* fatal */ -#define SSL3_AD_INAPPROPRIATE_FALLBACK 86 /* fatal */ - -typedef struct ssl3_record_st { - /* type is the record type. */ - uint8_t type; - /* length is the number of unconsumed bytes of |data|. */ - uint16_t length; - /* off is the number of consumed bytes of |data|. */ - uint16_t off; - /* data is a non-owning pointer to the record contents. The total length of - * the buffer is |off| + |length|. */ - uint8_t *data; - /* epoch, in DTLS, is the epoch number of the record. */ - uint16_t epoch; - /* seq_num, in DTLS, is the sequence number of the record. The top two bytes - * are always zero. - * - * TODO(davidben): This is confusing. They should include the epoch or the - * field should be six bytes. */ - uint8_t seq_num[8]; -} SSL3_RECORD; - -typedef struct ssl3_buffer_st { - uint8_t *buf; /* at least SSL3_RT_MAX_PACKET_SIZE bytes, see - ssl3_setup_buffers() */ - size_t len; /* buffer size */ - int offset; /* where to 'copy from' */ - int left; /* how many bytes left */ -} SSL3_BUFFER; - -#define SSL3_CT_RSA_SIGN 1 -#define SSL3_CT_DSS_SIGN 2 -#define SSL3_CT_RSA_FIXED_DH 3 -#define SSL3_CT_DSS_FIXED_DH 4 -#define SSL3_CT_RSA_EPHEMERAL_DH 5 -#define SSL3_CT_DSS_EPHEMERAL_DH 6 -#define SSL3_CT_FORTEZZA_DMS 20 - - -/* TODO(davidben): This flag can probably be merged into s3->change_cipher_spec - * to something tri-state. (Normal / Expect CCS / Between CCS and Finished). */ -#define SSL3_FLAGS_EXPECT_CCS 0x0080 - -typedef struct ssl3_state_st { - long flags; - - uint8_t read_sequence[8]; - int read_mac_secret_size; - uint8_t read_mac_secret[EVP_MAX_MD_SIZE]; - uint8_t write_sequence[8]; - int write_mac_secret_size; - uint8_t write_mac_secret[EVP_MAX_MD_SIZE]; - - uint8_t server_random[SSL3_RANDOM_SIZE]; - uint8_t client_random[SSL3_RANDOM_SIZE]; - - /* flags for countermeasure against known-IV weakness */ - int need_record_splitting; - - /* The value of 'extra' when the buffers were initialized */ - int init_extra; - - /* have_version is true if the connection's final version is known. Otherwise - * the version has not been negotiated yet. */ - char have_version; - - /* initial_handshake_complete is true if the initial handshake has - * completed. */ - char initial_handshake_complete; - - /* sniff_buffer is used by the server in the initial handshake to read a - * V2ClientHello before the record layer is initialized. */ - BUF_MEM *sniff_buffer; - size_t sniff_buffer_len; - - SSL3_BUFFER rbuf; /* read IO goes into here */ - SSL3_BUFFER wbuf; /* write IO goes into here */ - - SSL3_RECORD rrec; /* each decoded record goes in here */ - - /* storage for Handshake protocol data received but not yet processed by - * ssl3_read_bytes: */ - uint8_t handshake_fragment[4]; - unsigned int handshake_fragment_len; - - /* partial write - check the numbers match */ - unsigned int wnum; /* number of bytes sent so far */ - int wpend_tot; /* number bytes written */ - int wpend_type; - int wpend_ret; /* number of bytes submitted */ - const uint8_t *wpend_buf; - - /* used during startup, digest all incoming/outgoing packets */ - BIO *handshake_buffer; - /* When set of handshake digests is determined, buffer is hashed and freed - * and MD_CTX-es for all required digests are stored in this array */ - EVP_MD_CTX **handshake_dgst; - /* this is set whenerver we see a change_cipher_spec message come in when we - * are not looking for one */ - int change_cipher_spec; - - int warn_alert; - int fatal_alert; - /* we allow one fatal and one warning alert to be outstanding, send close - * alert via the warning alert */ - int alert_dispatch; - uint8_t send_alert[2]; - - int total_renegotiations; - - /* State pertaining to the pending handshake. - * - * TODO(davidben): State is current spread all over the place. Move - * pending handshake state here so it can be managed separately from - * established connection state in case of renegotiations. */ - struct { - /* actually only need to be 16+20 for SSLv3 and 12 for TLS */ - uint8_t finish_md[EVP_MAX_MD_SIZE * 2]; - int finish_md_len; - uint8_t peer_finish_md[EVP_MAX_MD_SIZE * 2]; - int peer_finish_md_len; - - unsigned long message_size; - int message_type; - - /* used to hold the new cipher we are going to use */ - const SSL_CIPHER *new_cipher; - DH *dh; - - EC_KEY *ecdh; /* holds short lived ECDH key */ - - /* used when SSL_ST_FLUSH_DATA is entered */ - int next_state; - - int reuse_message; - - /* Client-only: cert_req determines if a client certificate is to be sent. - * This is 0 if no client Certificate message is to be sent, 1 if there is - * a client certificate, and 2 to send an empty client Certificate - * message. */ - int cert_req; - - /* Client-only: ca_names contains the list of CAs received in a - * CertificateRequest message. */ - STACK_OF(X509_NAME) *ca_names; - - /* Client-only: certificate_types contains the set of certificate types - * received in a CertificateRequest message. */ - uint8_t *certificate_types; - size_t num_certificate_types; - - int key_block_length; - uint8_t *key_block; - - const EVP_AEAD *new_aead; - uint8_t new_mac_secret_len; - uint8_t new_fixed_iv_len; - uint8_t new_variable_iv_len; - - /* Server-only: cert_request is true if a client certificate was - * requested. */ - int cert_request; - - /* certificate_status_expected is true if OCSP stapling was negotiated and - * the server is expected to send a CertificateStatus message. */ - char certificate_status_expected; - - /* peer_ecpointformatlist contains the EC point formats advertised by the - * peer. */ - uint8_t *peer_ecpointformatlist; - size_t peer_ecpointformatlist_length; - - /* Server-only: peer_ellipticcurvelist contains the EC curve IDs advertised - * by the peer. This is only set on the server's end. The server does not - * advertise this extension to the client. */ - uint16_t *peer_ellipticcurvelist; - size_t peer_ellipticcurvelist_length; - - /* extended_master_secret indicates whether the extended master secret - * computation is used in this handshake. Note that this is different from - * whether it was used for the current session. If this is a resumption - * handshake then EMS might be negotiated in the client and server hello - * messages, but it doesn't matter if the session that's being resumed - * didn't use it to create the master secret initially. */ - char extended_master_secret; - - /* Client-only: peer_psk_identity_hint is the psk_identity_hint sent by the - * server when using a PSK key exchange. */ - char *peer_psk_identity_hint; - - /* new_mac_secret_size is unused and exists only until wpa_supplicant can - * be updated. It is only needed for EAP-FAST, which we don't support. */ - uint8_t new_mac_secret_size; - - /* Client-only: in_false_start is one if there is a pending handshake in - * False Start. The client may write data at this point. */ - char in_false_start; - } tmp; - - /* Connection binding to prevent renegotiation attacks */ - uint8_t previous_client_finished[EVP_MAX_MD_SIZE]; - uint8_t previous_client_finished_len; - uint8_t previous_server_finished[EVP_MAX_MD_SIZE]; - uint8_t previous_server_finished_len; - int send_connection_binding; /* TODOEKR */ - - /* Set if we saw the Next Protocol Negotiation extension from our peer. */ - int next_proto_neg_seen; - - /* ALPN information - * (we are in the process of transitioning from NPN to ALPN.) */ - - /* In a server these point to the selected ALPN protocol after the - * ClientHello has been processed. In a client these contain the protocol - * that the server selected once the ServerHello has been processed. */ - uint8_t *alpn_selected; - size_t alpn_selected_len; - - /* In a client, this means that the server supported Channel ID and that a - * Channel ID was sent. In a server it means that we echoed support for - * Channel IDs and that tlsext_channel_id will be valid after the - * handshake. */ - char tlsext_channel_id_valid; - /* tlsext_channel_id_new means that the updated Channel ID extension was - * negotiated. This is a temporary hack in the code to support both forms of - * Channel ID extension while we transition to the new format, which fixed a - * security issue. */ - char tlsext_channel_id_new; - /* For a server: - * If |tlsext_channel_id_valid| is true, then this contains the - * verified Channel ID from the client: a P256 point, (x,y), where - * each are big-endian values. */ - uint8_t tlsext_channel_id[64]; -} SSL3_STATE; - -/* SSLv3 */ -/* client */ -/* extra state */ -#define SSL3_ST_CW_FLUSH (0x100 | SSL_ST_CONNECT) -#define SSL3_ST_FALSE_START (0x101 | SSL_ST_CONNECT) -/* write to server */ -#define SSL3_ST_CW_CLNT_HELLO_A (0x110 | SSL_ST_CONNECT) -#define SSL3_ST_CW_CLNT_HELLO_B (0x111 | SSL_ST_CONNECT) -/* read from server */ -#define SSL3_ST_CR_SRVR_HELLO_A (0x120 | SSL_ST_CONNECT) -#define SSL3_ST_CR_SRVR_HELLO_B (0x121 | SSL_ST_CONNECT) -#define DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A (0x126 | SSL_ST_CONNECT) -#define DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B (0x127 | SSL_ST_CONNECT) -#define SSL3_ST_CR_CERT_A (0x130 | SSL_ST_CONNECT) -#define SSL3_ST_CR_CERT_B (0x131 | SSL_ST_CONNECT) -#define SSL3_ST_CR_KEY_EXCH_A (0x140 | SSL_ST_CONNECT) -#define SSL3_ST_CR_KEY_EXCH_B (0x141 | SSL_ST_CONNECT) -#define SSL3_ST_CR_CERT_REQ_A (0x150 | SSL_ST_CONNECT) -#define SSL3_ST_CR_CERT_REQ_B (0x151 | SSL_ST_CONNECT) -#define SSL3_ST_CR_SRVR_DONE_A (0x160 | SSL_ST_CONNECT) -#define SSL3_ST_CR_SRVR_DONE_B (0x161 | SSL_ST_CONNECT) -/* write to server */ -#define SSL3_ST_CW_CERT_A (0x170 | SSL_ST_CONNECT) -#define SSL3_ST_CW_CERT_B (0x171 | SSL_ST_CONNECT) -#define SSL3_ST_CW_CERT_C (0x172 | SSL_ST_CONNECT) -#define SSL3_ST_CW_CERT_D (0x173 | SSL_ST_CONNECT) -#define SSL3_ST_CW_KEY_EXCH_A (0x180 | SSL_ST_CONNECT) -#define SSL3_ST_CW_KEY_EXCH_B (0x181 | SSL_ST_CONNECT) -#define SSL3_ST_CW_CERT_VRFY_A (0x190 | SSL_ST_CONNECT) -#define SSL3_ST_CW_CERT_VRFY_B (0x191 | SSL_ST_CONNECT) -#define SSL3_ST_CW_CHANGE_A (0x1A0 | SSL_ST_CONNECT) -#define SSL3_ST_CW_CHANGE_B (0x1A1 | SSL_ST_CONNECT) -#define SSL3_ST_CW_NEXT_PROTO_A (0x200 | SSL_ST_CONNECT) -#define SSL3_ST_CW_NEXT_PROTO_B (0x201 | SSL_ST_CONNECT) -#define SSL3_ST_CW_CHANNEL_ID_A (0x220 | SSL_ST_CONNECT) -#define SSL3_ST_CW_CHANNEL_ID_B (0x221 | SSL_ST_CONNECT) -#define SSL3_ST_CW_FINISHED_A (0x1B0 | SSL_ST_CONNECT) -#define SSL3_ST_CW_FINISHED_B (0x1B1 | SSL_ST_CONNECT) -/* read from server */ -#define SSL3_ST_CR_CHANGE (0x1C0 | SSL_ST_CONNECT) -#define SSL3_ST_CR_FINISHED_A (0x1D0 | SSL_ST_CONNECT) -#define SSL3_ST_CR_FINISHED_B (0x1D1 | SSL_ST_CONNECT) -#define SSL3_ST_CR_SESSION_TICKET_A (0x1E0 | SSL_ST_CONNECT) -#define SSL3_ST_CR_SESSION_TICKET_B (0x1E1 | SSL_ST_CONNECT) -#define SSL3_ST_CR_CERT_STATUS_A (0x1F0 | SSL_ST_CONNECT) -#define SSL3_ST_CR_CERT_STATUS_B (0x1F1 | SSL_ST_CONNECT) - -/* server */ -/* extra state */ -#define SSL3_ST_SW_FLUSH (0x100 | SSL_ST_ACCEPT) -/* read from client */ -#define SSL3_ST_SR_INITIAL_BYTES (0x240 | SSL_ST_ACCEPT) -#define SSL3_ST_SR_V2_CLIENT_HELLO (0x241 | SSL_ST_ACCEPT) -/* Do not change the number values, they do matter */ -#define SSL3_ST_SR_CLNT_HELLO_A (0x110 | SSL_ST_ACCEPT) -#define SSL3_ST_SR_CLNT_HELLO_B (0x111 | SSL_ST_ACCEPT) -#define SSL3_ST_SR_CLNT_HELLO_C (0x112 | SSL_ST_ACCEPT) -#define SSL3_ST_SR_CLNT_HELLO_D (0x115 | SSL_ST_ACCEPT) -/* write to client */ -#define SSL3_ST_SW_HELLO_REQ_A (0x120 | SSL_ST_ACCEPT) -#define SSL3_ST_SW_HELLO_REQ_B (0x121 | SSL_ST_ACCEPT) -#define SSL3_ST_SW_HELLO_REQ_C (0x122 | SSL_ST_ACCEPT) -#define SSL3_ST_SW_SRVR_HELLO_A (0x130 | SSL_ST_ACCEPT) -#define SSL3_ST_SW_SRVR_HELLO_B (0x131 | SSL_ST_ACCEPT) -#define SSL3_ST_SW_CERT_A (0x140 | SSL_ST_ACCEPT) -#define SSL3_ST_SW_CERT_B (0x141 | SSL_ST_ACCEPT) -#define SSL3_ST_SW_KEY_EXCH_A (0x150 | SSL_ST_ACCEPT) -#define SSL3_ST_SW_KEY_EXCH_B (0x151 | SSL_ST_ACCEPT) -#define SSL3_ST_SW_CERT_REQ_A (0x160 | SSL_ST_ACCEPT) -#define SSL3_ST_SW_CERT_REQ_B (0x161 | SSL_ST_ACCEPT) -#define SSL3_ST_SW_SRVR_DONE_A (0x170 | SSL_ST_ACCEPT) -#define SSL3_ST_SW_SRVR_DONE_B (0x171 | SSL_ST_ACCEPT) -/* read from client */ -#define SSL3_ST_SR_CERT_A (0x180 | SSL_ST_ACCEPT) -#define SSL3_ST_SR_CERT_B (0x181 | SSL_ST_ACCEPT) -#define SSL3_ST_SR_KEY_EXCH_A (0x190 | SSL_ST_ACCEPT) -#define SSL3_ST_SR_KEY_EXCH_B (0x191 | SSL_ST_ACCEPT) -#define SSL3_ST_SR_CERT_VRFY_A (0x1A0 | SSL_ST_ACCEPT) -#define SSL3_ST_SR_CERT_VRFY_B (0x1A1 | SSL_ST_ACCEPT) -#define SSL3_ST_SR_CHANGE (0x1B0 | SSL_ST_ACCEPT) -#define SSL3_ST_SR_NEXT_PROTO_A (0x210 | SSL_ST_ACCEPT) -#define SSL3_ST_SR_NEXT_PROTO_B (0x211 | SSL_ST_ACCEPT) -#define SSL3_ST_SR_CHANNEL_ID_A (0x230 | SSL_ST_ACCEPT) -#define SSL3_ST_SR_CHANNEL_ID_B (0x231 | SSL_ST_ACCEPT) -#define SSL3_ST_SR_FINISHED_A (0x1C0 | SSL_ST_ACCEPT) -#define SSL3_ST_SR_FINISHED_B (0x1C1 | SSL_ST_ACCEPT) - -/* write to client */ -#define SSL3_ST_SW_CHANGE_A (0x1D0 | SSL_ST_ACCEPT) -#define SSL3_ST_SW_CHANGE_B (0x1D1 | SSL_ST_ACCEPT) -#define SSL3_ST_SW_FINISHED_A (0x1E0 | SSL_ST_ACCEPT) -#define SSL3_ST_SW_FINISHED_B (0x1E1 | SSL_ST_ACCEPT) -#define SSL3_ST_SW_SESSION_TICKET_A (0x1F0 | SSL_ST_ACCEPT) -#define SSL3_ST_SW_SESSION_TICKET_B (0x1F1 | SSL_ST_ACCEPT) -#define SSL3_ST_SW_CERT_STATUS_A (0x200 | SSL_ST_ACCEPT) -#define SSL3_ST_SW_CERT_STATUS_B (0x201 | SSL_ST_ACCEPT) -#define SSL3_ST_SW_SUPPLEMENTAL_DATA_A (0x220 | SSL_ST_ACCEPT) -#define SSL3_ST_SW_SUPPLEMENTAL_DATA_B (0x221 | SSL_ST_ACCEPT) - -#define SSL3_MT_HELLO_REQUEST 0 -#define SSL3_MT_CLIENT_HELLO 1 -#define SSL3_MT_SERVER_HELLO 2 -#define SSL3_MT_NEWSESSION_TICKET 4 -#define SSL3_MT_CERTIFICATE 11 -#define SSL3_MT_SERVER_KEY_EXCHANGE 12 -#define SSL3_MT_CERTIFICATE_REQUEST 13 -#define SSL3_MT_SERVER_DONE 14 -#define SSL3_MT_CERTIFICATE_VERIFY 15 -#define SSL3_MT_CLIENT_KEY_EXCHANGE 16 -#define SSL3_MT_FINISHED 20 -#define SSL3_MT_CERTIFICATE_STATUS 22 -#define SSL3_MT_SUPPLEMENTAL_DATA 23 -#define SSL3_MT_NEXT_PROTO 67 -#define SSL3_MT_ENCRYPTED_EXTENSIONS 203 -#define DTLS1_MT_HELLO_VERIFY_REQUEST 3 - - -#define SSL3_MT_CCS 1 - -/* These are used when changing over to a new cipher */ -#define SSL3_CC_READ 0x01 -#define SSL3_CC_WRITE 0x02 -#define SSL3_CC_CLIENT 0x10 -#define SSL3_CC_SERVER 0x20 -#define SSL3_CHANGE_CIPHER_CLIENT_WRITE (SSL3_CC_CLIENT | SSL3_CC_WRITE) -#define SSL3_CHANGE_CIPHER_SERVER_READ (SSL3_CC_SERVER | SSL3_CC_READ) -#define SSL3_CHANGE_CIPHER_CLIENT_READ (SSL3_CC_CLIENT | SSL3_CC_READ) -#define SSL3_CHANGE_CIPHER_SERVER_WRITE (SSL3_CC_SERVER | SSL3_CC_WRITE) - - -#ifdef __cplusplus -} -#endif -#endif diff --git a/third_party/boringssl/include/openssl/stack.h b/third_party/boringssl/include/openssl/stack.h deleted file mode 100644 index 350fa14578..0000000000 --- a/third_party/boringssl/include/openssl/stack.h +++ /dev/null @@ -1,301 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] */ - -#ifndef OPENSSL_HEADER_STACK_H -#define OPENSSL_HEADER_STACK_H - -#include - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* A stack, in OpenSSL, is an array of pointers. They are the most commonly - * used collection object. - * - * This file defines macros for type safe use of the stack functions. A stack - * of a specific type of object has type |STACK_OF(type)|. This can be defined - * (once) with |DEFINE_STACK_OF(type)| and declared where needed with - * |DECLARE_STACK_OF(type)|. For example: - * - * struct foo { - * int bar; - * }; - * - * DEFINE_STACK_OF(struct foo); - * - * Although note that the stack will contain /pointers/ to |foo|. - * - * A macro will be defined for each of the sk_* functions below. For - * STACK_OF(foo), the macros would be sk_foo_new, sk_foo_pop etc. */ - - -/* stack_cmp_func is a comparison function that returns a value < 0, 0 or > 0 - * if |*a| is less than, equal to or greater than |*b|, respectively. Note the - * extra indirection - the function is given a pointer to a pointer to the - * element. This differs from the usual qsort/bsearch comparison function. */ -typedef int (*stack_cmp_func)(const void **a, const void **b); - -/* stack_st contains an array of pointers. It is not designed to be used - * directly, rather the wrapper macros should be used. */ -typedef struct stack_st { - /* num contains the number of valid pointers in |data|. */ - size_t num; - void **data; - /* sorted is non-zero if the values pointed to by |data| are in ascending - * order, based on |comp|. */ - size_t sorted; - /* num_alloc contains the number of pointers allocated in the buffer pointed - * to by |data|, which may be larger than |num|. */ - size_t num_alloc; - /* comp is an optional comparison function. */ - stack_cmp_func comp; -} _STACK; - - -#define STACK_OF(type) struct stack_st_##type - -#define DEFINE_STACK_OF(type) \ -STACK_OF(type) {\ - _STACK stack; \ -} - -#define DECLARE_STACK_OF(type) STACK_OF(type); - -/* The make_macros.sh script in this directory parses the following lines and - * generates the stack_macros.h file that contains macros for the following - * types of stacks: - * - * STACK_OF:ACCESS_DESCRIPTION - * STACK_OF:ASN1_ADB_TABLE - * STACK_OF:ASN1_GENERALSTRING - * STACK_OF:ASN1_INTEGER - * STACK_OF:ASN1_OBJECT - * STACK_OF:ASN1_STRING_TABLE - * STACK_OF:ASN1_TYPE - * STACK_OF:ASN1_VALUE - * STACK_OF:BIO - * STACK_OF:BY_DIR_ENTRY - * STACK_OF:BY_DIR_HASH - * STACK_OF:CONF_VALUE - * STACK_OF:CRYPTO_EX_DATA_FUNCS - * STACK_OF:DIST_POINT - * STACK_OF:GENERAL_NAME - * STACK_OF:GENERAL_NAMES - * STACK_OF:GENERAL_SUBTREE - * STACK_OF:MIME_HEADER - * STACK_OF:PKCS7_SIGNER_INFO - * STACK_OF:PKCS7_RECIP_INFO - * STACK_OF:POLICYINFO - * STACK_OF:POLICYQUALINFO - * STACK_OF:POLICY_MAPPING - * STACK_OF:SSL_COMP - * STACK_OF:STACK_OF_X509_NAME_ENTRY - * STACK_OF:SXNETID - * STACK_OF:X509 - * STACK_OF:X509V3_EXT_METHOD - * STACK_OF:X509_ALGOR - * STACK_OF:X509_ATTRIBUTE - * STACK_OF:X509_CRL - * STACK_OF:X509_EXTENSION - * STACK_OF:X509_INFO - * STACK_OF:X509_LOOKUP - * STACK_OF:X509_NAME - * STACK_OF:X509_NAME_ENTRY - * STACK_OF:X509_OBJECT - * STACK_OF:X509_POLICY_DATA - * STACK_OF:X509_POLICY_NODE - * STACK_OF:X509_PURPOSE - * STACK_OF:X509_REVOKED - * STACK_OF:X509_TRUST - * STACK_OF:X509_VERIFY_PARAM - * STACK_OF:void - * - * Some stacks contain only const structures, so the stack should return const - * pointers to retain type-checking. - * - * CONST_STACK_OF:SRTP_PROTECTION_PROFILE - * CONST_STACK_OF:SSL_CIPHER */ - - -/* Some stacks are special because, although we would like STACK_OF(char *), - * that would actually be a stack of pointers to char*, but we just want to - * point to the string directly. In this case we call them "special" and use - * |DEFINE_SPECIAL_STACK_OF(type)| */ -#define DEFINE_SPECIAL_STACK_OF(type, inner) \ - STACK_OF(type) { _STACK special_stack; }; \ - OPENSSL_COMPILE_ASSERT(sizeof(type) == sizeof(void *), \ - special_stack_of_non_pointer_##type); - -typedef char *OPENSSL_STRING; - -DEFINE_SPECIAL_STACK_OF(OPENSSL_STRING, char) -DEFINE_SPECIAL_STACK_OF(OPENSSL_BLOCK, uint8_t) - -/* The make_macros.sh script in this directory parses the following lines and - * generates the stack_macros.h file that contains macros for the following - * types of stacks: - * - * SPECIAL_STACK_OF:OPENSSL_STRING - * SPECIAL_STACK_OF:OPENSSL_BLOCK */ - -#define IN_STACK_H -#include -#undef IN_STACK_H - - -/* These are the raw stack functions, you shouldn't be using them. Rather you - * should be using the type stack macros implemented above. */ - -/* sk_new creates a new, empty stack with the given comparison function, which - * may be zero. It returns the new stack or NULL on allocation failure. */ -OPENSSL_EXPORT _STACK *sk_new(stack_cmp_func comp); - -/* sk_new_null creates a new, empty stack. It returns the new stack or NULL on - * allocation failure. */ -OPENSSL_EXPORT _STACK *sk_new_null(void); - -/* sk_num returns the number of elements in |s|. */ -OPENSSL_EXPORT size_t sk_num(const _STACK *sk); - -/* sk_zero resets |sk| to the empty state but does nothing to free the - * individual elements themselves. */ -OPENSSL_EXPORT void sk_zero(_STACK *sk); - -/* sk_value returns the |i|th pointer in |sk|, or NULL if |i| is out of - * range. */ -OPENSSL_EXPORT void *sk_value(const _STACK *sk, size_t i); - -/* sk_set sets the |i|th pointer in |sk| to |p| and returns |p|. If |i| is out - * of range, it returns NULL. */ -OPENSSL_EXPORT void *sk_set(_STACK *sk, size_t i, void *p); - -/* sk_free frees the given stack and array of pointers, but does nothing to - * free the individual elements. Also see |sk_pop_free|. */ -OPENSSL_EXPORT void sk_free(_STACK *sk); - -/* sk_pop_free calls |free_func| on each element in the stack and then frees - * the stack itself. */ -OPENSSL_EXPORT void sk_pop_free(_STACK *sk, void (*free_func)(void *)); - -/* sk_insert inserts |p| into the stack at index |where|, moving existing - * elements if needed. It returns the length of the new stack, or zero on - * error. */ -OPENSSL_EXPORT size_t sk_insert(_STACK *sk, void *p, size_t where); - -/* sk_delete removes the pointer at index |where|, moving other elements down - * if needed. It returns the removed pointer, or NULL if |where| is out of - * range. */ -OPENSSL_EXPORT void *sk_delete(_STACK *sk, size_t where); - -/* sk_delete_ptr removes, at most, one instance of |p| from the stack based on - * pointer equality. If an instance of |p| is found then |p| is returned, - * otherwise it returns NULL. */ -OPENSSL_EXPORT void *sk_delete_ptr(_STACK *sk, void *p); - -/* sk_find returns the first value in the stack equal to |p|. If a comparison - * function has been set on the stack, then equality is defined by it and the - * stack will be sorted if need be so that a binary search can be used. - * Otherwise pointer equality is used. If a matching element is found, its - * index is written to |*out_index| (if |out_index| is not NULL) and one is - * returned. Otherwise zero is returned. */ -OPENSSL_EXPORT int sk_find(_STACK *sk, size_t *out_index, void *p); - -/* sk_shift removes and returns the first element in the stack, or returns NULL - * if the stack is empty. */ -OPENSSL_EXPORT void *sk_shift(_STACK *sk); - -/* sk_push appends |p| to the stack and returns the length of the new stack, or - * 0 on allocation failure. */ -OPENSSL_EXPORT size_t sk_push(_STACK *sk, void *p); - -/* sk_pop returns and removes the last element on the stack, or NULL if the - * stack is empty. */ -OPENSSL_EXPORT void *sk_pop(_STACK *sk); - -/* sk_dup performs a shallow copy of a stack and returns the new stack, or NULL - * on error. */ -OPENSSL_EXPORT _STACK *sk_dup(const _STACK *sk); - -/* sk_sort sorts the elements of |sk| into ascending order based on the - * comparison function. The stack maintains a |sorted| flag and sorting an - * already sorted stack is a no-op. */ -OPENSSL_EXPORT void sk_sort(_STACK *sk); - -/* sk_is_sorted returns one if |sk| is known to be sorted and zero - * otherwise. */ -OPENSSL_EXPORT int sk_is_sorted(const _STACK *sk); - -/* sk_set_cmp_func sets the comparison function to be used by |sk| and returns - * the previous one. */ -OPENSSL_EXPORT stack_cmp_func sk_set_cmp_func(_STACK *sk, stack_cmp_func comp); - -/* sk_deep_copy performs a copy of |sk| and of each of the non-NULL elements in - * |sk| by using |copy_func|. If an error occurs, |free_func| is used to free - * any copies already made and NULL is returned. */ -OPENSSL_EXPORT _STACK *sk_deep_copy(const _STACK *sk, - void *(*copy_func)(void *), - void (*free_func)(void *)); - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_STACK_H */ diff --git a/third_party/boringssl/include/openssl/stack_macros.h b/third_party/boringssl/include/openssl/stack_macros.h deleted file mode 100644 index dadcf6bec5..0000000000 --- a/third_party/boringssl/include/openssl/stack_macros.h +++ /dev/null @@ -1,4004 +0,0 @@ -/* Copyright (c) 2014, Google Inc. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -#if !defined(IN_STACK_H) -#error "Don't include this file directly. Include stack.h." -#endif - -/* ACCESS_DESCRIPTION */ -#define sk_ACCESS_DESCRIPTION_new(comp) \ - ((STACK_OF(ACCESS_DESCRIPTION) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, \ - int (*)(const ACCESS_DESCRIPTION **a, const ACCESS_DESCRIPTION **b), \ - comp))) - -#define sk_ACCESS_DESCRIPTION_new_null() \ - ((STACK_OF(ACCESS_DESCRIPTION) *)sk_new_null()) - -#define sk_ACCESS_DESCRIPTION_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(ACCESS_DESCRIPTION) *, sk)) - -#define sk_ACCESS_DESCRIPTION_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(ACCESS_DESCRIPTION) *, sk)); - -#define sk_ACCESS_DESCRIPTION_value(sk, i) \ - ((ACCESS_DESCRIPTION *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(ACCESS_DESCRIPTION) *, sk), (i))) - -#define sk_ACCESS_DESCRIPTION_set(sk, i, p) \ - ((ACCESS_DESCRIPTION *)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(ACCESS_DESCRIPTION) *, sk), (i), \ - CHECKED_CAST(void *, ACCESS_DESCRIPTION *, p))) - -#define sk_ACCESS_DESCRIPTION_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(ACCESS_DESCRIPTION) *, sk)) - -#define sk_ACCESS_DESCRIPTION_pop_free(sk, free_func) \ - sk_pop_free(CHECKED_CAST(_STACK *, STACK_OF(ACCESS_DESCRIPTION) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(ACCESS_DESCRIPTION *), \ - free_func)) - -#define sk_ACCESS_DESCRIPTION_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(ACCESS_DESCRIPTION) *, sk), \ - CHECKED_CAST(void *, ACCESS_DESCRIPTION *, p), (where)) - -#define sk_ACCESS_DESCRIPTION_delete(sk, where) \ - ((ACCESS_DESCRIPTION *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(ACCESS_DESCRIPTION) *, sk), (where))) - -#define sk_ACCESS_DESCRIPTION_delete_ptr(sk, p) \ - ((ACCESS_DESCRIPTION *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(ACCESS_DESCRIPTION) *, sk), \ - CHECKED_CAST(void *, ACCESS_DESCRIPTION *, p))) - -#define sk_ACCESS_DESCRIPTION_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(ACCESS_DESCRIPTION) *, sk), \ - (out_index), CHECKED_CAST(void *, ACCESS_DESCRIPTION *, p)) - -#define sk_ACCESS_DESCRIPTION_shift(sk) \ - ((ACCESS_DESCRIPTION *)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(ACCESS_DESCRIPTION) *, sk))) - -#define sk_ACCESS_DESCRIPTION_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(ACCESS_DESCRIPTION) *, sk), \ - CHECKED_CAST(void *, ACCESS_DESCRIPTION *, p)) - -#define sk_ACCESS_DESCRIPTION_pop(sk) \ - ((ACCESS_DESCRIPTION *)sk_pop( \ - CHECKED_CAST(_STACK *, STACK_OF(ACCESS_DESCRIPTION) *, sk))) - -#define sk_ACCESS_DESCRIPTION_dup(sk) \ - ((STACK_OF(ACCESS_DESCRIPTION) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(ACCESS_DESCRIPTION) *, sk))) - -#define sk_ACCESS_DESCRIPTION_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(ACCESS_DESCRIPTION) *, sk)) - -#define sk_ACCESS_DESCRIPTION_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(ACCESS_DESCRIPTION) *, sk)) - -#define sk_ACCESS_DESCRIPTION_set_cmp_func(sk, comp) \ - ((int (*)(const ACCESS_DESCRIPTION **a, const ACCESS_DESCRIPTION **b)) \ - sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(ACCESS_DESCRIPTION) *, sk), \ - CHECKED_CAST(stack_cmp_func, int (*)(const ACCESS_DESCRIPTION **a, \ - const ACCESS_DESCRIPTION **b), \ - comp))) - -#define sk_ACCESS_DESCRIPTION_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(ACCESS_DESCRIPTION) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(ACCESS_DESCRIPTION) *, sk), \ - CHECKED_CAST(void *(*)(void *), \ - ACCESS_DESCRIPTION *(*)(ACCESS_DESCRIPTION *), copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(ACCESS_DESCRIPTION *), \ - free_func))) - -/* ASN1_ADB_TABLE */ -#define sk_ASN1_ADB_TABLE_new(comp) \ - ((STACK_OF(ASN1_ADB_TABLE) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, \ - int (*)(const ASN1_ADB_TABLE **a, const ASN1_ADB_TABLE **b), comp))) - -#define sk_ASN1_ADB_TABLE_new_null() ((STACK_OF(ASN1_ADB_TABLE) *)sk_new_null()) - -#define sk_ASN1_ADB_TABLE_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(ASN1_ADB_TABLE) *, sk)) - -#define sk_ASN1_ADB_TABLE_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(ASN1_ADB_TABLE) *, sk)); - -#define sk_ASN1_ADB_TABLE_value(sk, i) \ - ((ASN1_ADB_TABLE *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(ASN1_ADB_TABLE) *, sk), (i))) - -#define sk_ASN1_ADB_TABLE_set(sk, i, p) \ - ((ASN1_ADB_TABLE *)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_ADB_TABLE) *, sk), (i), \ - CHECKED_CAST(void *, ASN1_ADB_TABLE *, p))) - -#define sk_ASN1_ADB_TABLE_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(ASN1_ADB_TABLE) *, sk)) - -#define sk_ASN1_ADB_TABLE_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_ADB_TABLE) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(ASN1_ADB_TABLE *), free_func)) - -#define sk_ASN1_ADB_TABLE_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(ASN1_ADB_TABLE) *, sk), \ - CHECKED_CAST(void *, ASN1_ADB_TABLE *, p), (where)) - -#define sk_ASN1_ADB_TABLE_delete(sk, where) \ - ((ASN1_ADB_TABLE *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_ADB_TABLE) *, sk), (where))) - -#define sk_ASN1_ADB_TABLE_delete_ptr(sk, p) \ - ((ASN1_ADB_TABLE *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_ADB_TABLE) *, sk), \ - CHECKED_CAST(void *, ASN1_ADB_TABLE *, p))) - -#define sk_ASN1_ADB_TABLE_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(ASN1_ADB_TABLE) *, sk), (out_index), \ - CHECKED_CAST(void *, ASN1_ADB_TABLE *, p)) - -#define sk_ASN1_ADB_TABLE_shift(sk) \ - ((ASN1_ADB_TABLE *)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_ADB_TABLE) *, sk))) - -#define sk_ASN1_ADB_TABLE_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(ASN1_ADB_TABLE) *, sk), \ - CHECKED_CAST(void *, ASN1_ADB_TABLE *, p)) - -#define sk_ASN1_ADB_TABLE_pop(sk) \ - ((ASN1_ADB_TABLE *)sk_pop( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_ADB_TABLE) *, sk))) - -#define sk_ASN1_ADB_TABLE_dup(sk) \ - ((STACK_OF(ASN1_ADB_TABLE) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(ASN1_ADB_TABLE) *, sk))) - -#define sk_ASN1_ADB_TABLE_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(ASN1_ADB_TABLE) *, sk)) - -#define sk_ASN1_ADB_TABLE_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(ASN1_ADB_TABLE) *, sk)) - -#define sk_ASN1_ADB_TABLE_set_cmp_func(sk, comp) \ - ((int (*)(const ASN1_ADB_TABLE **a, const ASN1_ADB_TABLE **b)) \ - sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_ADB_TABLE) *, sk), \ - CHECKED_CAST(stack_cmp_func, int (*)(const ASN1_ADB_TABLE **a, \ - const ASN1_ADB_TABLE **b), \ - comp))) - -#define sk_ASN1_ADB_TABLE_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(ASN1_ADB_TABLE) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(ASN1_ADB_TABLE) *, sk), \ - CHECKED_CAST(void *(*)(void *), ASN1_ADB_TABLE *(*)(ASN1_ADB_TABLE *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(ASN1_ADB_TABLE *), free_func))) - -/* ASN1_GENERALSTRING */ -#define sk_ASN1_GENERALSTRING_new(comp) \ - ((STACK_OF(ASN1_GENERALSTRING) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, \ - int (*)(const ASN1_GENERALSTRING **a, const ASN1_GENERALSTRING **b), \ - comp))) - -#define sk_ASN1_GENERALSTRING_new_null() \ - ((STACK_OF(ASN1_GENERALSTRING) *)sk_new_null()) - -#define sk_ASN1_GENERALSTRING_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(ASN1_GENERALSTRING) *, sk)) - -#define sk_ASN1_GENERALSTRING_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(ASN1_GENERALSTRING) *, sk)); - -#define sk_ASN1_GENERALSTRING_value(sk, i) \ - ((ASN1_GENERALSTRING *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(ASN1_GENERALSTRING) *, sk), (i))) - -#define sk_ASN1_GENERALSTRING_set(sk, i, p) \ - ((ASN1_GENERALSTRING *)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_GENERALSTRING) *, sk), (i), \ - CHECKED_CAST(void *, ASN1_GENERALSTRING *, p))) - -#define sk_ASN1_GENERALSTRING_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(ASN1_GENERALSTRING) *, sk)) - -#define sk_ASN1_GENERALSTRING_pop_free(sk, free_func) \ - sk_pop_free(CHECKED_CAST(_STACK *, STACK_OF(ASN1_GENERALSTRING) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(ASN1_GENERALSTRING *), \ - free_func)) - -#define sk_ASN1_GENERALSTRING_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(ASN1_GENERALSTRING) *, sk), \ - CHECKED_CAST(void *, ASN1_GENERALSTRING *, p), (where)) - -#define sk_ASN1_GENERALSTRING_delete(sk, where) \ - ((ASN1_GENERALSTRING *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_GENERALSTRING) *, sk), (where))) - -#define sk_ASN1_GENERALSTRING_delete_ptr(sk, p) \ - ((ASN1_GENERALSTRING *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_GENERALSTRING) *, sk), \ - CHECKED_CAST(void *, ASN1_GENERALSTRING *, p))) - -#define sk_ASN1_GENERALSTRING_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(ASN1_GENERALSTRING) *, sk), \ - (out_index), CHECKED_CAST(void *, ASN1_GENERALSTRING *, p)) - -#define sk_ASN1_GENERALSTRING_shift(sk) \ - ((ASN1_GENERALSTRING *)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_GENERALSTRING) *, sk))) - -#define sk_ASN1_GENERALSTRING_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(ASN1_GENERALSTRING) *, sk), \ - CHECKED_CAST(void *, ASN1_GENERALSTRING *, p)) - -#define sk_ASN1_GENERALSTRING_pop(sk) \ - ((ASN1_GENERALSTRING *)sk_pop( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_GENERALSTRING) *, sk))) - -#define sk_ASN1_GENERALSTRING_dup(sk) \ - ((STACK_OF(ASN1_GENERALSTRING) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(ASN1_GENERALSTRING) *, sk))) - -#define sk_ASN1_GENERALSTRING_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(ASN1_GENERALSTRING) *, sk)) - -#define sk_ASN1_GENERALSTRING_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(ASN1_GENERALSTRING) *, sk)) - -#define sk_ASN1_GENERALSTRING_set_cmp_func(sk, comp) \ - ((int (*)(const ASN1_GENERALSTRING **a, const ASN1_GENERALSTRING **b)) \ - sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_GENERALSTRING) *, sk), \ - CHECKED_CAST(stack_cmp_func, int (*)(const ASN1_GENERALSTRING **a, \ - const ASN1_GENERALSTRING **b), \ - comp))) - -#define sk_ASN1_GENERALSTRING_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(ASN1_GENERALSTRING) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(ASN1_GENERALSTRING) *, sk), \ - CHECKED_CAST(void *(*)(void *), \ - ASN1_GENERALSTRING *(*)(ASN1_GENERALSTRING *), copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(ASN1_GENERALSTRING *), \ - free_func))) - -/* ASN1_INTEGER */ -#define sk_ASN1_INTEGER_new(comp) \ - ((STACK_OF(ASN1_INTEGER) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, int (*)(const ASN1_INTEGER **a, const ASN1_INTEGER **b), \ - comp))) - -#define sk_ASN1_INTEGER_new_null() ((STACK_OF(ASN1_INTEGER) *)sk_new_null()) - -#define sk_ASN1_INTEGER_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(ASN1_INTEGER) *, sk)) - -#define sk_ASN1_INTEGER_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(ASN1_INTEGER) *, sk)); - -#define sk_ASN1_INTEGER_value(sk, i) \ - ((ASN1_INTEGER *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(ASN1_INTEGER) *, sk), (i))) - -#define sk_ASN1_INTEGER_set(sk, i, p) \ - ((ASN1_INTEGER *)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_INTEGER) *, sk), (i), \ - CHECKED_CAST(void *, ASN1_INTEGER *, p))) - -#define sk_ASN1_INTEGER_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(ASN1_INTEGER) *, sk)) - -#define sk_ASN1_INTEGER_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_INTEGER) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(ASN1_INTEGER *), free_func)) - -#define sk_ASN1_INTEGER_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(ASN1_INTEGER) *, sk), \ - CHECKED_CAST(void *, ASN1_INTEGER *, p), (where)) - -#define sk_ASN1_INTEGER_delete(sk, where) \ - ((ASN1_INTEGER *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_INTEGER) *, sk), (where))) - -#define sk_ASN1_INTEGER_delete_ptr(sk, p) \ - ((ASN1_INTEGER *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_INTEGER) *, sk), \ - CHECKED_CAST(void *, ASN1_INTEGER *, p))) - -#define sk_ASN1_INTEGER_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(ASN1_INTEGER) *, sk), (out_index), \ - CHECKED_CAST(void *, ASN1_INTEGER *, p)) - -#define sk_ASN1_INTEGER_shift(sk) \ - ((ASN1_INTEGER *)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_INTEGER) *, sk))) - -#define sk_ASN1_INTEGER_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(ASN1_INTEGER) *, sk), \ - CHECKED_CAST(void *, ASN1_INTEGER *, p)) - -#define sk_ASN1_INTEGER_pop(sk) \ - ((ASN1_INTEGER *)sk_pop(CHECKED_CAST(_STACK *, STACK_OF(ASN1_INTEGER) *, sk))) - -#define sk_ASN1_INTEGER_dup(sk) \ - ((STACK_OF(ASN1_INTEGER) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(ASN1_INTEGER) *, sk))) - -#define sk_ASN1_INTEGER_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(ASN1_INTEGER) *, sk)) - -#define sk_ASN1_INTEGER_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(ASN1_INTEGER) *, sk)) - -#define sk_ASN1_INTEGER_set_cmp_func(sk, comp) \ - ((int (*)(const ASN1_INTEGER **a, const ASN1_INTEGER **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_INTEGER) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const ASN1_INTEGER **a, const ASN1_INTEGER **b), \ - comp))) - -#define sk_ASN1_INTEGER_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(ASN1_INTEGER) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(ASN1_INTEGER) *, sk), \ - CHECKED_CAST(void *(*)(void *), ASN1_INTEGER *(*)(ASN1_INTEGER *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(ASN1_INTEGER *), free_func))) - -/* ASN1_OBJECT */ -#define sk_ASN1_OBJECT_new(comp) \ - ((STACK_OF(ASN1_OBJECT) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, int (*)(const ASN1_OBJECT **a, const ASN1_OBJECT **b), \ - comp))) - -#define sk_ASN1_OBJECT_new_null() ((STACK_OF(ASN1_OBJECT) *)sk_new_null()) - -#define sk_ASN1_OBJECT_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(ASN1_OBJECT) *, sk)) - -#define sk_ASN1_OBJECT_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(ASN1_OBJECT) *, sk)); - -#define sk_ASN1_OBJECT_value(sk, i) \ - ((ASN1_OBJECT *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(ASN1_OBJECT) *, sk), (i))) - -#define sk_ASN1_OBJECT_set(sk, i, p) \ - ((ASN1_OBJECT *)sk_set(CHECKED_CAST(_STACK *, STACK_OF(ASN1_OBJECT) *, sk), \ - (i), CHECKED_CAST(void *, ASN1_OBJECT *, p))) - -#define sk_ASN1_OBJECT_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(ASN1_OBJECT) *, sk)) - -#define sk_ASN1_OBJECT_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_OBJECT) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(ASN1_OBJECT *), free_func)) - -#define sk_ASN1_OBJECT_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(ASN1_OBJECT) *, sk), \ - CHECKED_CAST(void *, ASN1_OBJECT *, p), (where)) - -#define sk_ASN1_OBJECT_delete(sk, where) \ - ((ASN1_OBJECT *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_OBJECT) *, sk), (where))) - -#define sk_ASN1_OBJECT_delete_ptr(sk, p) \ - ((ASN1_OBJECT *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_OBJECT) *, sk), \ - CHECKED_CAST(void *, ASN1_OBJECT *, p))) - -#define sk_ASN1_OBJECT_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(ASN1_OBJECT) *, sk), (out_index), \ - CHECKED_CAST(void *, ASN1_OBJECT *, p)) - -#define sk_ASN1_OBJECT_shift(sk) \ - ((ASN1_OBJECT *)sk_shift(CHECKED_CAST(_STACK *, STACK_OF(ASN1_OBJECT) *, sk))) - -#define sk_ASN1_OBJECT_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(ASN1_OBJECT) *, sk), \ - CHECKED_CAST(void *, ASN1_OBJECT *, p)) - -#define sk_ASN1_OBJECT_pop(sk) \ - ((ASN1_OBJECT *)sk_pop(CHECKED_CAST(_STACK *, STACK_OF(ASN1_OBJECT) *, sk))) - -#define sk_ASN1_OBJECT_dup(sk) \ - ((STACK_OF(ASN1_OBJECT) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(ASN1_OBJECT) *, sk))) - -#define sk_ASN1_OBJECT_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(ASN1_OBJECT) *, sk)) - -#define sk_ASN1_OBJECT_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(ASN1_OBJECT) *, sk)) - -#define sk_ASN1_OBJECT_set_cmp_func(sk, comp) \ - ((int (*)(const ASN1_OBJECT **a, const ASN1_OBJECT **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_OBJECT) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const ASN1_OBJECT **a, const ASN1_OBJECT **b), \ - comp))) - -#define sk_ASN1_OBJECT_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(ASN1_OBJECT) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(ASN1_OBJECT) *, sk), \ - CHECKED_CAST(void *(*)(void *), ASN1_OBJECT *(*)(ASN1_OBJECT *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(ASN1_OBJECT *), free_func))) - -/* ASN1_STRING_TABLE */ -#define sk_ASN1_STRING_TABLE_new(comp) \ - ((STACK_OF(ASN1_STRING_TABLE) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, \ - int (*)(const ASN1_STRING_TABLE **a, const ASN1_STRING_TABLE **b), \ - comp))) - -#define sk_ASN1_STRING_TABLE_new_null() \ - ((STACK_OF(ASN1_STRING_TABLE) *)sk_new_null()) - -#define sk_ASN1_STRING_TABLE_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(ASN1_STRING_TABLE) *, sk)) - -#define sk_ASN1_STRING_TABLE_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(ASN1_STRING_TABLE) *, sk)); - -#define sk_ASN1_STRING_TABLE_value(sk, i) \ - ((ASN1_STRING_TABLE *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(ASN1_STRING_TABLE) *, sk), (i))) - -#define sk_ASN1_STRING_TABLE_set(sk, i, p) \ - ((ASN1_STRING_TABLE *)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_STRING_TABLE) *, sk), (i), \ - CHECKED_CAST(void *, ASN1_STRING_TABLE *, p))) - -#define sk_ASN1_STRING_TABLE_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(ASN1_STRING_TABLE) *, sk)) - -#define sk_ASN1_STRING_TABLE_pop_free(sk, free_func) \ - sk_pop_free(CHECKED_CAST(_STACK *, STACK_OF(ASN1_STRING_TABLE) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(ASN1_STRING_TABLE *), \ - free_func)) - -#define sk_ASN1_STRING_TABLE_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(ASN1_STRING_TABLE) *, sk), \ - CHECKED_CAST(void *, ASN1_STRING_TABLE *, p), (where)) - -#define sk_ASN1_STRING_TABLE_delete(sk, where) \ - ((ASN1_STRING_TABLE *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_STRING_TABLE) *, sk), (where))) - -#define sk_ASN1_STRING_TABLE_delete_ptr(sk, p) \ - ((ASN1_STRING_TABLE *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_STRING_TABLE) *, sk), \ - CHECKED_CAST(void *, ASN1_STRING_TABLE *, p))) - -#define sk_ASN1_STRING_TABLE_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(ASN1_STRING_TABLE) *, sk), \ - (out_index), CHECKED_CAST(void *, ASN1_STRING_TABLE *, p)) - -#define sk_ASN1_STRING_TABLE_shift(sk) \ - ((ASN1_STRING_TABLE *)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_STRING_TABLE) *, sk))) - -#define sk_ASN1_STRING_TABLE_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(ASN1_STRING_TABLE) *, sk), \ - CHECKED_CAST(void *, ASN1_STRING_TABLE *, p)) - -#define sk_ASN1_STRING_TABLE_pop(sk) \ - ((ASN1_STRING_TABLE *)sk_pop( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_STRING_TABLE) *, sk))) - -#define sk_ASN1_STRING_TABLE_dup(sk) \ - ((STACK_OF(ASN1_STRING_TABLE) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(ASN1_STRING_TABLE) *, sk))) - -#define sk_ASN1_STRING_TABLE_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(ASN1_STRING_TABLE) *, sk)) - -#define sk_ASN1_STRING_TABLE_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(ASN1_STRING_TABLE) *, sk)) - -#define sk_ASN1_STRING_TABLE_set_cmp_func(sk, comp) \ - ((int (*)(const ASN1_STRING_TABLE **a, const ASN1_STRING_TABLE **b)) \ - sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_STRING_TABLE) *, sk), \ - CHECKED_CAST(stack_cmp_func, int (*)(const ASN1_STRING_TABLE **a, \ - const ASN1_STRING_TABLE **b), \ - comp))) - -#define sk_ASN1_STRING_TABLE_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(ASN1_STRING_TABLE) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(ASN1_STRING_TABLE) *, sk), \ - CHECKED_CAST(void *(*)(void *), \ - ASN1_STRING_TABLE *(*)(ASN1_STRING_TABLE *), copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(ASN1_STRING_TABLE *), \ - free_func))) - -/* ASN1_TYPE */ -#define sk_ASN1_TYPE_new(comp) \ - ((STACK_OF(ASN1_TYPE) *)sk_new( \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const ASN1_TYPE **a, const ASN1_TYPE **b), comp))) - -#define sk_ASN1_TYPE_new_null() ((STACK_OF(ASN1_TYPE) *)sk_new_null()) - -#define sk_ASN1_TYPE_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(ASN1_TYPE) *, sk)) - -#define sk_ASN1_TYPE_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(ASN1_TYPE) *, sk)); - -#define sk_ASN1_TYPE_value(sk, i) \ - ((ASN1_TYPE *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(ASN1_TYPE) *, sk), (i))) - -#define sk_ASN1_TYPE_set(sk, i, p) \ - ((ASN1_TYPE *)sk_set(CHECKED_CAST(_STACK *, STACK_OF(ASN1_TYPE) *, sk), (i), \ - CHECKED_CAST(void *, ASN1_TYPE *, p))) - -#define sk_ASN1_TYPE_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(ASN1_TYPE) *, sk)) - -#define sk_ASN1_TYPE_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_TYPE) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(ASN1_TYPE *), free_func)) - -#define sk_ASN1_TYPE_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(ASN1_TYPE) *, sk), \ - CHECKED_CAST(void *, ASN1_TYPE *, p), (where)) - -#define sk_ASN1_TYPE_delete(sk, where) \ - ((ASN1_TYPE *)sk_delete(CHECKED_CAST(_STACK *, STACK_OF(ASN1_TYPE) *, sk), \ - (where))) - -#define sk_ASN1_TYPE_delete_ptr(sk, p) \ - ((ASN1_TYPE *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_TYPE) *, sk), \ - CHECKED_CAST(void *, ASN1_TYPE *, p))) - -#define sk_ASN1_TYPE_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(ASN1_TYPE) *, sk), (out_index), \ - CHECKED_CAST(void *, ASN1_TYPE *, p)) - -#define sk_ASN1_TYPE_shift(sk) \ - ((ASN1_TYPE *)sk_shift(CHECKED_CAST(_STACK *, STACK_OF(ASN1_TYPE) *, sk))) - -#define sk_ASN1_TYPE_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(ASN1_TYPE) *, sk), \ - CHECKED_CAST(void *, ASN1_TYPE *, p)) - -#define sk_ASN1_TYPE_pop(sk) \ - ((ASN1_TYPE *)sk_pop(CHECKED_CAST(_STACK *, STACK_OF(ASN1_TYPE) *, sk))) - -#define sk_ASN1_TYPE_dup(sk) \ - ((STACK_OF(ASN1_TYPE) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(ASN1_TYPE) *, sk))) - -#define sk_ASN1_TYPE_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(ASN1_TYPE) *, sk)) - -#define sk_ASN1_TYPE_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(ASN1_TYPE) *, sk)) - -#define sk_ASN1_TYPE_set_cmp_func(sk, comp) \ - ((int (*)(const ASN1_TYPE **a, const ASN1_TYPE **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_TYPE) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const ASN1_TYPE **a, const ASN1_TYPE **b), comp))) - -#define sk_ASN1_TYPE_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(ASN1_TYPE) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(ASN1_TYPE) *, sk), \ - CHECKED_CAST(void *(*)(void *), ASN1_TYPE *(*)(ASN1_TYPE *), copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(ASN1_TYPE *), free_func))) - -/* ASN1_VALUE */ -#define sk_ASN1_VALUE_new(comp) \ - ((STACK_OF(ASN1_VALUE) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, int (*)(const ASN1_VALUE **a, const ASN1_VALUE **b), \ - comp))) - -#define sk_ASN1_VALUE_new_null() ((STACK_OF(ASN1_VALUE) *)sk_new_null()) - -#define sk_ASN1_VALUE_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(ASN1_VALUE) *, sk)) - -#define sk_ASN1_VALUE_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(ASN1_VALUE) *, sk)); - -#define sk_ASN1_VALUE_value(sk, i) \ - ((ASN1_VALUE *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(ASN1_VALUE) *, sk), (i))) - -#define sk_ASN1_VALUE_set(sk, i, p) \ - ((ASN1_VALUE *)sk_set(CHECKED_CAST(_STACK *, STACK_OF(ASN1_VALUE) *, sk), \ - (i), CHECKED_CAST(void *, ASN1_VALUE *, p))) - -#define sk_ASN1_VALUE_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(ASN1_VALUE) *, sk)) - -#define sk_ASN1_VALUE_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_VALUE) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(ASN1_VALUE *), free_func)) - -#define sk_ASN1_VALUE_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(ASN1_VALUE) *, sk), \ - CHECKED_CAST(void *, ASN1_VALUE *, p), (where)) - -#define sk_ASN1_VALUE_delete(sk, where) \ - ((ASN1_VALUE *)sk_delete(CHECKED_CAST(_STACK *, STACK_OF(ASN1_VALUE) *, sk), \ - (where))) - -#define sk_ASN1_VALUE_delete_ptr(sk, p) \ - ((ASN1_VALUE *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_VALUE) *, sk), \ - CHECKED_CAST(void *, ASN1_VALUE *, p))) - -#define sk_ASN1_VALUE_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(ASN1_VALUE) *, sk), (out_index), \ - CHECKED_CAST(void *, ASN1_VALUE *, p)) - -#define sk_ASN1_VALUE_shift(sk) \ - ((ASN1_VALUE *)sk_shift(CHECKED_CAST(_STACK *, STACK_OF(ASN1_VALUE) *, sk))) - -#define sk_ASN1_VALUE_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(ASN1_VALUE) *, sk), \ - CHECKED_CAST(void *, ASN1_VALUE *, p)) - -#define sk_ASN1_VALUE_pop(sk) \ - ((ASN1_VALUE *)sk_pop(CHECKED_CAST(_STACK *, STACK_OF(ASN1_VALUE) *, sk))) - -#define sk_ASN1_VALUE_dup(sk) \ - ((STACK_OF(ASN1_VALUE) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(ASN1_VALUE) *, sk))) - -#define sk_ASN1_VALUE_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(ASN1_VALUE) *, sk)) - -#define sk_ASN1_VALUE_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(ASN1_VALUE) *, sk)) - -#define sk_ASN1_VALUE_set_cmp_func(sk, comp) \ - ((int (*)(const ASN1_VALUE **a, const ASN1_VALUE **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(ASN1_VALUE) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const ASN1_VALUE **a, const ASN1_VALUE **b), \ - comp))) - -#define sk_ASN1_VALUE_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(ASN1_VALUE) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(ASN1_VALUE) *, sk), \ - CHECKED_CAST(void *(*)(void *), ASN1_VALUE *(*)(ASN1_VALUE *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(ASN1_VALUE *), free_func))) - -/* BIO */ -#define sk_BIO_new(comp) \ - ((STACK_OF(BIO) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, int (*)(const BIO **a, const BIO **b), comp))) - -#define sk_BIO_new_null() ((STACK_OF(BIO) *)sk_new_null()) - -#define sk_BIO_num(sk) sk_num(CHECKED_CAST(_STACK *, STACK_OF(BIO) *, sk)) - -#define sk_BIO_zero(sk) sk_zero(CHECKED_CAST(_STACK *, STACK_OF(BIO) *, sk)); - -#define sk_BIO_value(sk, i) \ - ((BIO *)sk_value(CHECKED_CAST(_STACK *, const STACK_OF(BIO) *, sk), (i))) - -#define sk_BIO_set(sk, i, p) \ - ((BIO *)sk_set(CHECKED_CAST(_STACK *, STACK_OF(BIO) *, sk), (i), \ - CHECKED_CAST(void *, BIO *, p))) - -#define sk_BIO_free(sk) sk_free(CHECKED_CAST(_STACK *, STACK_OF(BIO) *, sk)) - -#define sk_BIO_pop_free(sk, free_func) \ - sk_pop_free(CHECKED_CAST(_STACK *, STACK_OF(BIO) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(BIO *), free_func)) - -#define sk_BIO_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(BIO) *, sk), \ - CHECKED_CAST(void *, BIO *, p), (where)) - -#define sk_BIO_delete(sk, where) \ - ((BIO *)sk_delete(CHECKED_CAST(_STACK *, STACK_OF(BIO) *, sk), (where))) - -#define sk_BIO_delete_ptr(sk, p) \ - ((BIO *)sk_delete_ptr(CHECKED_CAST(_STACK *, STACK_OF(BIO) *, sk), \ - CHECKED_CAST(void *, BIO *, p))) - -#define sk_BIO_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(BIO) *, sk), (out_index), \ - CHECKED_CAST(void *, BIO *, p)) - -#define sk_BIO_shift(sk) \ - ((BIO *)sk_shift(CHECKED_CAST(_STACK *, STACK_OF(BIO) *, sk))) - -#define sk_BIO_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(BIO) *, sk), \ - CHECKED_CAST(void *, BIO *, p)) - -#define sk_BIO_pop(sk) \ - ((BIO *)sk_pop(CHECKED_CAST(_STACK *, STACK_OF(BIO) *, sk))) - -#define sk_BIO_dup(sk) \ - ((STACK_OF(BIO) *)sk_dup(CHECKED_CAST(_STACK *, const STACK_OF(BIO) *, sk))) - -#define sk_BIO_sort(sk) sk_sort(CHECKED_CAST(_STACK *, STACK_OF(BIO) *, sk)) - -#define sk_BIO_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(BIO) *, sk)) - -#define sk_BIO_set_cmp_func(sk, comp) \ - ((int (*)(const BIO **a, const BIO **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(BIO) *, sk), \ - CHECKED_CAST(stack_cmp_func, int (*)(const BIO **a, const BIO **b), \ - comp))) - -#define sk_BIO_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(BIO) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(BIO) *, sk), \ - CHECKED_CAST(void *(*)(void *), BIO *(*)(BIO *), copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(BIO *), free_func))) - -/* BY_DIR_ENTRY */ -#define sk_BY_DIR_ENTRY_new(comp) \ - ((STACK_OF(BY_DIR_ENTRY) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, int (*)(const BY_DIR_ENTRY **a, const BY_DIR_ENTRY **b), \ - comp))) - -#define sk_BY_DIR_ENTRY_new_null() ((STACK_OF(BY_DIR_ENTRY) *)sk_new_null()) - -#define sk_BY_DIR_ENTRY_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_ENTRY) *, sk)) - -#define sk_BY_DIR_ENTRY_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_ENTRY) *, sk)); - -#define sk_BY_DIR_ENTRY_value(sk, i) \ - ((BY_DIR_ENTRY *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(BY_DIR_ENTRY) *, sk), (i))) - -#define sk_BY_DIR_ENTRY_set(sk, i, p) \ - ((BY_DIR_ENTRY *)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_ENTRY) *, sk), (i), \ - CHECKED_CAST(void *, BY_DIR_ENTRY *, p))) - -#define sk_BY_DIR_ENTRY_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_ENTRY) *, sk)) - -#define sk_BY_DIR_ENTRY_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_ENTRY) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(BY_DIR_ENTRY *), free_func)) - -#define sk_BY_DIR_ENTRY_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_ENTRY) *, sk), \ - CHECKED_CAST(void *, BY_DIR_ENTRY *, p), (where)) - -#define sk_BY_DIR_ENTRY_delete(sk, where) \ - ((BY_DIR_ENTRY *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_ENTRY) *, sk), (where))) - -#define sk_BY_DIR_ENTRY_delete_ptr(sk, p) \ - ((BY_DIR_ENTRY *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_ENTRY) *, sk), \ - CHECKED_CAST(void *, BY_DIR_ENTRY *, p))) - -#define sk_BY_DIR_ENTRY_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_ENTRY) *, sk), (out_index), \ - CHECKED_CAST(void *, BY_DIR_ENTRY *, p)) - -#define sk_BY_DIR_ENTRY_shift(sk) \ - ((BY_DIR_ENTRY *)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_ENTRY) *, sk))) - -#define sk_BY_DIR_ENTRY_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_ENTRY) *, sk), \ - CHECKED_CAST(void *, BY_DIR_ENTRY *, p)) - -#define sk_BY_DIR_ENTRY_pop(sk) \ - ((BY_DIR_ENTRY *)sk_pop(CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_ENTRY) *, sk))) - -#define sk_BY_DIR_ENTRY_dup(sk) \ - ((STACK_OF(BY_DIR_ENTRY) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(BY_DIR_ENTRY) *, sk))) - -#define sk_BY_DIR_ENTRY_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_ENTRY) *, sk)) - -#define sk_BY_DIR_ENTRY_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(BY_DIR_ENTRY) *, sk)) - -#define sk_BY_DIR_ENTRY_set_cmp_func(sk, comp) \ - ((int (*)(const BY_DIR_ENTRY **a, const BY_DIR_ENTRY **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_ENTRY) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const BY_DIR_ENTRY **a, const BY_DIR_ENTRY **b), \ - comp))) - -#define sk_BY_DIR_ENTRY_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(BY_DIR_ENTRY) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(BY_DIR_ENTRY) *, sk), \ - CHECKED_CAST(void *(*)(void *), BY_DIR_ENTRY *(*)(BY_DIR_ENTRY *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(BY_DIR_ENTRY *), free_func))) - -/* BY_DIR_HASH */ -#define sk_BY_DIR_HASH_new(comp) \ - ((STACK_OF(BY_DIR_HASH) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, int (*)(const BY_DIR_HASH **a, const BY_DIR_HASH **b), \ - comp))) - -#define sk_BY_DIR_HASH_new_null() ((STACK_OF(BY_DIR_HASH) *)sk_new_null()) - -#define sk_BY_DIR_HASH_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_HASH) *, sk)) - -#define sk_BY_DIR_HASH_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_HASH) *, sk)); - -#define sk_BY_DIR_HASH_value(sk, i) \ - ((BY_DIR_HASH *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(BY_DIR_HASH) *, sk), (i))) - -#define sk_BY_DIR_HASH_set(sk, i, p) \ - ((BY_DIR_HASH *)sk_set(CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_HASH) *, sk), \ - (i), CHECKED_CAST(void *, BY_DIR_HASH *, p))) - -#define sk_BY_DIR_HASH_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_HASH) *, sk)) - -#define sk_BY_DIR_HASH_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_HASH) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(BY_DIR_HASH *), free_func)) - -#define sk_BY_DIR_HASH_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_HASH) *, sk), \ - CHECKED_CAST(void *, BY_DIR_HASH *, p), (where)) - -#define sk_BY_DIR_HASH_delete(sk, where) \ - ((BY_DIR_HASH *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_HASH) *, sk), (where))) - -#define sk_BY_DIR_HASH_delete_ptr(sk, p) \ - ((BY_DIR_HASH *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_HASH) *, sk), \ - CHECKED_CAST(void *, BY_DIR_HASH *, p))) - -#define sk_BY_DIR_HASH_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_HASH) *, sk), (out_index), \ - CHECKED_CAST(void *, BY_DIR_HASH *, p)) - -#define sk_BY_DIR_HASH_shift(sk) \ - ((BY_DIR_HASH *)sk_shift(CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_HASH) *, sk))) - -#define sk_BY_DIR_HASH_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_HASH) *, sk), \ - CHECKED_CAST(void *, BY_DIR_HASH *, p)) - -#define sk_BY_DIR_HASH_pop(sk) \ - ((BY_DIR_HASH *)sk_pop(CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_HASH) *, sk))) - -#define sk_BY_DIR_HASH_dup(sk) \ - ((STACK_OF(BY_DIR_HASH) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(BY_DIR_HASH) *, sk))) - -#define sk_BY_DIR_HASH_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_HASH) *, sk)) - -#define sk_BY_DIR_HASH_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(BY_DIR_HASH) *, sk)) - -#define sk_BY_DIR_HASH_set_cmp_func(sk, comp) \ - ((int (*)(const BY_DIR_HASH **a, const BY_DIR_HASH **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(BY_DIR_HASH) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const BY_DIR_HASH **a, const BY_DIR_HASH **b), \ - comp))) - -#define sk_BY_DIR_HASH_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(BY_DIR_HASH) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(BY_DIR_HASH) *, sk), \ - CHECKED_CAST(void *(*)(void *), BY_DIR_HASH *(*)(BY_DIR_HASH *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(BY_DIR_HASH *), free_func))) - -/* CONF_VALUE */ -#define sk_CONF_VALUE_new(comp) \ - ((STACK_OF(CONF_VALUE) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, int (*)(const CONF_VALUE **a, const CONF_VALUE **b), \ - comp))) - -#define sk_CONF_VALUE_new_null() ((STACK_OF(CONF_VALUE) *)sk_new_null()) - -#define sk_CONF_VALUE_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(CONF_VALUE) *, sk)) - -#define sk_CONF_VALUE_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(CONF_VALUE) *, sk)); - -#define sk_CONF_VALUE_value(sk, i) \ - ((CONF_VALUE *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(CONF_VALUE) *, sk), (i))) - -#define sk_CONF_VALUE_set(sk, i, p) \ - ((CONF_VALUE *)sk_set(CHECKED_CAST(_STACK *, STACK_OF(CONF_VALUE) *, sk), \ - (i), CHECKED_CAST(void *, CONF_VALUE *, p))) - -#define sk_CONF_VALUE_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(CONF_VALUE) *, sk)) - -#define sk_CONF_VALUE_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(CONF_VALUE) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(CONF_VALUE *), free_func)) - -#define sk_CONF_VALUE_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(CONF_VALUE) *, sk), \ - CHECKED_CAST(void *, CONF_VALUE *, p), (where)) - -#define sk_CONF_VALUE_delete(sk, where) \ - ((CONF_VALUE *)sk_delete(CHECKED_CAST(_STACK *, STACK_OF(CONF_VALUE) *, sk), \ - (where))) - -#define sk_CONF_VALUE_delete_ptr(sk, p) \ - ((CONF_VALUE *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(CONF_VALUE) *, sk), \ - CHECKED_CAST(void *, CONF_VALUE *, p))) - -#define sk_CONF_VALUE_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(CONF_VALUE) *, sk), (out_index), \ - CHECKED_CAST(void *, CONF_VALUE *, p)) - -#define sk_CONF_VALUE_shift(sk) \ - ((CONF_VALUE *)sk_shift(CHECKED_CAST(_STACK *, STACK_OF(CONF_VALUE) *, sk))) - -#define sk_CONF_VALUE_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(CONF_VALUE) *, sk), \ - CHECKED_CAST(void *, CONF_VALUE *, p)) - -#define sk_CONF_VALUE_pop(sk) \ - ((CONF_VALUE *)sk_pop(CHECKED_CAST(_STACK *, STACK_OF(CONF_VALUE) *, sk))) - -#define sk_CONF_VALUE_dup(sk) \ - ((STACK_OF(CONF_VALUE) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(CONF_VALUE) *, sk))) - -#define sk_CONF_VALUE_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(CONF_VALUE) *, sk)) - -#define sk_CONF_VALUE_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(CONF_VALUE) *, sk)) - -#define sk_CONF_VALUE_set_cmp_func(sk, comp) \ - ((int (*)(const CONF_VALUE **a, const CONF_VALUE **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(CONF_VALUE) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const CONF_VALUE **a, const CONF_VALUE **b), \ - comp))) - -#define sk_CONF_VALUE_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(CONF_VALUE) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(CONF_VALUE) *, sk), \ - CHECKED_CAST(void *(*)(void *), CONF_VALUE *(*)(CONF_VALUE *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(CONF_VALUE *), free_func))) - -/* CRYPTO_EX_DATA_FUNCS */ -#define sk_CRYPTO_EX_DATA_FUNCS_new(comp) \ - ((STACK_OF(CRYPTO_EX_DATA_FUNCS) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, \ - int (*)(const CRYPTO_EX_DATA_FUNCS **a, const CRYPTO_EX_DATA_FUNCS **b), \ - comp))) - -#define sk_CRYPTO_EX_DATA_FUNCS_new_null() \ - ((STACK_OF(CRYPTO_EX_DATA_FUNCS) *)sk_new_null()) - -#define sk_CRYPTO_EX_DATA_FUNCS_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(CRYPTO_EX_DATA_FUNCS) *, sk)) - -#define sk_CRYPTO_EX_DATA_FUNCS_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(CRYPTO_EX_DATA_FUNCS) *, sk)); - -#define sk_CRYPTO_EX_DATA_FUNCS_value(sk, i) \ - ((CRYPTO_EX_DATA_FUNCS *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(CRYPTO_EX_DATA_FUNCS) *, sk), \ - (i))) - -#define sk_CRYPTO_EX_DATA_FUNCS_set(sk, i, p) \ - ((CRYPTO_EX_DATA_FUNCS *)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(CRYPTO_EX_DATA_FUNCS) *, sk), (i), \ - CHECKED_CAST(void *, CRYPTO_EX_DATA_FUNCS *, p))) - -#define sk_CRYPTO_EX_DATA_FUNCS_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(CRYPTO_EX_DATA_FUNCS) *, sk)) - -#define sk_CRYPTO_EX_DATA_FUNCS_pop_free(sk, free_func) \ - sk_pop_free(CHECKED_CAST(_STACK *, STACK_OF(CRYPTO_EX_DATA_FUNCS) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(CRYPTO_EX_DATA_FUNCS *), \ - free_func)) - -#define sk_CRYPTO_EX_DATA_FUNCS_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(CRYPTO_EX_DATA_FUNCS) *, sk), \ - CHECKED_CAST(void *, CRYPTO_EX_DATA_FUNCS *, p), (where)) - -#define sk_CRYPTO_EX_DATA_FUNCS_delete(sk, where) \ - ((CRYPTO_EX_DATA_FUNCS *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(CRYPTO_EX_DATA_FUNCS) *, sk), (where))) - -#define sk_CRYPTO_EX_DATA_FUNCS_delete_ptr(sk, p) \ - ((CRYPTO_EX_DATA_FUNCS *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(CRYPTO_EX_DATA_FUNCS) *, sk), \ - CHECKED_CAST(void *, CRYPTO_EX_DATA_FUNCS *, p))) - -#define sk_CRYPTO_EX_DATA_FUNCS_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(CRYPTO_EX_DATA_FUNCS) *, sk), \ - (out_index), CHECKED_CAST(void *, CRYPTO_EX_DATA_FUNCS *, p)) - -#define sk_CRYPTO_EX_DATA_FUNCS_shift(sk) \ - ((CRYPTO_EX_DATA_FUNCS *)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(CRYPTO_EX_DATA_FUNCS) *, sk))) - -#define sk_CRYPTO_EX_DATA_FUNCS_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(CRYPTO_EX_DATA_FUNCS) *, sk), \ - CHECKED_CAST(void *, CRYPTO_EX_DATA_FUNCS *, p)) - -#define sk_CRYPTO_EX_DATA_FUNCS_pop(sk) \ - ((CRYPTO_EX_DATA_FUNCS *)sk_pop( \ - CHECKED_CAST(_STACK *, STACK_OF(CRYPTO_EX_DATA_FUNCS) *, sk))) - -#define sk_CRYPTO_EX_DATA_FUNCS_dup(sk) \ - ((STACK_OF(CRYPTO_EX_DATA_FUNCS) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(CRYPTO_EX_DATA_FUNCS) *, sk))) - -#define sk_CRYPTO_EX_DATA_FUNCS_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(CRYPTO_EX_DATA_FUNCS) *, sk)) - -#define sk_CRYPTO_EX_DATA_FUNCS_is_sorted(sk) \ - sk_is_sorted( \ - CHECKED_CAST(_STACK *, const STACK_OF(CRYPTO_EX_DATA_FUNCS) *, sk)) - -#define sk_CRYPTO_EX_DATA_FUNCS_set_cmp_func(sk, comp) \ - ((int (*)(const CRYPTO_EX_DATA_FUNCS **a, const CRYPTO_EX_DATA_FUNCS **b)) \ - sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(CRYPTO_EX_DATA_FUNCS) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const CRYPTO_EX_DATA_FUNCS **a, \ - const CRYPTO_EX_DATA_FUNCS **b), \ - comp))) - -#define sk_CRYPTO_EX_DATA_FUNCS_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(CRYPTO_EX_DATA_FUNCS) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(CRYPTO_EX_DATA_FUNCS) *, \ - sk), \ - CHECKED_CAST(void *(*)(void *), \ - CRYPTO_EX_DATA_FUNCS *(*)(CRYPTO_EX_DATA_FUNCS *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(CRYPTO_EX_DATA_FUNCS *), \ - free_func))) - -/* DIST_POINT */ -#define sk_DIST_POINT_new(comp) \ - ((STACK_OF(DIST_POINT) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, int (*)(const DIST_POINT **a, const DIST_POINT **b), \ - comp))) - -#define sk_DIST_POINT_new_null() ((STACK_OF(DIST_POINT) *)sk_new_null()) - -#define sk_DIST_POINT_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(DIST_POINT) *, sk)) - -#define sk_DIST_POINT_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(DIST_POINT) *, sk)); - -#define sk_DIST_POINT_value(sk, i) \ - ((DIST_POINT *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(DIST_POINT) *, sk), (i))) - -#define sk_DIST_POINT_set(sk, i, p) \ - ((DIST_POINT *)sk_set(CHECKED_CAST(_STACK *, STACK_OF(DIST_POINT) *, sk), \ - (i), CHECKED_CAST(void *, DIST_POINT *, p))) - -#define sk_DIST_POINT_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(DIST_POINT) *, sk)) - -#define sk_DIST_POINT_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(DIST_POINT) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(DIST_POINT *), free_func)) - -#define sk_DIST_POINT_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(DIST_POINT) *, sk), \ - CHECKED_CAST(void *, DIST_POINT *, p), (where)) - -#define sk_DIST_POINT_delete(sk, where) \ - ((DIST_POINT *)sk_delete(CHECKED_CAST(_STACK *, STACK_OF(DIST_POINT) *, sk), \ - (where))) - -#define sk_DIST_POINT_delete_ptr(sk, p) \ - ((DIST_POINT *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(DIST_POINT) *, sk), \ - CHECKED_CAST(void *, DIST_POINT *, p))) - -#define sk_DIST_POINT_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(DIST_POINT) *, sk), (out_index), \ - CHECKED_CAST(void *, DIST_POINT *, p)) - -#define sk_DIST_POINT_shift(sk) \ - ((DIST_POINT *)sk_shift(CHECKED_CAST(_STACK *, STACK_OF(DIST_POINT) *, sk))) - -#define sk_DIST_POINT_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(DIST_POINT) *, sk), \ - CHECKED_CAST(void *, DIST_POINT *, p)) - -#define sk_DIST_POINT_pop(sk) \ - ((DIST_POINT *)sk_pop(CHECKED_CAST(_STACK *, STACK_OF(DIST_POINT) *, sk))) - -#define sk_DIST_POINT_dup(sk) \ - ((STACK_OF(DIST_POINT) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(DIST_POINT) *, sk))) - -#define sk_DIST_POINT_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(DIST_POINT) *, sk)) - -#define sk_DIST_POINT_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(DIST_POINT) *, sk)) - -#define sk_DIST_POINT_set_cmp_func(sk, comp) \ - ((int (*)(const DIST_POINT **a, const DIST_POINT **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(DIST_POINT) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const DIST_POINT **a, const DIST_POINT **b), \ - comp))) - -#define sk_DIST_POINT_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(DIST_POINT) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(DIST_POINT) *, sk), \ - CHECKED_CAST(void *(*)(void *), DIST_POINT *(*)(DIST_POINT *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(DIST_POINT *), free_func))) - -/* GENERAL_NAME */ -#define sk_GENERAL_NAME_new(comp) \ - ((STACK_OF(GENERAL_NAME) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, int (*)(const GENERAL_NAME **a, const GENERAL_NAME **b), \ - comp))) - -#define sk_GENERAL_NAME_new_null() ((STACK_OF(GENERAL_NAME) *)sk_new_null()) - -#define sk_GENERAL_NAME_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAME) *, sk)) - -#define sk_GENERAL_NAME_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAME) *, sk)); - -#define sk_GENERAL_NAME_value(sk, i) \ - ((GENERAL_NAME *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(GENERAL_NAME) *, sk), (i))) - -#define sk_GENERAL_NAME_set(sk, i, p) \ - ((GENERAL_NAME *)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAME) *, sk), (i), \ - CHECKED_CAST(void *, GENERAL_NAME *, p))) - -#define sk_GENERAL_NAME_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAME) *, sk)) - -#define sk_GENERAL_NAME_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAME) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(GENERAL_NAME *), free_func)) - -#define sk_GENERAL_NAME_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAME) *, sk), \ - CHECKED_CAST(void *, GENERAL_NAME *, p), (where)) - -#define sk_GENERAL_NAME_delete(sk, where) \ - ((GENERAL_NAME *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAME) *, sk), (where))) - -#define sk_GENERAL_NAME_delete_ptr(sk, p) \ - ((GENERAL_NAME *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAME) *, sk), \ - CHECKED_CAST(void *, GENERAL_NAME *, p))) - -#define sk_GENERAL_NAME_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAME) *, sk), (out_index), \ - CHECKED_CAST(void *, GENERAL_NAME *, p)) - -#define sk_GENERAL_NAME_shift(sk) \ - ((GENERAL_NAME *)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAME) *, sk))) - -#define sk_GENERAL_NAME_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAME) *, sk), \ - CHECKED_CAST(void *, GENERAL_NAME *, p)) - -#define sk_GENERAL_NAME_pop(sk) \ - ((GENERAL_NAME *)sk_pop(CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAME) *, sk))) - -#define sk_GENERAL_NAME_dup(sk) \ - ((STACK_OF(GENERAL_NAME) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(GENERAL_NAME) *, sk))) - -#define sk_GENERAL_NAME_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAME) *, sk)) - -#define sk_GENERAL_NAME_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(GENERAL_NAME) *, sk)) - -#define sk_GENERAL_NAME_set_cmp_func(sk, comp) \ - ((int (*)(const GENERAL_NAME **a, const GENERAL_NAME **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAME) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const GENERAL_NAME **a, const GENERAL_NAME **b), \ - comp))) - -#define sk_GENERAL_NAME_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(GENERAL_NAME) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(GENERAL_NAME) *, sk), \ - CHECKED_CAST(void *(*)(void *), GENERAL_NAME *(*)(GENERAL_NAME *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(GENERAL_NAME *), free_func))) - -/* GENERAL_NAMES */ -#define sk_GENERAL_NAMES_new(comp) \ - ((STACK_OF(GENERAL_NAMES) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, \ - int (*)(const GENERAL_NAMES **a, const GENERAL_NAMES **b), comp))) - -#define sk_GENERAL_NAMES_new_null() ((STACK_OF(GENERAL_NAMES) *)sk_new_null()) - -#define sk_GENERAL_NAMES_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAMES) *, sk)) - -#define sk_GENERAL_NAMES_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAMES) *, sk)); - -#define sk_GENERAL_NAMES_value(sk, i) \ - ((GENERAL_NAMES *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(GENERAL_NAMES) *, sk), (i))) - -#define sk_GENERAL_NAMES_set(sk, i, p) \ - ((GENERAL_NAMES *)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAMES) *, sk), (i), \ - CHECKED_CAST(void *, GENERAL_NAMES *, p))) - -#define sk_GENERAL_NAMES_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAMES) *, sk)) - -#define sk_GENERAL_NAMES_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAMES) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(GENERAL_NAMES *), free_func)) - -#define sk_GENERAL_NAMES_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAMES) *, sk), \ - CHECKED_CAST(void *, GENERAL_NAMES *, p), (where)) - -#define sk_GENERAL_NAMES_delete(sk, where) \ - ((GENERAL_NAMES *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAMES) *, sk), (where))) - -#define sk_GENERAL_NAMES_delete_ptr(sk, p) \ - ((GENERAL_NAMES *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAMES) *, sk), \ - CHECKED_CAST(void *, GENERAL_NAMES *, p))) - -#define sk_GENERAL_NAMES_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAMES) *, sk), (out_index), \ - CHECKED_CAST(void *, GENERAL_NAMES *, p)) - -#define sk_GENERAL_NAMES_shift(sk) \ - ((GENERAL_NAMES *)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAMES) *, sk))) - -#define sk_GENERAL_NAMES_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAMES) *, sk), \ - CHECKED_CAST(void *, GENERAL_NAMES *, p)) - -#define sk_GENERAL_NAMES_pop(sk) \ - ((GENERAL_NAMES *)sk_pop( \ - CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAMES) *, sk))) - -#define sk_GENERAL_NAMES_dup(sk) \ - ((STACK_OF(GENERAL_NAMES) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(GENERAL_NAMES) *, sk))) - -#define sk_GENERAL_NAMES_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAMES) *, sk)) - -#define sk_GENERAL_NAMES_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(GENERAL_NAMES) *, sk)) - -#define sk_GENERAL_NAMES_set_cmp_func(sk, comp) \ - ((int (*)(const GENERAL_NAMES **a, const GENERAL_NAMES **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(GENERAL_NAMES) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const GENERAL_NAMES **a, const GENERAL_NAMES **b), \ - comp))) - -#define sk_GENERAL_NAMES_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(GENERAL_NAMES) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(GENERAL_NAMES) *, sk), \ - CHECKED_CAST(void *(*)(void *), GENERAL_NAMES *(*)(GENERAL_NAMES *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(GENERAL_NAMES *), free_func))) - -/* GENERAL_SUBTREE */ -#define sk_GENERAL_SUBTREE_new(comp) \ - ((STACK_OF(GENERAL_SUBTREE) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, \ - int (*)(const GENERAL_SUBTREE **a, const GENERAL_SUBTREE **b), comp))) - -#define sk_GENERAL_SUBTREE_new_null() \ - ((STACK_OF(GENERAL_SUBTREE) *)sk_new_null()) - -#define sk_GENERAL_SUBTREE_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(GENERAL_SUBTREE) *, sk)) - -#define sk_GENERAL_SUBTREE_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(GENERAL_SUBTREE) *, sk)); - -#define sk_GENERAL_SUBTREE_value(sk, i) \ - ((GENERAL_SUBTREE *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(GENERAL_SUBTREE) *, sk), (i))) - -#define sk_GENERAL_SUBTREE_set(sk, i, p) \ - ((GENERAL_SUBTREE *)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(GENERAL_SUBTREE) *, sk), (i), \ - CHECKED_CAST(void *, GENERAL_SUBTREE *, p))) - -#define sk_GENERAL_SUBTREE_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(GENERAL_SUBTREE) *, sk)) - -#define sk_GENERAL_SUBTREE_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(GENERAL_SUBTREE) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(GENERAL_SUBTREE *), free_func)) - -#define sk_GENERAL_SUBTREE_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(GENERAL_SUBTREE) *, sk), \ - CHECKED_CAST(void *, GENERAL_SUBTREE *, p), (where)) - -#define sk_GENERAL_SUBTREE_delete(sk, where) \ - ((GENERAL_SUBTREE *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(GENERAL_SUBTREE) *, sk), (where))) - -#define sk_GENERAL_SUBTREE_delete_ptr(sk, p) \ - ((GENERAL_SUBTREE *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(GENERAL_SUBTREE) *, sk), \ - CHECKED_CAST(void *, GENERAL_SUBTREE *, p))) - -#define sk_GENERAL_SUBTREE_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(GENERAL_SUBTREE) *, sk), \ - (out_index), CHECKED_CAST(void *, GENERAL_SUBTREE *, p)) - -#define sk_GENERAL_SUBTREE_shift(sk) \ - ((GENERAL_SUBTREE *)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(GENERAL_SUBTREE) *, sk))) - -#define sk_GENERAL_SUBTREE_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(GENERAL_SUBTREE) *, sk), \ - CHECKED_CAST(void *, GENERAL_SUBTREE *, p)) - -#define sk_GENERAL_SUBTREE_pop(sk) \ - ((GENERAL_SUBTREE *)sk_pop( \ - CHECKED_CAST(_STACK *, STACK_OF(GENERAL_SUBTREE) *, sk))) - -#define sk_GENERAL_SUBTREE_dup(sk) \ - ((STACK_OF(GENERAL_SUBTREE) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(GENERAL_SUBTREE) *, sk))) - -#define sk_GENERAL_SUBTREE_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(GENERAL_SUBTREE) *, sk)) - -#define sk_GENERAL_SUBTREE_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(GENERAL_SUBTREE) *, sk)) - -#define sk_GENERAL_SUBTREE_set_cmp_func(sk, comp) \ - ((int (*)(const GENERAL_SUBTREE **a, const GENERAL_SUBTREE **b)) \ - sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(GENERAL_SUBTREE) *, sk), \ - CHECKED_CAST(stack_cmp_func, int (*)(const GENERAL_SUBTREE **a, \ - const GENERAL_SUBTREE **b), \ - comp))) - -#define sk_GENERAL_SUBTREE_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(GENERAL_SUBTREE) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(GENERAL_SUBTREE) *, sk), \ - CHECKED_CAST(void *(*)(void *), GENERAL_SUBTREE *(*)(GENERAL_SUBTREE *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(GENERAL_SUBTREE *), free_func))) - -/* MIME_HEADER */ -#define sk_MIME_HEADER_new(comp) \ - ((STACK_OF(MIME_HEADER) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, int (*)(const MIME_HEADER **a, const MIME_HEADER **b), \ - comp))) - -#define sk_MIME_HEADER_new_null() ((STACK_OF(MIME_HEADER) *)sk_new_null()) - -#define sk_MIME_HEADER_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(MIME_HEADER) *, sk)) - -#define sk_MIME_HEADER_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(MIME_HEADER) *, sk)); - -#define sk_MIME_HEADER_value(sk, i) \ - ((MIME_HEADER *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(MIME_HEADER) *, sk), (i))) - -#define sk_MIME_HEADER_set(sk, i, p) \ - ((MIME_HEADER *)sk_set(CHECKED_CAST(_STACK *, STACK_OF(MIME_HEADER) *, sk), \ - (i), CHECKED_CAST(void *, MIME_HEADER *, p))) - -#define sk_MIME_HEADER_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(MIME_HEADER) *, sk)) - -#define sk_MIME_HEADER_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(MIME_HEADER) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(MIME_HEADER *), free_func)) - -#define sk_MIME_HEADER_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(MIME_HEADER) *, sk), \ - CHECKED_CAST(void *, MIME_HEADER *, p), (where)) - -#define sk_MIME_HEADER_delete(sk, where) \ - ((MIME_HEADER *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(MIME_HEADER) *, sk), (where))) - -#define sk_MIME_HEADER_delete_ptr(sk, p) \ - ((MIME_HEADER *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(MIME_HEADER) *, sk), \ - CHECKED_CAST(void *, MIME_HEADER *, p))) - -#define sk_MIME_HEADER_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(MIME_HEADER) *, sk), (out_index), \ - CHECKED_CAST(void *, MIME_HEADER *, p)) - -#define sk_MIME_HEADER_shift(sk) \ - ((MIME_HEADER *)sk_shift(CHECKED_CAST(_STACK *, STACK_OF(MIME_HEADER) *, sk))) - -#define sk_MIME_HEADER_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(MIME_HEADER) *, sk), \ - CHECKED_CAST(void *, MIME_HEADER *, p)) - -#define sk_MIME_HEADER_pop(sk) \ - ((MIME_HEADER *)sk_pop(CHECKED_CAST(_STACK *, STACK_OF(MIME_HEADER) *, sk))) - -#define sk_MIME_HEADER_dup(sk) \ - ((STACK_OF(MIME_HEADER) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(MIME_HEADER) *, sk))) - -#define sk_MIME_HEADER_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(MIME_HEADER) *, sk)) - -#define sk_MIME_HEADER_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(MIME_HEADER) *, sk)) - -#define sk_MIME_HEADER_set_cmp_func(sk, comp) \ - ((int (*)(const MIME_HEADER **a, const MIME_HEADER **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(MIME_HEADER) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const MIME_HEADER **a, const MIME_HEADER **b), \ - comp))) - -#define sk_MIME_HEADER_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(MIME_HEADER) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(MIME_HEADER) *, sk), \ - CHECKED_CAST(void *(*)(void *), MIME_HEADER *(*)(MIME_HEADER *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(MIME_HEADER *), free_func))) - -/* PKCS7_SIGNER_INFO */ -#define sk_PKCS7_SIGNER_INFO_new(comp) \ - ((STACK_OF(PKCS7_SIGNER_INFO) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, \ - int (*)(const PKCS7_SIGNER_INFO **a, const PKCS7_SIGNER_INFO **b), \ - comp))) - -#define sk_PKCS7_SIGNER_INFO_new_null() \ - ((STACK_OF(PKCS7_SIGNER_INFO) *)sk_new_null()) - -#define sk_PKCS7_SIGNER_INFO_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(PKCS7_SIGNER_INFO) *, sk)) - -#define sk_PKCS7_SIGNER_INFO_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(PKCS7_SIGNER_INFO) *, sk)); - -#define sk_PKCS7_SIGNER_INFO_value(sk, i) \ - ((PKCS7_SIGNER_INFO *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(PKCS7_SIGNER_INFO) *, sk), (i))) - -#define sk_PKCS7_SIGNER_INFO_set(sk, i, p) \ - ((PKCS7_SIGNER_INFO *)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(PKCS7_SIGNER_INFO) *, sk), (i), \ - CHECKED_CAST(void *, PKCS7_SIGNER_INFO *, p))) - -#define sk_PKCS7_SIGNER_INFO_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(PKCS7_SIGNER_INFO) *, sk)) - -#define sk_PKCS7_SIGNER_INFO_pop_free(sk, free_func) \ - sk_pop_free(CHECKED_CAST(_STACK *, STACK_OF(PKCS7_SIGNER_INFO) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(PKCS7_SIGNER_INFO *), \ - free_func)) - -#define sk_PKCS7_SIGNER_INFO_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(PKCS7_SIGNER_INFO) *, sk), \ - CHECKED_CAST(void *, PKCS7_SIGNER_INFO *, p), (where)) - -#define sk_PKCS7_SIGNER_INFO_delete(sk, where) \ - ((PKCS7_SIGNER_INFO *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(PKCS7_SIGNER_INFO) *, sk), (where))) - -#define sk_PKCS7_SIGNER_INFO_delete_ptr(sk, p) \ - ((PKCS7_SIGNER_INFO *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(PKCS7_SIGNER_INFO) *, sk), \ - CHECKED_CAST(void *, PKCS7_SIGNER_INFO *, p))) - -#define sk_PKCS7_SIGNER_INFO_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(PKCS7_SIGNER_INFO) *, sk), \ - (out_index), CHECKED_CAST(void *, PKCS7_SIGNER_INFO *, p)) - -#define sk_PKCS7_SIGNER_INFO_shift(sk) \ - ((PKCS7_SIGNER_INFO *)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(PKCS7_SIGNER_INFO) *, sk))) - -#define sk_PKCS7_SIGNER_INFO_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(PKCS7_SIGNER_INFO) *, sk), \ - CHECKED_CAST(void *, PKCS7_SIGNER_INFO *, p)) - -#define sk_PKCS7_SIGNER_INFO_pop(sk) \ - ((PKCS7_SIGNER_INFO *)sk_pop( \ - CHECKED_CAST(_STACK *, STACK_OF(PKCS7_SIGNER_INFO) *, sk))) - -#define sk_PKCS7_SIGNER_INFO_dup(sk) \ - ((STACK_OF(PKCS7_SIGNER_INFO) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(PKCS7_SIGNER_INFO) *, sk))) - -#define sk_PKCS7_SIGNER_INFO_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(PKCS7_SIGNER_INFO) *, sk)) - -#define sk_PKCS7_SIGNER_INFO_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(PKCS7_SIGNER_INFO) *, sk)) - -#define sk_PKCS7_SIGNER_INFO_set_cmp_func(sk, comp) \ - ((int (*)(const PKCS7_SIGNER_INFO **a, const PKCS7_SIGNER_INFO **b)) \ - sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(PKCS7_SIGNER_INFO) *, sk), \ - CHECKED_CAST(stack_cmp_func, int (*)(const PKCS7_SIGNER_INFO **a, \ - const PKCS7_SIGNER_INFO **b), \ - comp))) - -#define sk_PKCS7_SIGNER_INFO_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(PKCS7_SIGNER_INFO) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(PKCS7_SIGNER_INFO) *, sk), \ - CHECKED_CAST(void *(*)(void *), \ - PKCS7_SIGNER_INFO *(*)(PKCS7_SIGNER_INFO *), copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(PKCS7_SIGNER_INFO *), \ - free_func))) - -/* PKCS7_RECIP_INFO */ -#define sk_PKCS7_RECIP_INFO_new(comp) \ - ((STACK_OF(PKCS7_RECIP_INFO) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, \ - int (*)(const PKCS7_RECIP_INFO **a, const PKCS7_RECIP_INFO **b), comp))) - -#define sk_PKCS7_RECIP_INFO_new_null() \ - ((STACK_OF(PKCS7_RECIP_INFO) *)sk_new_null()) - -#define sk_PKCS7_RECIP_INFO_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(PKCS7_RECIP_INFO) *, sk)) - -#define sk_PKCS7_RECIP_INFO_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(PKCS7_RECIP_INFO) *, sk)); - -#define sk_PKCS7_RECIP_INFO_value(sk, i) \ - ((PKCS7_RECIP_INFO *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(PKCS7_RECIP_INFO) *, sk), (i))) - -#define sk_PKCS7_RECIP_INFO_set(sk, i, p) \ - ((PKCS7_RECIP_INFO *)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(PKCS7_RECIP_INFO) *, sk), (i), \ - CHECKED_CAST(void *, PKCS7_RECIP_INFO *, p))) - -#define sk_PKCS7_RECIP_INFO_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(PKCS7_RECIP_INFO) *, sk)) - -#define sk_PKCS7_RECIP_INFO_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(PKCS7_RECIP_INFO) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(PKCS7_RECIP_INFO *), free_func)) - -#define sk_PKCS7_RECIP_INFO_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(PKCS7_RECIP_INFO) *, sk), \ - CHECKED_CAST(void *, PKCS7_RECIP_INFO *, p), (where)) - -#define sk_PKCS7_RECIP_INFO_delete(sk, where) \ - ((PKCS7_RECIP_INFO *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(PKCS7_RECIP_INFO) *, sk), (where))) - -#define sk_PKCS7_RECIP_INFO_delete_ptr(sk, p) \ - ((PKCS7_RECIP_INFO *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(PKCS7_RECIP_INFO) *, sk), \ - CHECKED_CAST(void *, PKCS7_RECIP_INFO *, p))) - -#define sk_PKCS7_RECIP_INFO_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(PKCS7_RECIP_INFO) *, sk), \ - (out_index), CHECKED_CAST(void *, PKCS7_RECIP_INFO *, p)) - -#define sk_PKCS7_RECIP_INFO_shift(sk) \ - ((PKCS7_RECIP_INFO *)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(PKCS7_RECIP_INFO) *, sk))) - -#define sk_PKCS7_RECIP_INFO_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(PKCS7_RECIP_INFO) *, sk), \ - CHECKED_CAST(void *, PKCS7_RECIP_INFO *, p)) - -#define sk_PKCS7_RECIP_INFO_pop(sk) \ - ((PKCS7_RECIP_INFO *)sk_pop( \ - CHECKED_CAST(_STACK *, STACK_OF(PKCS7_RECIP_INFO) *, sk))) - -#define sk_PKCS7_RECIP_INFO_dup(sk) \ - ((STACK_OF(PKCS7_RECIP_INFO) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(PKCS7_RECIP_INFO) *, sk))) - -#define sk_PKCS7_RECIP_INFO_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(PKCS7_RECIP_INFO) *, sk)) - -#define sk_PKCS7_RECIP_INFO_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(PKCS7_RECIP_INFO) *, sk)) - -#define sk_PKCS7_RECIP_INFO_set_cmp_func(sk, comp) \ - ((int (*)(const PKCS7_RECIP_INFO **a, const PKCS7_RECIP_INFO **b)) \ - sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(PKCS7_RECIP_INFO) *, sk), \ - CHECKED_CAST(stack_cmp_func, int (*)(const PKCS7_RECIP_INFO **a, \ - const PKCS7_RECIP_INFO **b), \ - comp))) - -#define sk_PKCS7_RECIP_INFO_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(PKCS7_RECIP_INFO) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(PKCS7_RECIP_INFO) *, sk), \ - CHECKED_CAST(void *(*)(void *), \ - PKCS7_RECIP_INFO *(*)(PKCS7_RECIP_INFO *), copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(PKCS7_RECIP_INFO *), \ - free_func))) - -/* POLICYINFO */ -#define sk_POLICYINFO_new(comp) \ - ((STACK_OF(POLICYINFO) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, int (*)(const POLICYINFO **a, const POLICYINFO **b), \ - comp))) - -#define sk_POLICYINFO_new_null() ((STACK_OF(POLICYINFO) *)sk_new_null()) - -#define sk_POLICYINFO_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(POLICYINFO) *, sk)) - -#define sk_POLICYINFO_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(POLICYINFO) *, sk)); - -#define sk_POLICYINFO_value(sk, i) \ - ((POLICYINFO *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(POLICYINFO) *, sk), (i))) - -#define sk_POLICYINFO_set(sk, i, p) \ - ((POLICYINFO *)sk_set(CHECKED_CAST(_STACK *, STACK_OF(POLICYINFO) *, sk), \ - (i), CHECKED_CAST(void *, POLICYINFO *, p))) - -#define sk_POLICYINFO_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(POLICYINFO) *, sk)) - -#define sk_POLICYINFO_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(POLICYINFO) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(POLICYINFO *), free_func)) - -#define sk_POLICYINFO_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(POLICYINFO) *, sk), \ - CHECKED_CAST(void *, POLICYINFO *, p), (where)) - -#define sk_POLICYINFO_delete(sk, where) \ - ((POLICYINFO *)sk_delete(CHECKED_CAST(_STACK *, STACK_OF(POLICYINFO) *, sk), \ - (where))) - -#define sk_POLICYINFO_delete_ptr(sk, p) \ - ((POLICYINFO *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(POLICYINFO) *, sk), \ - CHECKED_CAST(void *, POLICYINFO *, p))) - -#define sk_POLICYINFO_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(POLICYINFO) *, sk), (out_index), \ - CHECKED_CAST(void *, POLICYINFO *, p)) - -#define sk_POLICYINFO_shift(sk) \ - ((POLICYINFO *)sk_shift(CHECKED_CAST(_STACK *, STACK_OF(POLICYINFO) *, sk))) - -#define sk_POLICYINFO_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(POLICYINFO) *, sk), \ - CHECKED_CAST(void *, POLICYINFO *, p)) - -#define sk_POLICYINFO_pop(sk) \ - ((POLICYINFO *)sk_pop(CHECKED_CAST(_STACK *, STACK_OF(POLICYINFO) *, sk))) - -#define sk_POLICYINFO_dup(sk) \ - ((STACK_OF(POLICYINFO) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(POLICYINFO) *, sk))) - -#define sk_POLICYINFO_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(POLICYINFO) *, sk)) - -#define sk_POLICYINFO_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(POLICYINFO) *, sk)) - -#define sk_POLICYINFO_set_cmp_func(sk, comp) \ - ((int (*)(const POLICYINFO **a, const POLICYINFO **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(POLICYINFO) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const POLICYINFO **a, const POLICYINFO **b), \ - comp))) - -#define sk_POLICYINFO_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(POLICYINFO) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(POLICYINFO) *, sk), \ - CHECKED_CAST(void *(*)(void *), POLICYINFO *(*)(POLICYINFO *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(POLICYINFO *), free_func))) - -/* POLICYQUALINFO */ -#define sk_POLICYQUALINFO_new(comp) \ - ((STACK_OF(POLICYQUALINFO) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, \ - int (*)(const POLICYQUALINFO **a, const POLICYQUALINFO **b), comp))) - -#define sk_POLICYQUALINFO_new_null() ((STACK_OF(POLICYQUALINFO) *)sk_new_null()) - -#define sk_POLICYQUALINFO_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(POLICYQUALINFO) *, sk)) - -#define sk_POLICYQUALINFO_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(POLICYQUALINFO) *, sk)); - -#define sk_POLICYQUALINFO_value(sk, i) \ - ((POLICYQUALINFO *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(POLICYQUALINFO) *, sk), (i))) - -#define sk_POLICYQUALINFO_set(sk, i, p) \ - ((POLICYQUALINFO *)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(POLICYQUALINFO) *, sk), (i), \ - CHECKED_CAST(void *, POLICYQUALINFO *, p))) - -#define sk_POLICYQUALINFO_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(POLICYQUALINFO) *, sk)) - -#define sk_POLICYQUALINFO_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(POLICYQUALINFO) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(POLICYQUALINFO *), free_func)) - -#define sk_POLICYQUALINFO_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(POLICYQUALINFO) *, sk), \ - CHECKED_CAST(void *, POLICYQUALINFO *, p), (where)) - -#define sk_POLICYQUALINFO_delete(sk, where) \ - ((POLICYQUALINFO *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(POLICYQUALINFO) *, sk), (where))) - -#define sk_POLICYQUALINFO_delete_ptr(sk, p) \ - ((POLICYQUALINFO *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(POLICYQUALINFO) *, sk), \ - CHECKED_CAST(void *, POLICYQUALINFO *, p))) - -#define sk_POLICYQUALINFO_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(POLICYQUALINFO) *, sk), (out_index), \ - CHECKED_CAST(void *, POLICYQUALINFO *, p)) - -#define sk_POLICYQUALINFO_shift(sk) \ - ((POLICYQUALINFO *)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(POLICYQUALINFO) *, sk))) - -#define sk_POLICYQUALINFO_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(POLICYQUALINFO) *, sk), \ - CHECKED_CAST(void *, POLICYQUALINFO *, p)) - -#define sk_POLICYQUALINFO_pop(sk) \ - ((POLICYQUALINFO *)sk_pop( \ - CHECKED_CAST(_STACK *, STACK_OF(POLICYQUALINFO) *, sk))) - -#define sk_POLICYQUALINFO_dup(sk) \ - ((STACK_OF(POLICYQUALINFO) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(POLICYQUALINFO) *, sk))) - -#define sk_POLICYQUALINFO_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(POLICYQUALINFO) *, sk)) - -#define sk_POLICYQUALINFO_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(POLICYQUALINFO) *, sk)) - -#define sk_POLICYQUALINFO_set_cmp_func(sk, comp) \ - ((int (*)(const POLICYQUALINFO **a, const POLICYQUALINFO **b)) \ - sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(POLICYQUALINFO) *, sk), \ - CHECKED_CAST(stack_cmp_func, int (*)(const POLICYQUALINFO **a, \ - const POLICYQUALINFO **b), \ - comp))) - -#define sk_POLICYQUALINFO_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(POLICYQUALINFO) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(POLICYQUALINFO) *, sk), \ - CHECKED_CAST(void *(*)(void *), POLICYQUALINFO *(*)(POLICYQUALINFO *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(POLICYQUALINFO *), free_func))) - -/* POLICY_MAPPING */ -#define sk_POLICY_MAPPING_new(comp) \ - ((STACK_OF(POLICY_MAPPING) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, \ - int (*)(const POLICY_MAPPING **a, const POLICY_MAPPING **b), comp))) - -#define sk_POLICY_MAPPING_new_null() ((STACK_OF(POLICY_MAPPING) *)sk_new_null()) - -#define sk_POLICY_MAPPING_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(POLICY_MAPPING) *, sk)) - -#define sk_POLICY_MAPPING_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(POLICY_MAPPING) *, sk)); - -#define sk_POLICY_MAPPING_value(sk, i) \ - ((POLICY_MAPPING *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(POLICY_MAPPING) *, sk), (i))) - -#define sk_POLICY_MAPPING_set(sk, i, p) \ - ((POLICY_MAPPING *)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(POLICY_MAPPING) *, sk), (i), \ - CHECKED_CAST(void *, POLICY_MAPPING *, p))) - -#define sk_POLICY_MAPPING_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(POLICY_MAPPING) *, sk)) - -#define sk_POLICY_MAPPING_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(POLICY_MAPPING) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(POLICY_MAPPING *), free_func)) - -#define sk_POLICY_MAPPING_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(POLICY_MAPPING) *, sk), \ - CHECKED_CAST(void *, POLICY_MAPPING *, p), (where)) - -#define sk_POLICY_MAPPING_delete(sk, where) \ - ((POLICY_MAPPING *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(POLICY_MAPPING) *, sk), (where))) - -#define sk_POLICY_MAPPING_delete_ptr(sk, p) \ - ((POLICY_MAPPING *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(POLICY_MAPPING) *, sk), \ - CHECKED_CAST(void *, POLICY_MAPPING *, p))) - -#define sk_POLICY_MAPPING_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(POLICY_MAPPING) *, sk), (out_index), \ - CHECKED_CAST(void *, POLICY_MAPPING *, p)) - -#define sk_POLICY_MAPPING_shift(sk) \ - ((POLICY_MAPPING *)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(POLICY_MAPPING) *, sk))) - -#define sk_POLICY_MAPPING_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(POLICY_MAPPING) *, sk), \ - CHECKED_CAST(void *, POLICY_MAPPING *, p)) - -#define sk_POLICY_MAPPING_pop(sk) \ - ((POLICY_MAPPING *)sk_pop( \ - CHECKED_CAST(_STACK *, STACK_OF(POLICY_MAPPING) *, sk))) - -#define sk_POLICY_MAPPING_dup(sk) \ - ((STACK_OF(POLICY_MAPPING) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(POLICY_MAPPING) *, sk))) - -#define sk_POLICY_MAPPING_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(POLICY_MAPPING) *, sk)) - -#define sk_POLICY_MAPPING_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(POLICY_MAPPING) *, sk)) - -#define sk_POLICY_MAPPING_set_cmp_func(sk, comp) \ - ((int (*)(const POLICY_MAPPING **a, const POLICY_MAPPING **b)) \ - sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(POLICY_MAPPING) *, sk), \ - CHECKED_CAST(stack_cmp_func, int (*)(const POLICY_MAPPING **a, \ - const POLICY_MAPPING **b), \ - comp))) - -#define sk_POLICY_MAPPING_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(POLICY_MAPPING) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(POLICY_MAPPING) *, sk), \ - CHECKED_CAST(void *(*)(void *), POLICY_MAPPING *(*)(POLICY_MAPPING *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(POLICY_MAPPING *), free_func))) - -/* SSL_COMP */ -#define sk_SSL_COMP_new(comp) \ - ((STACK_OF(SSL_COMP) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, int (*)(const SSL_COMP **a, const SSL_COMP **b), comp))) - -#define sk_SSL_COMP_new_null() ((STACK_OF(SSL_COMP) *)sk_new_null()) - -#define sk_SSL_COMP_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(SSL_COMP) *, sk)) - -#define sk_SSL_COMP_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(SSL_COMP) *, sk)); - -#define sk_SSL_COMP_value(sk, i) \ - ((SSL_COMP *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(SSL_COMP) *, sk), (i))) - -#define sk_SSL_COMP_set(sk, i, p) \ - ((SSL_COMP *)sk_set(CHECKED_CAST(_STACK *, STACK_OF(SSL_COMP) *, sk), (i), \ - CHECKED_CAST(void *, SSL_COMP *, p))) - -#define sk_SSL_COMP_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(SSL_COMP) *, sk)) - -#define sk_SSL_COMP_pop_free(sk, free_func) \ - sk_pop_free(CHECKED_CAST(_STACK *, STACK_OF(SSL_COMP) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(SSL_COMP *), free_func)) - -#define sk_SSL_COMP_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(SSL_COMP) *, sk), \ - CHECKED_CAST(void *, SSL_COMP *, p), (where)) - -#define sk_SSL_COMP_delete(sk, where) \ - ((SSL_COMP *)sk_delete(CHECKED_CAST(_STACK *, STACK_OF(SSL_COMP) *, sk), \ - (where))) - -#define sk_SSL_COMP_delete_ptr(sk, p) \ - ((SSL_COMP *)sk_delete_ptr(CHECKED_CAST(_STACK *, STACK_OF(SSL_COMP) *, sk), \ - CHECKED_CAST(void *, SSL_COMP *, p))) - -#define sk_SSL_COMP_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(SSL_COMP) *, sk), (out_index), \ - CHECKED_CAST(void *, SSL_COMP *, p)) - -#define sk_SSL_COMP_shift(sk) \ - ((SSL_COMP *)sk_shift(CHECKED_CAST(_STACK *, STACK_OF(SSL_COMP) *, sk))) - -#define sk_SSL_COMP_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(SSL_COMP) *, sk), \ - CHECKED_CAST(void *, SSL_COMP *, p)) - -#define sk_SSL_COMP_pop(sk) \ - ((SSL_COMP *)sk_pop(CHECKED_CAST(_STACK *, STACK_OF(SSL_COMP) *, sk))) - -#define sk_SSL_COMP_dup(sk) \ - ((STACK_OF(SSL_COMP) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(SSL_COMP) *, sk))) - -#define sk_SSL_COMP_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(SSL_COMP) *, sk)) - -#define sk_SSL_COMP_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(SSL_COMP) *, sk)) - -#define sk_SSL_COMP_set_cmp_func(sk, comp) \ - ((int (*)(const SSL_COMP **a, const SSL_COMP **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(SSL_COMP) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const SSL_COMP **a, const SSL_COMP **b), comp))) - -#define sk_SSL_COMP_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(SSL_COMP) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(SSL_COMP) *, sk), \ - CHECKED_CAST(void *(*)(void *), SSL_COMP *(*)(SSL_COMP *), copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(SSL_COMP *), free_func))) - -/* STACK_OF_X509_NAME_ENTRY */ -#define sk_STACK_OF_X509_NAME_ENTRY_new(comp) \ - ((STACK_OF(STACK_OF_X509_NAME_ENTRY) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, int (*)(const STACK_OF_X509_NAME_ENTRY **a, \ - const STACK_OF_X509_NAME_ENTRY **b), \ - comp))) - -#define sk_STACK_OF_X509_NAME_ENTRY_new_null() \ - ((STACK_OF(STACK_OF_X509_NAME_ENTRY) *)sk_new_null()) - -#define sk_STACK_OF_X509_NAME_ENTRY_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(STACK_OF_X509_NAME_ENTRY) *, sk)) - -#define sk_STACK_OF_X509_NAME_ENTRY_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(STACK_OF_X509_NAME_ENTRY) *, sk)); - -#define sk_STACK_OF_X509_NAME_ENTRY_value(sk, i) \ - ((STACK_OF_X509_NAME_ENTRY *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(STACK_OF_X509_NAME_ENTRY) *, sk), \ - (i))) - -#define sk_STACK_OF_X509_NAME_ENTRY_set(sk, i, p) \ - ((STACK_OF_X509_NAME_ENTRY *)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(STACK_OF_X509_NAME_ENTRY) *, sk), (i), \ - CHECKED_CAST(void *, STACK_OF_X509_NAME_ENTRY *, p))) - -#define sk_STACK_OF_X509_NAME_ENTRY_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(STACK_OF_X509_NAME_ENTRY) *, sk)) - -#define sk_STACK_OF_X509_NAME_ENTRY_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(STACK_OF_X509_NAME_ENTRY) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(STACK_OF_X509_NAME_ENTRY *), \ - free_func)) - -#define sk_STACK_OF_X509_NAME_ENTRY_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(STACK_OF_X509_NAME_ENTRY) *, sk), \ - CHECKED_CAST(void *, STACK_OF_X509_NAME_ENTRY *, p), (where)) - -#define sk_STACK_OF_X509_NAME_ENTRY_delete(sk, where) \ - ((STACK_OF_X509_NAME_ENTRY *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(STACK_OF_X509_NAME_ENTRY) *, sk), \ - (where))) - -#define sk_STACK_OF_X509_NAME_ENTRY_delete_ptr(sk, p) \ - ((STACK_OF_X509_NAME_ENTRY *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(STACK_OF_X509_NAME_ENTRY) *, sk), \ - CHECKED_CAST(void *, STACK_OF_X509_NAME_ENTRY *, p))) - -#define sk_STACK_OF_X509_NAME_ENTRY_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(STACK_OF_X509_NAME_ENTRY) *, sk), \ - (out_index), CHECKED_CAST(void *, STACK_OF_X509_NAME_ENTRY *, p)) - -#define sk_STACK_OF_X509_NAME_ENTRY_shift(sk) \ - ((STACK_OF_X509_NAME_ENTRY *)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(STACK_OF_X509_NAME_ENTRY) *, sk))) - -#define sk_STACK_OF_X509_NAME_ENTRY_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(STACK_OF_X509_NAME_ENTRY) *, sk), \ - CHECKED_CAST(void *, STACK_OF_X509_NAME_ENTRY *, p)) - -#define sk_STACK_OF_X509_NAME_ENTRY_pop(sk) \ - ((STACK_OF_X509_NAME_ENTRY *)sk_pop( \ - CHECKED_CAST(_STACK *, STACK_OF(STACK_OF_X509_NAME_ENTRY) *, sk))) - -#define sk_STACK_OF_X509_NAME_ENTRY_dup(sk) \ - ((STACK_OF(STACK_OF_X509_NAME_ENTRY) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(STACK_OF_X509_NAME_ENTRY) *, sk))) - -#define sk_STACK_OF_X509_NAME_ENTRY_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(STACK_OF_X509_NAME_ENTRY) *, sk)) - -#define sk_STACK_OF_X509_NAME_ENTRY_is_sorted(sk) \ - sk_is_sorted( \ - CHECKED_CAST(_STACK *, const STACK_OF(STACK_OF_X509_NAME_ENTRY) *, sk)) - -#define sk_STACK_OF_X509_NAME_ENTRY_set_cmp_func(sk, comp) \ - ((int (*)(const STACK_OF_X509_NAME_ENTRY **a, \ - const STACK_OF_X509_NAME_ENTRY **b)) \ - sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(STACK_OF_X509_NAME_ENTRY) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const STACK_OF_X509_NAME_ENTRY **a, \ - const STACK_OF_X509_NAME_ENTRY **b), \ - comp))) - -#define sk_STACK_OF_X509_NAME_ENTRY_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(STACK_OF_X509_NAME_ENTRY) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(STACK_OF_X509_NAME_ENTRY) *, \ - sk), \ - CHECKED_CAST(void *(*)(void *), \ - STACK_OF_X509_NAME_ENTRY *(*)(STACK_OF_X509_NAME_ENTRY *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(STACK_OF_X509_NAME_ENTRY *), \ - free_func))) - -/* SXNETID */ -#define sk_SXNETID_new(comp) \ - ((STACK_OF(SXNETID) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, int (*)(const SXNETID **a, const SXNETID **b), comp))) - -#define sk_SXNETID_new_null() ((STACK_OF(SXNETID) *)sk_new_null()) - -#define sk_SXNETID_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(SXNETID) *, sk)) - -#define sk_SXNETID_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(SXNETID) *, sk)); - -#define sk_SXNETID_value(sk, i) \ - ((SXNETID *)sk_value(CHECKED_CAST(_STACK *, const STACK_OF(SXNETID) *, sk), \ - (i))) - -#define sk_SXNETID_set(sk, i, p) \ - ((SXNETID *)sk_set(CHECKED_CAST(_STACK *, STACK_OF(SXNETID) *, sk), (i), \ - CHECKED_CAST(void *, SXNETID *, p))) - -#define sk_SXNETID_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(SXNETID) *, sk)) - -#define sk_SXNETID_pop_free(sk, free_func) \ - sk_pop_free(CHECKED_CAST(_STACK *, STACK_OF(SXNETID) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(SXNETID *), free_func)) - -#define sk_SXNETID_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(SXNETID) *, sk), \ - CHECKED_CAST(void *, SXNETID *, p), (where)) - -#define sk_SXNETID_delete(sk, where) \ - ((SXNETID *)sk_delete(CHECKED_CAST(_STACK *, STACK_OF(SXNETID) *, sk), \ - (where))) - -#define sk_SXNETID_delete_ptr(sk, p) \ - ((SXNETID *)sk_delete_ptr(CHECKED_CAST(_STACK *, STACK_OF(SXNETID) *, sk), \ - CHECKED_CAST(void *, SXNETID *, p))) - -#define sk_SXNETID_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(SXNETID) *, sk), (out_index), \ - CHECKED_CAST(void *, SXNETID *, p)) - -#define sk_SXNETID_shift(sk) \ - ((SXNETID *)sk_shift(CHECKED_CAST(_STACK *, STACK_OF(SXNETID) *, sk))) - -#define sk_SXNETID_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(SXNETID) *, sk), \ - CHECKED_CAST(void *, SXNETID *, p)) - -#define sk_SXNETID_pop(sk) \ - ((SXNETID *)sk_pop(CHECKED_CAST(_STACK *, STACK_OF(SXNETID) *, sk))) - -#define sk_SXNETID_dup(sk) \ - ((STACK_OF(SXNETID) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(SXNETID) *, sk))) - -#define sk_SXNETID_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(SXNETID) *, sk)) - -#define sk_SXNETID_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(SXNETID) *, sk)) - -#define sk_SXNETID_set_cmp_func(sk, comp) \ - ((int (*)(const SXNETID **a, const SXNETID **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(SXNETID) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const SXNETID **a, const SXNETID **b), comp))) - -#define sk_SXNETID_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(SXNETID) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(SXNETID) *, sk), \ - CHECKED_CAST(void *(*)(void *), SXNETID *(*)(SXNETID *), copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(SXNETID *), free_func))) - -/* X509 */ -#define sk_X509_new(comp) \ - ((STACK_OF(X509) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, int (*)(const X509 **a, const X509 **b), comp))) - -#define sk_X509_new_null() ((STACK_OF(X509) *)sk_new_null()) - -#define sk_X509_num(sk) sk_num(CHECKED_CAST(_STACK *, STACK_OF(X509) *, sk)) - -#define sk_X509_zero(sk) sk_zero(CHECKED_CAST(_STACK *, STACK_OF(X509) *, sk)); - -#define sk_X509_value(sk, i) \ - ((X509 *)sk_value(CHECKED_CAST(_STACK *, const STACK_OF(X509) *, sk), (i))) - -#define sk_X509_set(sk, i, p) \ - ((X509 *)sk_set(CHECKED_CAST(_STACK *, STACK_OF(X509) *, sk), (i), \ - CHECKED_CAST(void *, X509 *, p))) - -#define sk_X509_free(sk) sk_free(CHECKED_CAST(_STACK *, STACK_OF(X509) *, sk)) - -#define sk_X509_pop_free(sk, free_func) \ - sk_pop_free(CHECKED_CAST(_STACK *, STACK_OF(X509) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(X509 *), free_func)) - -#define sk_X509_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(X509) *, sk), \ - CHECKED_CAST(void *, X509 *, p), (where)) - -#define sk_X509_delete(sk, where) \ - ((X509 *)sk_delete(CHECKED_CAST(_STACK *, STACK_OF(X509) *, sk), (where))) - -#define sk_X509_delete_ptr(sk, p) \ - ((X509 *)sk_delete_ptr(CHECKED_CAST(_STACK *, STACK_OF(X509) *, sk), \ - CHECKED_CAST(void *, X509 *, p))) - -#define sk_X509_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(X509) *, sk), (out_index), \ - CHECKED_CAST(void *, X509 *, p)) - -#define sk_X509_shift(sk) \ - ((X509 *)sk_shift(CHECKED_CAST(_STACK *, STACK_OF(X509) *, sk))) - -#define sk_X509_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(X509) *, sk), \ - CHECKED_CAST(void *, X509 *, p)) - -#define sk_X509_pop(sk) \ - ((X509 *)sk_pop(CHECKED_CAST(_STACK *, STACK_OF(X509) *, sk))) - -#define sk_X509_dup(sk) \ - ((STACK_OF(X509) *)sk_dup(CHECKED_CAST(_STACK *, const STACK_OF(X509) *, sk))) - -#define sk_X509_sort(sk) sk_sort(CHECKED_CAST(_STACK *, STACK_OF(X509) *, sk)) - -#define sk_X509_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(X509) *, sk)) - -#define sk_X509_set_cmp_func(sk, comp) \ - ((int (*)(const X509 **a, const X509 **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(X509) *, sk), \ - CHECKED_CAST(stack_cmp_func, int (*)(const X509 **a, const X509 **b), \ - comp))) - -#define sk_X509_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(X509) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(X509) *, sk), \ - CHECKED_CAST(void *(*)(void *), X509 *(*)(X509 *), copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(X509 *), free_func))) - -/* X509V3_EXT_METHOD */ -#define sk_X509V3_EXT_METHOD_new(comp) \ - ((STACK_OF(X509V3_EXT_METHOD) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, \ - int (*)(const X509V3_EXT_METHOD **a, const X509V3_EXT_METHOD **b), \ - comp))) - -#define sk_X509V3_EXT_METHOD_new_null() \ - ((STACK_OF(X509V3_EXT_METHOD) *)sk_new_null()) - -#define sk_X509V3_EXT_METHOD_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(X509V3_EXT_METHOD) *, sk)) - -#define sk_X509V3_EXT_METHOD_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(X509V3_EXT_METHOD) *, sk)); - -#define sk_X509V3_EXT_METHOD_value(sk, i) \ - ((X509V3_EXT_METHOD *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509V3_EXT_METHOD) *, sk), (i))) - -#define sk_X509V3_EXT_METHOD_set(sk, i, p) \ - ((X509V3_EXT_METHOD *)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(X509V3_EXT_METHOD) *, sk), (i), \ - CHECKED_CAST(void *, X509V3_EXT_METHOD *, p))) - -#define sk_X509V3_EXT_METHOD_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(X509V3_EXT_METHOD) *, sk)) - -#define sk_X509V3_EXT_METHOD_pop_free(sk, free_func) \ - sk_pop_free(CHECKED_CAST(_STACK *, STACK_OF(X509V3_EXT_METHOD) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(X509V3_EXT_METHOD *), \ - free_func)) - -#define sk_X509V3_EXT_METHOD_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(X509V3_EXT_METHOD) *, sk), \ - CHECKED_CAST(void *, X509V3_EXT_METHOD *, p), (where)) - -#define sk_X509V3_EXT_METHOD_delete(sk, where) \ - ((X509V3_EXT_METHOD *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(X509V3_EXT_METHOD) *, sk), (where))) - -#define sk_X509V3_EXT_METHOD_delete_ptr(sk, p) \ - ((X509V3_EXT_METHOD *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(X509V3_EXT_METHOD) *, sk), \ - CHECKED_CAST(void *, X509V3_EXT_METHOD *, p))) - -#define sk_X509V3_EXT_METHOD_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(X509V3_EXT_METHOD) *, sk), \ - (out_index), CHECKED_CAST(void *, X509V3_EXT_METHOD *, p)) - -#define sk_X509V3_EXT_METHOD_shift(sk) \ - ((X509V3_EXT_METHOD *)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(X509V3_EXT_METHOD) *, sk))) - -#define sk_X509V3_EXT_METHOD_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(X509V3_EXT_METHOD) *, sk), \ - CHECKED_CAST(void *, X509V3_EXT_METHOD *, p)) - -#define sk_X509V3_EXT_METHOD_pop(sk) \ - ((X509V3_EXT_METHOD *)sk_pop( \ - CHECKED_CAST(_STACK *, STACK_OF(X509V3_EXT_METHOD) *, sk))) - -#define sk_X509V3_EXT_METHOD_dup(sk) \ - ((STACK_OF(X509V3_EXT_METHOD) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509V3_EXT_METHOD) *, sk))) - -#define sk_X509V3_EXT_METHOD_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(X509V3_EXT_METHOD) *, sk)) - -#define sk_X509V3_EXT_METHOD_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(X509V3_EXT_METHOD) *, sk)) - -#define sk_X509V3_EXT_METHOD_set_cmp_func(sk, comp) \ - ((int (*)(const X509V3_EXT_METHOD **a, const X509V3_EXT_METHOD **b)) \ - sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(X509V3_EXT_METHOD) *, sk), \ - CHECKED_CAST(stack_cmp_func, int (*)(const X509V3_EXT_METHOD **a, \ - const X509V3_EXT_METHOD **b), \ - comp))) - -#define sk_X509V3_EXT_METHOD_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(X509V3_EXT_METHOD) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(X509V3_EXT_METHOD) *, sk), \ - CHECKED_CAST(void *(*)(void *), \ - X509V3_EXT_METHOD *(*)(X509V3_EXT_METHOD *), copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(X509V3_EXT_METHOD *), \ - free_func))) - -/* X509_ALGOR */ -#define sk_X509_ALGOR_new(comp) \ - ((STACK_OF(X509_ALGOR) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, int (*)(const X509_ALGOR **a, const X509_ALGOR **b), \ - comp))) - -#define sk_X509_ALGOR_new_null() ((STACK_OF(X509_ALGOR) *)sk_new_null()) - -#define sk_X509_ALGOR_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(X509_ALGOR) *, sk)) - -#define sk_X509_ALGOR_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(X509_ALGOR) *, sk)); - -#define sk_X509_ALGOR_value(sk, i) \ - ((X509_ALGOR *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_ALGOR) *, sk), (i))) - -#define sk_X509_ALGOR_set(sk, i, p) \ - ((X509_ALGOR *)sk_set(CHECKED_CAST(_STACK *, STACK_OF(X509_ALGOR) *, sk), \ - (i), CHECKED_CAST(void *, X509_ALGOR *, p))) - -#define sk_X509_ALGOR_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(X509_ALGOR) *, sk)) - -#define sk_X509_ALGOR_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_ALGOR) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_ALGOR *), free_func)) - -#define sk_X509_ALGOR_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(X509_ALGOR) *, sk), \ - CHECKED_CAST(void *, X509_ALGOR *, p), (where)) - -#define sk_X509_ALGOR_delete(sk, where) \ - ((X509_ALGOR *)sk_delete(CHECKED_CAST(_STACK *, STACK_OF(X509_ALGOR) *, sk), \ - (where))) - -#define sk_X509_ALGOR_delete_ptr(sk, p) \ - ((X509_ALGOR *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_ALGOR) *, sk), \ - CHECKED_CAST(void *, X509_ALGOR *, p))) - -#define sk_X509_ALGOR_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(X509_ALGOR) *, sk), (out_index), \ - CHECKED_CAST(void *, X509_ALGOR *, p)) - -#define sk_X509_ALGOR_shift(sk) \ - ((X509_ALGOR *)sk_shift(CHECKED_CAST(_STACK *, STACK_OF(X509_ALGOR) *, sk))) - -#define sk_X509_ALGOR_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(X509_ALGOR) *, sk), \ - CHECKED_CAST(void *, X509_ALGOR *, p)) - -#define sk_X509_ALGOR_pop(sk) \ - ((X509_ALGOR *)sk_pop(CHECKED_CAST(_STACK *, STACK_OF(X509_ALGOR) *, sk))) - -#define sk_X509_ALGOR_dup(sk) \ - ((STACK_OF(X509_ALGOR) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_ALGOR) *, sk))) - -#define sk_X509_ALGOR_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(X509_ALGOR) *, sk)) - -#define sk_X509_ALGOR_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(X509_ALGOR) *, sk)) - -#define sk_X509_ALGOR_set_cmp_func(sk, comp) \ - ((int (*)(const X509_ALGOR **a, const X509_ALGOR **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_ALGOR) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const X509_ALGOR **a, const X509_ALGOR **b), \ - comp))) - -#define sk_X509_ALGOR_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(X509_ALGOR) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(X509_ALGOR) *, sk), \ - CHECKED_CAST(void *(*)(void *), X509_ALGOR *(*)(X509_ALGOR *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_ALGOR *), free_func))) - -/* X509_ATTRIBUTE */ -#define sk_X509_ATTRIBUTE_new(comp) \ - ((STACK_OF(X509_ATTRIBUTE) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, \ - int (*)(const X509_ATTRIBUTE **a, const X509_ATTRIBUTE **b), comp))) - -#define sk_X509_ATTRIBUTE_new_null() ((STACK_OF(X509_ATTRIBUTE) *)sk_new_null()) - -#define sk_X509_ATTRIBUTE_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(X509_ATTRIBUTE) *, sk)) - -#define sk_X509_ATTRIBUTE_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(X509_ATTRIBUTE) *, sk)); - -#define sk_X509_ATTRIBUTE_value(sk, i) \ - ((X509_ATTRIBUTE *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_ATTRIBUTE) *, sk), (i))) - -#define sk_X509_ATTRIBUTE_set(sk, i, p) \ - ((X509_ATTRIBUTE *)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_ATTRIBUTE) *, sk), (i), \ - CHECKED_CAST(void *, X509_ATTRIBUTE *, p))) - -#define sk_X509_ATTRIBUTE_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(X509_ATTRIBUTE) *, sk)) - -#define sk_X509_ATTRIBUTE_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_ATTRIBUTE) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_ATTRIBUTE *), free_func)) - -#define sk_X509_ATTRIBUTE_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(X509_ATTRIBUTE) *, sk), \ - CHECKED_CAST(void *, X509_ATTRIBUTE *, p), (where)) - -#define sk_X509_ATTRIBUTE_delete(sk, where) \ - ((X509_ATTRIBUTE *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_ATTRIBUTE) *, sk), (where))) - -#define sk_X509_ATTRIBUTE_delete_ptr(sk, p) \ - ((X509_ATTRIBUTE *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_ATTRIBUTE) *, sk), \ - CHECKED_CAST(void *, X509_ATTRIBUTE *, p))) - -#define sk_X509_ATTRIBUTE_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(X509_ATTRIBUTE) *, sk), (out_index), \ - CHECKED_CAST(void *, X509_ATTRIBUTE *, p)) - -#define sk_X509_ATTRIBUTE_shift(sk) \ - ((X509_ATTRIBUTE *)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_ATTRIBUTE) *, sk))) - -#define sk_X509_ATTRIBUTE_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(X509_ATTRIBUTE) *, sk), \ - CHECKED_CAST(void *, X509_ATTRIBUTE *, p)) - -#define sk_X509_ATTRIBUTE_pop(sk) \ - ((X509_ATTRIBUTE *)sk_pop( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_ATTRIBUTE) *, sk))) - -#define sk_X509_ATTRIBUTE_dup(sk) \ - ((STACK_OF(X509_ATTRIBUTE) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_ATTRIBUTE) *, sk))) - -#define sk_X509_ATTRIBUTE_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(X509_ATTRIBUTE) *, sk)) - -#define sk_X509_ATTRIBUTE_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(X509_ATTRIBUTE) *, sk)) - -#define sk_X509_ATTRIBUTE_set_cmp_func(sk, comp) \ - ((int (*)(const X509_ATTRIBUTE **a, const X509_ATTRIBUTE **b)) \ - sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_ATTRIBUTE) *, sk), \ - CHECKED_CAST(stack_cmp_func, int (*)(const X509_ATTRIBUTE **a, \ - const X509_ATTRIBUTE **b), \ - comp))) - -#define sk_X509_ATTRIBUTE_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(X509_ATTRIBUTE) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(X509_ATTRIBUTE) *, sk), \ - CHECKED_CAST(void *(*)(void *), X509_ATTRIBUTE *(*)(X509_ATTRIBUTE *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_ATTRIBUTE *), free_func))) - -/* X509_CRL */ -#define sk_X509_CRL_new(comp) \ - ((STACK_OF(X509_CRL) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, int (*)(const X509_CRL **a, const X509_CRL **b), comp))) - -#define sk_X509_CRL_new_null() ((STACK_OF(X509_CRL) *)sk_new_null()) - -#define sk_X509_CRL_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(X509_CRL) *, sk)) - -#define sk_X509_CRL_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(X509_CRL) *, sk)); - -#define sk_X509_CRL_value(sk, i) \ - ((X509_CRL *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_CRL) *, sk), (i))) - -#define sk_X509_CRL_set(sk, i, p) \ - ((X509_CRL *)sk_set(CHECKED_CAST(_STACK *, STACK_OF(X509_CRL) *, sk), (i), \ - CHECKED_CAST(void *, X509_CRL *, p))) - -#define sk_X509_CRL_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(X509_CRL) *, sk)) - -#define sk_X509_CRL_pop_free(sk, free_func) \ - sk_pop_free(CHECKED_CAST(_STACK *, STACK_OF(X509_CRL) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_CRL *), free_func)) - -#define sk_X509_CRL_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(X509_CRL) *, sk), \ - CHECKED_CAST(void *, X509_CRL *, p), (where)) - -#define sk_X509_CRL_delete(sk, where) \ - ((X509_CRL *)sk_delete(CHECKED_CAST(_STACK *, STACK_OF(X509_CRL) *, sk), \ - (where))) - -#define sk_X509_CRL_delete_ptr(sk, p) \ - ((X509_CRL *)sk_delete_ptr(CHECKED_CAST(_STACK *, STACK_OF(X509_CRL) *, sk), \ - CHECKED_CAST(void *, X509_CRL *, p))) - -#define sk_X509_CRL_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(X509_CRL) *, sk), (out_index), \ - CHECKED_CAST(void *, X509_CRL *, p)) - -#define sk_X509_CRL_shift(sk) \ - ((X509_CRL *)sk_shift(CHECKED_CAST(_STACK *, STACK_OF(X509_CRL) *, sk))) - -#define sk_X509_CRL_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(X509_CRL) *, sk), \ - CHECKED_CAST(void *, X509_CRL *, p)) - -#define sk_X509_CRL_pop(sk) \ - ((X509_CRL *)sk_pop(CHECKED_CAST(_STACK *, STACK_OF(X509_CRL) *, sk))) - -#define sk_X509_CRL_dup(sk) \ - ((STACK_OF(X509_CRL) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_CRL) *, sk))) - -#define sk_X509_CRL_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(X509_CRL) *, sk)) - -#define sk_X509_CRL_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(X509_CRL) *, sk)) - -#define sk_X509_CRL_set_cmp_func(sk, comp) \ - ((int (*)(const X509_CRL **a, const X509_CRL **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_CRL) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const X509_CRL **a, const X509_CRL **b), comp))) - -#define sk_X509_CRL_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(X509_CRL) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(X509_CRL) *, sk), \ - CHECKED_CAST(void *(*)(void *), X509_CRL *(*)(X509_CRL *), copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_CRL *), free_func))) - -/* X509_EXTENSION */ -#define sk_X509_EXTENSION_new(comp) \ - ((STACK_OF(X509_EXTENSION) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, \ - int (*)(const X509_EXTENSION **a, const X509_EXTENSION **b), comp))) - -#define sk_X509_EXTENSION_new_null() ((STACK_OF(X509_EXTENSION) *)sk_new_null()) - -#define sk_X509_EXTENSION_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(X509_EXTENSION) *, sk)) - -#define sk_X509_EXTENSION_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(X509_EXTENSION) *, sk)); - -#define sk_X509_EXTENSION_value(sk, i) \ - ((X509_EXTENSION *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_EXTENSION) *, sk), (i))) - -#define sk_X509_EXTENSION_set(sk, i, p) \ - ((X509_EXTENSION *)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_EXTENSION) *, sk), (i), \ - CHECKED_CAST(void *, X509_EXTENSION *, p))) - -#define sk_X509_EXTENSION_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(X509_EXTENSION) *, sk)) - -#define sk_X509_EXTENSION_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_EXTENSION) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_EXTENSION *), free_func)) - -#define sk_X509_EXTENSION_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(X509_EXTENSION) *, sk), \ - CHECKED_CAST(void *, X509_EXTENSION *, p), (where)) - -#define sk_X509_EXTENSION_delete(sk, where) \ - ((X509_EXTENSION *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_EXTENSION) *, sk), (where))) - -#define sk_X509_EXTENSION_delete_ptr(sk, p) \ - ((X509_EXTENSION *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_EXTENSION) *, sk), \ - CHECKED_CAST(void *, X509_EXTENSION *, p))) - -#define sk_X509_EXTENSION_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(X509_EXTENSION) *, sk), (out_index), \ - CHECKED_CAST(void *, X509_EXTENSION *, p)) - -#define sk_X509_EXTENSION_shift(sk) \ - ((X509_EXTENSION *)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_EXTENSION) *, sk))) - -#define sk_X509_EXTENSION_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(X509_EXTENSION) *, sk), \ - CHECKED_CAST(void *, X509_EXTENSION *, p)) - -#define sk_X509_EXTENSION_pop(sk) \ - ((X509_EXTENSION *)sk_pop( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_EXTENSION) *, sk))) - -#define sk_X509_EXTENSION_dup(sk) \ - ((STACK_OF(X509_EXTENSION) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_EXTENSION) *, sk))) - -#define sk_X509_EXTENSION_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(X509_EXTENSION) *, sk)) - -#define sk_X509_EXTENSION_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(X509_EXTENSION) *, sk)) - -#define sk_X509_EXTENSION_set_cmp_func(sk, comp) \ - ((int (*)(const X509_EXTENSION **a, const X509_EXTENSION **b)) \ - sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_EXTENSION) *, sk), \ - CHECKED_CAST(stack_cmp_func, int (*)(const X509_EXTENSION **a, \ - const X509_EXTENSION **b), \ - comp))) - -#define sk_X509_EXTENSION_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(X509_EXTENSION) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(X509_EXTENSION) *, sk), \ - CHECKED_CAST(void *(*)(void *), X509_EXTENSION *(*)(X509_EXTENSION *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_EXTENSION *), free_func))) - -/* X509_INFO */ -#define sk_X509_INFO_new(comp) \ - ((STACK_OF(X509_INFO) *)sk_new( \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const X509_INFO **a, const X509_INFO **b), comp))) - -#define sk_X509_INFO_new_null() ((STACK_OF(X509_INFO) *)sk_new_null()) - -#define sk_X509_INFO_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(X509_INFO) *, sk)) - -#define sk_X509_INFO_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(X509_INFO) *, sk)); - -#define sk_X509_INFO_value(sk, i) \ - ((X509_INFO *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_INFO) *, sk), (i))) - -#define sk_X509_INFO_set(sk, i, p) \ - ((X509_INFO *)sk_set(CHECKED_CAST(_STACK *, STACK_OF(X509_INFO) *, sk), (i), \ - CHECKED_CAST(void *, X509_INFO *, p))) - -#define sk_X509_INFO_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(X509_INFO) *, sk)) - -#define sk_X509_INFO_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_INFO) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_INFO *), free_func)) - -#define sk_X509_INFO_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(X509_INFO) *, sk), \ - CHECKED_CAST(void *, X509_INFO *, p), (where)) - -#define sk_X509_INFO_delete(sk, where) \ - ((X509_INFO *)sk_delete(CHECKED_CAST(_STACK *, STACK_OF(X509_INFO) *, sk), \ - (where))) - -#define sk_X509_INFO_delete_ptr(sk, p) \ - ((X509_INFO *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_INFO) *, sk), \ - CHECKED_CAST(void *, X509_INFO *, p))) - -#define sk_X509_INFO_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(X509_INFO) *, sk), (out_index), \ - CHECKED_CAST(void *, X509_INFO *, p)) - -#define sk_X509_INFO_shift(sk) \ - ((X509_INFO *)sk_shift(CHECKED_CAST(_STACK *, STACK_OF(X509_INFO) *, sk))) - -#define sk_X509_INFO_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(X509_INFO) *, sk), \ - CHECKED_CAST(void *, X509_INFO *, p)) - -#define sk_X509_INFO_pop(sk) \ - ((X509_INFO *)sk_pop(CHECKED_CAST(_STACK *, STACK_OF(X509_INFO) *, sk))) - -#define sk_X509_INFO_dup(sk) \ - ((STACK_OF(X509_INFO) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_INFO) *, sk))) - -#define sk_X509_INFO_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(X509_INFO) *, sk)) - -#define sk_X509_INFO_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(X509_INFO) *, sk)) - -#define sk_X509_INFO_set_cmp_func(sk, comp) \ - ((int (*)(const X509_INFO **a, const X509_INFO **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_INFO) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const X509_INFO **a, const X509_INFO **b), comp))) - -#define sk_X509_INFO_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(X509_INFO) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(X509_INFO) *, sk), \ - CHECKED_CAST(void *(*)(void *), X509_INFO *(*)(X509_INFO *), copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_INFO *), free_func))) - -/* X509_LOOKUP */ -#define sk_X509_LOOKUP_new(comp) \ - ((STACK_OF(X509_LOOKUP) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, int (*)(const X509_LOOKUP **a, const X509_LOOKUP **b), \ - comp))) - -#define sk_X509_LOOKUP_new_null() ((STACK_OF(X509_LOOKUP) *)sk_new_null()) - -#define sk_X509_LOOKUP_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(X509_LOOKUP) *, sk)) - -#define sk_X509_LOOKUP_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(X509_LOOKUP) *, sk)); - -#define sk_X509_LOOKUP_value(sk, i) \ - ((X509_LOOKUP *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_LOOKUP) *, sk), (i))) - -#define sk_X509_LOOKUP_set(sk, i, p) \ - ((X509_LOOKUP *)sk_set(CHECKED_CAST(_STACK *, STACK_OF(X509_LOOKUP) *, sk), \ - (i), CHECKED_CAST(void *, X509_LOOKUP *, p))) - -#define sk_X509_LOOKUP_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(X509_LOOKUP) *, sk)) - -#define sk_X509_LOOKUP_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_LOOKUP) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_LOOKUP *), free_func)) - -#define sk_X509_LOOKUP_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(X509_LOOKUP) *, sk), \ - CHECKED_CAST(void *, X509_LOOKUP *, p), (where)) - -#define sk_X509_LOOKUP_delete(sk, where) \ - ((X509_LOOKUP *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_LOOKUP) *, sk), (where))) - -#define sk_X509_LOOKUP_delete_ptr(sk, p) \ - ((X509_LOOKUP *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_LOOKUP) *, sk), \ - CHECKED_CAST(void *, X509_LOOKUP *, p))) - -#define sk_X509_LOOKUP_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(X509_LOOKUP) *, sk), (out_index), \ - CHECKED_CAST(void *, X509_LOOKUP *, p)) - -#define sk_X509_LOOKUP_shift(sk) \ - ((X509_LOOKUP *)sk_shift(CHECKED_CAST(_STACK *, STACK_OF(X509_LOOKUP) *, sk))) - -#define sk_X509_LOOKUP_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(X509_LOOKUP) *, sk), \ - CHECKED_CAST(void *, X509_LOOKUP *, p)) - -#define sk_X509_LOOKUP_pop(sk) \ - ((X509_LOOKUP *)sk_pop(CHECKED_CAST(_STACK *, STACK_OF(X509_LOOKUP) *, sk))) - -#define sk_X509_LOOKUP_dup(sk) \ - ((STACK_OF(X509_LOOKUP) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_LOOKUP) *, sk))) - -#define sk_X509_LOOKUP_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(X509_LOOKUP) *, sk)) - -#define sk_X509_LOOKUP_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(X509_LOOKUP) *, sk)) - -#define sk_X509_LOOKUP_set_cmp_func(sk, comp) \ - ((int (*)(const X509_LOOKUP **a, const X509_LOOKUP **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_LOOKUP) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const X509_LOOKUP **a, const X509_LOOKUP **b), \ - comp))) - -#define sk_X509_LOOKUP_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(X509_LOOKUP) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(X509_LOOKUP) *, sk), \ - CHECKED_CAST(void *(*)(void *), X509_LOOKUP *(*)(X509_LOOKUP *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_LOOKUP *), free_func))) - -/* X509_NAME */ -#define sk_X509_NAME_new(comp) \ - ((STACK_OF(X509_NAME) *)sk_new( \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const X509_NAME **a, const X509_NAME **b), comp))) - -#define sk_X509_NAME_new_null() ((STACK_OF(X509_NAME) *)sk_new_null()) - -#define sk_X509_NAME_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(X509_NAME) *, sk)) - -#define sk_X509_NAME_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(X509_NAME) *, sk)); - -#define sk_X509_NAME_value(sk, i) \ - ((X509_NAME *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_NAME) *, sk), (i))) - -#define sk_X509_NAME_set(sk, i, p) \ - ((X509_NAME *)sk_set(CHECKED_CAST(_STACK *, STACK_OF(X509_NAME) *, sk), (i), \ - CHECKED_CAST(void *, X509_NAME *, p))) - -#define sk_X509_NAME_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(X509_NAME) *, sk)) - -#define sk_X509_NAME_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_NAME) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_NAME *), free_func)) - -#define sk_X509_NAME_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(X509_NAME) *, sk), \ - CHECKED_CAST(void *, X509_NAME *, p), (where)) - -#define sk_X509_NAME_delete(sk, where) \ - ((X509_NAME *)sk_delete(CHECKED_CAST(_STACK *, STACK_OF(X509_NAME) *, sk), \ - (where))) - -#define sk_X509_NAME_delete_ptr(sk, p) \ - ((X509_NAME *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_NAME) *, sk), \ - CHECKED_CAST(void *, X509_NAME *, p))) - -#define sk_X509_NAME_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(X509_NAME) *, sk), (out_index), \ - CHECKED_CAST(void *, X509_NAME *, p)) - -#define sk_X509_NAME_shift(sk) \ - ((X509_NAME *)sk_shift(CHECKED_CAST(_STACK *, STACK_OF(X509_NAME) *, sk))) - -#define sk_X509_NAME_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(X509_NAME) *, sk), \ - CHECKED_CAST(void *, X509_NAME *, p)) - -#define sk_X509_NAME_pop(sk) \ - ((X509_NAME *)sk_pop(CHECKED_CAST(_STACK *, STACK_OF(X509_NAME) *, sk))) - -#define sk_X509_NAME_dup(sk) \ - ((STACK_OF(X509_NAME) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_NAME) *, sk))) - -#define sk_X509_NAME_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(X509_NAME) *, sk)) - -#define sk_X509_NAME_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(X509_NAME) *, sk)) - -#define sk_X509_NAME_set_cmp_func(sk, comp) \ - ((int (*)(const X509_NAME **a, const X509_NAME **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_NAME) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const X509_NAME **a, const X509_NAME **b), comp))) - -#define sk_X509_NAME_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(X509_NAME) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(X509_NAME) *, sk), \ - CHECKED_CAST(void *(*)(void *), X509_NAME *(*)(X509_NAME *), copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_NAME *), free_func))) - -/* X509_NAME_ENTRY */ -#define sk_X509_NAME_ENTRY_new(comp) \ - ((STACK_OF(X509_NAME_ENTRY) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, \ - int (*)(const X509_NAME_ENTRY **a, const X509_NAME_ENTRY **b), comp))) - -#define sk_X509_NAME_ENTRY_new_null() \ - ((STACK_OF(X509_NAME_ENTRY) *)sk_new_null()) - -#define sk_X509_NAME_ENTRY_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(X509_NAME_ENTRY) *, sk)) - -#define sk_X509_NAME_ENTRY_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(X509_NAME_ENTRY) *, sk)); - -#define sk_X509_NAME_ENTRY_value(sk, i) \ - ((X509_NAME_ENTRY *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_NAME_ENTRY) *, sk), (i))) - -#define sk_X509_NAME_ENTRY_set(sk, i, p) \ - ((X509_NAME_ENTRY *)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_NAME_ENTRY) *, sk), (i), \ - CHECKED_CAST(void *, X509_NAME_ENTRY *, p))) - -#define sk_X509_NAME_ENTRY_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(X509_NAME_ENTRY) *, sk)) - -#define sk_X509_NAME_ENTRY_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_NAME_ENTRY) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_NAME_ENTRY *), free_func)) - -#define sk_X509_NAME_ENTRY_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(X509_NAME_ENTRY) *, sk), \ - CHECKED_CAST(void *, X509_NAME_ENTRY *, p), (where)) - -#define sk_X509_NAME_ENTRY_delete(sk, where) \ - ((X509_NAME_ENTRY *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_NAME_ENTRY) *, sk), (where))) - -#define sk_X509_NAME_ENTRY_delete_ptr(sk, p) \ - ((X509_NAME_ENTRY *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_NAME_ENTRY) *, sk), \ - CHECKED_CAST(void *, X509_NAME_ENTRY *, p))) - -#define sk_X509_NAME_ENTRY_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(X509_NAME_ENTRY) *, sk), \ - (out_index), CHECKED_CAST(void *, X509_NAME_ENTRY *, p)) - -#define sk_X509_NAME_ENTRY_shift(sk) \ - ((X509_NAME_ENTRY *)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_NAME_ENTRY) *, sk))) - -#define sk_X509_NAME_ENTRY_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(X509_NAME_ENTRY) *, sk), \ - CHECKED_CAST(void *, X509_NAME_ENTRY *, p)) - -#define sk_X509_NAME_ENTRY_pop(sk) \ - ((X509_NAME_ENTRY *)sk_pop( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_NAME_ENTRY) *, sk))) - -#define sk_X509_NAME_ENTRY_dup(sk) \ - ((STACK_OF(X509_NAME_ENTRY) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_NAME_ENTRY) *, sk))) - -#define sk_X509_NAME_ENTRY_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(X509_NAME_ENTRY) *, sk)) - -#define sk_X509_NAME_ENTRY_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(X509_NAME_ENTRY) *, sk)) - -#define sk_X509_NAME_ENTRY_set_cmp_func(sk, comp) \ - ((int (*)(const X509_NAME_ENTRY **a, const X509_NAME_ENTRY **b)) \ - sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_NAME_ENTRY) *, sk), \ - CHECKED_CAST(stack_cmp_func, int (*)(const X509_NAME_ENTRY **a, \ - const X509_NAME_ENTRY **b), \ - comp))) - -#define sk_X509_NAME_ENTRY_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(X509_NAME_ENTRY) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(X509_NAME_ENTRY) *, sk), \ - CHECKED_CAST(void *(*)(void *), X509_NAME_ENTRY *(*)(X509_NAME_ENTRY *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_NAME_ENTRY *), free_func))) - -/* X509_OBJECT */ -#define sk_X509_OBJECT_new(comp) \ - ((STACK_OF(X509_OBJECT) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, int (*)(const X509_OBJECT **a, const X509_OBJECT **b), \ - comp))) - -#define sk_X509_OBJECT_new_null() ((STACK_OF(X509_OBJECT) *)sk_new_null()) - -#define sk_X509_OBJECT_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(X509_OBJECT) *, sk)) - -#define sk_X509_OBJECT_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(X509_OBJECT) *, sk)); - -#define sk_X509_OBJECT_value(sk, i) \ - ((X509_OBJECT *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_OBJECT) *, sk), (i))) - -#define sk_X509_OBJECT_set(sk, i, p) \ - ((X509_OBJECT *)sk_set(CHECKED_CAST(_STACK *, STACK_OF(X509_OBJECT) *, sk), \ - (i), CHECKED_CAST(void *, X509_OBJECT *, p))) - -#define sk_X509_OBJECT_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(X509_OBJECT) *, sk)) - -#define sk_X509_OBJECT_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_OBJECT) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_OBJECT *), free_func)) - -#define sk_X509_OBJECT_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(X509_OBJECT) *, sk), \ - CHECKED_CAST(void *, X509_OBJECT *, p), (where)) - -#define sk_X509_OBJECT_delete(sk, where) \ - ((X509_OBJECT *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_OBJECT) *, sk), (where))) - -#define sk_X509_OBJECT_delete_ptr(sk, p) \ - ((X509_OBJECT *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_OBJECT) *, sk), \ - CHECKED_CAST(void *, X509_OBJECT *, p))) - -#define sk_X509_OBJECT_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(X509_OBJECT) *, sk), (out_index), \ - CHECKED_CAST(void *, X509_OBJECT *, p)) - -#define sk_X509_OBJECT_shift(sk) \ - ((X509_OBJECT *)sk_shift(CHECKED_CAST(_STACK *, STACK_OF(X509_OBJECT) *, sk))) - -#define sk_X509_OBJECT_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(X509_OBJECT) *, sk), \ - CHECKED_CAST(void *, X509_OBJECT *, p)) - -#define sk_X509_OBJECT_pop(sk) \ - ((X509_OBJECT *)sk_pop(CHECKED_CAST(_STACK *, STACK_OF(X509_OBJECT) *, sk))) - -#define sk_X509_OBJECT_dup(sk) \ - ((STACK_OF(X509_OBJECT) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_OBJECT) *, sk))) - -#define sk_X509_OBJECT_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(X509_OBJECT) *, sk)) - -#define sk_X509_OBJECT_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(X509_OBJECT) *, sk)) - -#define sk_X509_OBJECT_set_cmp_func(sk, comp) \ - ((int (*)(const X509_OBJECT **a, const X509_OBJECT **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_OBJECT) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const X509_OBJECT **a, const X509_OBJECT **b), \ - comp))) - -#define sk_X509_OBJECT_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(X509_OBJECT) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(X509_OBJECT) *, sk), \ - CHECKED_CAST(void *(*)(void *), X509_OBJECT *(*)(X509_OBJECT *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_OBJECT *), free_func))) - -/* X509_POLICY_DATA */ -#define sk_X509_POLICY_DATA_new(comp) \ - ((STACK_OF(X509_POLICY_DATA) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, \ - int (*)(const X509_POLICY_DATA **a, const X509_POLICY_DATA **b), comp))) - -#define sk_X509_POLICY_DATA_new_null() \ - ((STACK_OF(X509_POLICY_DATA) *)sk_new_null()) - -#define sk_X509_POLICY_DATA_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_DATA) *, sk)) - -#define sk_X509_POLICY_DATA_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_DATA) *, sk)); - -#define sk_X509_POLICY_DATA_value(sk, i) \ - ((X509_POLICY_DATA *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_POLICY_DATA) *, sk), (i))) - -#define sk_X509_POLICY_DATA_set(sk, i, p) \ - ((X509_POLICY_DATA *)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_DATA) *, sk), (i), \ - CHECKED_CAST(void *, X509_POLICY_DATA *, p))) - -#define sk_X509_POLICY_DATA_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_DATA) *, sk)) - -#define sk_X509_POLICY_DATA_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_DATA) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_POLICY_DATA *), free_func)) - -#define sk_X509_POLICY_DATA_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_DATA) *, sk), \ - CHECKED_CAST(void *, X509_POLICY_DATA *, p), (where)) - -#define sk_X509_POLICY_DATA_delete(sk, where) \ - ((X509_POLICY_DATA *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_DATA) *, sk), (where))) - -#define sk_X509_POLICY_DATA_delete_ptr(sk, p) \ - ((X509_POLICY_DATA *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_DATA) *, sk), \ - CHECKED_CAST(void *, X509_POLICY_DATA *, p))) - -#define sk_X509_POLICY_DATA_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_DATA) *, sk), \ - (out_index), CHECKED_CAST(void *, X509_POLICY_DATA *, p)) - -#define sk_X509_POLICY_DATA_shift(sk) \ - ((X509_POLICY_DATA *)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_DATA) *, sk))) - -#define sk_X509_POLICY_DATA_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_DATA) *, sk), \ - CHECKED_CAST(void *, X509_POLICY_DATA *, p)) - -#define sk_X509_POLICY_DATA_pop(sk) \ - ((X509_POLICY_DATA *)sk_pop( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_DATA) *, sk))) - -#define sk_X509_POLICY_DATA_dup(sk) \ - ((STACK_OF(X509_POLICY_DATA) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_POLICY_DATA) *, sk))) - -#define sk_X509_POLICY_DATA_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_DATA) *, sk)) - -#define sk_X509_POLICY_DATA_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(X509_POLICY_DATA) *, sk)) - -#define sk_X509_POLICY_DATA_set_cmp_func(sk, comp) \ - ((int (*)(const X509_POLICY_DATA **a, const X509_POLICY_DATA **b)) \ - sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_DATA) *, sk), \ - CHECKED_CAST(stack_cmp_func, int (*)(const X509_POLICY_DATA **a, \ - const X509_POLICY_DATA **b), \ - comp))) - -#define sk_X509_POLICY_DATA_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(X509_POLICY_DATA) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(X509_POLICY_DATA) *, sk), \ - CHECKED_CAST(void *(*)(void *), \ - X509_POLICY_DATA *(*)(X509_POLICY_DATA *), copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_POLICY_DATA *), \ - free_func))) - -/* X509_POLICY_NODE */ -#define sk_X509_POLICY_NODE_new(comp) \ - ((STACK_OF(X509_POLICY_NODE) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, \ - int (*)(const X509_POLICY_NODE **a, const X509_POLICY_NODE **b), comp))) - -#define sk_X509_POLICY_NODE_new_null() \ - ((STACK_OF(X509_POLICY_NODE) *)sk_new_null()) - -#define sk_X509_POLICY_NODE_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_NODE) *, sk)) - -#define sk_X509_POLICY_NODE_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_NODE) *, sk)); - -#define sk_X509_POLICY_NODE_value(sk, i) \ - ((X509_POLICY_NODE *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_POLICY_NODE) *, sk), (i))) - -#define sk_X509_POLICY_NODE_set(sk, i, p) \ - ((X509_POLICY_NODE *)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_NODE) *, sk), (i), \ - CHECKED_CAST(void *, X509_POLICY_NODE *, p))) - -#define sk_X509_POLICY_NODE_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_NODE) *, sk)) - -#define sk_X509_POLICY_NODE_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_NODE) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_POLICY_NODE *), free_func)) - -#define sk_X509_POLICY_NODE_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_NODE) *, sk), \ - CHECKED_CAST(void *, X509_POLICY_NODE *, p), (where)) - -#define sk_X509_POLICY_NODE_delete(sk, where) \ - ((X509_POLICY_NODE *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_NODE) *, sk), (where))) - -#define sk_X509_POLICY_NODE_delete_ptr(sk, p) \ - ((X509_POLICY_NODE *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_NODE) *, sk), \ - CHECKED_CAST(void *, X509_POLICY_NODE *, p))) - -#define sk_X509_POLICY_NODE_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_NODE) *, sk), \ - (out_index), CHECKED_CAST(void *, X509_POLICY_NODE *, p)) - -#define sk_X509_POLICY_NODE_shift(sk) \ - ((X509_POLICY_NODE *)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_NODE) *, sk))) - -#define sk_X509_POLICY_NODE_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_NODE) *, sk), \ - CHECKED_CAST(void *, X509_POLICY_NODE *, p)) - -#define sk_X509_POLICY_NODE_pop(sk) \ - ((X509_POLICY_NODE *)sk_pop( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_NODE) *, sk))) - -#define sk_X509_POLICY_NODE_dup(sk) \ - ((STACK_OF(X509_POLICY_NODE) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_POLICY_NODE) *, sk))) - -#define sk_X509_POLICY_NODE_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_NODE) *, sk)) - -#define sk_X509_POLICY_NODE_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(X509_POLICY_NODE) *, sk)) - -#define sk_X509_POLICY_NODE_set_cmp_func(sk, comp) \ - ((int (*)(const X509_POLICY_NODE **a, const X509_POLICY_NODE **b)) \ - sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_POLICY_NODE) *, sk), \ - CHECKED_CAST(stack_cmp_func, int (*)(const X509_POLICY_NODE **a, \ - const X509_POLICY_NODE **b), \ - comp))) - -#define sk_X509_POLICY_NODE_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(X509_POLICY_NODE) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(X509_POLICY_NODE) *, sk), \ - CHECKED_CAST(void *(*)(void *), \ - X509_POLICY_NODE *(*)(X509_POLICY_NODE *), copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_POLICY_NODE *), \ - free_func))) - -/* X509_PURPOSE */ -#define sk_X509_PURPOSE_new(comp) \ - ((STACK_OF(X509_PURPOSE) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, int (*)(const X509_PURPOSE **a, const X509_PURPOSE **b), \ - comp))) - -#define sk_X509_PURPOSE_new_null() ((STACK_OF(X509_PURPOSE) *)sk_new_null()) - -#define sk_X509_PURPOSE_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(X509_PURPOSE) *, sk)) - -#define sk_X509_PURPOSE_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(X509_PURPOSE) *, sk)); - -#define sk_X509_PURPOSE_value(sk, i) \ - ((X509_PURPOSE *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_PURPOSE) *, sk), (i))) - -#define sk_X509_PURPOSE_set(sk, i, p) \ - ((X509_PURPOSE *)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_PURPOSE) *, sk), (i), \ - CHECKED_CAST(void *, X509_PURPOSE *, p))) - -#define sk_X509_PURPOSE_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(X509_PURPOSE) *, sk)) - -#define sk_X509_PURPOSE_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_PURPOSE) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_PURPOSE *), free_func)) - -#define sk_X509_PURPOSE_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(X509_PURPOSE) *, sk), \ - CHECKED_CAST(void *, X509_PURPOSE *, p), (where)) - -#define sk_X509_PURPOSE_delete(sk, where) \ - ((X509_PURPOSE *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_PURPOSE) *, sk), (where))) - -#define sk_X509_PURPOSE_delete_ptr(sk, p) \ - ((X509_PURPOSE *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_PURPOSE) *, sk), \ - CHECKED_CAST(void *, X509_PURPOSE *, p))) - -#define sk_X509_PURPOSE_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(X509_PURPOSE) *, sk), (out_index), \ - CHECKED_CAST(void *, X509_PURPOSE *, p)) - -#define sk_X509_PURPOSE_shift(sk) \ - ((X509_PURPOSE *)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_PURPOSE) *, sk))) - -#define sk_X509_PURPOSE_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(X509_PURPOSE) *, sk), \ - CHECKED_CAST(void *, X509_PURPOSE *, p)) - -#define sk_X509_PURPOSE_pop(sk) \ - ((X509_PURPOSE *)sk_pop(CHECKED_CAST(_STACK *, STACK_OF(X509_PURPOSE) *, sk))) - -#define sk_X509_PURPOSE_dup(sk) \ - ((STACK_OF(X509_PURPOSE) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_PURPOSE) *, sk))) - -#define sk_X509_PURPOSE_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(X509_PURPOSE) *, sk)) - -#define sk_X509_PURPOSE_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(X509_PURPOSE) *, sk)) - -#define sk_X509_PURPOSE_set_cmp_func(sk, comp) \ - ((int (*)(const X509_PURPOSE **a, const X509_PURPOSE **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_PURPOSE) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const X509_PURPOSE **a, const X509_PURPOSE **b), \ - comp))) - -#define sk_X509_PURPOSE_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(X509_PURPOSE) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(X509_PURPOSE) *, sk), \ - CHECKED_CAST(void *(*)(void *), X509_PURPOSE *(*)(X509_PURPOSE *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_PURPOSE *), free_func))) - -/* X509_REVOKED */ -#define sk_X509_REVOKED_new(comp) \ - ((STACK_OF(X509_REVOKED) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, int (*)(const X509_REVOKED **a, const X509_REVOKED **b), \ - comp))) - -#define sk_X509_REVOKED_new_null() ((STACK_OF(X509_REVOKED) *)sk_new_null()) - -#define sk_X509_REVOKED_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(X509_REVOKED) *, sk)) - -#define sk_X509_REVOKED_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(X509_REVOKED) *, sk)); - -#define sk_X509_REVOKED_value(sk, i) \ - ((X509_REVOKED *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_REVOKED) *, sk), (i))) - -#define sk_X509_REVOKED_set(sk, i, p) \ - ((X509_REVOKED *)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_REVOKED) *, sk), (i), \ - CHECKED_CAST(void *, X509_REVOKED *, p))) - -#define sk_X509_REVOKED_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(X509_REVOKED) *, sk)) - -#define sk_X509_REVOKED_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_REVOKED) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_REVOKED *), free_func)) - -#define sk_X509_REVOKED_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(X509_REVOKED) *, sk), \ - CHECKED_CAST(void *, X509_REVOKED *, p), (where)) - -#define sk_X509_REVOKED_delete(sk, where) \ - ((X509_REVOKED *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_REVOKED) *, sk), (where))) - -#define sk_X509_REVOKED_delete_ptr(sk, p) \ - ((X509_REVOKED *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_REVOKED) *, sk), \ - CHECKED_CAST(void *, X509_REVOKED *, p))) - -#define sk_X509_REVOKED_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(X509_REVOKED) *, sk), (out_index), \ - CHECKED_CAST(void *, X509_REVOKED *, p)) - -#define sk_X509_REVOKED_shift(sk) \ - ((X509_REVOKED *)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_REVOKED) *, sk))) - -#define sk_X509_REVOKED_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(X509_REVOKED) *, sk), \ - CHECKED_CAST(void *, X509_REVOKED *, p)) - -#define sk_X509_REVOKED_pop(sk) \ - ((X509_REVOKED *)sk_pop(CHECKED_CAST(_STACK *, STACK_OF(X509_REVOKED) *, sk))) - -#define sk_X509_REVOKED_dup(sk) \ - ((STACK_OF(X509_REVOKED) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_REVOKED) *, sk))) - -#define sk_X509_REVOKED_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(X509_REVOKED) *, sk)) - -#define sk_X509_REVOKED_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(X509_REVOKED) *, sk)) - -#define sk_X509_REVOKED_set_cmp_func(sk, comp) \ - ((int (*)(const X509_REVOKED **a, const X509_REVOKED **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_REVOKED) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const X509_REVOKED **a, const X509_REVOKED **b), \ - comp))) - -#define sk_X509_REVOKED_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(X509_REVOKED) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(X509_REVOKED) *, sk), \ - CHECKED_CAST(void *(*)(void *), X509_REVOKED *(*)(X509_REVOKED *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_REVOKED *), free_func))) - -/* X509_TRUST */ -#define sk_X509_TRUST_new(comp) \ - ((STACK_OF(X509_TRUST) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, int (*)(const X509_TRUST **a, const X509_TRUST **b), \ - comp))) - -#define sk_X509_TRUST_new_null() ((STACK_OF(X509_TRUST) *)sk_new_null()) - -#define sk_X509_TRUST_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(X509_TRUST) *, sk)) - -#define sk_X509_TRUST_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(X509_TRUST) *, sk)); - -#define sk_X509_TRUST_value(sk, i) \ - ((X509_TRUST *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_TRUST) *, sk), (i))) - -#define sk_X509_TRUST_set(sk, i, p) \ - ((X509_TRUST *)sk_set(CHECKED_CAST(_STACK *, STACK_OF(X509_TRUST) *, sk), \ - (i), CHECKED_CAST(void *, X509_TRUST *, p))) - -#define sk_X509_TRUST_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(X509_TRUST) *, sk)) - -#define sk_X509_TRUST_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_TRUST) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_TRUST *), free_func)) - -#define sk_X509_TRUST_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(X509_TRUST) *, sk), \ - CHECKED_CAST(void *, X509_TRUST *, p), (where)) - -#define sk_X509_TRUST_delete(sk, where) \ - ((X509_TRUST *)sk_delete(CHECKED_CAST(_STACK *, STACK_OF(X509_TRUST) *, sk), \ - (where))) - -#define sk_X509_TRUST_delete_ptr(sk, p) \ - ((X509_TRUST *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_TRUST) *, sk), \ - CHECKED_CAST(void *, X509_TRUST *, p))) - -#define sk_X509_TRUST_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(X509_TRUST) *, sk), (out_index), \ - CHECKED_CAST(void *, X509_TRUST *, p)) - -#define sk_X509_TRUST_shift(sk) \ - ((X509_TRUST *)sk_shift(CHECKED_CAST(_STACK *, STACK_OF(X509_TRUST) *, sk))) - -#define sk_X509_TRUST_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(X509_TRUST) *, sk), \ - CHECKED_CAST(void *, X509_TRUST *, p)) - -#define sk_X509_TRUST_pop(sk) \ - ((X509_TRUST *)sk_pop(CHECKED_CAST(_STACK *, STACK_OF(X509_TRUST) *, sk))) - -#define sk_X509_TRUST_dup(sk) \ - ((STACK_OF(X509_TRUST) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_TRUST) *, sk))) - -#define sk_X509_TRUST_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(X509_TRUST) *, sk)) - -#define sk_X509_TRUST_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(X509_TRUST) *, sk)) - -#define sk_X509_TRUST_set_cmp_func(sk, comp) \ - ((int (*)(const X509_TRUST **a, const X509_TRUST **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_TRUST) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const X509_TRUST **a, const X509_TRUST **b), \ - comp))) - -#define sk_X509_TRUST_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(X509_TRUST) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(X509_TRUST) *, sk), \ - CHECKED_CAST(void *(*)(void *), X509_TRUST *(*)(X509_TRUST *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_TRUST *), free_func))) - -/* X509_VERIFY_PARAM */ -#define sk_X509_VERIFY_PARAM_new(comp) \ - ((STACK_OF(X509_VERIFY_PARAM) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, \ - int (*)(const X509_VERIFY_PARAM **a, const X509_VERIFY_PARAM **b), \ - comp))) - -#define sk_X509_VERIFY_PARAM_new_null() \ - ((STACK_OF(X509_VERIFY_PARAM) *)sk_new_null()) - -#define sk_X509_VERIFY_PARAM_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(X509_VERIFY_PARAM) *, sk)) - -#define sk_X509_VERIFY_PARAM_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(X509_VERIFY_PARAM) *, sk)); - -#define sk_X509_VERIFY_PARAM_value(sk, i) \ - ((X509_VERIFY_PARAM *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_VERIFY_PARAM) *, sk), (i))) - -#define sk_X509_VERIFY_PARAM_set(sk, i, p) \ - ((X509_VERIFY_PARAM *)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_VERIFY_PARAM) *, sk), (i), \ - CHECKED_CAST(void *, X509_VERIFY_PARAM *, p))) - -#define sk_X509_VERIFY_PARAM_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(X509_VERIFY_PARAM) *, sk)) - -#define sk_X509_VERIFY_PARAM_pop_free(sk, free_func) \ - sk_pop_free(CHECKED_CAST(_STACK *, STACK_OF(X509_VERIFY_PARAM) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_VERIFY_PARAM *), \ - free_func)) - -#define sk_X509_VERIFY_PARAM_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(X509_VERIFY_PARAM) *, sk), \ - CHECKED_CAST(void *, X509_VERIFY_PARAM *, p), (where)) - -#define sk_X509_VERIFY_PARAM_delete(sk, where) \ - ((X509_VERIFY_PARAM *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_VERIFY_PARAM) *, sk), (where))) - -#define sk_X509_VERIFY_PARAM_delete_ptr(sk, p) \ - ((X509_VERIFY_PARAM *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_VERIFY_PARAM) *, sk), \ - CHECKED_CAST(void *, X509_VERIFY_PARAM *, p))) - -#define sk_X509_VERIFY_PARAM_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(X509_VERIFY_PARAM) *, sk), \ - (out_index), CHECKED_CAST(void *, X509_VERIFY_PARAM *, p)) - -#define sk_X509_VERIFY_PARAM_shift(sk) \ - ((X509_VERIFY_PARAM *)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_VERIFY_PARAM) *, sk))) - -#define sk_X509_VERIFY_PARAM_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(X509_VERIFY_PARAM) *, sk), \ - CHECKED_CAST(void *, X509_VERIFY_PARAM *, p)) - -#define sk_X509_VERIFY_PARAM_pop(sk) \ - ((X509_VERIFY_PARAM *)sk_pop( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_VERIFY_PARAM) *, sk))) - -#define sk_X509_VERIFY_PARAM_dup(sk) \ - ((STACK_OF(X509_VERIFY_PARAM) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(X509_VERIFY_PARAM) *, sk))) - -#define sk_X509_VERIFY_PARAM_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(X509_VERIFY_PARAM) *, sk)) - -#define sk_X509_VERIFY_PARAM_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(X509_VERIFY_PARAM) *, sk)) - -#define sk_X509_VERIFY_PARAM_set_cmp_func(sk, comp) \ - ((int (*)(const X509_VERIFY_PARAM **a, const X509_VERIFY_PARAM **b)) \ - sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(X509_VERIFY_PARAM) *, sk), \ - CHECKED_CAST(stack_cmp_func, int (*)(const X509_VERIFY_PARAM **a, \ - const X509_VERIFY_PARAM **b), \ - comp))) - -#define sk_X509_VERIFY_PARAM_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(X509_VERIFY_PARAM) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(X509_VERIFY_PARAM) *, sk), \ - CHECKED_CAST(void *(*)(void *), \ - X509_VERIFY_PARAM *(*)(X509_VERIFY_PARAM *), copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(X509_VERIFY_PARAM *), \ - free_func))) - -/* void */ -#define sk_void_new(comp) \ - ((STACK_OF(void)*)sk_new(CHECKED_CAST( \ - stack_cmp_func, int (*)(const void **a, const void **b), comp))) - -#define sk_void_new_null() ((STACK_OF(void)*)sk_new_null()) - -#define sk_void_num(sk) sk_num(CHECKED_CAST(_STACK *, STACK_OF(void)*, sk)) - -#define sk_void_zero(sk) sk_zero(CHECKED_CAST(_STACK *, STACK_OF(void)*, sk)); - -#define sk_void_value(sk, i) \ - ((void *)sk_value(CHECKED_CAST(_STACK *, const STACK_OF(void)*, sk), (i))) - -#define sk_void_set(sk, i, p) \ - ((void *)sk_set(CHECKED_CAST(_STACK *, STACK_OF(void)*, sk), (i), \ - CHECKED_CAST(void *, void *, p))) - -#define sk_void_free(sk) sk_free(CHECKED_CAST(_STACK *, STACK_OF(void)*, sk)) - -#define sk_void_pop_free(sk, free_func) \ - sk_pop_free(CHECKED_CAST(_STACK *, STACK_OF(void)*, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(void *), free_func)) - -#define sk_void_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(void)*, sk), \ - CHECKED_CAST(void *, void *, p), (where)) - -#define sk_void_delete(sk, where) \ - ((void *)sk_delete(CHECKED_CAST(_STACK *, STACK_OF(void)*, sk), (where))) - -#define sk_void_delete_ptr(sk, p) \ - ((void *)sk_delete_ptr(CHECKED_CAST(_STACK *, STACK_OF(void)*, sk), \ - CHECKED_CAST(void *, void *, p))) - -#define sk_void_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(void)*, sk), (out_index), \ - CHECKED_CAST(void *, void *, p)) - -#define sk_void_shift(sk) \ - ((void *)sk_shift(CHECKED_CAST(_STACK *, STACK_OF(void)*, sk))) - -#define sk_void_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(void)*, sk), \ - CHECKED_CAST(void *, void *, p)) - -#define sk_void_pop(sk) \ - ((void *)sk_pop(CHECKED_CAST(_STACK *, STACK_OF(void)*, sk))) - -#define sk_void_dup(sk) \ - ((STACK_OF(void)*)sk_dup(CHECKED_CAST(_STACK *, const STACK_OF(void)*, sk))) - -#define sk_void_sort(sk) sk_sort(CHECKED_CAST(_STACK *, STACK_OF(void)*, sk)) - -#define sk_void_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(void)*, sk)) - -#define sk_void_set_cmp_func(sk, comp) \ - ((int (*)(const void **a, const void **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(void)*, sk), \ - CHECKED_CAST(stack_cmp_func, int (*)(const void **a, const void **b), \ - comp))) - -#define sk_void_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(void)*)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(void)*, sk), \ - CHECKED_CAST(void *(*)(void *), void *(*)(void *), copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(void *), free_func))) - -/* SRTP_PROTECTION_PROFILE */ -#define sk_SRTP_PROTECTION_PROFILE_new(comp) \ - ((STACK_OF(SRTP_PROTECTION_PROFILE) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, int (*)(const const SRTP_PROTECTION_PROFILE **a, \ - const const SRTP_PROTECTION_PROFILE **b), \ - comp))) - -#define sk_SRTP_PROTECTION_PROFILE_new_null() \ - ((STACK_OF(SRTP_PROTECTION_PROFILE) *)sk_new_null()) - -#define sk_SRTP_PROTECTION_PROFILE_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(SRTP_PROTECTION_PROFILE) *, sk)) - -#define sk_SRTP_PROTECTION_PROFILE_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(SRTP_PROTECTION_PROFILE) *, sk)); - -#define sk_SRTP_PROTECTION_PROFILE_value(sk, i) \ - ((const SRTP_PROTECTION_PROFILE *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(SRTP_PROTECTION_PROFILE) *, sk), \ - (i))) - -#define sk_SRTP_PROTECTION_PROFILE_set(sk, i, p) \ - ((const SRTP_PROTECTION_PROFILE *)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(SRTP_PROTECTION_PROFILE) *, sk), (i), \ - CHECKED_CAST(void *, const SRTP_PROTECTION_PROFILE *, p))) - -#define sk_SRTP_PROTECTION_PROFILE_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(SRTP_PROTECTION_PROFILE) *, sk)) - -#define sk_SRTP_PROTECTION_PROFILE_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(SRTP_PROTECTION_PROFILE) *, sk), \ - CHECKED_CAST(void (*)(void *), \ - void (*)(const SRTP_PROTECTION_PROFILE *), free_func)) - -#define sk_SRTP_PROTECTION_PROFILE_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(SRTP_PROTECTION_PROFILE) *, sk), \ - CHECKED_CAST(void *, const SRTP_PROTECTION_PROFILE *, p), (where)) - -#define sk_SRTP_PROTECTION_PROFILE_delete(sk, where) \ - ((const SRTP_PROTECTION_PROFILE *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(SRTP_PROTECTION_PROFILE) *, sk), \ - (where))) - -#define sk_SRTP_PROTECTION_PROFILE_delete_ptr(sk, p) \ - ((const SRTP_PROTECTION_PROFILE *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(SRTP_PROTECTION_PROFILE) *, sk), \ - CHECKED_CAST(void *, const SRTP_PROTECTION_PROFILE *, p))) - -#define sk_SRTP_PROTECTION_PROFILE_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(SRTP_PROTECTION_PROFILE) *, sk), \ - (out_index), \ - CHECKED_CAST(void *, const SRTP_PROTECTION_PROFILE *, p)) - -#define sk_SRTP_PROTECTION_PROFILE_shift(sk) \ - ((const SRTP_PROTECTION_PROFILE *)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(SRTP_PROTECTION_PROFILE) *, sk))) - -#define sk_SRTP_PROTECTION_PROFILE_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(SRTP_PROTECTION_PROFILE) *, sk), \ - CHECKED_CAST(void *, const SRTP_PROTECTION_PROFILE *, p)) - -#define sk_SRTP_PROTECTION_PROFILE_pop(sk) \ - ((const SRTP_PROTECTION_PROFILE *)sk_pop( \ - CHECKED_CAST(_STACK *, STACK_OF(SRTP_PROTECTION_PROFILE) *, sk))) - -#define sk_SRTP_PROTECTION_PROFILE_dup(sk) \ - ((STACK_OF(SRTP_PROTECTION_PROFILE) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(SRTP_PROTECTION_PROFILE) *, sk))) - -#define sk_SRTP_PROTECTION_PROFILE_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(SRTP_PROTECTION_PROFILE) *, sk)) - -#define sk_SRTP_PROTECTION_PROFILE_is_sorted(sk) \ - sk_is_sorted( \ - CHECKED_CAST(_STACK *, const STACK_OF(SRTP_PROTECTION_PROFILE) *, sk)) - -#define sk_SRTP_PROTECTION_PROFILE_set_cmp_func(sk, comp) \ - ((int (*)(const SRTP_PROTECTION_PROFILE **a, \ - const SRTP_PROTECTION_PROFILE **b)) \ - sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(SRTP_PROTECTION_PROFILE) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const SRTP_PROTECTION_PROFILE **a, \ - const SRTP_PROTECTION_PROFILE **b), \ - comp))) - -#define sk_SRTP_PROTECTION_PROFILE_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(SRTP_PROTECTION_PROFILE) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(SRTP_PROTECTION_PROFILE) *, \ - sk), \ - CHECKED_CAST(void *(*)(void *), const SRTP_PROTECTION_PROFILE *(*)( \ - const SRTP_PROTECTION_PROFILE *), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), \ - void (*)(const SRTP_PROTECTION_PROFILE *), free_func))) - -/* SSL_CIPHER */ -#define sk_SSL_CIPHER_new(comp) \ - ((STACK_OF(SSL_CIPHER) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, \ - int (*)(const const SSL_CIPHER **a, const const SSL_CIPHER **b), comp))) - -#define sk_SSL_CIPHER_new_null() ((STACK_OF(SSL_CIPHER) *)sk_new_null()) - -#define sk_SSL_CIPHER_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(SSL_CIPHER) *, sk)) - -#define sk_SSL_CIPHER_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(SSL_CIPHER) *, sk)); - -#define sk_SSL_CIPHER_value(sk, i) \ - ((const SSL_CIPHER *)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(SSL_CIPHER) *, sk), (i))) - -#define sk_SSL_CIPHER_set(sk, i, p) \ - ((const SSL_CIPHER *)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(SSL_CIPHER) *, sk), (i), \ - CHECKED_CAST(void *, const SSL_CIPHER *, p))) - -#define sk_SSL_CIPHER_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(SSL_CIPHER) *, sk)) - -#define sk_SSL_CIPHER_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(SSL_CIPHER) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(const SSL_CIPHER *), free_func)) - -#define sk_SSL_CIPHER_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(SSL_CIPHER) *, sk), \ - CHECKED_CAST(void *, const SSL_CIPHER *, p), (where)) - -#define sk_SSL_CIPHER_delete(sk, where) \ - ((const SSL_CIPHER *)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(SSL_CIPHER) *, sk), (where))) - -#define sk_SSL_CIPHER_delete_ptr(sk, p) \ - ((const SSL_CIPHER *)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(SSL_CIPHER) *, sk), \ - CHECKED_CAST(void *, const SSL_CIPHER *, p))) - -#define sk_SSL_CIPHER_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(SSL_CIPHER) *, sk), (out_index), \ - CHECKED_CAST(void *, const SSL_CIPHER *, p)) - -#define sk_SSL_CIPHER_shift(sk) \ - ((const SSL_CIPHER *)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(SSL_CIPHER) *, sk))) - -#define sk_SSL_CIPHER_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(SSL_CIPHER) *, sk), \ - CHECKED_CAST(void *, const SSL_CIPHER *, p)) - -#define sk_SSL_CIPHER_pop(sk) \ - ((const SSL_CIPHER *)sk_pop( \ - CHECKED_CAST(_STACK *, STACK_OF(SSL_CIPHER) *, sk))) - -#define sk_SSL_CIPHER_dup(sk) \ - ((STACK_OF(SSL_CIPHER) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(SSL_CIPHER) *, sk))) - -#define sk_SSL_CIPHER_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(SSL_CIPHER) *, sk)) - -#define sk_SSL_CIPHER_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(SSL_CIPHER) *, sk)) - -#define sk_SSL_CIPHER_set_cmp_func(sk, comp) \ - ((int (*)(const SSL_CIPHER **a, const SSL_CIPHER **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(SSL_CIPHER) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const SSL_CIPHER **a, const SSL_CIPHER **b), \ - comp))) - -#define sk_SSL_CIPHER_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(SSL_CIPHER) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(SSL_CIPHER) *, sk), \ - CHECKED_CAST(void *(*)(void *), \ - const SSL_CIPHER *(*)(const SSL_CIPHER *), copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(const SSL_CIPHER *), \ - free_func))) - -/* OPENSSL_STRING */ -#define sk_OPENSSL_STRING_new(comp) \ - ((STACK_OF(OPENSSL_STRING) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, \ - int (*)(const OPENSSL_STRING *a, const OPENSSL_STRING *b), comp))) - -#define sk_OPENSSL_STRING_new_null() ((STACK_OF(OPENSSL_STRING) *)sk_new_null()) - -#define sk_OPENSSL_STRING_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_STRING) *, sk)) - -#define sk_OPENSSL_STRING_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_STRING) *, sk)); - -#define sk_OPENSSL_STRING_value(sk, i) \ - ((OPENSSL_STRING)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(OPENSSL_STRING) *, sk), (i))) - -#define sk_OPENSSL_STRING_set(sk, i, p) \ - ((OPENSSL_STRING)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_STRING) *, sk), (i), \ - CHECKED_CAST(void *, OPENSSL_STRING, p))) - -#define sk_OPENSSL_STRING_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_STRING) *, sk)) - -#define sk_OPENSSL_STRING_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_STRING) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(OPENSSL_STRING), free_func)) - -#define sk_OPENSSL_STRING_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_STRING) *, sk), \ - CHECKED_CAST(void *, OPENSSL_STRING, p), (where)) - -#define sk_OPENSSL_STRING_delete(sk, where) \ - ((OPENSSL_STRING)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_STRING) *, sk), (where))) - -#define sk_OPENSSL_STRING_delete_ptr(sk, p) \ - ((OPENSSL_STRING)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_STRING) *, sk), \ - CHECKED_CAST(void *, OPENSSL_STRING, p))) - -#define sk_OPENSSL_STRING_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_STRING) *, sk), (out_index), \ - CHECKED_CAST(void *, OPENSSL_STRING, p)) - -#define sk_OPENSSL_STRING_shift(sk) \ - ((OPENSSL_STRING)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_STRING) *, sk))) - -#define sk_OPENSSL_STRING_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_STRING) *, sk), \ - CHECKED_CAST(void *, OPENSSL_STRING, p)) - -#define sk_OPENSSL_STRING_pop(sk) \ - ((OPENSSL_STRING)sk_pop( \ - CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_STRING) *, sk))) - -#define sk_OPENSSL_STRING_dup(sk) \ - ((STACK_OF(OPENSSL_STRING) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(OPENSSL_STRING) *, sk))) - -#define sk_OPENSSL_STRING_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_STRING) *, sk)) - -#define sk_OPENSSL_STRING_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(OPENSSL_STRING) *, sk)) - -#define sk_OPENSSL_STRING_set_cmp_func(sk, comp) \ - ((int (*)(const OPENSSL_STRING **a, const OPENSSL_STRING **b)) \ - sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_STRING) *, sk), \ - CHECKED_CAST(stack_cmp_func, int (*)(const OPENSSL_STRING **a, \ - const OPENSSL_STRING **b), \ - comp))) - -#define sk_OPENSSL_STRING_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(OPENSSL_STRING) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(OPENSSL_STRING) *, sk), \ - CHECKED_CAST(void *(*)(void *), OPENSSL_STRING (*)(OPENSSL_STRING), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(OPENSSL_STRING), free_func))) - -/* OPENSSL_BLOCK */ -#define sk_OPENSSL_BLOCK_new(comp) \ - ((STACK_OF(OPENSSL_BLOCK) *)sk_new(CHECKED_CAST( \ - stack_cmp_func, int (*)(const OPENSSL_BLOCK *a, const OPENSSL_BLOCK *b), \ - comp))) - -#define sk_OPENSSL_BLOCK_new_null() ((STACK_OF(OPENSSL_BLOCK) *)sk_new_null()) - -#define sk_OPENSSL_BLOCK_num(sk) \ - sk_num(CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_BLOCK) *, sk)) - -#define sk_OPENSSL_BLOCK_zero(sk) \ - sk_zero(CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_BLOCK) *, sk)); - -#define sk_OPENSSL_BLOCK_value(sk, i) \ - ((OPENSSL_BLOCK)sk_value( \ - CHECKED_CAST(_STACK *, const STACK_OF(OPENSSL_BLOCK) *, sk), (i))) - -#define sk_OPENSSL_BLOCK_set(sk, i, p) \ - ((OPENSSL_BLOCK)sk_set( \ - CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_BLOCK) *, sk), (i), \ - CHECKED_CAST(void *, OPENSSL_BLOCK, p))) - -#define sk_OPENSSL_BLOCK_free(sk) \ - sk_free(CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_BLOCK) *, sk)) - -#define sk_OPENSSL_BLOCK_pop_free(sk, free_func) \ - sk_pop_free( \ - CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_BLOCK) *, sk), \ - CHECKED_CAST(void (*)(void *), void (*)(OPENSSL_BLOCK), free_func)) - -#define sk_OPENSSL_BLOCK_insert(sk, p, where) \ - sk_insert(CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_BLOCK) *, sk), \ - CHECKED_CAST(void *, OPENSSL_BLOCK, p), (where)) - -#define sk_OPENSSL_BLOCK_delete(sk, where) \ - ((OPENSSL_BLOCK)sk_delete( \ - CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_BLOCK) *, sk), (where))) - -#define sk_OPENSSL_BLOCK_delete_ptr(sk, p) \ - ((OPENSSL_BLOCK)sk_delete_ptr( \ - CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_BLOCK) *, sk), \ - CHECKED_CAST(void *, OPENSSL_BLOCK, p))) - -#define sk_OPENSSL_BLOCK_find(sk, out_index, p) \ - sk_find(CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_BLOCK) *, sk), (out_index), \ - CHECKED_CAST(void *, OPENSSL_BLOCK, p)) - -#define sk_OPENSSL_BLOCK_shift(sk) \ - ((OPENSSL_BLOCK)sk_shift( \ - CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_BLOCK) *, sk))) - -#define sk_OPENSSL_BLOCK_push(sk, p) \ - sk_push(CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_BLOCK) *, sk), \ - CHECKED_CAST(void *, OPENSSL_BLOCK, p)) - -#define sk_OPENSSL_BLOCK_pop(sk) \ - ((OPENSSL_BLOCK)sk_pop(CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_BLOCK) *, sk))) - -#define sk_OPENSSL_BLOCK_dup(sk) \ - ((STACK_OF(OPENSSL_BLOCK) *)sk_dup( \ - CHECKED_CAST(_STACK *, const STACK_OF(OPENSSL_BLOCK) *, sk))) - -#define sk_OPENSSL_BLOCK_sort(sk) \ - sk_sort(CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_BLOCK) *, sk)) - -#define sk_OPENSSL_BLOCK_is_sorted(sk) \ - sk_is_sorted(CHECKED_CAST(_STACK *, const STACK_OF(OPENSSL_BLOCK) *, sk)) - -#define sk_OPENSSL_BLOCK_set_cmp_func(sk, comp) \ - ((int (*)(const OPENSSL_BLOCK **a, const OPENSSL_BLOCK **b))sk_set_cmp_func( \ - CHECKED_CAST(_STACK *, STACK_OF(OPENSSL_BLOCK) *, sk), \ - CHECKED_CAST(stack_cmp_func, \ - int (*)(const OPENSSL_BLOCK **a, const OPENSSL_BLOCK **b), \ - comp))) - -#define sk_OPENSSL_BLOCK_deep_copy(sk, copy_func, free_func) \ - ((STACK_OF(OPENSSL_BLOCK) *)sk_deep_copy( \ - CHECKED_CAST(const _STACK *, const STACK_OF(OPENSSL_BLOCK) *, sk), \ - CHECKED_CAST(void *(*)(void *), OPENSSL_BLOCK (*)(OPENSSL_BLOCK), \ - copy_func), \ - CHECKED_CAST(void (*)(void *), void (*)(OPENSSL_BLOCK), free_func))) diff --git a/third_party/boringssl/include/openssl/thread.h b/third_party/boringssl/include/openssl/thread.h deleted file mode 100644 index 568a858332..0000000000 --- a/third_party/boringssl/include/openssl/thread.h +++ /dev/null @@ -1,173 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] */ - -#ifndef OPENSSL_HEADER_THREAD_H -#define OPENSSL_HEADER_THREAD_H - -#include - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -#if defined(OPENSSL_NO_THREADS) -typedef struct crypto_mutex_st {} CRYPTO_MUTEX; -#elif defined(OPENSSL_WINDOWS) -/* CRYPTO_MUTEX can appear in public header files so we really don't want to - * pull in windows.h. It's statically asserted that this structure is large - * enough to contain a Windows CRITICAL_SECTION by thread_win.c. */ -typedef union crypto_mutex_st { - double alignment; - uint8_t padding[4*sizeof(void*) + 2*sizeof(int)]; -} CRYPTO_MUTEX; -#elif defined(__MACH__) && defined(__APPLE__) -typedef pthread_rwlock_t CRYPTO_MUTEX; -#else -/* It is reasonable to include pthread.h on non-Windows systems, however the - * |pthread_rwlock_t| that we need is hidden under feature flags, and we can't - * ensure that we'll be able to get it. It's statically asserted that this - * structure is large enough to contain a |pthread_rwlock_t| by - * thread_pthread.c. */ -typedef union crypto_mutex_st { - double alignment; - uint8_t padding[3*sizeof(int) + 5*sizeof(unsigned) + 16 + 8]; -} CRYPTO_MUTEX; -#endif - -/* CRYPTO_refcount_t is the type of a reference count. - * - * Since some platforms use C11 atomics to access this, it should have the - * _Atomic qualifier. However, this header is included by C++ programs as well - * as C code that might not set -std=c11. So, in practice, it's not possible to - * do that. Instead we statically assert that the size and native alignment of - * a plain uint32_t and an _Atomic uint32_t are equal in refcount_c11.c. */ -typedef uint32_t CRYPTO_refcount_t; - - -/* Deprecated functions */ - -/* These defines do nothing but are provided to make old code easier to - * compile. */ -#define CRYPTO_LOCK 1 -#define CRYPTO_UNLOCK 2 -#define CRYPTO_READ 4 -#define CRYPTO_WRITE 8 - -/* CRYPTO_num_locks returns one. (This is non-zero that callers who allocate - * sizeof(lock) times this value don't get zero and then fail because malloc(0) - * returned NULL.) */ -OPENSSL_EXPORT int CRYPTO_num_locks(void); - -/* CRYPTO_set_locking_callback does nothing. */ -OPENSSL_EXPORT void CRYPTO_set_locking_callback( - void (*func)(int mode, int lock_num, const char *file, int line)); - -/* CRYPTO_set_add_lock_callback does nothing. */ -OPENSSL_EXPORT void CRYPTO_set_add_lock_callback(int (*func)( - int *num, int amount, int lock_num, const char *file, int line)); - -/* CRYPTO_get_lock_name returns a fixed, dummy string. */ -OPENSSL_EXPORT const char *CRYPTO_get_lock_name(int lock_num); - -/* CRYPTO_THREADID_set_callback returns one. */ -OPENSSL_EXPORT int CRYPTO_THREADID_set_callback( - void (*threadid_func)(CRYPTO_THREADID *threadid)); - -/* CRYPTO_THREADID_set_numeric does nothing. */ -OPENSSL_EXPORT void CRYPTO_THREADID_set_numeric(CRYPTO_THREADID *id, - unsigned long val); - -/* CRYPTO_THREADID_set_pointer does nothing. */ -OPENSSL_EXPORT void CRYPTO_THREADID_set_pointer(CRYPTO_THREADID *id, void *ptr); - -/* CRYPTO_THREADID_current does nothing. */ -OPENSSL_EXPORT void CRYPTO_THREADID_current(CRYPTO_THREADID *id); - - -/* Private functions. - * - * Some old code calls these functions and so no-op implementations are - * provided. - * - * TODO(fork): cleanup callers and remove. */ - -OPENSSL_EXPORT void CRYPTO_set_id_callback(unsigned long (*func)(void)); - -typedef struct { - int references; - struct CRYPTO_dynlock_value *data; -} CRYPTO_dynlock; - -OPENSSL_EXPORT void CRYPTO_set_dynlock_create_callback( - struct CRYPTO_dynlock_value *(*dyn_create_function)(const char *file, - int line)); - -OPENSSL_EXPORT void CRYPTO_set_dynlock_lock_callback(void (*dyn_lock_function)( - int mode, struct CRYPTO_dynlock_value *l, const char *file, int line)); - -OPENSSL_EXPORT void CRYPTO_set_dynlock_destroy_callback( - void (*dyn_destroy_function)(struct CRYPTO_dynlock_value *l, - const char *file, int line)); - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_THREAD_H */ diff --git a/third_party/boringssl/include/openssl/time_support.h b/third_party/boringssl/include/openssl/time_support.h deleted file mode 100644 index 912e672415..0000000000 --- a/third_party/boringssl/include/openssl/time_support.h +++ /dev/null @@ -1,90 +0,0 @@ -/* Written by Richard Levitte (richard@levitte.org) for the OpenSSL - * project 2001. - * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL - * project 2008. - */ -/* ==================================================================== - * Copyright (c) 2001 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * licensing@OpenSSL.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS 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. - * ==================================================================== - * - * This product includes cryptographic software written by Eric Young - * (eay@cryptsoft.com). This product includes software written by Tim - * Hudson (tjh@cryptsoft.com). */ - -#ifndef OPENSSL_HEADER_TIME_H -#define OPENSSL_HEADER_TIME_H - -#include - - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* Wrapper functions for time functions. */ - - -/* OPENSSL_gmtime wraps |gmtime_r|. See the manual page for that function. */ -struct tm *OPENSSL_gmtime(const time_t *timer, struct tm *result); - -/* OPENSSL_gmtime_adj updates |tm| by adding |offset_day| days and |offset_sec| - * seconds. */ -int OPENSSL_gmtime_adj(struct tm *tm, int offset_day, long offset_sec); - -/* OPENSSL_gmtime_diff calculates the difference between |from| and |to| and - * outputs the difference as a number of days and seconds in |*out_days| and - * |*out_secs|. */ -int OPENSSL_gmtime_diff(int *out_days, int *out_secs, const struct tm *from, - const struct tm *to); - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_TIME_H */ diff --git a/third_party/boringssl/include/openssl/tls1.h b/third_party/boringssl/include/openssl/tls1.h deleted file mode 100644 index f2bee2738f..0000000000 --- a/third_party/boringssl/include/openssl/tls1.h +++ /dev/null @@ -1,714 +0,0 @@ -/* ssl/tls1.h */ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] - */ -/* ==================================================================== - * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * openssl-core@openssl.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.openssl.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS 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. - * ==================================================================== - * - * This product includes cryptographic software written by Eric Young - * (eay@cryptsoft.com). This product includes software written by Tim - * Hudson (tjh@cryptsoft.com). - * - */ -/* ==================================================================== - * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. - * - * Portions of the attached software ("Contribution") are developed by - * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project. - * - * The Contribution is licensed pursuant to the OpenSSL open source - * license provided above. - * - * ECC cipher suite support in OpenSSL originally written by - * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories. - * - */ -/* ==================================================================== - * Copyright 2005 Nokia. All rights reserved. - * - * The portions of the attached software ("Contribution") is developed by - * Nokia Corporation and is licensed pursuant to the OpenSSL open source - * license. - * - * The Contribution, originally written by Mika Kousa and Pasi Eronen of - * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites - * support (see RFC 4279) to OpenSSL. - * - * No patent licenses or other rights except those expressly stated in - * the OpenSSL open source license shall be deemed granted or received - * expressly, by implication, estoppel, or otherwise. - * - * No assurances are provided by Nokia that the Contribution does not - * infringe the patent or other intellectual property rights of any third - * party or that the license provides you with all the necessary rights - * to make use of the Contribution. - * - * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN - * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA - * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY - * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR - * OTHERWISE. - */ - -#ifndef HEADER_TLS1_H -#define HEADER_TLS1_H - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - - -#define TLS1_ALLOW_EXPERIMENTAL_CIPHERSUITES 0 - -#define TLS1_AD_DECRYPTION_FAILED 21 -#define TLS1_AD_RECORD_OVERFLOW 22 -#define TLS1_AD_UNKNOWN_CA 48 /* fatal */ -#define TLS1_AD_ACCESS_DENIED 49 /* fatal */ -#define TLS1_AD_DECODE_ERROR 50 /* fatal */ -#define TLS1_AD_DECRYPT_ERROR 51 -#define TLS1_AD_EXPORT_RESTRICTION 60 /* fatal */ -#define TLS1_AD_PROTOCOL_VERSION 70 /* fatal */ -#define TLS1_AD_INSUFFICIENT_SECURITY 71 /* fatal */ -#define TLS1_AD_INTERNAL_ERROR 80 /* fatal */ -#define TLS1_AD_USER_CANCELLED 90 -#define TLS1_AD_NO_RENEGOTIATION 100 -/* codes 110-114 are from RFC3546 */ -#define TLS1_AD_UNSUPPORTED_EXTENSION 110 -#define TLS1_AD_CERTIFICATE_UNOBTAINABLE 111 -#define TLS1_AD_UNRECOGNIZED_NAME 112 -#define TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE 113 -#define TLS1_AD_BAD_CERTIFICATE_HASH_VALUE 114 -#define TLS1_AD_UNKNOWN_PSK_IDENTITY 115 /* fatal */ - -/* ExtensionType values from RFC3546 / RFC4366 / RFC6066 */ -#define TLSEXT_TYPE_server_name 0 -#define TLSEXT_TYPE_max_fragment_length 1 -#define TLSEXT_TYPE_client_certificate_url 2 -#define TLSEXT_TYPE_trusted_ca_keys 3 -#define TLSEXT_TYPE_truncated_hmac 4 -#define TLSEXT_TYPE_status_request 5 -/* ExtensionType values from RFC4681 */ -#define TLSEXT_TYPE_user_mapping 6 - -/* ExtensionType values from RFC5878 */ -#define TLSEXT_TYPE_client_authz 7 -#define TLSEXT_TYPE_server_authz 8 - -/* ExtensionType values from RFC6091 */ -#define TLSEXT_TYPE_cert_type 9 - -/* ExtensionType values from RFC4492 */ -#define TLSEXT_TYPE_elliptic_curves 10 -#define TLSEXT_TYPE_ec_point_formats 11 - -/* ExtensionType value from RFC5054 */ -#define TLSEXT_TYPE_srp 12 - -/* ExtensionType values from RFC5246 */ -#define TLSEXT_TYPE_signature_algorithms 13 - -/* ExtensionType value from RFC5764 */ -#define TLSEXT_TYPE_use_srtp 14 - -/* ExtensionType value from RFC5620 */ -#define TLSEXT_TYPE_heartbeat 15 - -/* ExtensionType value from RFC7301 */ -#define TLSEXT_TYPE_application_layer_protocol_negotiation 16 - -/* ExtensionType value for TLS padding extension. - * http://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml - * http://tools.ietf.org/html/draft-agl-tls-padding-03 - */ -#define TLSEXT_TYPE_padding 21 - -/* https://tools.ietf.org/html/draft-ietf-tls-session-hash-01 */ -#define TLSEXT_TYPE_extended_master_secret 23 - -/* ExtensionType value from RFC4507 */ -#define TLSEXT_TYPE_session_ticket 35 - -/* ExtensionType value from RFC5746 */ -#define TLSEXT_TYPE_renegotiate 0xff01 - -/* ExtensionType value from RFC6962 */ -#define TLSEXT_TYPE_certificate_timestamp 18 - -/* This is not an IANA defined extension number */ -#define TLSEXT_TYPE_next_proto_neg 13172 - -/* This is not an IANA defined extension number */ -#define TLSEXT_TYPE_channel_id 30031 -#define TLSEXT_TYPE_channel_id_new 30032 - -/* NameType value from RFC 3546 */ -#define TLSEXT_NAMETYPE_host_name 0 -/* status request value from RFC 3546 */ -#define TLSEXT_STATUSTYPE_ocsp 1 - -/* ECPointFormat values from RFC 4492 */ -#define TLSEXT_ECPOINTFORMAT_uncompressed 0 -#define TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime 1 -#define TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2 2 - -/* Signature and hash algorithms from RFC 5246 */ - -#define TLSEXT_signature_anonymous 0 -#define TLSEXT_signature_rsa 1 -#define TLSEXT_signature_dsa 2 -#define TLSEXT_signature_ecdsa 3 - -#define TLSEXT_hash_none 0 -#define TLSEXT_hash_md5 1 -#define TLSEXT_hash_sha1 2 -#define TLSEXT_hash_sha224 3 -#define TLSEXT_hash_sha256 4 -#define TLSEXT_hash_sha384 5 -#define TLSEXT_hash_sha512 6 - -/* Flag set for unrecognised algorithms */ -#define TLSEXT_nid_unknown 0x1000000 - -/* ECC curves */ - -#define TLSEXT_curve_P_256 23 -#define TLSEXT_curve_P_384 24 - - -#define TLSEXT_MAXLEN_host_name 255 - -OPENSSL_EXPORT const char *SSL_get_servername(const SSL *s, const int type); -OPENSSL_EXPORT int SSL_get_servername_type(const SSL *s); - -/* SSL_export_keying_material exports a value derived from the master secret, as - * specified in RFC 5705. It writes |out_len| bytes to |out| given a label and - * optional context. (Since a zero length context is allowed, the |use_context| - * flag controls whether a context is included.) - * - * It returns one on success and zero otherwise. */ -OPENSSL_EXPORT int SSL_export_keying_material( - SSL *s, uint8_t *out, size_t out_len, const char *label, size_t label_len, - const uint8_t *context, size_t context_len, int use_context); - -OPENSSL_EXPORT int SSL_get_sigalgs(SSL *s, int idx, int *psign, int *phash, - int *psignandhash, uint8_t *rsig, - uint8_t *rhash); - -OPENSSL_EXPORT int SSL_get_shared_sigalgs(SSL *s, int idx, int *psign, - int *phash, int *psignandhash, - uint8_t *rsig, uint8_t *rhash); - -/* SSL_set_tlsext_host_name, for a client, configures |ssl| to advertise |name| - * in the server_name extension. It returns one on success and zero on error. */ -OPENSSL_EXPORT int SSL_set_tlsext_host_name(SSL *ssl, const char *name); - -/* SSL_CTX_set_tlsext_servername_callback configures |callback| to be called on - * the server after ClientHello extensions have been parsed and returns one. - * |callback| may use |SSL_get_servername| to examine the server_name extension - * and return a |SSL_TLSEXT_ERR_*| value. If it returns |SSL_TLSEXT_ERR_NOACK|, - * the server_name extension is not acknowledged in the ServerHello. If the - * return value signals an alert, |callback| should set |*out_alert| to the - * alert to send. */ -OPENSSL_EXPORT int SSL_CTX_set_tlsext_servername_callback( - SSL_CTX *ctx, int (*callback)(SSL *ssl, int *out_alert, void *arg)); - -#define SSL_TLSEXT_ERR_OK 0 -#define SSL_TLSEXT_ERR_ALERT_WARNING 1 -#define SSL_TLSEXT_ERR_ALERT_FATAL 2 -#define SSL_TLSEXT_ERR_NOACK 3 - -/* SSL_CTX_set_tlsext_servername_arg sets the argument to the servername - * callback and returns one. See |SSL_CTX_set_tlsext_servername_callback|. */ -OPENSSL_EXPORT int SSL_CTX_set_tlsext_servername_arg(SSL_CTX *ctx, void *arg); - -#define SSL_CTX_get_tlsext_ticket_keys(ctx, keys, keylen) \ - SSL_CTX_ctrl((ctx), SSL_CTRL_GET_TLSEXT_TICKET_KEYS, (keylen), (keys)) -#define SSL_CTX_set_tlsext_ticket_keys(ctx, keys, keylen) \ - SSL_CTX_ctrl((ctx), SSL_CTRL_SET_TLSEXT_TICKET_KEYS, (keylen), (keys)) - -/* SSL_CTX_set_tlsext_ticket_key_cb sets the ticket callback to |callback| and - * returns one. |callback| will be called when encrypting a new ticket and when - * decrypting a ticket from the client. - * - * In both modes, |ctx| and |hmac_ctx| will already have been initialized with - * |EVP_CIPHER_CTX_init| and |HMAC_CTX_init|, respectively. |callback| - * configures |hmac_ctx| with an HMAC digest and key, and configures |ctx| - * for encryption or decryption, based on the mode. - * - * When encrypting a new ticket, |encrypt| will be one. It writes a public - * 16-byte key name to |key_name| and a fresh IV to |iv|. The output IV length - * must match |EVP_CIPHER_CTX_iv_length| of the cipher selected. In this mode, - * |callback| returns 1 on success and -1 on error. - * - * When decrypting a ticket, |encrypt| will be zero. |key_name| will point to a - * 16-byte key name and |iv| points to an IV. The length of the IV consumed must - * match |EVP_CIPHER_CTX_iv_length| of the cipher selected. In this mode, - * |callback| returns -1 to abort the handshake, 0 if decrypting the ticket - * failed, and 1 or 2 on success. If it returns 2, the ticket will be renewed. - * This may be used to re-key the ticket. - * - * WARNING: |callback| wildly breaks the usual return value convention and is - * called in two different modes. */ -OPENSSL_EXPORT int SSL_CTX_set_tlsext_ticket_key_cb( - SSL_CTX *ctx, int (*callback)(SSL *ssl, uint8_t *key_name, uint8_t *iv, - EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx, - int encrypt)); - -/* PSK ciphersuites from 4279 */ -#define TLS1_CK_PSK_WITH_RC4_128_SHA 0x0300008A -#define TLS1_CK_PSK_WITH_3DES_EDE_CBC_SHA 0x0300008B -#define TLS1_CK_PSK_WITH_AES_128_CBC_SHA 0x0300008C -#define TLS1_CK_PSK_WITH_AES_256_CBC_SHA 0x0300008D - -/* PSK ciphersuites from RFC 5489 */ -#define TLS1_CK_ECDHE_PSK_WITH_AES_128_CBC_SHA 0x0300C035 -#define TLS1_CK_ECDHE_PSK_WITH_AES_256_CBC_SHA 0x0300C036 - -/* Additional TLS ciphersuites from expired Internet Draft - * draft-ietf-tls-56-bit-ciphersuites-01.txt - * (available if TLS1_ALLOW_EXPERIMENTAL_CIPHERSUITES is defined, see - * s3_lib.c). We actually treat them like SSL 3.0 ciphers, which we probably - * shouldn't. Note that the first two are actually not in the IDs. */ -#define TLS1_CK_RSA_EXPORT1024_WITH_RC4_56_MD5 0x03000060 /* not in ID */ -#define TLS1_CK_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5 0x03000061 /* not in ID */ -#define TLS1_CK_RSA_EXPORT1024_WITH_DES_CBC_SHA 0x03000062 -#define TLS1_CK_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA 0x03000063 -#define TLS1_CK_RSA_EXPORT1024_WITH_RC4_56_SHA 0x03000064 -#define TLS1_CK_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA 0x03000065 -#define TLS1_CK_DHE_DSS_WITH_RC4_128_SHA 0x03000066 - -/* AES ciphersuites from RFC3268 */ - -#define TLS1_CK_RSA_WITH_AES_128_SHA 0x0300002F -#define TLS1_CK_DH_DSS_WITH_AES_128_SHA 0x03000030 -#define TLS1_CK_DH_RSA_WITH_AES_128_SHA 0x03000031 -#define TLS1_CK_DHE_DSS_WITH_AES_128_SHA 0x03000032 -#define TLS1_CK_DHE_RSA_WITH_AES_128_SHA 0x03000033 -#define TLS1_CK_ADH_WITH_AES_128_SHA 0x03000034 - -#define TLS1_CK_RSA_WITH_AES_256_SHA 0x03000035 -#define TLS1_CK_DH_DSS_WITH_AES_256_SHA 0x03000036 -#define TLS1_CK_DH_RSA_WITH_AES_256_SHA 0x03000037 -#define TLS1_CK_DHE_DSS_WITH_AES_256_SHA 0x03000038 -#define TLS1_CK_DHE_RSA_WITH_AES_256_SHA 0x03000039 -#define TLS1_CK_ADH_WITH_AES_256_SHA 0x0300003A - -/* TLS v1.2 ciphersuites */ -#define TLS1_CK_RSA_WITH_NULL_SHA256 0x0300003B -#define TLS1_CK_RSA_WITH_AES_128_SHA256 0x0300003C -#define TLS1_CK_RSA_WITH_AES_256_SHA256 0x0300003D -#define TLS1_CK_DH_DSS_WITH_AES_128_SHA256 0x0300003E -#define TLS1_CK_DH_RSA_WITH_AES_128_SHA256 0x0300003F -#define TLS1_CK_DHE_DSS_WITH_AES_128_SHA256 0x03000040 - -/* Camellia ciphersuites from RFC4132 */ -#define TLS1_CK_RSA_WITH_CAMELLIA_128_CBC_SHA 0x03000041 -#define TLS1_CK_DH_DSS_WITH_CAMELLIA_128_CBC_SHA 0x03000042 -#define TLS1_CK_DH_RSA_WITH_CAMELLIA_128_CBC_SHA 0x03000043 -#define TLS1_CK_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA 0x03000044 -#define TLS1_CK_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA 0x03000045 -#define TLS1_CK_ADH_WITH_CAMELLIA_128_CBC_SHA 0x03000046 - -/* TLS v1.2 ciphersuites */ -#define TLS1_CK_DHE_RSA_WITH_AES_128_SHA256 0x03000067 -#define TLS1_CK_DH_DSS_WITH_AES_256_SHA256 0x03000068 -#define TLS1_CK_DH_RSA_WITH_AES_256_SHA256 0x03000069 -#define TLS1_CK_DHE_DSS_WITH_AES_256_SHA256 0x0300006A -#define TLS1_CK_DHE_RSA_WITH_AES_256_SHA256 0x0300006B -#define TLS1_CK_ADH_WITH_AES_128_SHA256 0x0300006C -#define TLS1_CK_ADH_WITH_AES_256_SHA256 0x0300006D - -/* Camellia ciphersuites from RFC4132 */ -#define TLS1_CK_RSA_WITH_CAMELLIA_256_CBC_SHA 0x03000084 -#define TLS1_CK_DH_DSS_WITH_CAMELLIA_256_CBC_SHA 0x03000085 -#define TLS1_CK_DH_RSA_WITH_CAMELLIA_256_CBC_SHA 0x03000086 -#define TLS1_CK_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA 0x03000087 -#define TLS1_CK_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA 0x03000088 -#define TLS1_CK_ADH_WITH_CAMELLIA_256_CBC_SHA 0x03000089 - -/* SEED ciphersuites from RFC4162 */ -#define TLS1_CK_RSA_WITH_SEED_SHA 0x03000096 -#define TLS1_CK_DH_DSS_WITH_SEED_SHA 0x03000097 -#define TLS1_CK_DH_RSA_WITH_SEED_SHA 0x03000098 -#define TLS1_CK_DHE_DSS_WITH_SEED_SHA 0x03000099 -#define TLS1_CK_DHE_RSA_WITH_SEED_SHA 0x0300009A -#define TLS1_CK_ADH_WITH_SEED_SHA 0x0300009B - -/* TLS v1.2 GCM ciphersuites from RFC5288 */ -#define TLS1_CK_RSA_WITH_AES_128_GCM_SHA256 0x0300009C -#define TLS1_CK_RSA_WITH_AES_256_GCM_SHA384 0x0300009D -#define TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256 0x0300009E -#define TLS1_CK_DHE_RSA_WITH_AES_256_GCM_SHA384 0x0300009F -#define TLS1_CK_DH_RSA_WITH_AES_128_GCM_SHA256 0x030000A0 -#define TLS1_CK_DH_RSA_WITH_AES_256_GCM_SHA384 0x030000A1 -#define TLS1_CK_DHE_DSS_WITH_AES_128_GCM_SHA256 0x030000A2 -#define TLS1_CK_DHE_DSS_WITH_AES_256_GCM_SHA384 0x030000A3 -#define TLS1_CK_DH_DSS_WITH_AES_128_GCM_SHA256 0x030000A4 -#define TLS1_CK_DH_DSS_WITH_AES_256_GCM_SHA384 0x030000A5 -#define TLS1_CK_ADH_WITH_AES_128_GCM_SHA256 0x030000A6 -#define TLS1_CK_ADH_WITH_AES_256_GCM_SHA384 0x030000A7 - -/* ECC ciphersuites from RFC4492 */ -#define TLS1_CK_ECDH_ECDSA_WITH_NULL_SHA 0x0300C001 -#define TLS1_CK_ECDH_ECDSA_WITH_RC4_128_SHA 0x0300C002 -#define TLS1_CK_ECDH_ECDSA_WITH_DES_192_CBC3_SHA 0x0300C003 -#define TLS1_CK_ECDH_ECDSA_WITH_AES_128_CBC_SHA 0x0300C004 -#define TLS1_CK_ECDH_ECDSA_WITH_AES_256_CBC_SHA 0x0300C005 - -#define TLS1_CK_ECDHE_ECDSA_WITH_NULL_SHA 0x0300C006 -#define TLS1_CK_ECDHE_ECDSA_WITH_RC4_128_SHA 0x0300C007 -#define TLS1_CK_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA 0x0300C008 -#define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CBC_SHA 0x0300C009 -#define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CBC_SHA 0x0300C00A - -#define TLS1_CK_ECDH_RSA_WITH_NULL_SHA 0x0300C00B -#define TLS1_CK_ECDH_RSA_WITH_RC4_128_SHA 0x0300C00C -#define TLS1_CK_ECDH_RSA_WITH_DES_192_CBC3_SHA 0x0300C00D -#define TLS1_CK_ECDH_RSA_WITH_AES_128_CBC_SHA 0x0300C00E -#define TLS1_CK_ECDH_RSA_WITH_AES_256_CBC_SHA 0x0300C00F - -#define TLS1_CK_ECDHE_RSA_WITH_NULL_SHA 0x0300C010 -#define TLS1_CK_ECDHE_RSA_WITH_RC4_128_SHA 0x0300C011 -#define TLS1_CK_ECDHE_RSA_WITH_DES_192_CBC3_SHA 0x0300C012 -#define TLS1_CK_ECDHE_RSA_WITH_AES_128_CBC_SHA 0x0300C013 -#define TLS1_CK_ECDHE_RSA_WITH_AES_256_CBC_SHA 0x0300C014 - -#define TLS1_CK_ECDH_anon_WITH_NULL_SHA 0x0300C015 -#define TLS1_CK_ECDH_anon_WITH_RC4_128_SHA 0x0300C016 -#define TLS1_CK_ECDH_anon_WITH_DES_192_CBC3_SHA 0x0300C017 -#define TLS1_CK_ECDH_anon_WITH_AES_128_CBC_SHA 0x0300C018 -#define TLS1_CK_ECDH_anon_WITH_AES_256_CBC_SHA 0x0300C019 - -/* SRP ciphersuites from RFC 5054 */ -#define TLS1_CK_SRP_SHA_WITH_3DES_EDE_CBC_SHA 0x0300C01A -#define TLS1_CK_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA 0x0300C01B -#define TLS1_CK_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA 0x0300C01C -#define TLS1_CK_SRP_SHA_WITH_AES_128_CBC_SHA 0x0300C01D -#define TLS1_CK_SRP_SHA_RSA_WITH_AES_128_CBC_SHA 0x0300C01E -#define TLS1_CK_SRP_SHA_DSS_WITH_AES_128_CBC_SHA 0x0300C01F -#define TLS1_CK_SRP_SHA_WITH_AES_256_CBC_SHA 0x0300C020 -#define TLS1_CK_SRP_SHA_RSA_WITH_AES_256_CBC_SHA 0x0300C021 -#define TLS1_CK_SRP_SHA_DSS_WITH_AES_256_CBC_SHA 0x0300C022 - -/* ECDH HMAC based ciphersuites from RFC5289 */ - -#define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_SHA256 0x0300C023 -#define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_SHA384 0x0300C024 -#define TLS1_CK_ECDH_ECDSA_WITH_AES_128_SHA256 0x0300C025 -#define TLS1_CK_ECDH_ECDSA_WITH_AES_256_SHA384 0x0300C026 -#define TLS1_CK_ECDHE_RSA_WITH_AES_128_SHA256 0x0300C027 -#define TLS1_CK_ECDHE_RSA_WITH_AES_256_SHA384 0x0300C028 -#define TLS1_CK_ECDH_RSA_WITH_AES_128_SHA256 0x0300C029 -#define TLS1_CK_ECDH_RSA_WITH_AES_256_SHA384 0x0300C02A - -/* ECDH GCM based ciphersuites from RFC5289 */ -#define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0x0300C02B -#define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0x0300C02C -#define TLS1_CK_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0x0300C02D -#define TLS1_CK_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 0x0300C02E -#define TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0x0300C02F -#define TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0x0300C030 -#define TLS1_CK_ECDH_RSA_WITH_AES_128_GCM_SHA256 0x0300C031 -#define TLS1_CK_ECDH_RSA_WITH_AES_256_GCM_SHA384 0x0300C032 - -#define TLS1_CK_ECDHE_RSA_CHACHA20_POLY1305 0x0300CC13 -#define TLS1_CK_ECDHE_ECDSA_CHACHA20_POLY1305 0x0300CC14 -#define TLS1_CK_DHE_RSA_CHACHA20_POLY1305 0x0300CC15 - -/* XXX - * Inconsistency alert: - * The OpenSSL names of ciphers with ephemeral DH here include the string - * "DHE", while elsewhere it has always been "EDH". - * (The alias for the list of all such ciphers also is "EDH".) - * The specifications speak of "EDH"; maybe we should allow both forms - * for everything. */ -#define TLS1_TXT_RSA_EXPORT1024_WITH_RC4_56_MD5 "EXP1024-RC4-MD5" -#define TLS1_TXT_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5 "EXP1024-RC2-CBC-MD5" -#define TLS1_TXT_RSA_EXPORT1024_WITH_DES_CBC_SHA "EXP1024-DES-CBC-SHA" -#define TLS1_TXT_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA \ - "EXP1024-DHE-DSS-DES-CBC-SHA" -#define TLS1_TXT_RSA_EXPORT1024_WITH_RC4_56_SHA "EXP1024-RC4-SHA" -#define TLS1_TXT_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA "EXP1024-DHE-DSS-RC4-SHA" -#define TLS1_TXT_DHE_DSS_WITH_RC4_128_SHA "DHE-DSS-RC4-SHA" - -/* AES ciphersuites from RFC3268 */ -#define TLS1_TXT_RSA_WITH_AES_128_SHA "AES128-SHA" -#define TLS1_TXT_DH_DSS_WITH_AES_128_SHA "DH-DSS-AES128-SHA" -#define TLS1_TXT_DH_RSA_WITH_AES_128_SHA "DH-RSA-AES128-SHA" -#define TLS1_TXT_DHE_DSS_WITH_AES_128_SHA "DHE-DSS-AES128-SHA" -#define TLS1_TXT_DHE_RSA_WITH_AES_128_SHA "DHE-RSA-AES128-SHA" -#define TLS1_TXT_ADH_WITH_AES_128_SHA "ADH-AES128-SHA" - -#define TLS1_TXT_RSA_WITH_AES_256_SHA "AES256-SHA" -#define TLS1_TXT_DH_DSS_WITH_AES_256_SHA "DH-DSS-AES256-SHA" -#define TLS1_TXT_DH_RSA_WITH_AES_256_SHA "DH-RSA-AES256-SHA" -#define TLS1_TXT_DHE_DSS_WITH_AES_256_SHA "DHE-DSS-AES256-SHA" -#define TLS1_TXT_DHE_RSA_WITH_AES_256_SHA "DHE-RSA-AES256-SHA" -#define TLS1_TXT_ADH_WITH_AES_256_SHA "ADH-AES256-SHA" - -/* ECC ciphersuites from RFC4492 */ -#define TLS1_TXT_ECDH_ECDSA_WITH_NULL_SHA "ECDH-ECDSA-NULL-SHA" -#define TLS1_TXT_ECDH_ECDSA_WITH_RC4_128_SHA "ECDH-ECDSA-RC4-SHA" -#define TLS1_TXT_ECDH_ECDSA_WITH_DES_192_CBC3_SHA "ECDH-ECDSA-DES-CBC3-SHA" -#define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_CBC_SHA "ECDH-ECDSA-AES128-SHA" -#define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_CBC_SHA "ECDH-ECDSA-AES256-SHA" - -#define TLS1_TXT_ECDHE_ECDSA_WITH_NULL_SHA "ECDHE-ECDSA-NULL-SHA" -#define TLS1_TXT_ECDHE_ECDSA_WITH_RC4_128_SHA "ECDHE-ECDSA-RC4-SHA" -#define TLS1_TXT_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA "ECDHE-ECDSA-DES-CBC3-SHA" -#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CBC_SHA "ECDHE-ECDSA-AES128-SHA" -#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CBC_SHA "ECDHE-ECDSA-AES256-SHA" - -#define TLS1_TXT_ECDH_RSA_WITH_NULL_SHA "ECDH-RSA-NULL-SHA" -#define TLS1_TXT_ECDH_RSA_WITH_RC4_128_SHA "ECDH-RSA-RC4-SHA" -#define TLS1_TXT_ECDH_RSA_WITH_DES_192_CBC3_SHA "ECDH-RSA-DES-CBC3-SHA" -#define TLS1_TXT_ECDH_RSA_WITH_AES_128_CBC_SHA "ECDH-RSA-AES128-SHA" -#define TLS1_TXT_ECDH_RSA_WITH_AES_256_CBC_SHA "ECDH-RSA-AES256-SHA" - -#define TLS1_TXT_ECDHE_RSA_WITH_NULL_SHA "ECDHE-RSA-NULL-SHA" -#define TLS1_TXT_ECDHE_RSA_WITH_RC4_128_SHA "ECDHE-RSA-RC4-SHA" -#define TLS1_TXT_ECDHE_RSA_WITH_DES_192_CBC3_SHA "ECDHE-RSA-DES-CBC3-SHA" -#define TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA "ECDHE-RSA-AES128-SHA" -#define TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA "ECDHE-RSA-AES256-SHA" - -#define TLS1_TXT_ECDH_anon_WITH_NULL_SHA "AECDH-NULL-SHA" -#define TLS1_TXT_ECDH_anon_WITH_RC4_128_SHA "AECDH-RC4-SHA" -#define TLS1_TXT_ECDH_anon_WITH_DES_192_CBC3_SHA "AECDH-DES-CBC3-SHA" -#define TLS1_TXT_ECDH_anon_WITH_AES_128_CBC_SHA "AECDH-AES128-SHA" -#define TLS1_TXT_ECDH_anon_WITH_AES_256_CBC_SHA "AECDH-AES256-SHA" - -/* PSK ciphersuites from RFC 4279 */ -#define TLS1_TXT_PSK_WITH_RC4_128_SHA "PSK-RC4-SHA" -#define TLS1_TXT_PSK_WITH_3DES_EDE_CBC_SHA "PSK-3DES-EDE-CBC-SHA" -#define TLS1_TXT_PSK_WITH_AES_128_CBC_SHA "PSK-AES128-CBC-SHA" -#define TLS1_TXT_PSK_WITH_AES_256_CBC_SHA "PSK-AES256-CBC-SHA" - -/* PSK ciphersuites from RFC 5489 */ -#define TLS1_TXT_ECDHE_PSK_WITH_AES_128_CBC_SHA "ECDHE-PSK-AES128-CBC-SHA" -#define TLS1_TXT_ECDHE_PSK_WITH_AES_256_CBC_SHA "ECDHE-PSK-AES256-CBC-SHA" - -/* SRP ciphersuite from RFC 5054 */ -#define TLS1_TXT_SRP_SHA_WITH_3DES_EDE_CBC_SHA "SRP-3DES-EDE-CBC-SHA" -#define TLS1_TXT_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA "SRP-RSA-3DES-EDE-CBC-SHA" -#define TLS1_TXT_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA "SRP-DSS-3DES-EDE-CBC-SHA" -#define TLS1_TXT_SRP_SHA_WITH_AES_128_CBC_SHA "SRP-AES-128-CBC-SHA" -#define TLS1_TXT_SRP_SHA_RSA_WITH_AES_128_CBC_SHA "SRP-RSA-AES-128-CBC-SHA" -#define TLS1_TXT_SRP_SHA_DSS_WITH_AES_128_CBC_SHA "SRP-DSS-AES-128-CBC-SHA" -#define TLS1_TXT_SRP_SHA_WITH_AES_256_CBC_SHA "SRP-AES-256-CBC-SHA" -#define TLS1_TXT_SRP_SHA_RSA_WITH_AES_256_CBC_SHA "SRP-RSA-AES-256-CBC-SHA" -#define TLS1_TXT_SRP_SHA_DSS_WITH_AES_256_CBC_SHA "SRP-DSS-AES-256-CBC-SHA" - -/* Camellia ciphersuites from RFC4132 */ -#define TLS1_TXT_RSA_WITH_CAMELLIA_128_CBC_SHA "CAMELLIA128-SHA" -#define TLS1_TXT_DH_DSS_WITH_CAMELLIA_128_CBC_SHA "DH-DSS-CAMELLIA128-SHA" -#define TLS1_TXT_DH_RSA_WITH_CAMELLIA_128_CBC_SHA "DH-RSA-CAMELLIA128-SHA" -#define TLS1_TXT_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA "DHE-DSS-CAMELLIA128-SHA" -#define TLS1_TXT_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA "DHE-RSA-CAMELLIA128-SHA" -#define TLS1_TXT_ADH_WITH_CAMELLIA_128_CBC_SHA "ADH-CAMELLIA128-SHA" - -#define TLS1_TXT_RSA_WITH_CAMELLIA_256_CBC_SHA "CAMELLIA256-SHA" -#define TLS1_TXT_DH_DSS_WITH_CAMELLIA_256_CBC_SHA "DH-DSS-CAMELLIA256-SHA" -#define TLS1_TXT_DH_RSA_WITH_CAMELLIA_256_CBC_SHA "DH-RSA-CAMELLIA256-SHA" -#define TLS1_TXT_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA "DHE-DSS-CAMELLIA256-SHA" -#define TLS1_TXT_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA "DHE-RSA-CAMELLIA256-SHA" -#define TLS1_TXT_ADH_WITH_CAMELLIA_256_CBC_SHA "ADH-CAMELLIA256-SHA" - -/* SEED ciphersuites from RFC4162 */ -#define TLS1_TXT_RSA_WITH_SEED_SHA "SEED-SHA" -#define TLS1_TXT_DH_DSS_WITH_SEED_SHA "DH-DSS-SEED-SHA" -#define TLS1_TXT_DH_RSA_WITH_SEED_SHA "DH-RSA-SEED-SHA" -#define TLS1_TXT_DHE_DSS_WITH_SEED_SHA "DHE-DSS-SEED-SHA" -#define TLS1_TXT_DHE_RSA_WITH_SEED_SHA "DHE-RSA-SEED-SHA" -#define TLS1_TXT_ADH_WITH_SEED_SHA "ADH-SEED-SHA" - -/* TLS v1.2 ciphersuites */ -#define TLS1_TXT_RSA_WITH_NULL_SHA256 "NULL-SHA256" -#define TLS1_TXT_RSA_WITH_AES_128_SHA256 "AES128-SHA256" -#define TLS1_TXT_RSA_WITH_AES_256_SHA256 "AES256-SHA256" -#define TLS1_TXT_DH_DSS_WITH_AES_128_SHA256 "DH-DSS-AES128-SHA256" -#define TLS1_TXT_DH_RSA_WITH_AES_128_SHA256 "DH-RSA-AES128-SHA256" -#define TLS1_TXT_DHE_DSS_WITH_AES_128_SHA256 "DHE-DSS-AES128-SHA256" -#define TLS1_TXT_DHE_RSA_WITH_AES_128_SHA256 "DHE-RSA-AES128-SHA256" -#define TLS1_TXT_DH_DSS_WITH_AES_256_SHA256 "DH-DSS-AES256-SHA256" -#define TLS1_TXT_DH_RSA_WITH_AES_256_SHA256 "DH-RSA-AES256-SHA256" -#define TLS1_TXT_DHE_DSS_WITH_AES_256_SHA256 "DHE-DSS-AES256-SHA256" -#define TLS1_TXT_DHE_RSA_WITH_AES_256_SHA256 "DHE-RSA-AES256-SHA256" -#define TLS1_TXT_ADH_WITH_AES_128_SHA256 "ADH-AES128-SHA256" -#define TLS1_TXT_ADH_WITH_AES_256_SHA256 "ADH-AES256-SHA256" - -/* TLS v1.2 GCM ciphersuites from RFC5288 */ -#define TLS1_TXT_RSA_WITH_AES_128_GCM_SHA256 "AES128-GCM-SHA256" -#define TLS1_TXT_RSA_WITH_AES_256_GCM_SHA384 "AES256-GCM-SHA384" -#define TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256 "DHE-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384 "DHE-RSA-AES256-GCM-SHA384" -#define TLS1_TXT_DH_RSA_WITH_AES_128_GCM_SHA256 "DH-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_DH_RSA_WITH_AES_256_GCM_SHA384 "DH-RSA-AES256-GCM-SHA384" -#define TLS1_TXT_DHE_DSS_WITH_AES_128_GCM_SHA256 "DHE-DSS-AES128-GCM-SHA256" -#define TLS1_TXT_DHE_DSS_WITH_AES_256_GCM_SHA384 "DHE-DSS-AES256-GCM-SHA384" -#define TLS1_TXT_DH_DSS_WITH_AES_128_GCM_SHA256 "DH-DSS-AES128-GCM-SHA256" -#define TLS1_TXT_DH_DSS_WITH_AES_256_GCM_SHA384 "DH-DSS-AES256-GCM-SHA384" -#define TLS1_TXT_ADH_WITH_AES_128_GCM_SHA256 "ADH-AES128-GCM-SHA256" -#define TLS1_TXT_ADH_WITH_AES_256_GCM_SHA384 "ADH-AES256-GCM-SHA384" - -/* ECDH HMAC based ciphersuites from RFC5289 */ - -#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_SHA256 "ECDHE-ECDSA-AES128-SHA256" -#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_SHA384 "ECDHE-ECDSA-AES256-SHA384" -#define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_SHA256 "ECDH-ECDSA-AES128-SHA256" -#define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_SHA384 "ECDH-ECDSA-AES256-SHA384" -#define TLS1_TXT_ECDHE_RSA_WITH_AES_128_SHA256 "ECDHE-RSA-AES128-SHA256" -#define TLS1_TXT_ECDHE_RSA_WITH_AES_256_SHA384 "ECDHE-RSA-AES256-SHA384" -#define TLS1_TXT_ECDH_RSA_WITH_AES_128_SHA256 "ECDH-RSA-AES128-SHA256" -#define TLS1_TXT_ECDH_RSA_WITH_AES_256_SHA384 "ECDH-RSA-AES256-SHA384" - -/* ECDH GCM based ciphersuites from RFC5289 */ -#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 \ - "ECDHE-ECDSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 \ - "ECDHE-ECDSA-AES256-GCM-SHA384" -#define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 \ - "ECDH-ECDSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 \ - "ECDH-ECDSA-AES256-GCM-SHA384" -#define TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 "ECDHE-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384 "ECDHE-RSA-AES256-GCM-SHA384" -#define TLS1_TXT_ECDH_RSA_WITH_AES_128_GCM_SHA256 "ECDH-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDH_RSA_WITH_AES_256_GCM_SHA384 "ECDH-RSA-AES256-GCM-SHA384" - -#define TLS1_TXT_ECDHE_RSA_WITH_CHACHA20_POLY1305 "ECDHE-RSA-CHACHA20-POLY1305" -#define TLS1_TXT_ECDHE_ECDSA_WITH_CHACHA20_POLY1305 \ - "ECDHE-ECDSA-CHACHA20-POLY1305" -#define TLS1_TXT_DHE_RSA_WITH_CHACHA20_POLY1305 "DHE-RSA-CHACHA20-POLY1305" - -#define TLS_CT_RSA_SIGN 1 -#define TLS_CT_DSS_SIGN 2 -#define TLS_CT_RSA_FIXED_DH 3 -#define TLS_CT_DSS_FIXED_DH 4 -#define TLS_CT_ECDSA_SIGN 64 -#define TLS_CT_RSA_FIXED_ECDH 65 -#define TLS_CT_ECDSA_FIXED_ECDH 66 - -#define TLS_MD_MAX_CONST_SIZE 20 -#define TLS_MD_CLIENT_FINISH_CONST "client finished" -#define TLS_MD_CLIENT_FINISH_CONST_SIZE 15 -#define TLS_MD_SERVER_FINISH_CONST "server finished" -#define TLS_MD_SERVER_FINISH_CONST_SIZE 15 -#define TLS_MD_KEY_EXPANSION_CONST "key expansion" -#define TLS_MD_KEY_EXPANSION_CONST_SIZE 13 -#define TLS_MD_CLIENT_WRITE_KEY_CONST "client write key" -#define TLS_MD_CLIENT_WRITE_KEY_CONST_SIZE 16 -#define TLS_MD_SERVER_WRITE_KEY_CONST "server write key" -#define TLS_MD_SERVER_WRITE_KEY_CONST_SIZE 16 -#define TLS_MD_IV_BLOCK_CONST "IV block" -#define TLS_MD_IV_BLOCK_CONST_SIZE 8 -#define TLS_MD_MASTER_SECRET_CONST "master secret" -#define TLS_MD_MASTER_SECRET_CONST_SIZE 13 -#define TLS_MD_EXTENDED_MASTER_SECRET_CONST "extended master secret" -#define TLS_MD_EXTENDED_MASTER_SECRET_CONST_SIZE 22 - - -#ifdef __cplusplus -} -#endif -#endif diff --git a/third_party/boringssl/include/openssl/type_check.h b/third_party/boringssl/include/openssl/type_check.h deleted file mode 100644 index 674913a354..0000000000 --- a/third_party/boringssl/include/openssl/type_check.h +++ /dev/null @@ -1,91 +0,0 @@ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] */ - -#ifndef OPENSSL_HEADER_TYPE_CHECK_H -#define OPENSSL_HEADER_TYPE_CHECK_H - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - - -/* This header file contains some common macros for enforcing type checking. - * Several, common OpenSSL structures (i.e. stack and lhash) operate on void - * pointers, but we wish to have type checking when they are used with a - * specific type. */ - -/* CHECKED_CAST casts |p| from type |from| to type |to|. */ -#define CHECKED_CAST(to, from, p) ((to) (1 ? (p) : (from)0)) - -/* CHECKED_PTR_OF casts a given pointer to void* and statically checks that it - * was a pointer to |type|. */ -#define CHECKED_PTR_OF(type, p) CHECKED_CAST(void*, type*, (p)) - -#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L -#define OPENSSL_COMPILE_ASSERT(cond, msg) _Static_assert(cond, #msg) -#else -#define OPENSSL_COMPILE_ASSERT(cond, msg) \ - typedef char OPENSSL_COMPILE_ASSERT_##msg[((cond) ? 1 : -1)] -#endif - - -#if defined(__cplusplus) -} /* extern C */ -#endif - -#endif /* OPENSSL_HEADER_TYPE_CHECK_H */ diff --git a/third_party/boringssl/include/openssl/x509.h b/third_party/boringssl/include/openssl/x509.h deleted file mode 100644 index 69c7da64e8..0000000000 --- a/third_party/boringssl/include/openssl/x509.h +++ /dev/null @@ -1,1317 +0,0 @@ -/* crypto/x509/x509.h */ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] - */ -/* ==================================================================== - * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. - * ECDH support in OpenSSL originally developed by - * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. - */ - -#ifndef HEADER_X509_H -#define HEADER_X509_H - -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - - -#define X509_FILETYPE_PEM 1 -#define X509_FILETYPE_ASN1 2 -#define X509_FILETYPE_DEFAULT 3 - -#define X509v3_KU_DIGITAL_SIGNATURE 0x0080 -#define X509v3_KU_NON_REPUDIATION 0x0040 -#define X509v3_KU_KEY_ENCIPHERMENT 0x0020 -#define X509v3_KU_DATA_ENCIPHERMENT 0x0010 -#define X509v3_KU_KEY_AGREEMENT 0x0008 -#define X509v3_KU_KEY_CERT_SIGN 0x0004 -#define X509v3_KU_CRL_SIGN 0x0002 -#define X509v3_KU_ENCIPHER_ONLY 0x0001 -#define X509v3_KU_DECIPHER_ONLY 0x8000 -#define X509v3_KU_UNDEF 0xffff - -typedef struct X509_objects_st - { - int nid; - int (*a2i)(void); - int (*i2a)(void); - } X509_OBJECTS; - -DECLARE_ASN1_SET_OF(X509_ALGOR) - -typedef STACK_OF(X509_ALGOR) X509_ALGORS; - -typedef struct X509_val_st - { - ASN1_TIME *notBefore; - ASN1_TIME *notAfter; - } X509_VAL; - -struct X509_pubkey_st - { - X509_ALGOR *algor; - ASN1_BIT_STRING *public_key; - EVP_PKEY *pkey; - }; - -typedef struct X509_sig_st - { - X509_ALGOR *algor; - ASN1_OCTET_STRING *digest; - } X509_SIG; - -typedef struct X509_name_entry_st - { - ASN1_OBJECT *object; - ASN1_STRING *value; - int set; - int size; /* temp variable */ - } X509_NAME_ENTRY; - -DECLARE_STACK_OF(X509_NAME_ENTRY) -DECLARE_ASN1_SET_OF(X509_NAME_ENTRY) - -/* we always keep X509_NAMEs in 2 forms. */ -typedef struct X509_name_st - { - STACK_OF(X509_NAME_ENTRY) *entries; - int modified; /* true if 'bytes' needs to be built */ -#ifndef OPENSSL_NO_BUFFER - BUF_MEM *bytes; -#else - char *bytes; -#endif -/* unsigned long hash; Keep the hash around for lookups */ - unsigned char *canon_enc; - int canon_enclen; - } X509_NAME; - -DECLARE_STACK_OF(X509_NAME) - -#define X509_EX_V_NETSCAPE_HACK 0x8000 -#define X509_EX_V_INIT 0x0001 -typedef struct X509_extension_st - { - ASN1_OBJECT *object; - ASN1_BOOLEAN critical; - ASN1_OCTET_STRING *value; - } X509_EXTENSION; - -typedef STACK_OF(X509_EXTENSION) X509_EXTENSIONS; - -DECLARE_STACK_OF(X509_EXTENSION) -DECLARE_ASN1_SET_OF(X509_EXTENSION) - -/* a sequence of these are used */ -typedef struct x509_attributes_st - { - ASN1_OBJECT *object; - int single; /* 0 for a set, 1 for a single item (which is wrong) */ - union { - char *ptr; -/* 0 */ STACK_OF(ASN1_TYPE) *set; -/* 1 */ ASN1_TYPE *single; - } value; - } X509_ATTRIBUTE; - -DECLARE_STACK_OF(X509_ATTRIBUTE) -DECLARE_ASN1_SET_OF(X509_ATTRIBUTE) - - -typedef struct X509_req_info_st - { - ASN1_ENCODING enc; - ASN1_INTEGER *version; - X509_NAME *subject; - X509_PUBKEY *pubkey; - /* d=2 hl=2 l= 0 cons: cont: 00 */ - STACK_OF(X509_ATTRIBUTE) *attributes; /* [ 0 ] */ - } X509_REQ_INFO; - -typedef struct X509_req_st - { - X509_REQ_INFO *req_info; - X509_ALGOR *sig_alg; - ASN1_BIT_STRING *signature; - CRYPTO_refcount_t references; - } X509_REQ; - -typedef struct x509_cinf_st - { - ASN1_INTEGER *version; /* [ 0 ] default of v1 */ - ASN1_INTEGER *serialNumber; - X509_ALGOR *signature; - X509_NAME *issuer; - X509_VAL *validity; - X509_NAME *subject; - X509_PUBKEY *key; - ASN1_BIT_STRING *issuerUID; /* [ 1 ] optional in v2 */ - ASN1_BIT_STRING *subjectUID; /* [ 2 ] optional in v2 */ - STACK_OF(X509_EXTENSION) *extensions; /* [ 3 ] optional in v3 */ - ASN1_ENCODING enc; - } X509_CINF; - -/* This stuff is certificate "auxiliary info" - * it contains details which are useful in certificate - * stores and databases. When used this is tagged onto - * the end of the certificate itself - */ - -typedef struct x509_cert_aux_st - { - STACK_OF(ASN1_OBJECT) *trust; /* trusted uses */ - STACK_OF(ASN1_OBJECT) *reject; /* rejected uses */ - ASN1_UTF8STRING *alias; /* "friendly name" */ - ASN1_OCTET_STRING *keyid; /* key id of private key */ - STACK_OF(X509_ALGOR) *other; /* other unspecified info */ - } X509_CERT_AUX; - -struct x509_st - { - X509_CINF *cert_info; - X509_ALGOR *sig_alg; - ASN1_BIT_STRING *signature; - int valid; - CRYPTO_refcount_t references; - char *name; - CRYPTO_EX_DATA ex_data; - /* These contain copies of various extension values */ - long ex_pathlen; - long ex_pcpathlen; - unsigned long ex_flags; - unsigned long ex_kusage; - unsigned long ex_xkusage; - unsigned long ex_nscert; - ASN1_OCTET_STRING *skid; - AUTHORITY_KEYID *akid; - X509_POLICY_CACHE *policy_cache; - STACK_OF(DIST_POINT) *crldp; - STACK_OF(GENERAL_NAME) *altname; - NAME_CONSTRAINTS *nc; - unsigned char sha1_hash[SHA_DIGEST_LENGTH]; - X509_CERT_AUX *aux; - } /* X509 */; - -DECLARE_STACK_OF(X509) -DECLARE_ASN1_SET_OF(X509) - -/* This is used for a table of trust checking functions */ - -typedef struct x509_trust_st { - int trust; - int flags; - int (*check_trust)(struct x509_trust_st *, X509 *, int); - char *name; - int arg1; - void *arg2; -} X509_TRUST; - -DECLARE_STACK_OF(X509_TRUST) - -typedef struct x509_cert_pair_st { - X509 *forward; - X509 *reverse; -} X509_CERT_PAIR; - -/* standard trust ids */ - -#define X509_TRUST_DEFAULT -1 /* Only valid in purpose settings */ - -#define X509_TRUST_COMPAT 1 -#define X509_TRUST_SSL_CLIENT 2 -#define X509_TRUST_SSL_SERVER 3 -#define X509_TRUST_EMAIL 4 -#define X509_TRUST_OBJECT_SIGN 5 -#define X509_TRUST_OCSP_SIGN 6 -#define X509_TRUST_OCSP_REQUEST 7 -#define X509_TRUST_TSA 8 - -/* Keep these up to date! */ -#define X509_TRUST_MIN 1 -#define X509_TRUST_MAX 8 - - -/* trust_flags values */ -#define X509_TRUST_DYNAMIC 1 -#define X509_TRUST_DYNAMIC_NAME 2 - -/* check_trust return codes */ - -#define X509_TRUST_TRUSTED 1 -#define X509_TRUST_REJECTED 2 -#define X509_TRUST_UNTRUSTED 3 - -/* Flags for X509_print_ex() */ - -#define X509_FLAG_COMPAT 0 -#define X509_FLAG_NO_HEADER 1L -#define X509_FLAG_NO_VERSION (1L << 1) -#define X509_FLAG_NO_SERIAL (1L << 2) -#define X509_FLAG_NO_SIGNAME (1L << 3) -#define X509_FLAG_NO_ISSUER (1L << 4) -#define X509_FLAG_NO_VALIDITY (1L << 5) -#define X509_FLAG_NO_SUBJECT (1L << 6) -#define X509_FLAG_NO_PUBKEY (1L << 7) -#define X509_FLAG_NO_EXTENSIONS (1L << 8) -#define X509_FLAG_NO_SIGDUMP (1L << 9) -#define X509_FLAG_NO_AUX (1L << 10) -#define X509_FLAG_NO_ATTRIBUTES (1L << 11) -#define X509_FLAG_NO_IDS (1L << 12) - -/* Flags specific to X509_NAME_print_ex() */ - -/* The field separator information */ - -#define XN_FLAG_SEP_MASK (0xf << 16) - -#define XN_FLAG_COMPAT 0 /* Traditional SSLeay: use old X509_NAME_print */ -#define XN_FLAG_SEP_COMMA_PLUS (1 << 16) /* RFC2253 ,+ */ -#define XN_FLAG_SEP_CPLUS_SPC (2 << 16) /* ,+ spaced: more readable */ -#define XN_FLAG_SEP_SPLUS_SPC (3 << 16) /* ;+ spaced */ -#define XN_FLAG_SEP_MULTILINE (4 << 16) /* One line per field */ - -#define XN_FLAG_DN_REV (1 << 20) /* Reverse DN order */ - -/* How the field name is shown */ - -#define XN_FLAG_FN_MASK (0x3 << 21) - -#define XN_FLAG_FN_SN 0 /* Object short name */ -#define XN_FLAG_FN_LN (1 << 21) /* Object long name */ -#define XN_FLAG_FN_OID (2 << 21) /* Always use OIDs */ -#define XN_FLAG_FN_NONE (3 << 21) /* No field names */ - -#define XN_FLAG_SPC_EQ (1 << 23) /* Put spaces round '=' */ - -/* This determines if we dump fields we don't recognise: - * RFC2253 requires this. - */ - -#define XN_FLAG_DUMP_UNKNOWN_FIELDS (1 << 24) - -#define XN_FLAG_FN_ALIGN (1 << 25) /* Align field names to 20 characters */ - -/* Complete set of RFC2253 flags */ - -#define XN_FLAG_RFC2253 (ASN1_STRFLGS_RFC2253 | \ - XN_FLAG_SEP_COMMA_PLUS | \ - XN_FLAG_DN_REV | \ - XN_FLAG_FN_SN | \ - XN_FLAG_DUMP_UNKNOWN_FIELDS) - -/* readable oneline form */ - -#define XN_FLAG_ONELINE (ASN1_STRFLGS_RFC2253 | \ - ASN1_STRFLGS_ESC_QUOTE | \ - XN_FLAG_SEP_CPLUS_SPC | \ - XN_FLAG_SPC_EQ | \ - XN_FLAG_FN_SN) - -/* readable multiline form */ - -#define XN_FLAG_MULTILINE (ASN1_STRFLGS_ESC_CTRL | \ - ASN1_STRFLGS_ESC_MSB | \ - XN_FLAG_SEP_MULTILINE | \ - XN_FLAG_SPC_EQ | \ - XN_FLAG_FN_LN | \ - XN_FLAG_FN_ALIGN) - -struct x509_revoked_st - { - ASN1_INTEGER *serialNumber; - ASN1_TIME *revocationDate; - STACK_OF(X509_EXTENSION) /* optional */ *extensions; - /* Set up if indirect CRL */ - STACK_OF(GENERAL_NAME) *issuer; - /* Revocation reason */ - int reason; - int sequence; /* load sequence */ - }; - -DECLARE_STACK_OF(X509_REVOKED) -DECLARE_ASN1_SET_OF(X509_REVOKED) - -typedef struct X509_crl_info_st - { - ASN1_INTEGER *version; - X509_ALGOR *sig_alg; - X509_NAME *issuer; - ASN1_TIME *lastUpdate; - ASN1_TIME *nextUpdate; - STACK_OF(X509_REVOKED) *revoked; - STACK_OF(X509_EXTENSION) /* [0] */ *extensions; - ASN1_ENCODING enc; - } X509_CRL_INFO; - -struct X509_crl_st - { - /* actual signature */ - X509_CRL_INFO *crl; - X509_ALGOR *sig_alg; - ASN1_BIT_STRING *signature; - CRYPTO_refcount_t references; - int flags; - /* Copies of various extensions */ - AUTHORITY_KEYID *akid; - ISSUING_DIST_POINT *idp; - /* Convenient breakdown of IDP */ - int idp_flags; - int idp_reasons; - /* CRL and base CRL numbers for delta processing */ - ASN1_INTEGER *crl_number; - ASN1_INTEGER *base_crl_number; - unsigned char sha1_hash[SHA_DIGEST_LENGTH]; - STACK_OF(GENERAL_NAMES) *issuers; - const X509_CRL_METHOD *meth; - void *meth_data; - } /* X509_CRL */; - -DECLARE_STACK_OF(X509_CRL) -DECLARE_ASN1_SET_OF(X509_CRL) - -typedef struct private_key_st - { - int version; - /* The PKCS#8 data types */ - X509_ALGOR *enc_algor; - ASN1_OCTET_STRING *enc_pkey; /* encrypted pub key */ - - /* When decrypted, the following will not be NULL */ - EVP_PKEY *dec_pkey; - - /* used to encrypt and decrypt */ - int key_length; - char *key_data; - int key_free; /* true if we should auto free key_data */ - - /* expanded version of 'enc_algor' */ - EVP_CIPHER_INFO cipher; - } X509_PKEY; - -#ifndef OPENSSL_NO_EVP -typedef struct X509_info_st - { - X509 *x509; - X509_CRL *crl; - X509_PKEY *x_pkey; - - EVP_CIPHER_INFO enc_cipher; - int enc_len; - char *enc_data; - - } X509_INFO; - -DECLARE_STACK_OF(X509_INFO) -#endif - -/* The next 2 structures and their 8 routines were sent to me by - * Pat Richard and are used to manipulate - * Netscapes spki structures - useful if you are writing a CA web page - */ -typedef struct Netscape_spkac_st - { - X509_PUBKEY *pubkey; - ASN1_IA5STRING *challenge; /* challenge sent in atlas >= PR2 */ - } NETSCAPE_SPKAC; - -typedef struct Netscape_spki_st - { - NETSCAPE_SPKAC *spkac; /* signed public key and challenge */ - X509_ALGOR *sig_algor; - ASN1_BIT_STRING *signature; - } NETSCAPE_SPKI; - -/* Netscape certificate sequence structure */ -typedef struct Netscape_certificate_sequence - { - ASN1_OBJECT *type; - STACK_OF(X509) *certs; - } NETSCAPE_CERT_SEQUENCE; - -/* Unused (and iv length is wrong) -typedef struct CBCParameter_st - { - unsigned char iv[8]; - } CBC_PARAM; -*/ - -/* Password based encryption structure */ - -typedef struct PBEPARAM_st { -ASN1_OCTET_STRING *salt; -ASN1_INTEGER *iter; -} PBEPARAM; - -/* Password based encryption V2 structures */ - -typedef struct PBE2PARAM_st { -X509_ALGOR *keyfunc; -X509_ALGOR *encryption; -} PBE2PARAM; - -typedef struct PBKDF2PARAM_st { -ASN1_TYPE *salt; /* Usually OCTET STRING but could be anything */ -ASN1_INTEGER *iter; -ASN1_INTEGER *keylength; -X509_ALGOR *prf; -} PBKDF2PARAM; - - -/* PKCS#8 private key info structure */ - -struct pkcs8_priv_key_info_st - { - int broken; /* Flag for various broken formats */ -#define PKCS8_OK 0 -#define PKCS8_NO_OCTET 1 -#define PKCS8_EMBEDDED_PARAM 2 -#define PKCS8_NS_DB 3 -#define PKCS8_NEG_PRIVKEY 4 - ASN1_INTEGER *version; - X509_ALGOR *pkeyalg; - ASN1_TYPE *pkey; /* Should be OCTET STRING but some are broken */ - STACK_OF(X509_ATTRIBUTE) *attributes; - }; - -#ifdef __cplusplus -} -#endif - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define X509_EXT_PACK_UNKNOWN 1 -#define X509_EXT_PACK_STRING 2 - -#define X509_get_version(x) ASN1_INTEGER_get((x)->cert_info->version) -/* #define X509_get_serialNumber(x) ((x)->cert_info->serialNumber) */ -#define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore) -#define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter) -#define X509_get_cert_info(x) ((x)->cert_info) -#define X509_extract_key(x) X509_get_pubkey(x) /*****/ -#define X509_REQ_get_version(x) ASN1_INTEGER_get((x)->req_info->version) -#define X509_REQ_get_subject_name(x) ((x)->req_info->subject) -#define X509_REQ_extract_key(a) X509_REQ_get_pubkey(a) -#define X509_name_cmp(a,b) X509_NAME_cmp((a),(b)) -#define X509_get_signature_type(x) EVP_PKEY_type(OBJ_obj2nid((x)->sig_alg->algorithm)) - -#define X509_CRL_get_version(x) ASN1_INTEGER_get((x)->crl->version) -#define X509_CRL_get_lastUpdate(x) ((x)->crl->lastUpdate) -#define X509_CRL_get_nextUpdate(x) ((x)->crl->nextUpdate) -#define X509_CRL_get_issuer(x) ((x)->crl->issuer) -#define X509_CRL_get_REVOKED(x) ((x)->crl->revoked) - -#define X509_CINF_set_modified(c) ((c)->enc.modified = 1) -#define X509_CINF_get_issuer(c) (&(c)->issuer) -#define X509_CINF_get_extensions(c) ((c)->extensions) -#define X509_CINF_get_signature(c) ((c)->signature) - -OPENSSL_EXPORT void X509_CRL_set_default_method(const X509_CRL_METHOD *meth); -OPENSSL_EXPORT X509_CRL_METHOD *X509_CRL_METHOD_new( - int (*crl_init)(X509_CRL *crl), - int (*crl_free)(X509_CRL *crl), - int (*crl_lookup)(X509_CRL *crl, X509_REVOKED **ret, - ASN1_INTEGER *ser, X509_NAME *issuer), - int (*crl_verify)(X509_CRL *crl, EVP_PKEY *pk)); -OPENSSL_EXPORT void X509_CRL_METHOD_free(X509_CRL_METHOD *m); - -OPENSSL_EXPORT void X509_CRL_set_meth_data(X509_CRL *crl, void *dat); -OPENSSL_EXPORT void *X509_CRL_get_meth_data(X509_CRL *crl); - -/* This one is only used so that a binary form can output, as in - * i2d_X509_NAME(X509_get_X509_PUBKEY(x),&buf) */ -#define X509_get_X509_PUBKEY(x) ((x)->cert_info->key) - - -OPENSSL_EXPORT const char *X509_verify_cert_error_string(long n); - -#ifndef OPENSSL_NO_EVP -OPENSSL_EXPORT int X509_verify(X509 *a, EVP_PKEY *r); - -OPENSSL_EXPORT int X509_REQ_verify(X509_REQ *a, EVP_PKEY *r); -OPENSSL_EXPORT int X509_CRL_verify(X509_CRL *a, EVP_PKEY *r); -OPENSSL_EXPORT int NETSCAPE_SPKI_verify(NETSCAPE_SPKI *a, EVP_PKEY *r); - -OPENSSL_EXPORT NETSCAPE_SPKI * NETSCAPE_SPKI_b64_decode(const char *str, int len); -OPENSSL_EXPORT char * NETSCAPE_SPKI_b64_encode(NETSCAPE_SPKI *x); -OPENSSL_EXPORT EVP_PKEY *NETSCAPE_SPKI_get_pubkey(NETSCAPE_SPKI *x); -OPENSSL_EXPORT int NETSCAPE_SPKI_set_pubkey(NETSCAPE_SPKI *x, EVP_PKEY *pkey); - -OPENSSL_EXPORT int NETSCAPE_SPKI_print(BIO *out, NETSCAPE_SPKI *spki); - -OPENSSL_EXPORT int X509_signature_dump(BIO *bp,const ASN1_STRING *sig, int indent); -OPENSSL_EXPORT int X509_signature_print(BIO *bp,X509_ALGOR *alg, ASN1_STRING *sig); - -OPENSSL_EXPORT int X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md); -OPENSSL_EXPORT int X509_sign_ctx(X509 *x, EVP_MD_CTX *ctx); -/* int X509_http_nbio(OCSP_REQ_CTX *rctx, X509 **pcert); */ -OPENSSL_EXPORT int X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md); -OPENSSL_EXPORT int X509_REQ_sign_ctx(X509_REQ *x, EVP_MD_CTX *ctx); -OPENSSL_EXPORT int X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md); -OPENSSL_EXPORT int X509_CRL_sign_ctx(X509_CRL *x, EVP_MD_CTX *ctx); -/* int X509_CRL_http_nbio(OCSP_REQ_CTX *rctx, X509_CRL **pcrl); */ -OPENSSL_EXPORT int NETSCAPE_SPKI_sign(NETSCAPE_SPKI *x, EVP_PKEY *pkey, const EVP_MD *md); - -OPENSSL_EXPORT int X509_pubkey_digest(const X509 *data,const EVP_MD *type, - unsigned char *md, unsigned int *len); -OPENSSL_EXPORT int X509_digest(const X509 *data,const EVP_MD *type, - unsigned char *md, unsigned int *len); -OPENSSL_EXPORT int X509_CRL_digest(const X509_CRL *data,const EVP_MD *type, - unsigned char *md, unsigned int *len); -OPENSSL_EXPORT int X509_REQ_digest(const X509_REQ *data,const EVP_MD *type, - unsigned char *md, unsigned int *len); -OPENSSL_EXPORT int X509_NAME_digest(const X509_NAME *data,const EVP_MD *type, - unsigned char *md, unsigned int *len); -#endif - -#ifndef OPENSSL_NO_FP_API -OPENSSL_EXPORT X509 *d2i_X509_fp(FILE *fp, X509 **x509); -OPENSSL_EXPORT int i2d_X509_fp(FILE *fp,X509 *x509); -OPENSSL_EXPORT X509_CRL *d2i_X509_CRL_fp(FILE *fp,X509_CRL **crl); -OPENSSL_EXPORT int i2d_X509_CRL_fp(FILE *fp,X509_CRL *crl); -OPENSSL_EXPORT X509_REQ *d2i_X509_REQ_fp(FILE *fp,X509_REQ **req); -OPENSSL_EXPORT int i2d_X509_REQ_fp(FILE *fp,X509_REQ *req); -OPENSSL_EXPORT RSA *d2i_RSAPrivateKey_fp(FILE *fp,RSA **rsa); -OPENSSL_EXPORT int i2d_RSAPrivateKey_fp(FILE *fp,RSA *rsa); -OPENSSL_EXPORT RSA *d2i_RSAPublicKey_fp(FILE *fp,RSA **rsa); -OPENSSL_EXPORT int i2d_RSAPublicKey_fp(FILE *fp,RSA *rsa); -OPENSSL_EXPORT RSA *d2i_RSA_PUBKEY_fp(FILE *fp,RSA **rsa); -OPENSSL_EXPORT int i2d_RSA_PUBKEY_fp(FILE *fp,RSA *rsa); -#ifndef OPENSSL_NO_DSA -OPENSSL_EXPORT DSA *d2i_DSA_PUBKEY_fp(FILE *fp, DSA **dsa); -OPENSSL_EXPORT int i2d_DSA_PUBKEY_fp(FILE *fp, DSA *dsa); -OPENSSL_EXPORT DSA *d2i_DSAPrivateKey_fp(FILE *fp, DSA **dsa); -OPENSSL_EXPORT int i2d_DSAPrivateKey_fp(FILE *fp, DSA *dsa); -#endif -OPENSSL_EXPORT EC_KEY *d2i_EC_PUBKEY_fp(FILE *fp, EC_KEY **eckey); -OPENSSL_EXPORT int i2d_EC_PUBKEY_fp(FILE *fp, EC_KEY *eckey); -OPENSSL_EXPORT EC_KEY *d2i_ECPrivateKey_fp(FILE *fp, EC_KEY **eckey); -OPENSSL_EXPORT int i2d_ECPrivateKey_fp(FILE *fp, EC_KEY *eckey); -OPENSSL_EXPORT X509_SIG *d2i_PKCS8_fp(FILE *fp,X509_SIG **p8); -OPENSSL_EXPORT int i2d_PKCS8_fp(FILE *fp,X509_SIG *p8); -OPENSSL_EXPORT PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO_fp(FILE *fp, - PKCS8_PRIV_KEY_INFO **p8inf); -OPENSSL_EXPORT int i2d_PKCS8_PRIV_KEY_INFO_fp(FILE *fp,PKCS8_PRIV_KEY_INFO *p8inf); -OPENSSL_EXPORT int i2d_PKCS8PrivateKeyInfo_fp(FILE *fp, EVP_PKEY *key); -OPENSSL_EXPORT int i2d_PrivateKey_fp(FILE *fp, EVP_PKEY *pkey); -OPENSSL_EXPORT EVP_PKEY *d2i_PrivateKey_fp(FILE *fp, EVP_PKEY **a); -OPENSSL_EXPORT int i2d_PUBKEY_fp(FILE *fp, EVP_PKEY *pkey); -OPENSSL_EXPORT EVP_PKEY *d2i_PUBKEY_fp(FILE *fp, EVP_PKEY **a); -#endif - -OPENSSL_EXPORT X509 *d2i_X509_bio(BIO *bp,X509 **x509); -OPENSSL_EXPORT int i2d_X509_bio(BIO *bp,X509 *x509); -OPENSSL_EXPORT X509_CRL *d2i_X509_CRL_bio(BIO *bp,X509_CRL **crl); -OPENSSL_EXPORT int i2d_X509_CRL_bio(BIO *bp,X509_CRL *crl); -OPENSSL_EXPORT X509_REQ *d2i_X509_REQ_bio(BIO *bp,X509_REQ **req); -OPENSSL_EXPORT int i2d_X509_REQ_bio(BIO *bp,X509_REQ *req); -OPENSSL_EXPORT RSA *d2i_RSAPrivateKey_bio(BIO *bp,RSA **rsa); -OPENSSL_EXPORT int i2d_RSAPrivateKey_bio(BIO *bp,RSA *rsa); -OPENSSL_EXPORT RSA *d2i_RSAPublicKey_bio(BIO *bp,RSA **rsa); -OPENSSL_EXPORT int i2d_RSAPublicKey_bio(BIO *bp,RSA *rsa); -OPENSSL_EXPORT RSA *d2i_RSA_PUBKEY_bio(BIO *bp,RSA **rsa); -OPENSSL_EXPORT int i2d_RSA_PUBKEY_bio(BIO *bp,RSA *rsa); -#ifndef OPENSSL_NO_DSA -OPENSSL_EXPORT DSA *d2i_DSA_PUBKEY_bio(BIO *bp, DSA **dsa); -OPENSSL_EXPORT int i2d_DSA_PUBKEY_bio(BIO *bp, DSA *dsa); -OPENSSL_EXPORT DSA *d2i_DSAPrivateKey_bio(BIO *bp, DSA **dsa); -OPENSSL_EXPORT int i2d_DSAPrivateKey_bio(BIO *bp, DSA *dsa); -#endif -OPENSSL_EXPORT EC_KEY *d2i_EC_PUBKEY_bio(BIO *bp, EC_KEY **eckey); -OPENSSL_EXPORT int i2d_EC_PUBKEY_bio(BIO *bp, EC_KEY *eckey); -OPENSSL_EXPORT EC_KEY *d2i_ECPrivateKey_bio(BIO *bp, EC_KEY **eckey); -OPENSSL_EXPORT int i2d_ECPrivateKey_bio(BIO *bp, EC_KEY *eckey); -OPENSSL_EXPORT X509_SIG *d2i_PKCS8_bio(BIO *bp,X509_SIG **p8); -OPENSSL_EXPORT int i2d_PKCS8_bio(BIO *bp,X509_SIG *p8); -OPENSSL_EXPORT PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO_bio(BIO *bp, - PKCS8_PRIV_KEY_INFO **p8inf); -OPENSSL_EXPORT int i2d_PKCS8_PRIV_KEY_INFO_bio(BIO *bp,PKCS8_PRIV_KEY_INFO *p8inf); -OPENSSL_EXPORT int i2d_PKCS8PrivateKeyInfo_bio(BIO *bp, EVP_PKEY *key); -OPENSSL_EXPORT int i2d_PrivateKey_bio(BIO *bp, EVP_PKEY *pkey); -OPENSSL_EXPORT EVP_PKEY *d2i_PrivateKey_bio(BIO *bp, EVP_PKEY **a); -OPENSSL_EXPORT int i2d_PUBKEY_bio(BIO *bp, EVP_PKEY *pkey); -OPENSSL_EXPORT EVP_PKEY *d2i_PUBKEY_bio(BIO *bp, EVP_PKEY **a); - -OPENSSL_EXPORT X509 *X509_dup(X509 *x509); -OPENSSL_EXPORT X509_ATTRIBUTE *X509_ATTRIBUTE_dup(X509_ATTRIBUTE *xa); -OPENSSL_EXPORT X509_EXTENSION *X509_EXTENSION_dup(X509_EXTENSION *ex); -OPENSSL_EXPORT X509_CRL *X509_CRL_dup(X509_CRL *crl); -OPENSSL_EXPORT X509_REVOKED *X509_REVOKED_dup(X509_REVOKED *rev); -OPENSSL_EXPORT X509_REQ *X509_REQ_dup(X509_REQ *req); -OPENSSL_EXPORT X509_ALGOR *X509_ALGOR_dup(X509_ALGOR *xn); -OPENSSL_EXPORT int X509_ALGOR_set0(X509_ALGOR *alg, const ASN1_OBJECT *aobj, int ptype, void *pval); -OPENSSL_EXPORT void X509_ALGOR_get0(ASN1_OBJECT **paobj, int *pptype, void **ppval, - X509_ALGOR *algor); -OPENSSL_EXPORT void X509_ALGOR_set_md(X509_ALGOR *alg, const EVP_MD *md); -OPENSSL_EXPORT int X509_ALGOR_cmp(const X509_ALGOR *a, const X509_ALGOR *b); - -OPENSSL_EXPORT X509_NAME *X509_NAME_dup(X509_NAME *xn); -OPENSSL_EXPORT X509_NAME_ENTRY *X509_NAME_ENTRY_dup(X509_NAME_ENTRY *ne); - -OPENSSL_EXPORT int X509_cmp_time(const ASN1_TIME *s, time_t *t); -OPENSSL_EXPORT int X509_cmp_current_time(const ASN1_TIME *s); -OPENSSL_EXPORT ASN1_TIME * X509_time_adj(ASN1_TIME *s, long adj, time_t *t); -OPENSSL_EXPORT ASN1_TIME * X509_time_adj_ex(ASN1_TIME *s, int offset_day, long offset_sec, time_t *t); -OPENSSL_EXPORT ASN1_TIME * X509_gmtime_adj(ASN1_TIME *s, long adj); - -OPENSSL_EXPORT const char * X509_get_default_cert_area(void ); -OPENSSL_EXPORT const char * X509_get_default_cert_dir(void ); -OPENSSL_EXPORT const char * X509_get_default_cert_file(void ); -OPENSSL_EXPORT const char * X509_get_default_cert_dir_env(void ); -OPENSSL_EXPORT const char * X509_get_default_cert_file_env(void ); -OPENSSL_EXPORT const char * X509_get_default_private_dir(void ); - -OPENSSL_EXPORT X509_REQ * X509_to_X509_REQ(X509 *x, EVP_PKEY *pkey, const EVP_MD *md); -OPENSSL_EXPORT X509 * X509_REQ_to_X509(X509_REQ *r, int days,EVP_PKEY *pkey); - -DECLARE_ASN1_ENCODE_FUNCTIONS(X509_ALGORS, X509_ALGORS, X509_ALGORS) -DECLARE_ASN1_FUNCTIONS(X509_VAL) - -DECLARE_ASN1_FUNCTIONS(X509_PUBKEY) - -OPENSSL_EXPORT int X509_PUBKEY_set(X509_PUBKEY **x, EVP_PKEY *pkey); -OPENSSL_EXPORT EVP_PKEY * X509_PUBKEY_get(X509_PUBKEY *key); -OPENSSL_EXPORT int i2d_PUBKEY(const EVP_PKEY *a,unsigned char **pp); -OPENSSL_EXPORT EVP_PKEY * d2i_PUBKEY(EVP_PKEY **a,const unsigned char **pp, - long length); -OPENSSL_EXPORT int i2d_RSA_PUBKEY(const RSA *a,unsigned char **pp); -OPENSSL_EXPORT RSA * d2i_RSA_PUBKEY(RSA **a,const unsigned char **pp, - long length); -#ifndef OPENSSL_NO_DSA -OPENSSL_EXPORT int i2d_DSA_PUBKEY(const DSA *a,unsigned char **pp); -OPENSSL_EXPORT DSA * d2i_DSA_PUBKEY(DSA **a,const unsigned char **pp, - long length); -#endif -OPENSSL_EXPORT int i2d_EC_PUBKEY(const EC_KEY *a, unsigned char **pp); -OPENSSL_EXPORT EC_KEY *d2i_EC_PUBKEY(EC_KEY **a, const unsigned char **pp, - long length); - -DECLARE_ASN1_FUNCTIONS(X509_SIG) -DECLARE_ASN1_FUNCTIONS(X509_REQ_INFO) -DECLARE_ASN1_FUNCTIONS(X509_REQ) - -DECLARE_ASN1_FUNCTIONS(X509_ATTRIBUTE) -OPENSSL_EXPORT X509_ATTRIBUTE *X509_ATTRIBUTE_create(int nid, int atrtype, void *value); - -DECLARE_ASN1_FUNCTIONS(X509_EXTENSION) -DECLARE_ASN1_ENCODE_FUNCTIONS(X509_EXTENSIONS, X509_EXTENSIONS, X509_EXTENSIONS) - -DECLARE_ASN1_FUNCTIONS(X509_NAME_ENTRY) - -DECLARE_ASN1_FUNCTIONS(X509_NAME) - -OPENSSL_EXPORT int X509_NAME_set(X509_NAME **xn, X509_NAME *name); - -DECLARE_ASN1_FUNCTIONS(X509_CINF) - -DECLARE_ASN1_FUNCTIONS(X509) -DECLARE_ASN1_FUNCTIONS(X509_CERT_AUX) - -DECLARE_ASN1_FUNCTIONS(X509_CERT_PAIR) - -/* X509_up_ref adds one to the reference count of |x| and returns - * |x|. */ -OPENSSL_EXPORT X509 *X509_up_ref(X509 *x); - -OPENSSL_EXPORT int X509_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func, - CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func); -OPENSSL_EXPORT int X509_set_ex_data(X509 *r, int idx, void *arg); -OPENSSL_EXPORT void *X509_get_ex_data(X509 *r, int idx); -OPENSSL_EXPORT int i2d_X509_AUX(X509 *a,unsigned char **pp); -OPENSSL_EXPORT X509 * d2i_X509_AUX(X509 **a,const unsigned char **pp,long length); - -OPENSSL_EXPORT void X509_get0_signature(ASN1_BIT_STRING **psig, X509_ALGOR **palg, - const X509 *x); -OPENSSL_EXPORT int X509_get_signature_nid(const X509 *x); - -OPENSSL_EXPORT int X509_alias_set1(X509 *x, unsigned char *name, int len); -OPENSSL_EXPORT int X509_keyid_set1(X509 *x, unsigned char *id, int len); -OPENSSL_EXPORT unsigned char * X509_alias_get0(X509 *x, int *len); -OPENSSL_EXPORT unsigned char * X509_keyid_get0(X509 *x, int *len); -OPENSSL_EXPORT int (*X509_TRUST_set_default(int (*trust)(int , X509 *, int)))(int, X509 *, int); -OPENSSL_EXPORT int X509_TRUST_set(int *t, int trust); -OPENSSL_EXPORT int X509_add1_trust_object(X509 *x, ASN1_OBJECT *obj); -OPENSSL_EXPORT int X509_add1_reject_object(X509 *x, ASN1_OBJECT *obj); -OPENSSL_EXPORT void X509_trust_clear(X509 *x); -OPENSSL_EXPORT void X509_reject_clear(X509 *x); - -DECLARE_ASN1_FUNCTIONS(X509_REVOKED) -DECLARE_ASN1_FUNCTIONS(X509_CRL_INFO) -DECLARE_ASN1_FUNCTIONS(X509_CRL) - -OPENSSL_EXPORT int X509_CRL_add0_revoked(X509_CRL *crl, X509_REVOKED *rev); -OPENSSL_EXPORT int X509_CRL_get0_by_serial(X509_CRL *crl, - X509_REVOKED **ret, ASN1_INTEGER *serial); -OPENSSL_EXPORT int X509_CRL_get0_by_cert(X509_CRL *crl, X509_REVOKED **ret, X509 *x); - -OPENSSL_EXPORT X509_PKEY * X509_PKEY_new(void ); -OPENSSL_EXPORT void X509_PKEY_free(X509_PKEY *a); - -DECLARE_ASN1_FUNCTIONS(NETSCAPE_SPKI) -DECLARE_ASN1_FUNCTIONS(NETSCAPE_SPKAC) -DECLARE_ASN1_FUNCTIONS(NETSCAPE_CERT_SEQUENCE) - -#ifndef OPENSSL_NO_EVP -OPENSSL_EXPORT X509_INFO * X509_INFO_new(void); -OPENSSL_EXPORT void X509_INFO_free(X509_INFO *a); -OPENSSL_EXPORT char * X509_NAME_oneline(X509_NAME *a,char *buf,int size); - -OPENSSL_EXPORT int ASN1_digest(i2d_of_void *i2d,const EVP_MD *type,char *data, - unsigned char *md,unsigned int *len); - -OPENSSL_EXPORT int ASN1_item_digest(const ASN1_ITEM *it,const EVP_MD *type,void *data, - unsigned char *md,unsigned int *len); - -OPENSSL_EXPORT int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *algor1, - ASN1_BIT_STRING *signature,void *data,EVP_PKEY *pkey); - -OPENSSL_EXPORT int ASN1_item_sign(const ASN1_ITEM *it, X509_ALGOR *algor1, X509_ALGOR *algor2, - ASN1_BIT_STRING *signature, - void *data, EVP_PKEY *pkey, const EVP_MD *type); -OPENSSL_EXPORT int ASN1_item_sign_ctx(const ASN1_ITEM *it, - X509_ALGOR *algor1, X509_ALGOR *algor2, - ASN1_BIT_STRING *signature, void *asn, EVP_MD_CTX *ctx); -#endif - -OPENSSL_EXPORT int X509_set_version(X509 *x,long version); -OPENSSL_EXPORT int X509_set_serialNumber(X509 *x, ASN1_INTEGER *serial); -OPENSSL_EXPORT ASN1_INTEGER * X509_get_serialNumber(X509 *x); -OPENSSL_EXPORT int X509_set_issuer_name(X509 *x, X509_NAME *name); -OPENSSL_EXPORT X509_NAME * X509_get_issuer_name(X509 *a); -OPENSSL_EXPORT int X509_set_subject_name(X509 *x, X509_NAME *name); -OPENSSL_EXPORT X509_NAME * X509_get_subject_name(X509 *a); -OPENSSL_EXPORT int X509_set_notBefore(X509 *x, const ASN1_TIME *tm); -OPENSSL_EXPORT int X509_set_notAfter(X509 *x, const ASN1_TIME *tm); -OPENSSL_EXPORT int X509_set_pubkey(X509 *x, EVP_PKEY *pkey); -OPENSSL_EXPORT EVP_PKEY * X509_get_pubkey(X509 *x); -OPENSSL_EXPORT ASN1_BIT_STRING * X509_get0_pubkey_bitstr(const X509 *x); -OPENSSL_EXPORT int X509_certificate_type(X509 *x,EVP_PKEY *pubkey /* optional */); - -OPENSSL_EXPORT int X509_REQ_set_version(X509_REQ *x,long version); -OPENSSL_EXPORT int X509_REQ_set_subject_name(X509_REQ *req,X509_NAME *name); -OPENSSL_EXPORT int X509_REQ_set_pubkey(X509_REQ *x, EVP_PKEY *pkey); -OPENSSL_EXPORT EVP_PKEY * X509_REQ_get_pubkey(X509_REQ *req); -OPENSSL_EXPORT int X509_REQ_extension_nid(int nid); -OPENSSL_EXPORT const int * X509_REQ_get_extension_nids(void); -OPENSSL_EXPORT void X509_REQ_set_extension_nids(const int *nids); -OPENSSL_EXPORT STACK_OF(X509_EXTENSION) *X509_REQ_get_extensions(X509_REQ *req); -OPENSSL_EXPORT int X509_REQ_add_extensions_nid(X509_REQ *req, STACK_OF(X509_EXTENSION) *exts, - int nid); -OPENSSL_EXPORT int X509_REQ_add_extensions(X509_REQ *req, STACK_OF(X509_EXTENSION) *exts); -OPENSSL_EXPORT int X509_REQ_get_attr_count(const X509_REQ *req); -OPENSSL_EXPORT int X509_REQ_get_attr_by_NID(const X509_REQ *req, int nid, - int lastpos); -OPENSSL_EXPORT int X509_REQ_get_attr_by_OBJ(const X509_REQ *req, ASN1_OBJECT *obj, - int lastpos); -OPENSSL_EXPORT X509_ATTRIBUTE *X509_REQ_get_attr(const X509_REQ *req, int loc); -OPENSSL_EXPORT X509_ATTRIBUTE *X509_REQ_delete_attr(X509_REQ *req, int loc); -OPENSSL_EXPORT int X509_REQ_add1_attr(X509_REQ *req, X509_ATTRIBUTE *attr); -OPENSSL_EXPORT int X509_REQ_add1_attr_by_OBJ(X509_REQ *req, - const ASN1_OBJECT *obj, int type, - const unsigned char *bytes, int len); -OPENSSL_EXPORT int X509_REQ_add1_attr_by_NID(X509_REQ *req, - int nid, int type, - const unsigned char *bytes, int len); -OPENSSL_EXPORT int X509_REQ_add1_attr_by_txt(X509_REQ *req, - const char *attrname, int type, - const unsigned char *bytes, int len); - -OPENSSL_EXPORT int X509_CRL_set_version(X509_CRL *x, long version); -OPENSSL_EXPORT int X509_CRL_set_issuer_name(X509_CRL *x, X509_NAME *name); -OPENSSL_EXPORT int X509_CRL_set_lastUpdate(X509_CRL *x, const ASN1_TIME *tm); -OPENSSL_EXPORT int X509_CRL_set_nextUpdate(X509_CRL *x, const ASN1_TIME *tm); -OPENSSL_EXPORT int X509_CRL_sort(X509_CRL *crl); - -OPENSSL_EXPORT int X509_REVOKED_set_serialNumber(X509_REVOKED *x, ASN1_INTEGER *serial); -OPENSSL_EXPORT int X509_REVOKED_set_revocationDate(X509_REVOKED *r, ASN1_TIME *tm); - -OPENSSL_EXPORT X509_CRL *X509_CRL_diff(X509_CRL *base, X509_CRL *newer, - EVP_PKEY *skey, const EVP_MD *md, unsigned int flags); - -OPENSSL_EXPORT int X509_REQ_check_private_key(X509_REQ *x509,EVP_PKEY *pkey); - -OPENSSL_EXPORT int X509_check_private_key(X509 *x509,EVP_PKEY *pkey); -OPENSSL_EXPORT int X509_chain_check_suiteb(int *perror_depth, - X509 *x, STACK_OF(X509) *chain, - unsigned long flags); -OPENSSL_EXPORT int X509_CRL_check_suiteb(X509_CRL *crl, EVP_PKEY *pk, - unsigned long flags); -OPENSSL_EXPORT STACK_OF(X509) *X509_chain_up_ref(STACK_OF(X509) *chain); - -OPENSSL_EXPORT int X509_issuer_and_serial_cmp(const X509 *a, const X509 *b); -OPENSSL_EXPORT unsigned long X509_issuer_and_serial_hash(X509 *a); - -OPENSSL_EXPORT int X509_issuer_name_cmp(const X509 *a, const X509 *b); -OPENSSL_EXPORT unsigned long X509_issuer_name_hash(X509 *a); - -OPENSSL_EXPORT int X509_subject_name_cmp(const X509 *a, const X509 *b); -OPENSSL_EXPORT unsigned long X509_subject_name_hash(X509 *x); - -OPENSSL_EXPORT unsigned long X509_issuer_name_hash_old(X509 *a); -OPENSSL_EXPORT unsigned long X509_subject_name_hash_old(X509 *x); - -OPENSSL_EXPORT int X509_cmp(const X509 *a, const X509 *b); -OPENSSL_EXPORT int X509_NAME_cmp(const X509_NAME *a, const X509_NAME *b); -OPENSSL_EXPORT unsigned long X509_NAME_hash(X509_NAME *x); -OPENSSL_EXPORT unsigned long X509_NAME_hash_old(X509_NAME *x); - -OPENSSL_EXPORT int X509_CRL_cmp(const X509_CRL *a, const X509_CRL *b); -OPENSSL_EXPORT int X509_CRL_match(const X509_CRL *a, const X509_CRL *b); -#ifndef OPENSSL_NO_FP_API -OPENSSL_EXPORT int X509_print_ex_fp(FILE *bp,X509 *x, unsigned long nmflag, unsigned long cflag); -OPENSSL_EXPORT int X509_print_fp(FILE *bp,X509 *x); -OPENSSL_EXPORT int X509_CRL_print_fp(FILE *bp,X509_CRL *x); -OPENSSL_EXPORT int X509_REQ_print_fp(FILE *bp,X509_REQ *req); -OPENSSL_EXPORT int X509_NAME_print_ex_fp(FILE *fp, X509_NAME *nm, int indent, unsigned long flags); -#endif - -OPENSSL_EXPORT int X509_NAME_print(BIO *bp, X509_NAME *name, int obase); -OPENSSL_EXPORT int X509_NAME_print_ex(BIO *out, X509_NAME *nm, int indent, unsigned long flags); -OPENSSL_EXPORT int X509_print_ex(BIO *bp,X509 *x, unsigned long nmflag, unsigned long cflag); -OPENSSL_EXPORT int X509_print(BIO *bp,X509 *x); -OPENSSL_EXPORT int X509_ocspid_print(BIO *bp,X509 *x); -OPENSSL_EXPORT int X509_CERT_AUX_print(BIO *bp,X509_CERT_AUX *x, int indent); -OPENSSL_EXPORT int X509_CRL_print(BIO *bp,X509_CRL *x); -OPENSSL_EXPORT int X509_REQ_print_ex(BIO *bp, X509_REQ *x, unsigned long nmflag, unsigned long cflag); -OPENSSL_EXPORT int X509_REQ_print(BIO *bp,X509_REQ *req); - -OPENSSL_EXPORT int X509_NAME_entry_count(X509_NAME *name); -OPENSSL_EXPORT int X509_NAME_get_text_by_NID(X509_NAME *name, int nid, - char *buf,int len); -OPENSSL_EXPORT int X509_NAME_get_text_by_OBJ(X509_NAME *name, const ASN1_OBJECT *obj, - char *buf,int len); - -/* NOTE: you should be passsing -1, not 0 as lastpos. The functions that use - * lastpos, search after that position on. */ -OPENSSL_EXPORT int X509_NAME_get_index_by_NID(X509_NAME *name,int nid,int lastpos); -OPENSSL_EXPORT int X509_NAME_get_index_by_OBJ(X509_NAME *name, const ASN1_OBJECT *obj, - int lastpos); -OPENSSL_EXPORT X509_NAME_ENTRY *X509_NAME_get_entry(X509_NAME *name, int loc); -OPENSSL_EXPORT X509_NAME_ENTRY *X509_NAME_delete_entry(X509_NAME *name, int loc); -OPENSSL_EXPORT int X509_NAME_add_entry(X509_NAME *name,X509_NAME_ENTRY *ne, - int loc, int set); -OPENSSL_EXPORT int X509_NAME_add_entry_by_OBJ(X509_NAME *name, ASN1_OBJECT *obj, int type, - unsigned char *bytes, int len, int loc, int set); -OPENSSL_EXPORT int X509_NAME_add_entry_by_NID(X509_NAME *name, int nid, int type, - unsigned char *bytes, int len, int loc, int set); -OPENSSL_EXPORT X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_txt(X509_NAME_ENTRY **ne, - const char *field, int type, const unsigned char *bytes, int len); -OPENSSL_EXPORT X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_NID(X509_NAME_ENTRY **ne, int nid, - int type,unsigned char *bytes, int len); -OPENSSL_EXPORT int X509_NAME_add_entry_by_txt(X509_NAME *name, const char *field, int type, - const unsigned char *bytes, int len, int loc, int set); -OPENSSL_EXPORT X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_OBJ(X509_NAME_ENTRY **ne, - const ASN1_OBJECT *obj, int type,const unsigned char *bytes, - int len); -OPENSSL_EXPORT int X509_NAME_ENTRY_set_object(X509_NAME_ENTRY *ne, - const ASN1_OBJECT *obj); -OPENSSL_EXPORT int X509_NAME_ENTRY_set_data(X509_NAME_ENTRY *ne, int type, - const unsigned char *bytes, int len); -OPENSSL_EXPORT ASN1_OBJECT * X509_NAME_ENTRY_get_object(X509_NAME_ENTRY *ne); -OPENSSL_EXPORT ASN1_STRING * X509_NAME_ENTRY_get_data(X509_NAME_ENTRY *ne); - -OPENSSL_EXPORT int X509v3_get_ext_count(const STACK_OF(X509_EXTENSION) *x); -OPENSSL_EXPORT int X509v3_get_ext_by_NID(const STACK_OF(X509_EXTENSION) *x, - int nid, int lastpos); -OPENSSL_EXPORT int X509v3_get_ext_by_OBJ(const STACK_OF(X509_EXTENSION) *x, - const ASN1_OBJECT *obj,int lastpos); -OPENSSL_EXPORT int X509v3_get_ext_by_critical(const STACK_OF(X509_EXTENSION) *x, - int crit, int lastpos); -OPENSSL_EXPORT X509_EXTENSION *X509v3_get_ext(const STACK_OF(X509_EXTENSION) *x, int loc); -OPENSSL_EXPORT X509_EXTENSION *X509v3_delete_ext(STACK_OF(X509_EXTENSION) *x, int loc); -OPENSSL_EXPORT STACK_OF(X509_EXTENSION) *X509v3_add_ext(STACK_OF(X509_EXTENSION) **x, - X509_EXTENSION *ex, int loc); - -OPENSSL_EXPORT int X509_get_ext_count(X509 *x); -OPENSSL_EXPORT int X509_get_ext_by_NID(X509 *x, int nid, int lastpos); -OPENSSL_EXPORT int X509_get_ext_by_OBJ(X509 *x,ASN1_OBJECT *obj,int lastpos); -OPENSSL_EXPORT int X509_get_ext_by_critical(X509 *x, int crit, int lastpos); -OPENSSL_EXPORT X509_EXTENSION *X509_get_ext(X509 *x, int loc); -OPENSSL_EXPORT X509_EXTENSION *X509_delete_ext(X509 *x, int loc); -OPENSSL_EXPORT int X509_add_ext(X509 *x, X509_EXTENSION *ex, int loc); -OPENSSL_EXPORT void * X509_get_ext_d2i(X509 *x, int nid, int *crit, int *idx); -OPENSSL_EXPORT int X509_add1_ext_i2d(X509 *x, int nid, void *value, int crit, - unsigned long flags); - -OPENSSL_EXPORT int X509_CRL_get_ext_count(X509_CRL *x); -OPENSSL_EXPORT int X509_CRL_get_ext_by_NID(X509_CRL *x, int nid, int lastpos); -OPENSSL_EXPORT int X509_CRL_get_ext_by_OBJ(X509_CRL *x,ASN1_OBJECT *obj,int lastpos); -OPENSSL_EXPORT int X509_CRL_get_ext_by_critical(X509_CRL *x, int crit, int lastpos); -OPENSSL_EXPORT X509_EXTENSION *X509_CRL_get_ext(X509_CRL *x, int loc); -OPENSSL_EXPORT X509_EXTENSION *X509_CRL_delete_ext(X509_CRL *x, int loc); -OPENSSL_EXPORT int X509_CRL_add_ext(X509_CRL *x, X509_EXTENSION *ex, int loc); -OPENSSL_EXPORT void * X509_CRL_get_ext_d2i(X509_CRL *x, int nid, int *crit, int *idx); -OPENSSL_EXPORT int X509_CRL_add1_ext_i2d(X509_CRL *x, int nid, void *value, int crit, - unsigned long flags); - -OPENSSL_EXPORT int X509_REVOKED_get_ext_count(X509_REVOKED *x); -OPENSSL_EXPORT int X509_REVOKED_get_ext_by_NID(X509_REVOKED *x, int nid, int lastpos); -OPENSSL_EXPORT int X509_REVOKED_get_ext_by_OBJ(X509_REVOKED *x,ASN1_OBJECT *obj,int lastpos); -OPENSSL_EXPORT int X509_REVOKED_get_ext_by_critical(X509_REVOKED *x, int crit, int lastpos); -OPENSSL_EXPORT X509_EXTENSION *X509_REVOKED_get_ext(X509_REVOKED *x, int loc); -OPENSSL_EXPORT X509_EXTENSION *X509_REVOKED_delete_ext(X509_REVOKED *x, int loc); -OPENSSL_EXPORT int X509_REVOKED_add_ext(X509_REVOKED *x, X509_EXTENSION *ex, int loc); -OPENSSL_EXPORT void * X509_REVOKED_get_ext_d2i(X509_REVOKED *x, int nid, int *crit, int *idx); -OPENSSL_EXPORT int X509_REVOKED_add1_ext_i2d(X509_REVOKED *x, int nid, void *value, int crit, - unsigned long flags); - -OPENSSL_EXPORT X509_EXTENSION *X509_EXTENSION_create_by_NID(X509_EXTENSION **ex, - int nid, int crit, ASN1_OCTET_STRING *data); -OPENSSL_EXPORT X509_EXTENSION *X509_EXTENSION_create_by_OBJ(X509_EXTENSION **ex, - const ASN1_OBJECT *obj,int crit,ASN1_OCTET_STRING *data); -OPENSSL_EXPORT int X509_EXTENSION_set_object(X509_EXTENSION *ex,const ASN1_OBJECT *obj); -OPENSSL_EXPORT int X509_EXTENSION_set_critical(X509_EXTENSION *ex, int crit); -OPENSSL_EXPORT int X509_EXTENSION_set_data(X509_EXTENSION *ex, - ASN1_OCTET_STRING *data); -OPENSSL_EXPORT ASN1_OBJECT * X509_EXTENSION_get_object(X509_EXTENSION *ex); -OPENSSL_EXPORT ASN1_OCTET_STRING *X509_EXTENSION_get_data(X509_EXTENSION *ne); -OPENSSL_EXPORT int X509_EXTENSION_get_critical(X509_EXTENSION *ex); - -OPENSSL_EXPORT int X509at_get_attr_count(const STACK_OF(X509_ATTRIBUTE) *x); -OPENSSL_EXPORT int X509at_get_attr_by_NID(const STACK_OF(X509_ATTRIBUTE) *x, int nid, - int lastpos); -OPENSSL_EXPORT int X509at_get_attr_by_OBJ(const STACK_OF(X509_ATTRIBUTE) *sk, const ASN1_OBJECT *obj, - int lastpos); -OPENSSL_EXPORT X509_ATTRIBUTE *X509at_get_attr(const STACK_OF(X509_ATTRIBUTE) *x, int loc); -OPENSSL_EXPORT X509_ATTRIBUTE *X509at_delete_attr(STACK_OF(X509_ATTRIBUTE) *x, int loc); -OPENSSL_EXPORT STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr(STACK_OF(X509_ATTRIBUTE) **x, - X509_ATTRIBUTE *attr); -OPENSSL_EXPORT STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_OBJ(STACK_OF(X509_ATTRIBUTE) **x, - const ASN1_OBJECT *obj, int type, - const unsigned char *bytes, int len); -OPENSSL_EXPORT STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_NID(STACK_OF(X509_ATTRIBUTE) **x, - int nid, int type, - const unsigned char *bytes, int len); -OPENSSL_EXPORT STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_txt(STACK_OF(X509_ATTRIBUTE) **x, - const char *attrname, int type, - const unsigned char *bytes, int len); -OPENSSL_EXPORT void *X509at_get0_data_by_OBJ(STACK_OF(X509_ATTRIBUTE) *x, - ASN1_OBJECT *obj, int lastpos, int type); -OPENSSL_EXPORT X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_NID(X509_ATTRIBUTE **attr, int nid, - int atrtype, const void *data, int len); -OPENSSL_EXPORT X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_OBJ(X509_ATTRIBUTE **attr, - const ASN1_OBJECT *obj, int atrtype, const void *data, int len); -OPENSSL_EXPORT X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_txt(X509_ATTRIBUTE **attr, - const char *atrname, int type, const unsigned char *bytes, int len); -OPENSSL_EXPORT int X509_ATTRIBUTE_set1_object(X509_ATTRIBUTE *attr, const ASN1_OBJECT *obj); -OPENSSL_EXPORT int X509_ATTRIBUTE_set1_data(X509_ATTRIBUTE *attr, int attrtype, const void *data, int len); -OPENSSL_EXPORT void *X509_ATTRIBUTE_get0_data(X509_ATTRIBUTE *attr, int idx, - int atrtype, void *data); -OPENSSL_EXPORT int X509_ATTRIBUTE_count(X509_ATTRIBUTE *attr); -OPENSSL_EXPORT ASN1_OBJECT *X509_ATTRIBUTE_get0_object(X509_ATTRIBUTE *attr); -OPENSSL_EXPORT ASN1_TYPE *X509_ATTRIBUTE_get0_type(X509_ATTRIBUTE *attr, int idx); - -OPENSSL_EXPORT int EVP_PKEY_get_attr_count(const EVP_PKEY *key); -OPENSSL_EXPORT int EVP_PKEY_get_attr_by_NID(const EVP_PKEY *key, int nid, - int lastpos); -OPENSSL_EXPORT int EVP_PKEY_get_attr_by_OBJ(const EVP_PKEY *key, ASN1_OBJECT *obj, - int lastpos); -OPENSSL_EXPORT X509_ATTRIBUTE *EVP_PKEY_get_attr(const EVP_PKEY *key, int loc); -OPENSSL_EXPORT X509_ATTRIBUTE *EVP_PKEY_delete_attr(EVP_PKEY *key, int loc); -OPENSSL_EXPORT int EVP_PKEY_add1_attr(EVP_PKEY *key, X509_ATTRIBUTE *attr); -OPENSSL_EXPORT int EVP_PKEY_add1_attr_by_OBJ(EVP_PKEY *key, - const ASN1_OBJECT *obj, int type, - const unsigned char *bytes, int len); -OPENSSL_EXPORT int EVP_PKEY_add1_attr_by_NID(EVP_PKEY *key, - int nid, int type, - const unsigned char *bytes, int len); -OPENSSL_EXPORT int EVP_PKEY_add1_attr_by_txt(EVP_PKEY *key, - const char *attrname, int type, - const unsigned char *bytes, int len); - -OPENSSL_EXPORT int X509_verify_cert(X509_STORE_CTX *ctx); - -/* lookup a cert from a X509 STACK */ -OPENSSL_EXPORT X509 *X509_find_by_issuer_and_serial(STACK_OF(X509) *sk,X509_NAME *name, - ASN1_INTEGER *serial); -OPENSSL_EXPORT X509 *X509_find_by_subject(STACK_OF(X509) *sk,X509_NAME *name); - -DECLARE_ASN1_FUNCTIONS(PBEPARAM) -DECLARE_ASN1_FUNCTIONS(PBE2PARAM) -DECLARE_ASN1_FUNCTIONS(PBKDF2PARAM) - -OPENSSL_EXPORT int PKCS5_pbe_set0_algor(X509_ALGOR *algor, int alg, int iter, - const unsigned char *salt, int saltlen); - -OPENSSL_EXPORT X509_ALGOR *PKCS5_pbe_set(int alg, int iter, - const unsigned char *salt, int saltlen); -OPENSSL_EXPORT X509_ALGOR *PKCS5_pbe2_set(const EVP_CIPHER *cipher, int iter, - unsigned char *salt, int saltlen); -OPENSSL_EXPORT X509_ALGOR *PKCS5_pbe2_set_iv(const EVP_CIPHER *cipher, int iter, - unsigned char *salt, int saltlen, - unsigned char *aiv, int prf_nid); - -OPENSSL_EXPORT X509_ALGOR *PKCS5_pbkdf2_set(int iter, unsigned char *salt, int saltlen, - int prf_nid, int keylen); - -/* PKCS#8 utilities */ - -DECLARE_ASN1_FUNCTIONS(PKCS8_PRIV_KEY_INFO) - -OPENSSL_EXPORT EVP_PKEY *EVP_PKCS82PKEY(PKCS8_PRIV_KEY_INFO *p8); -OPENSSL_EXPORT PKCS8_PRIV_KEY_INFO *EVP_PKEY2PKCS8(EVP_PKEY *pkey); -OPENSSL_EXPORT PKCS8_PRIV_KEY_INFO *EVP_PKEY2PKCS8_broken(EVP_PKEY *pkey, int broken); -OPENSSL_EXPORT PKCS8_PRIV_KEY_INFO *PKCS8_set_broken(PKCS8_PRIV_KEY_INFO *p8, int broken); - -OPENSSL_EXPORT int PKCS8_pkey_set0(PKCS8_PRIV_KEY_INFO *priv, ASN1_OBJECT *aobj, - int version, int ptype, void *pval, - unsigned char *penc, int penclen); -OPENSSL_EXPORT int PKCS8_pkey_get0(ASN1_OBJECT **ppkalg, - const unsigned char **pk, int *ppklen, - X509_ALGOR **pa, - PKCS8_PRIV_KEY_INFO *p8); - -OPENSSL_EXPORT int X509_PUBKEY_set0_param(X509_PUBKEY *pub, const ASN1_OBJECT *aobj, - int ptype, void *pval, - unsigned char *penc, int penclen); -OPENSSL_EXPORT int X509_PUBKEY_get0_param(ASN1_OBJECT **ppkalg, - const unsigned char **pk, int *ppklen, - X509_ALGOR **pa, - X509_PUBKEY *pub); - -OPENSSL_EXPORT int X509_check_trust(X509 *x, int id, int flags); -OPENSSL_EXPORT int X509_TRUST_get_count(void); -OPENSSL_EXPORT X509_TRUST * X509_TRUST_get0(int idx); -OPENSSL_EXPORT int X509_TRUST_get_by_id(int id); -OPENSSL_EXPORT int X509_TRUST_add(int id, int flags, int (*ck)(X509_TRUST *, X509 *, int), - char *name, int arg1, void *arg2); -OPENSSL_EXPORT void X509_TRUST_cleanup(void); -OPENSSL_EXPORT int X509_TRUST_get_flags(X509_TRUST *xp); -OPENSSL_EXPORT char *X509_TRUST_get0_name(X509_TRUST *xp); -OPENSSL_EXPORT int X509_TRUST_get_trust(X509_TRUST *xp); - -/* PKCS7_get_certificates parses a PKCS#7, SignedData structure from |cbs| and - * appends the included certificates to |out_certs|. It returns one on success - * and zero on error. */ -OPENSSL_EXPORT int PKCS7_get_certificates(STACK_OF(X509) *out_certs, CBS *cbs); - -/* PKCS7_bundle_certificates appends a PKCS#7, SignedData structure containing - * |certs| to |out|. It returns one on success and zero on error. */ -OPENSSL_EXPORT int PKCS7_bundle_certificates( - CBB *out, const STACK_OF(X509) *certs); - -/* PKCS7_get_CRLs parses a PKCS#7, SignedData structure from |cbs| and appends - * the included CRLs to |out_crls|. It returns one on success and zero on - * error. */ -OPENSSL_EXPORT int PKCS7_get_CRLs(STACK_OF(X509_CRL) *out_crls, CBS *cbs); - -/* PKCS7_bundle_CRLs appends a PKCS#7, SignedData structure containing - * |crls| to |out|. It returns one on success and zero on error. */ -OPENSSL_EXPORT int PKCS7_bundle_CRLs(CBB *out, const STACK_OF(X509_CRL) *crls); - -/* PKCS7_get_PEM_certificates reads a PEM-encoded, PKCS#7, SignedData structure - * from |pem_bio| and appends the included certificates to |out_certs|. It - * returns one on success and zero on error. */ -OPENSSL_EXPORT int PKCS7_get_PEM_certificates(STACK_OF(X509) *out_certs, - BIO *pem_bio); - -/* PKCS7_get_PEM_CRLs reads a PEM-encoded, PKCS#7, SignedData structure from - * |pem_bio| and appends the included CRLs to |out_crls|. It returns one on - * success and zero on error. */ -OPENSSL_EXPORT int PKCS7_get_PEM_CRLs(STACK_OF(X509_CRL) *out_crls, - BIO *pem_bio); - -/* EVP_PK values indicate the algorithm of the public key in a certificate. */ - -#define EVP_PK_RSA 0x0001 -#define EVP_PK_DSA 0x0002 -#define EVP_PK_DH 0x0004 -#define EVP_PK_EC 0x0008 - -/* EVP_PKS values indicate the algorithm used to sign a certificate. */ - -#define EVP_PKS_RSA 0x0100 -#define EVP_PKS_DSA 0x0200 -#define EVP_PKS_EC 0x0400 - -/* EVP_PKT values are flags that define what public-key operations can be - * performed with the public key from a certificate. */ - -/* EVP_PKT_SIGN indicates that the public key can be used for signing. */ -#define EVP_PKT_SIGN 0x0010 -/* EVP_PKT_ENC indicates that a session key can be encrypted to the public - * key. */ -#define EVP_PKT_ENC 0x0020 -/* EVP_PKT_EXCH indicates that key-agreement can be performed. */ -#define EVP_PKT_EXCH 0x0040 -/* EVP_PKT_EXP indicates that key is weak (i.e. "export"). */ -#define EVP_PKT_EXP 0x1000 - - -#ifdef __cplusplus -} -#endif - -#define X509_F_ASN1_digest 100 -#define X509_F_ASN1_item_sign_ctx 101 -#define X509_F_ASN1_item_verify 102 -#define X509_F_NETSCAPE_SPKI_b64_decode 103 -#define X509_F_NETSCAPE_SPKI_b64_encode 104 -#define X509_F_PKCS7_get_certificates 105 -#define X509_F_X509_ATTRIBUTE_create_by_NID 106 -#define X509_F_X509_ATTRIBUTE_create_by_OBJ 107 -#define X509_F_X509_ATTRIBUTE_create_by_txt 108 -#define X509_F_X509_ATTRIBUTE_get0_data 109 -#define X509_F_X509_ATTRIBUTE_set1_data 110 -#define X509_F_X509_CRL_add0_revoked 111 -#define X509_F_X509_CRL_diff 112 -#define X509_F_X509_CRL_print_fp 113 -#define X509_F_X509_EXTENSION_create_by_NID 114 -#define X509_F_X509_EXTENSION_create_by_OBJ 115 -#define X509_F_X509_INFO_new 116 -#define X509_F_X509_NAME_ENTRY_create_by_NID 117 -#define X509_F_X509_NAME_ENTRY_create_by_txt 118 -#define X509_F_X509_NAME_ENTRY_set_object 119 -#define X509_F_X509_NAME_add_entry 120 -#define X509_F_X509_NAME_oneline 121 -#define X509_F_X509_NAME_print 122 -#define X509_F_X509_PKEY_new 123 -#define X509_F_X509_PUBKEY_get 124 -#define X509_F_X509_PUBKEY_set 125 -#define X509_F_X509_REQ_check_private_key 126 -#define X509_F_X509_REQ_to_X509 127 -#define X509_F_X509_STORE_CTX_get1_issuer 128 -#define X509_F_X509_STORE_CTX_init 129 -#define X509_F_X509_STORE_CTX_new 130 -#define X509_F_X509_STORE_CTX_purpose_inherit 131 -#define X509_F_X509_STORE_add_cert 132 -#define X509_F_X509_STORE_add_crl 133 -#define X509_F_X509_TRUST_add 134 -#define X509_F_X509_TRUST_set 135 -#define X509_F_X509_check_private_key 136 -#define X509_F_X509_get_pubkey_parameters 137 -#define X509_F_X509_load_cert_crl_file 138 -#define X509_F_X509_load_cert_file 139 -#define X509_F_X509_load_crl_file 140 -#define X509_F_X509_print_ex_fp 141 -#define X509_F_X509_to_X509_REQ 142 -#define X509_F_X509_verify_cert 143 -#define X509_F_X509at_add1_attr 144 -#define X509_F_X509v3_add_ext 145 -#define X509_F_add_cert_dir 146 -#define X509_F_by_file_ctrl 147 -#define X509_F_check_policy 148 -#define X509_F_dir_ctrl 149 -#define X509_F_get_cert_by_subject 150 -#define X509_F_i2d_DSA_PUBKEY 151 -#define X509_F_i2d_EC_PUBKEY 152 -#define X509_F_i2d_RSA_PUBKEY 153 -#define X509_F_x509_name_encode 154 -#define X509_F_x509_name_ex_d2i 155 -#define X509_F_x509_name_ex_new 156 -#define X509_F_pkcs7_parse_header 157 -#define X509_F_PKCS7_get_CRLs 158 -#define X509_R_AKID_MISMATCH 100 -#define X509_R_BAD_PKCS7_VERSION 101 -#define X509_R_BAD_X509_FILETYPE 102 -#define X509_R_BASE64_DECODE_ERROR 103 -#define X509_R_CANT_CHECK_DH_KEY 104 -#define X509_R_CERT_ALREADY_IN_HASH_TABLE 105 -#define X509_R_CRL_ALREADY_DELTA 106 -#define X509_R_CRL_VERIFY_FAILURE 107 -#define X509_R_IDP_MISMATCH 108 -#define X509_R_INVALID_BIT_STRING_BITS_LEFT 109 -#define X509_R_INVALID_DIRECTORY 110 -#define X509_R_INVALID_FIELD_NAME 111 -#define X509_R_INVALID_TRUST 112 -#define X509_R_ISSUER_MISMATCH 113 -#define X509_R_KEY_TYPE_MISMATCH 114 -#define X509_R_KEY_VALUES_MISMATCH 115 -#define X509_R_LOADING_CERT_DIR 116 -#define X509_R_LOADING_DEFAULTS 117 -#define X509_R_METHOD_NOT_SUPPORTED 118 -#define X509_R_NEWER_CRL_NOT_NEWER 119 -#define X509_R_NOT_PKCS7_SIGNED_DATA 120 -#define X509_R_NO_CERTIFICATES_INCLUDED 121 -#define X509_R_NO_CERT_SET_FOR_US_TO_VERIFY 122 -#define X509_R_NO_CRL_NUMBER 123 -#define X509_R_PUBLIC_KEY_DECODE_ERROR 124 -#define X509_R_PUBLIC_KEY_ENCODE_ERROR 125 -#define X509_R_SHOULD_RETRY 126 -#define X509_R_UNABLE_TO_FIND_PARAMETERS_IN_CHAIN 127 -#define X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY 128 -#define X509_R_UNKNOWN_KEY_TYPE 129 -#define X509_R_UNKNOWN_NID 130 -#define X509_R_UNKNOWN_PURPOSE_ID 131 -#define X509_R_UNKNOWN_TRUST_ID 132 -#define X509_R_UNSUPPORTED_ALGORITHM 133 -#define X509_R_WRONG_LOOKUP_TYPE 134 -#define X509_R_WRONG_TYPE 135 -#define X509_R_NO_CRLS_INCLUDED 136 - -#endif diff --git a/third_party/boringssl/include/openssl/x509_vfy.h b/third_party/boringssl/include/openssl/x509_vfy.h deleted file mode 100644 index 146e047a6d..0000000000 --- a/third_party/boringssl/include/openssl/x509_vfy.h +++ /dev/null @@ -1,612 +0,0 @@ -/* crypto/x509/x509_vfy.h */ -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - * - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - * - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - * - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] - */ - -#ifndef HEADER_X509_H -#include -/* openssl/x509.h ends up #include-ing this file at about the only - * appropriate moment. */ -#endif - -#ifndef HEADER_X509_VFY_H -#define HEADER_X509_VFY_H - -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#if 0 -/* Outer object */ -typedef struct x509_hash_dir_st - { - int num_dirs; - char **dirs; - int *dirs_type; - int num_dirs_alloced; - } X509_HASH_DIR_CTX; -#endif - -typedef struct x509_file_st - { - int num_paths; /* number of paths to files or directories */ - int num_alloced; - char **paths; /* the list of paths or directories */ - int *path_type; - } X509_CERT_FILE_CTX; - -/*******************************/ -/* -SSL_CTX -> X509_STORE - -> X509_LOOKUP - ->X509_LOOKUP_METHOD - -> X509_LOOKUP - ->X509_LOOKUP_METHOD - -SSL -> X509_STORE_CTX - ->X509_STORE - -The X509_STORE holds the tables etc for verification stuff. -A X509_STORE_CTX is used while validating a single certificate. -The X509_STORE has X509_LOOKUPs for looking up certs. -The X509_STORE then calls a function to actually verify the -certificate chain. -*/ - -#define X509_LU_RETRY -1 -#define X509_LU_FAIL 0 -#define X509_LU_X509 1 -#define X509_LU_CRL 2 -#define X509_LU_PKEY 3 - -typedef struct x509_object_st - { - /* one of the above types */ - int type; - union { - char *ptr; - X509 *x509; - X509_CRL *crl; - EVP_PKEY *pkey; - } data; - } X509_OBJECT; - -typedef struct x509_lookup_st X509_LOOKUP; - -DECLARE_STACK_OF(X509_LOOKUP) -DECLARE_STACK_OF(X509_OBJECT) - -/* This is a static that defines the function interface */ -typedef struct x509_lookup_method_st - { - const char *name; - int (*new_item)(X509_LOOKUP *ctx); - void (*free)(X509_LOOKUP *ctx); - int (*init)(X509_LOOKUP *ctx); - int (*shutdown)(X509_LOOKUP *ctx); - int (*ctrl)(X509_LOOKUP *ctx,int cmd,const char *argc,long argl, - char **ret); - int (*get_by_subject)(X509_LOOKUP *ctx,int type,X509_NAME *name, - X509_OBJECT *ret); - int (*get_by_issuer_serial)(X509_LOOKUP *ctx,int type,X509_NAME *name, - ASN1_INTEGER *serial,X509_OBJECT *ret); - int (*get_by_fingerprint)(X509_LOOKUP *ctx,int type, - unsigned char *bytes,int len, - X509_OBJECT *ret); - int (*get_by_alias)(X509_LOOKUP *ctx,int type,char *str,int len, - X509_OBJECT *ret); - } X509_LOOKUP_METHOD; - -typedef struct X509_VERIFY_PARAM_ID_st X509_VERIFY_PARAM_ID; - -/* This structure hold all parameters associated with a verify operation - * by including an X509_VERIFY_PARAM structure in related structures the - * parameters used can be customized - */ - -typedef struct X509_VERIFY_PARAM_st - { - char *name; - time_t check_time; /* Time to use */ - unsigned long inh_flags; /* Inheritance flags */ - unsigned long flags; /* Various verify flags */ - int purpose; /* purpose to check untrusted certificates */ - int trust; /* trust setting to check */ - int depth; /* Verify depth */ - STACK_OF(ASN1_OBJECT) *policies; /* Permissible policies */ - X509_VERIFY_PARAM_ID *id; /* opaque ID data */ - } X509_VERIFY_PARAM; - -DECLARE_STACK_OF(X509_VERIFY_PARAM) - -/* This is used to hold everything. It is used for all certificate - * validation. Once we have a certificate chain, the 'verify' - * function is then called to actually check the cert chain. */ -struct x509_store_st - { - /* The following is a cache of trusted certs */ - int cache; /* if true, stash any hits */ - STACK_OF(X509_OBJECT) *objs; /* Cache of all objects */ - CRYPTO_MUTEX objs_lock; - - /* These are external lookup methods */ - STACK_OF(X509_LOOKUP) *get_cert_methods; - - X509_VERIFY_PARAM *param; - - /* Callbacks for various operations */ - int (*verify)(X509_STORE_CTX *ctx); /* called to verify a certificate */ - int (*verify_cb)(int ok,X509_STORE_CTX *ctx); /* error callback */ - int (*get_issuer)(X509 **issuer, X509_STORE_CTX *ctx, X509 *x); /* get issuers cert from ctx */ - int (*check_issued)(X509_STORE_CTX *ctx, X509 *x, X509 *issuer); /* check issued */ - int (*check_revocation)(X509_STORE_CTX *ctx); /* Check revocation status of chain */ - int (*get_crl)(X509_STORE_CTX *ctx, X509_CRL **crl, X509 *x); /* retrieve CRL */ - int (*check_crl)(X509_STORE_CTX *ctx, X509_CRL *crl); /* Check CRL validity */ - int (*cert_crl)(X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x); /* Check certificate against CRL */ - STACK_OF(X509) * (*lookup_certs)(X509_STORE_CTX *ctx, X509_NAME *nm); - STACK_OF(X509_CRL) * (*lookup_crls)(X509_STORE_CTX *ctx, X509_NAME *nm); - int (*cleanup)(X509_STORE_CTX *ctx); - - CRYPTO_refcount_t references; - } /* X509_STORE */; - -OPENSSL_EXPORT int X509_STORE_set_depth(X509_STORE *store, int depth); - -#define X509_STORE_set_verify_cb_func(ctx,func) ((ctx)->verify_cb=(func)) -#define X509_STORE_set_verify_func(ctx,func) ((ctx)->verify=(func)) - -/* This is the functions plus an instance of the local variables. */ -struct x509_lookup_st - { - int init; /* have we been started */ - int skip; /* don't use us. */ - X509_LOOKUP_METHOD *method; /* the functions */ - char *method_data; /* method data */ - - X509_STORE *store_ctx; /* who owns us */ - } /* X509_LOOKUP */; - -/* This is a used when verifying cert chains. Since the - * gathering of the cert chain can take some time (and have to be - * 'retried', this needs to be kept and passed around. */ -struct x509_store_ctx_st /* X509_STORE_CTX */ - { - X509_STORE *ctx; - int current_method; /* used when looking up certs */ - - /* The following are set by the caller */ - X509 *cert; /* The cert to check */ - STACK_OF(X509) *untrusted; /* chain of X509s - untrusted - passed in */ - STACK_OF(X509_CRL) *crls; /* set of CRLs passed in */ - - X509_VERIFY_PARAM *param; - void *other_ctx; /* Other info for use with get_issuer() */ - - /* Callbacks for various operations */ - int (*verify)(X509_STORE_CTX *ctx); /* called to verify a certificate */ - int (*verify_cb)(int ok,X509_STORE_CTX *ctx); /* error callback */ - int (*get_issuer)(X509 **issuer, X509_STORE_CTX *ctx, X509 *x); /* get issuers cert from ctx */ - int (*check_issued)(X509_STORE_CTX *ctx, X509 *x, X509 *issuer); /* check issued */ - int (*check_revocation)(X509_STORE_CTX *ctx); /* Check revocation status of chain */ - int (*get_crl)(X509_STORE_CTX *ctx, X509_CRL **crl, X509 *x); /* retrieve CRL */ - int (*check_crl)(X509_STORE_CTX *ctx, X509_CRL *crl); /* Check CRL validity */ - int (*cert_crl)(X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x); /* Check certificate against CRL */ - int (*check_policy)(X509_STORE_CTX *ctx); - STACK_OF(X509) * (*lookup_certs)(X509_STORE_CTX *ctx, X509_NAME *nm); - STACK_OF(X509_CRL) * (*lookup_crls)(X509_STORE_CTX *ctx, X509_NAME *nm); - int (*cleanup)(X509_STORE_CTX *ctx); - - /* The following is built up */ - int valid; /* if 0, rebuild chain */ - int last_untrusted; /* index of last untrusted cert */ - STACK_OF(X509) *chain; /* chain of X509s - built up and trusted */ - X509_POLICY_TREE *tree; /* Valid policy tree */ - - int explicit_policy; /* Require explicit policy value */ - - /* When something goes wrong, this is why */ - int error_depth; - int error; - X509 *current_cert; - X509 *current_issuer; /* cert currently being tested as valid issuer */ - X509_CRL *current_crl; /* current CRL */ - - int current_crl_score; /* score of current CRL */ - unsigned int current_reasons; /* Reason mask */ - - X509_STORE_CTX *parent; /* For CRL path validation: parent context */ - - CRYPTO_EX_DATA ex_data; - } /* X509_STORE_CTX */; - -OPENSSL_EXPORT void X509_STORE_CTX_set_depth(X509_STORE_CTX *ctx, int depth); - -#define X509_STORE_CTX_set_app_data(ctx,data) \ - X509_STORE_CTX_set_ex_data(ctx,0,data) -#define X509_STORE_CTX_get_app_data(ctx) \ - X509_STORE_CTX_get_ex_data(ctx,0) - -#define X509_L_FILE_LOAD 1 -#define X509_L_ADD_DIR 2 - -#define X509_LOOKUP_load_file(x,name,type) \ - X509_LOOKUP_ctrl((x),X509_L_FILE_LOAD,(name),(long)(type),NULL) - -#define X509_LOOKUP_add_dir(x,name,type) \ - X509_LOOKUP_ctrl((x),X509_L_ADD_DIR,(name),(long)(type),NULL) - -#define X509_V_OK 0 -/* illegal error (for uninitialized values, to avoid X509_V_OK): 1 */ - -#define X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT 2 -#define X509_V_ERR_UNABLE_TO_GET_CRL 3 -#define X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE 4 -#define X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE 5 -#define X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY 6 -#define X509_V_ERR_CERT_SIGNATURE_FAILURE 7 -#define X509_V_ERR_CRL_SIGNATURE_FAILURE 8 -#define X509_V_ERR_CERT_NOT_YET_VALID 9 -#define X509_V_ERR_CERT_HAS_EXPIRED 10 -#define X509_V_ERR_CRL_NOT_YET_VALID 11 -#define X509_V_ERR_CRL_HAS_EXPIRED 12 -#define X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD 13 -#define X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD 14 -#define X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD 15 -#define X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD 16 -#define X509_V_ERR_OUT_OF_MEM 17 -#define X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT 18 -#define X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN 19 -#define X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY 20 -#define X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE 21 -#define X509_V_ERR_CERT_CHAIN_TOO_LONG 22 -#define X509_V_ERR_CERT_REVOKED 23 -#define X509_V_ERR_INVALID_CA 24 -#define X509_V_ERR_PATH_LENGTH_EXCEEDED 25 -#define X509_V_ERR_INVALID_PURPOSE 26 -#define X509_V_ERR_CERT_UNTRUSTED 27 -#define X509_V_ERR_CERT_REJECTED 28 -/* These are 'informational' when looking for issuer cert */ -#define X509_V_ERR_SUBJECT_ISSUER_MISMATCH 29 -#define X509_V_ERR_AKID_SKID_MISMATCH 30 -#define X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH 31 -#define X509_V_ERR_KEYUSAGE_NO_CERTSIGN 32 - -#define X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER 33 -#define X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION 34 -#define X509_V_ERR_KEYUSAGE_NO_CRL_SIGN 35 -#define X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION 36 -#define X509_V_ERR_INVALID_NON_CA 37 -#define X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED 38 -#define X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE 39 -#define X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED 40 - -#define X509_V_ERR_INVALID_EXTENSION 41 -#define X509_V_ERR_INVALID_POLICY_EXTENSION 42 -#define X509_V_ERR_NO_EXPLICIT_POLICY 43 -#define X509_V_ERR_DIFFERENT_CRL_SCOPE 44 -#define X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE 45 - -#define X509_V_ERR_UNNESTED_RESOURCE 46 - -#define X509_V_ERR_PERMITTED_VIOLATION 47 -#define X509_V_ERR_EXCLUDED_VIOLATION 48 -#define X509_V_ERR_SUBTREE_MINMAX 49 -#define X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE 51 -#define X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX 52 -#define X509_V_ERR_UNSUPPORTED_NAME_SYNTAX 53 -#define X509_V_ERR_CRL_PATH_VALIDATION_ERROR 54 - -/* Suite B mode algorithm violation */ -#define X509_V_ERR_SUITE_B_INVALID_VERSION 56 -#define X509_V_ERR_SUITE_B_INVALID_ALGORITHM 57 -#define X509_V_ERR_SUITE_B_INVALID_CURVE 58 -#define X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM 59 -#define X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED 60 -#define X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256 61 - -/* Host, email and IP check errors */ -#define X509_V_ERR_HOSTNAME_MISMATCH 62 -#define X509_V_ERR_EMAIL_MISMATCH 63 -#define X509_V_ERR_IP_ADDRESS_MISMATCH 64 - -/* The application is not happy */ -#define X509_V_ERR_APPLICATION_VERIFICATION 50 - -/* Certificate verify flags */ - -/* Send issuer+subject checks to verify_cb */ -#define X509_V_FLAG_CB_ISSUER_CHECK 0x1 -/* Use check time instead of current time */ -#define X509_V_FLAG_USE_CHECK_TIME 0x2 -/* Lookup CRLs */ -#define X509_V_FLAG_CRL_CHECK 0x4 -/* Lookup CRLs for whole chain */ -#define X509_V_FLAG_CRL_CHECK_ALL 0x8 -/* Ignore unhandled critical extensions */ -#define X509_V_FLAG_IGNORE_CRITICAL 0x10 -/* Disable workarounds for broken certificates */ -#define X509_V_FLAG_X509_STRICT 0x20 -/* Enable proxy certificate validation */ -#define X509_V_FLAG_ALLOW_PROXY_CERTS 0x40 -/* Enable policy checking */ -#define X509_V_FLAG_POLICY_CHECK 0x80 -/* Policy variable require-explicit-policy */ -#define X509_V_FLAG_EXPLICIT_POLICY 0x100 -/* Policy variable inhibit-any-policy */ -#define X509_V_FLAG_INHIBIT_ANY 0x200 -/* Policy variable inhibit-policy-mapping */ -#define X509_V_FLAG_INHIBIT_MAP 0x400 -/* Notify callback that policy is OK */ -#define X509_V_FLAG_NOTIFY_POLICY 0x800 -/* Extended CRL features such as indirect CRLs, alternate CRL signing keys */ -#define X509_V_FLAG_EXTENDED_CRL_SUPPORT 0x1000 -/* Delta CRL support */ -#define X509_V_FLAG_USE_DELTAS 0x2000 -/* Check selfsigned CA signature */ -#define X509_V_FLAG_CHECK_SS_SIGNATURE 0x4000 -/* Use trusted store first */ -#define X509_V_FLAG_TRUSTED_FIRST 0x8000 -/* Suite B 128 bit only mode: not normally used */ -#define X509_V_FLAG_SUITEB_128_LOS_ONLY 0x10000 -/* Suite B 192 bit only mode */ -#define X509_V_FLAG_SUITEB_192_LOS 0x20000 -/* Suite B 128 bit mode allowing 192 bit algorithms */ -#define X509_V_FLAG_SUITEB_128_LOS 0x30000 - -/* Allow partial chains if at least one certificate is in trusted store */ -#define X509_V_FLAG_PARTIAL_CHAIN 0x80000 - -#define X509_VP_FLAG_DEFAULT 0x1 -#define X509_VP_FLAG_OVERWRITE 0x2 -#define X509_VP_FLAG_RESET_FLAGS 0x4 -#define X509_VP_FLAG_LOCKED 0x8 -#define X509_VP_FLAG_ONCE 0x10 - -/* Internal use: mask of policy related options */ -#define X509_V_FLAG_POLICY_MASK (X509_V_FLAG_POLICY_CHECK \ - | X509_V_FLAG_EXPLICIT_POLICY \ - | X509_V_FLAG_INHIBIT_ANY \ - | X509_V_FLAG_INHIBIT_MAP) - -OPENSSL_EXPORT int X509_OBJECT_idx_by_subject(STACK_OF(X509_OBJECT) *h, int type, - X509_NAME *name); -OPENSSL_EXPORT X509_OBJECT *X509_OBJECT_retrieve_by_subject(STACK_OF(X509_OBJECT) *h,int type,X509_NAME *name); -OPENSSL_EXPORT X509_OBJECT *X509_OBJECT_retrieve_match(STACK_OF(X509_OBJECT) *h, X509_OBJECT *x); -OPENSSL_EXPORT void X509_OBJECT_up_ref_count(X509_OBJECT *a); -OPENSSL_EXPORT void X509_OBJECT_free_contents(X509_OBJECT *a); -OPENSSL_EXPORT X509_STORE *X509_STORE_new(void ); -OPENSSL_EXPORT void X509_STORE_free(X509_STORE *v); - -OPENSSL_EXPORT STACK_OF(X509)* X509_STORE_get1_certs(X509_STORE_CTX *st, X509_NAME *nm); -OPENSSL_EXPORT STACK_OF(X509_CRL)* X509_STORE_get1_crls(X509_STORE_CTX *st, X509_NAME *nm); -OPENSSL_EXPORT int X509_STORE_set_flags(X509_STORE *ctx, unsigned long flags); -OPENSSL_EXPORT int X509_STORE_set_purpose(X509_STORE *ctx, int purpose); -OPENSSL_EXPORT int X509_STORE_set_trust(X509_STORE *ctx, int trust); -OPENSSL_EXPORT int X509_STORE_set1_param(X509_STORE *ctx, X509_VERIFY_PARAM *pm); - -OPENSSL_EXPORT void X509_STORE_set_verify_cb(X509_STORE *ctx, - int (*verify_cb)(int, X509_STORE_CTX *)); - -OPENSSL_EXPORT void X509_STORE_set_lookup_crls_cb(X509_STORE *ctx, - STACK_OF(X509_CRL)* (*cb)(X509_STORE_CTX *ctx, X509_NAME *nm)); - -OPENSSL_EXPORT X509_STORE_CTX *X509_STORE_CTX_new(void); - -OPENSSL_EXPORT int X509_STORE_CTX_get1_issuer(X509 **issuer, X509_STORE_CTX *ctx, X509 *x); - -OPENSSL_EXPORT void X509_STORE_CTX_free(X509_STORE_CTX *ctx); -OPENSSL_EXPORT int X509_STORE_CTX_init(X509_STORE_CTX *ctx, X509_STORE *store, - X509 *x509, STACK_OF(X509) *chain); -OPENSSL_EXPORT void X509_STORE_CTX_trusted_stack(X509_STORE_CTX *ctx, STACK_OF(X509) *sk); -OPENSSL_EXPORT void X509_STORE_CTX_cleanup(X509_STORE_CTX *ctx); - -OPENSSL_EXPORT X509_STORE *X509_STORE_CTX_get0_store(X509_STORE_CTX *ctx); - -OPENSSL_EXPORT X509_LOOKUP *X509_STORE_add_lookup(X509_STORE *v, X509_LOOKUP_METHOD *m); - -OPENSSL_EXPORT X509_LOOKUP_METHOD *X509_LOOKUP_hash_dir(void); -OPENSSL_EXPORT X509_LOOKUP_METHOD *X509_LOOKUP_file(void); - -OPENSSL_EXPORT int X509_STORE_add_cert(X509_STORE *ctx, X509 *x); -OPENSSL_EXPORT int X509_STORE_add_crl(X509_STORE *ctx, X509_CRL *x); - -OPENSSL_EXPORT int X509_STORE_get_by_subject(X509_STORE_CTX *vs,int type,X509_NAME *name, - X509_OBJECT *ret); - -OPENSSL_EXPORT int X509_LOOKUP_ctrl(X509_LOOKUP *ctx, int cmd, const char *argc, - long argl, char **ret); - -#ifndef OPENSSL_NO_STDIO -OPENSSL_EXPORT int X509_load_cert_file(X509_LOOKUP *ctx, const char *file, int type); -OPENSSL_EXPORT int X509_load_crl_file(X509_LOOKUP *ctx, const char *file, int type); -OPENSSL_EXPORT int X509_load_cert_crl_file(X509_LOOKUP *ctx, const char *file, int type); -#endif - - -OPENSSL_EXPORT X509_LOOKUP *X509_LOOKUP_new(X509_LOOKUP_METHOD *method); -OPENSSL_EXPORT void X509_LOOKUP_free(X509_LOOKUP *ctx); -OPENSSL_EXPORT int X509_LOOKUP_init(X509_LOOKUP *ctx); -OPENSSL_EXPORT int X509_LOOKUP_by_subject(X509_LOOKUP *ctx, int type, X509_NAME *name, - X509_OBJECT *ret); -OPENSSL_EXPORT int X509_LOOKUP_by_issuer_serial(X509_LOOKUP *ctx, int type, X509_NAME *name, - ASN1_INTEGER *serial, X509_OBJECT *ret); -OPENSSL_EXPORT int X509_LOOKUP_by_fingerprint(X509_LOOKUP *ctx, int type, - unsigned char *bytes, int len, X509_OBJECT *ret); -OPENSSL_EXPORT int X509_LOOKUP_by_alias(X509_LOOKUP *ctx, int type, char *str, - int len, X509_OBJECT *ret); -OPENSSL_EXPORT int X509_LOOKUP_shutdown(X509_LOOKUP *ctx); - -#ifndef OPENSSL_NO_STDIO -OPENSSL_EXPORT int X509_STORE_load_locations (X509_STORE *ctx, - const char *file, const char *dir); -OPENSSL_EXPORT int X509_STORE_set_default_paths(X509_STORE *ctx); -#endif - -OPENSSL_EXPORT int X509_STORE_CTX_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func, - CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func); -OPENSSL_EXPORT int X509_STORE_CTX_set_ex_data(X509_STORE_CTX *ctx,int idx,void *data); -OPENSSL_EXPORT void * X509_STORE_CTX_get_ex_data(X509_STORE_CTX *ctx,int idx); -OPENSSL_EXPORT int X509_STORE_CTX_get_error(X509_STORE_CTX *ctx); -OPENSSL_EXPORT void X509_STORE_CTX_set_error(X509_STORE_CTX *ctx,int s); -OPENSSL_EXPORT int X509_STORE_CTX_get_error_depth(X509_STORE_CTX *ctx); -OPENSSL_EXPORT X509 * X509_STORE_CTX_get_current_cert(X509_STORE_CTX *ctx); -OPENSSL_EXPORT X509 *X509_STORE_CTX_get0_current_issuer(X509_STORE_CTX *ctx); -OPENSSL_EXPORT X509_CRL *X509_STORE_CTX_get0_current_crl(X509_STORE_CTX *ctx); -OPENSSL_EXPORT X509_STORE_CTX *X509_STORE_CTX_get0_parent_ctx(X509_STORE_CTX *ctx); -OPENSSL_EXPORT STACK_OF(X509) *X509_STORE_CTX_get_chain(X509_STORE_CTX *ctx); -OPENSSL_EXPORT STACK_OF(X509) *X509_STORE_CTX_get1_chain(X509_STORE_CTX *ctx); -OPENSSL_EXPORT void X509_STORE_CTX_set_cert(X509_STORE_CTX *c,X509 *x); -OPENSSL_EXPORT void X509_STORE_CTX_set_chain(X509_STORE_CTX *c,STACK_OF(X509) *sk); -OPENSSL_EXPORT void X509_STORE_CTX_set0_crls(X509_STORE_CTX *c,STACK_OF(X509_CRL) *sk); -OPENSSL_EXPORT int X509_STORE_CTX_set_purpose(X509_STORE_CTX *ctx, int purpose); -OPENSSL_EXPORT int X509_STORE_CTX_set_trust(X509_STORE_CTX *ctx, int trust); -OPENSSL_EXPORT int X509_STORE_CTX_purpose_inherit(X509_STORE_CTX *ctx, int def_purpose, - int purpose, int trust); -OPENSSL_EXPORT void X509_STORE_CTX_set_flags(X509_STORE_CTX *ctx, unsigned long flags); -OPENSSL_EXPORT void X509_STORE_CTX_set_time(X509_STORE_CTX *ctx, unsigned long flags, - time_t t); -OPENSSL_EXPORT void X509_STORE_CTX_set_verify_cb(X509_STORE_CTX *ctx, - int (*verify_cb)(int, X509_STORE_CTX *)); - -OPENSSL_EXPORT X509_POLICY_TREE *X509_STORE_CTX_get0_policy_tree(X509_STORE_CTX *ctx); -OPENSSL_EXPORT int X509_STORE_CTX_get_explicit_policy(X509_STORE_CTX *ctx); - -OPENSSL_EXPORT X509_VERIFY_PARAM *X509_STORE_CTX_get0_param(X509_STORE_CTX *ctx); -OPENSSL_EXPORT void X509_STORE_CTX_set0_param(X509_STORE_CTX *ctx, X509_VERIFY_PARAM *param); -OPENSSL_EXPORT int X509_STORE_CTX_set_default(X509_STORE_CTX *ctx, const char *name); - -/* X509_VERIFY_PARAM functions */ - -OPENSSL_EXPORT X509_VERIFY_PARAM *X509_VERIFY_PARAM_new(void); -OPENSSL_EXPORT void X509_VERIFY_PARAM_free(X509_VERIFY_PARAM *param); -OPENSSL_EXPORT int X509_VERIFY_PARAM_inherit(X509_VERIFY_PARAM *to, - const X509_VERIFY_PARAM *from); -OPENSSL_EXPORT int X509_VERIFY_PARAM_set1(X509_VERIFY_PARAM *to, - const X509_VERIFY_PARAM *from); -OPENSSL_EXPORT int X509_VERIFY_PARAM_set1_name(X509_VERIFY_PARAM *param, const char *name); -OPENSSL_EXPORT int X509_VERIFY_PARAM_set_flags(X509_VERIFY_PARAM *param, unsigned long flags); -OPENSSL_EXPORT int X509_VERIFY_PARAM_clear_flags(X509_VERIFY_PARAM *param, - unsigned long flags); -OPENSSL_EXPORT unsigned long X509_VERIFY_PARAM_get_flags(X509_VERIFY_PARAM *param); -OPENSSL_EXPORT int X509_VERIFY_PARAM_set_purpose(X509_VERIFY_PARAM *param, int purpose); -OPENSSL_EXPORT int X509_VERIFY_PARAM_set_trust(X509_VERIFY_PARAM *param, int trust); -OPENSSL_EXPORT void X509_VERIFY_PARAM_set_depth(X509_VERIFY_PARAM *param, int depth); -OPENSSL_EXPORT void X509_VERIFY_PARAM_set_time(X509_VERIFY_PARAM *param, time_t t); -OPENSSL_EXPORT int X509_VERIFY_PARAM_add0_policy(X509_VERIFY_PARAM *param, - ASN1_OBJECT *policy); -OPENSSL_EXPORT int X509_VERIFY_PARAM_set1_policies(X509_VERIFY_PARAM *param, - STACK_OF(ASN1_OBJECT) *policies); - -OPENSSL_EXPORT int X509_VERIFY_PARAM_set1_host(X509_VERIFY_PARAM *param, - const char *name, size_t namelen); -OPENSSL_EXPORT int X509_VERIFY_PARAM_add1_host(X509_VERIFY_PARAM *param, - const char *name, - size_t namelen); -OPENSSL_EXPORT void X509_VERIFY_PARAM_set_hostflags(X509_VERIFY_PARAM *param, - unsigned int flags); -OPENSSL_EXPORT char *X509_VERIFY_PARAM_get0_peername(X509_VERIFY_PARAM *); -OPENSSL_EXPORT int X509_VERIFY_PARAM_set1_email(X509_VERIFY_PARAM *param, - const char *email, size_t emaillen); -OPENSSL_EXPORT int X509_VERIFY_PARAM_set1_ip(X509_VERIFY_PARAM *param, - const unsigned char *ip, size_t iplen); -OPENSSL_EXPORT int X509_VERIFY_PARAM_set1_ip_asc(X509_VERIFY_PARAM *param, const char *ipasc); - -OPENSSL_EXPORT int X509_VERIFY_PARAM_get_depth(const X509_VERIFY_PARAM *param); -OPENSSL_EXPORT const char *X509_VERIFY_PARAM_get0_name(const X509_VERIFY_PARAM *param); - -OPENSSL_EXPORT int X509_VERIFY_PARAM_add0_table(X509_VERIFY_PARAM *param); -OPENSSL_EXPORT int X509_VERIFY_PARAM_get_count(void); -OPENSSL_EXPORT const X509_VERIFY_PARAM *X509_VERIFY_PARAM_get0(int id); -OPENSSL_EXPORT const X509_VERIFY_PARAM *X509_VERIFY_PARAM_lookup(const char *name); -OPENSSL_EXPORT void X509_VERIFY_PARAM_table_cleanup(void); - -OPENSSL_EXPORT int X509_policy_check(X509_POLICY_TREE **ptree, int *pexplicit_policy, - STACK_OF(X509) *certs, - STACK_OF(ASN1_OBJECT) *policy_oids, - unsigned int flags); - -OPENSSL_EXPORT void X509_policy_tree_free(X509_POLICY_TREE *tree); - -OPENSSL_EXPORT int X509_policy_tree_level_count(const X509_POLICY_TREE *tree); -OPENSSL_EXPORT X509_POLICY_LEVEL * - X509_policy_tree_get0_level(const X509_POLICY_TREE *tree, int i); - -OPENSSL_EXPORT STACK_OF(X509_POLICY_NODE) * - X509_policy_tree_get0_policies(const X509_POLICY_TREE *tree); - -OPENSSL_EXPORT STACK_OF(X509_POLICY_NODE) * - X509_policy_tree_get0_user_policies(const X509_POLICY_TREE *tree); - -OPENSSL_EXPORT int X509_policy_level_node_count(X509_POLICY_LEVEL *level); - -OPENSSL_EXPORT X509_POLICY_NODE *X509_policy_level_get0_node(X509_POLICY_LEVEL *level, int i); - -OPENSSL_EXPORT const ASN1_OBJECT *X509_policy_node_get0_policy(const X509_POLICY_NODE *node); - -OPENSSL_EXPORT STACK_OF(POLICYQUALINFO) * - X509_policy_node_get0_qualifiers(const X509_POLICY_NODE *node); -OPENSSL_EXPORT const X509_POLICY_NODE * - X509_policy_node_get0_parent(const X509_POLICY_NODE *node); - -#ifdef __cplusplus -} -#endif -#endif - diff --git a/third_party/boringssl/include/openssl/x509v3.h b/third_party/boringssl/include/openssl/x509v3.h deleted file mode 100644 index 5caa5c1f4e..0000000000 --- a/third_party/boringssl/include/openssl/x509v3.h +++ /dev/null @@ -1,855 +0,0 @@ -/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL - * project 1999. */ -/* ==================================================================== - * Copyright (c) 1999-2004 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * licensing@OpenSSL.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS 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. - * ==================================================================== - * - * This product includes cryptographic software written by Eric Young - * (eay@cryptsoft.com). This product includes software written by Tim - * Hudson (tjh@cryptsoft.com). */ - -#ifndef HEADER_X509V3_H -#define HEADER_X509V3_H - -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* Forward reference */ -struct v3_ext_method; -struct v3_ext_ctx; - -/* Useful typedefs */ - -typedef void * (*X509V3_EXT_NEW)(void); -typedef void (*X509V3_EXT_FREE)(void *); -typedef void * (*X509V3_EXT_D2I)(void *, const unsigned char ** , long); -typedef int (*X509V3_EXT_I2D)(void *, unsigned char **); -typedef STACK_OF(CONF_VALUE) * - (*X509V3_EXT_I2V)(const struct v3_ext_method *method, void *ext, - STACK_OF(CONF_VALUE) *extlist); -typedef void * (*X509V3_EXT_V2I)(const struct v3_ext_method *method, - struct v3_ext_ctx *ctx, - STACK_OF(CONF_VALUE) *values); -typedef char * (*X509V3_EXT_I2S)(const struct v3_ext_method *method, void *ext); -typedef void * (*X509V3_EXT_S2I)(const struct v3_ext_method *method, - struct v3_ext_ctx *ctx, const char *str); -typedef int (*X509V3_EXT_I2R)(const struct v3_ext_method *method, void *ext, - BIO *out, int indent); -typedef void * (*X509V3_EXT_R2I)(const struct v3_ext_method *method, - struct v3_ext_ctx *ctx, const char *str); - -/* V3 extension structure */ - -struct v3_ext_method { -int ext_nid; -int ext_flags; -/* If this is set the following four fields are ignored */ -ASN1_ITEM_EXP *it; -/* Old style ASN1 calls */ -X509V3_EXT_NEW ext_new; -X509V3_EXT_FREE ext_free; -X509V3_EXT_D2I d2i; -X509V3_EXT_I2D i2d; - -/* The following pair is used for string extensions */ -X509V3_EXT_I2S i2s; -X509V3_EXT_S2I s2i; - -/* The following pair is used for multi-valued extensions */ -X509V3_EXT_I2V i2v; -X509V3_EXT_V2I v2i; - -/* The following are used for raw extensions */ -X509V3_EXT_I2R i2r; -X509V3_EXT_R2I r2i; - -void *usr_data; /* Any extension specific data */ -}; - -typedef struct X509V3_CONF_METHOD_st { -char * (*get_string)(void *db, char *section, char *value); -STACK_OF(CONF_VALUE) * (*get_section)(void *db, char *section); -void (*free_string)(void *db, char * string); -void (*free_section)(void *db, STACK_OF(CONF_VALUE) *section); -} X509V3_CONF_METHOD; - -/* Context specific info */ -struct v3_ext_ctx { -#define CTX_TEST 0x1 -int flags; -X509 *issuer_cert; -X509 *subject_cert; -X509_REQ *subject_req; -X509_CRL *crl; -const X509V3_CONF_METHOD *db_meth; -void *db; -/* Maybe more here */ -}; - -typedef struct v3_ext_method X509V3_EXT_METHOD; - -DECLARE_STACK_OF(X509V3_EXT_METHOD) - -/* ext_flags values */ -#define X509V3_EXT_DYNAMIC 0x1 -#define X509V3_EXT_CTX_DEP 0x2 -#define X509V3_EXT_MULTILINE 0x4 - -typedef BIT_STRING_BITNAME ENUMERATED_NAMES; - -typedef struct BASIC_CONSTRAINTS_st { -int ca; -ASN1_INTEGER *pathlen; -} BASIC_CONSTRAINTS; - - -typedef struct PKEY_USAGE_PERIOD_st { -ASN1_GENERALIZEDTIME *notBefore; -ASN1_GENERALIZEDTIME *notAfter; -} PKEY_USAGE_PERIOD; - -typedef struct otherName_st { -ASN1_OBJECT *type_id; -ASN1_TYPE *value; -} OTHERNAME; - -typedef struct EDIPartyName_st { - ASN1_STRING *nameAssigner; - ASN1_STRING *partyName; -} EDIPARTYNAME; - -typedef struct GENERAL_NAME_st { - -#define GEN_OTHERNAME 0 -#define GEN_EMAIL 1 -#define GEN_DNS 2 -#define GEN_X400 3 -#define GEN_DIRNAME 4 -#define GEN_EDIPARTY 5 -#define GEN_URI 6 -#define GEN_IPADD 7 -#define GEN_RID 8 - -int type; -union { - char *ptr; - OTHERNAME *otherName; /* otherName */ - ASN1_IA5STRING *rfc822Name; - ASN1_IA5STRING *dNSName; - ASN1_TYPE *x400Address; - X509_NAME *directoryName; - EDIPARTYNAME *ediPartyName; - ASN1_IA5STRING *uniformResourceIdentifier; - ASN1_OCTET_STRING *iPAddress; - ASN1_OBJECT *registeredID; - - /* Old names */ - ASN1_OCTET_STRING *ip; /* iPAddress */ - X509_NAME *dirn; /* dirn */ - ASN1_IA5STRING *ia5;/* rfc822Name, dNSName, uniformResourceIdentifier */ - ASN1_OBJECT *rid; /* registeredID */ - ASN1_TYPE *other; /* x400Address */ -} d; -} GENERAL_NAME; - -typedef STACK_OF(GENERAL_NAME) GENERAL_NAMES; - -typedef struct ACCESS_DESCRIPTION_st { - ASN1_OBJECT *method; - GENERAL_NAME *location; -} ACCESS_DESCRIPTION; - -typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS; - -typedef STACK_OF(ASN1_OBJECT) EXTENDED_KEY_USAGE; - -DECLARE_STACK_OF(GENERAL_NAME) -DECLARE_ASN1_SET_OF(GENERAL_NAME) - -DECLARE_STACK_OF(ACCESS_DESCRIPTION) -DECLARE_ASN1_SET_OF(ACCESS_DESCRIPTION) - -typedef struct DIST_POINT_NAME_st { -int type; -union { - GENERAL_NAMES *fullname; - STACK_OF(X509_NAME_ENTRY) *relativename; -} name; -/* If relativename then this contains the full distribution point name */ -X509_NAME *dpname; -} DIST_POINT_NAME; -/* All existing reasons */ -#define CRLDP_ALL_REASONS 0x807f - -#define CRL_REASON_NONE -1 -#define CRL_REASON_UNSPECIFIED 0 -#define CRL_REASON_KEY_COMPROMISE 1 -#define CRL_REASON_CA_COMPROMISE 2 -#define CRL_REASON_AFFILIATION_CHANGED 3 -#define CRL_REASON_SUPERSEDED 4 -#define CRL_REASON_CESSATION_OF_OPERATION 5 -#define CRL_REASON_CERTIFICATE_HOLD 6 -#define CRL_REASON_REMOVE_FROM_CRL 8 -#define CRL_REASON_PRIVILEGE_WITHDRAWN 9 -#define CRL_REASON_AA_COMPROMISE 10 - -struct DIST_POINT_st { -DIST_POINT_NAME *distpoint; -ASN1_BIT_STRING *reasons; -GENERAL_NAMES *CRLissuer; -int dp_reasons; -}; - -typedef STACK_OF(DIST_POINT) CRL_DIST_POINTS; - -DECLARE_STACK_OF(DIST_POINT) -DECLARE_ASN1_SET_OF(DIST_POINT) - -struct AUTHORITY_KEYID_st { -ASN1_OCTET_STRING *keyid; -GENERAL_NAMES *issuer; -ASN1_INTEGER *serial; -}; - -/* Strong extranet structures */ - -typedef struct SXNET_ID_st { - ASN1_INTEGER *zone; - ASN1_OCTET_STRING *user; -} SXNETID; - -DECLARE_STACK_OF(SXNETID) -DECLARE_ASN1_SET_OF(SXNETID) - -typedef struct SXNET_st { - ASN1_INTEGER *version; - STACK_OF(SXNETID) *ids; -} SXNET; - -typedef struct NOTICEREF_st { - ASN1_STRING *organization; - STACK_OF(ASN1_INTEGER) *noticenos; -} NOTICEREF; - -typedef struct USERNOTICE_st { - NOTICEREF *noticeref; - ASN1_STRING *exptext; -} USERNOTICE; - -typedef struct POLICYQUALINFO_st { - ASN1_OBJECT *pqualid; - union { - ASN1_IA5STRING *cpsuri; - USERNOTICE *usernotice; - ASN1_TYPE *other; - } d; -} POLICYQUALINFO; - -DECLARE_STACK_OF(POLICYQUALINFO) -DECLARE_ASN1_SET_OF(POLICYQUALINFO) - -typedef struct POLICYINFO_st { - ASN1_OBJECT *policyid; - STACK_OF(POLICYQUALINFO) *qualifiers; -} POLICYINFO; - -typedef STACK_OF(POLICYINFO) CERTIFICATEPOLICIES; - -DECLARE_STACK_OF(POLICYINFO) -DECLARE_ASN1_SET_OF(POLICYINFO) - -typedef struct POLICY_MAPPING_st { - ASN1_OBJECT *issuerDomainPolicy; - ASN1_OBJECT *subjectDomainPolicy; -} POLICY_MAPPING; - -DECLARE_STACK_OF(POLICY_MAPPING) - -typedef STACK_OF(POLICY_MAPPING) POLICY_MAPPINGS; - -typedef struct GENERAL_SUBTREE_st { - GENERAL_NAME *base; - ASN1_INTEGER *minimum; - ASN1_INTEGER *maximum; -} GENERAL_SUBTREE; - -DECLARE_STACK_OF(GENERAL_SUBTREE) - -struct NAME_CONSTRAINTS_st { - STACK_OF(GENERAL_SUBTREE) *permittedSubtrees; - STACK_OF(GENERAL_SUBTREE) *excludedSubtrees; -}; - -typedef struct POLICY_CONSTRAINTS_st { - ASN1_INTEGER *requireExplicitPolicy; - ASN1_INTEGER *inhibitPolicyMapping; -} POLICY_CONSTRAINTS; - -/* Proxy certificate structures, see RFC 3820 */ -typedef struct PROXY_POLICY_st - { - ASN1_OBJECT *policyLanguage; - ASN1_OCTET_STRING *policy; - } PROXY_POLICY; - -typedef struct PROXY_CERT_INFO_EXTENSION_st - { - ASN1_INTEGER *pcPathLengthConstraint; - PROXY_POLICY *proxyPolicy; - } PROXY_CERT_INFO_EXTENSION; - -DECLARE_ASN1_FUNCTIONS(PROXY_POLICY) -DECLARE_ASN1_FUNCTIONS(PROXY_CERT_INFO_EXTENSION) - -struct ISSUING_DIST_POINT_st - { - DIST_POINT_NAME *distpoint; - int onlyuser; - int onlyCA; - ASN1_BIT_STRING *onlysomereasons; - int indirectCRL; - int onlyattr; - }; - -/* Values in idp_flags field */ -/* IDP present */ -#define IDP_PRESENT 0x1 -/* IDP values inconsistent */ -#define IDP_INVALID 0x2 -/* onlyuser true */ -#define IDP_ONLYUSER 0x4 -/* onlyCA true */ -#define IDP_ONLYCA 0x8 -/* onlyattr true */ -#define IDP_ONLYATTR 0x10 -/* indirectCRL true */ -#define IDP_INDIRECT 0x20 -/* onlysomereasons present */ -#define IDP_REASONS 0x40 - -#define X509V3_conf_err(val) ERR_add_error_data(6, "section:", val->section, \ -",name:", val->name, ",value:", val->value); - -#define X509V3_set_ctx_test(ctx) \ - X509V3_set_ctx(ctx, NULL, NULL, NULL, NULL, CTX_TEST) -#define X509V3_set_ctx_nodb(ctx) (ctx)->db = NULL; - -#define EXT_BITSTRING(nid, table) { nid, 0, ASN1_ITEM_ref(ASN1_BIT_STRING), \ - 0,0,0,0, \ - 0,0, \ - (X509V3_EXT_I2V)i2v_ASN1_BIT_STRING, \ - (X509V3_EXT_V2I)v2i_ASN1_BIT_STRING, \ - NULL, NULL, \ - (void *)table} - -#define EXT_IA5STRING(nid) { nid, 0, ASN1_ITEM_ref(ASN1_IA5STRING), \ - 0,0,0,0, \ - (X509V3_EXT_I2S)i2s_ASN1_IA5STRING, \ - (X509V3_EXT_S2I)s2i_ASN1_IA5STRING, \ - 0,0,0,0, \ - NULL} - -#define EXT_END { -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} - - -/* X509_PURPOSE stuff */ - -#define EXFLAG_BCONS 0x1 -#define EXFLAG_KUSAGE 0x2 -#define EXFLAG_XKUSAGE 0x4 -#define EXFLAG_NSCERT 0x8 - -#define EXFLAG_CA 0x10 -/* Really self issued not necessarily self signed */ -#define EXFLAG_SI 0x20 -#define EXFLAG_V1 0x40 -#define EXFLAG_INVALID 0x80 -#define EXFLAG_SET 0x100 -#define EXFLAG_CRITICAL 0x200 -#define EXFLAG_PROXY 0x400 - -#define EXFLAG_INVALID_POLICY 0x800 -#define EXFLAG_FRESHEST 0x1000 -/* Self signed */ -#define EXFLAG_SS 0x2000 - -#define KU_DIGITAL_SIGNATURE 0x0080 -#define KU_NON_REPUDIATION 0x0040 -#define KU_KEY_ENCIPHERMENT 0x0020 -#define KU_DATA_ENCIPHERMENT 0x0010 -#define KU_KEY_AGREEMENT 0x0008 -#define KU_KEY_CERT_SIGN 0x0004 -#define KU_CRL_SIGN 0x0002 -#define KU_ENCIPHER_ONLY 0x0001 -#define KU_DECIPHER_ONLY 0x8000 - -#define NS_SSL_CLIENT 0x80 -#define NS_SSL_SERVER 0x40 -#define NS_SMIME 0x20 -#define NS_OBJSIGN 0x10 -#define NS_SSL_CA 0x04 -#define NS_SMIME_CA 0x02 -#define NS_OBJSIGN_CA 0x01 -#define NS_ANY_CA (NS_SSL_CA|NS_SMIME_CA|NS_OBJSIGN_CA) - -#define XKU_SSL_SERVER 0x1 -#define XKU_SSL_CLIENT 0x2 -#define XKU_SMIME 0x4 -#define XKU_CODE_SIGN 0x8 -#define XKU_SGC 0x10 -#define XKU_OCSP_SIGN 0x20 -#define XKU_TIMESTAMP 0x40 -#define XKU_DVCS 0x80 -#define XKU_ANYEKU 0x100 - -#define X509_PURPOSE_DYNAMIC 0x1 -#define X509_PURPOSE_DYNAMIC_NAME 0x2 - -typedef struct x509_purpose_st { - int purpose; - int trust; /* Default trust ID */ - int flags; - int (*check_purpose)(const struct x509_purpose_st *, - const X509 *, int); - char *name; - char *sname; - void *usr_data; -} X509_PURPOSE; - -#define X509_PURPOSE_SSL_CLIENT 1 -#define X509_PURPOSE_SSL_SERVER 2 -#define X509_PURPOSE_NS_SSL_SERVER 3 -#define X509_PURPOSE_SMIME_SIGN 4 -#define X509_PURPOSE_SMIME_ENCRYPT 5 -#define X509_PURPOSE_CRL_SIGN 6 -#define X509_PURPOSE_ANY 7 -#define X509_PURPOSE_OCSP_HELPER 8 -#define X509_PURPOSE_TIMESTAMP_SIGN 9 - -#define X509_PURPOSE_MIN 1 -#define X509_PURPOSE_MAX 9 - -/* Flags for X509V3_EXT_print() */ - -#define X509V3_EXT_UNKNOWN_MASK (0xfL << 16) -/* Return error for unknown extensions */ -#define X509V3_EXT_DEFAULT 0 -/* Print error for unknown extensions */ -#define X509V3_EXT_ERROR_UNKNOWN (1L << 16) -/* ASN1 parse unknown extensions */ -#define X509V3_EXT_PARSE_UNKNOWN (2L << 16) -/* BIO_dump unknown extensions */ -#define X509V3_EXT_DUMP_UNKNOWN (3L << 16) - -/* Flags for X509V3_add1_i2d */ - -#define X509V3_ADD_OP_MASK 0xfL -#define X509V3_ADD_DEFAULT 0L -#define X509V3_ADD_APPEND 1L -#define X509V3_ADD_REPLACE 2L -#define X509V3_ADD_REPLACE_EXISTING 3L -#define X509V3_ADD_KEEP_EXISTING 4L -#define X509V3_ADD_DELETE 5L -#define X509V3_ADD_SILENT 0x10 - -DECLARE_STACK_OF(X509_PURPOSE) - -DECLARE_ASN1_FUNCTIONS(BASIC_CONSTRAINTS) - -DECLARE_ASN1_FUNCTIONS(SXNET) -DECLARE_ASN1_FUNCTIONS(SXNETID) - -int SXNET_add_id_asc(SXNET **psx, char *zone, char *user, int userlen); -int SXNET_add_id_ulong(SXNET **psx, unsigned long lzone, char *user, int userlen); -int SXNET_add_id_INTEGER(SXNET **psx, ASN1_INTEGER *izone, char *user, int userlen); - -ASN1_OCTET_STRING *SXNET_get_id_asc(SXNET *sx, char *zone); -ASN1_OCTET_STRING *SXNET_get_id_ulong(SXNET *sx, unsigned long lzone); -ASN1_OCTET_STRING *SXNET_get_id_INTEGER(SXNET *sx, ASN1_INTEGER *zone); - -DECLARE_ASN1_FUNCTIONS(AUTHORITY_KEYID) - -DECLARE_ASN1_FUNCTIONS(PKEY_USAGE_PERIOD) - -DECLARE_ASN1_FUNCTIONS(GENERAL_NAME) -OPENSSL_EXPORT GENERAL_NAME *GENERAL_NAME_dup(GENERAL_NAME *a); -OPENSSL_EXPORT int GENERAL_NAME_cmp(GENERAL_NAME *a, GENERAL_NAME *b); - - - -OPENSSL_EXPORT ASN1_BIT_STRING *v2i_ASN1_BIT_STRING(X509V3_EXT_METHOD *method, - X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval); -OPENSSL_EXPORT STACK_OF(CONF_VALUE) *i2v_ASN1_BIT_STRING(X509V3_EXT_METHOD *method, - ASN1_BIT_STRING *bits, - STACK_OF(CONF_VALUE) *extlist); - -OPENSSL_EXPORT STACK_OF(CONF_VALUE) *i2v_GENERAL_NAME(X509V3_EXT_METHOD *method, GENERAL_NAME *gen, STACK_OF(CONF_VALUE) *ret); -OPENSSL_EXPORT int GENERAL_NAME_print(BIO *out, GENERAL_NAME *gen); - -DECLARE_ASN1_FUNCTIONS(GENERAL_NAMES) - -OPENSSL_EXPORT STACK_OF(CONF_VALUE) *i2v_GENERAL_NAMES(X509V3_EXT_METHOD *method, - GENERAL_NAMES *gen, STACK_OF(CONF_VALUE) *extlist); -OPENSSL_EXPORT GENERAL_NAMES *v2i_GENERAL_NAMES(const X509V3_EXT_METHOD *method, - X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval); - -DECLARE_ASN1_FUNCTIONS(OTHERNAME) -DECLARE_ASN1_FUNCTIONS(EDIPARTYNAME) -OPENSSL_EXPORT int OTHERNAME_cmp(OTHERNAME *a, OTHERNAME *b); -OPENSSL_EXPORT void GENERAL_NAME_set0_value(GENERAL_NAME *a, int type, void *value); -OPENSSL_EXPORT void *GENERAL_NAME_get0_value(GENERAL_NAME *a, int *ptype); -OPENSSL_EXPORT int GENERAL_NAME_set0_othername(GENERAL_NAME *gen, - ASN1_OBJECT *oid, ASN1_TYPE *value); -OPENSSL_EXPORT int GENERAL_NAME_get0_otherName(GENERAL_NAME *gen, - ASN1_OBJECT **poid, ASN1_TYPE **pvalue); - -OPENSSL_EXPORT char *i2s_ASN1_OCTET_STRING(X509V3_EXT_METHOD *method, ASN1_OCTET_STRING *ia5); -OPENSSL_EXPORT ASN1_OCTET_STRING *s2i_ASN1_OCTET_STRING(X509V3_EXT_METHOD *method, X509V3_CTX *ctx, char *str); - -DECLARE_ASN1_FUNCTIONS(EXTENDED_KEY_USAGE) -OPENSSL_EXPORT int i2a_ACCESS_DESCRIPTION(BIO *bp, ACCESS_DESCRIPTION* a); - -DECLARE_ASN1_FUNCTIONS(CERTIFICATEPOLICIES) -DECLARE_ASN1_FUNCTIONS(POLICYINFO) -DECLARE_ASN1_FUNCTIONS(POLICYQUALINFO) -DECLARE_ASN1_FUNCTIONS(USERNOTICE) -DECLARE_ASN1_FUNCTIONS(NOTICEREF) - -DECLARE_ASN1_FUNCTIONS(CRL_DIST_POINTS) -DECLARE_ASN1_FUNCTIONS(DIST_POINT) -DECLARE_ASN1_FUNCTIONS(DIST_POINT_NAME) -DECLARE_ASN1_FUNCTIONS(ISSUING_DIST_POINT) - -OPENSSL_EXPORT int DIST_POINT_set_dpname(DIST_POINT_NAME *dpn, X509_NAME *iname); - -OPENSSL_EXPORT int NAME_CONSTRAINTS_check(X509 *x, NAME_CONSTRAINTS *nc); - -DECLARE_ASN1_FUNCTIONS(ACCESS_DESCRIPTION) -DECLARE_ASN1_FUNCTIONS(AUTHORITY_INFO_ACCESS) - -DECLARE_ASN1_ITEM(POLICY_MAPPING) -DECLARE_ASN1_ALLOC_FUNCTIONS(POLICY_MAPPING) -DECLARE_ASN1_ITEM(POLICY_MAPPINGS) - -DECLARE_ASN1_ITEM(GENERAL_SUBTREE) -DECLARE_ASN1_ALLOC_FUNCTIONS(GENERAL_SUBTREE) - -DECLARE_ASN1_ITEM(NAME_CONSTRAINTS) -DECLARE_ASN1_ALLOC_FUNCTIONS(NAME_CONSTRAINTS) - -DECLARE_ASN1_ALLOC_FUNCTIONS(POLICY_CONSTRAINTS) -DECLARE_ASN1_ITEM(POLICY_CONSTRAINTS) - -OPENSSL_EXPORT GENERAL_NAME *a2i_GENERAL_NAME(GENERAL_NAME *out, - const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, - int gen_type, char *value, int is_nc); - -OPENSSL_EXPORT GENERAL_NAME *v2i_GENERAL_NAME(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, - CONF_VALUE *cnf); -OPENSSL_EXPORT GENERAL_NAME *v2i_GENERAL_NAME_ex(GENERAL_NAME *out, - const X509V3_EXT_METHOD *method, - X509V3_CTX *ctx, CONF_VALUE *cnf, int is_nc); -OPENSSL_EXPORT void X509V3_conf_free(CONF_VALUE *val); - -OPENSSL_EXPORT X509_EXTENSION *X509V3_EXT_nconf_nid(CONF *conf, X509V3_CTX *ctx, int ext_nid, char *value); -OPENSSL_EXPORT X509_EXTENSION *X509V3_EXT_nconf(CONF *conf, X509V3_CTX *ctx, char *name, char *value); -OPENSSL_EXPORT int X509V3_EXT_add_nconf_sk(CONF *conf, X509V3_CTX *ctx, char *section, STACK_OF(X509_EXTENSION) **sk); -OPENSSL_EXPORT int X509V3_EXT_add_nconf(CONF *conf, X509V3_CTX *ctx, char *section, X509 *cert); -OPENSSL_EXPORT int X509V3_EXT_REQ_add_nconf(CONF *conf, X509V3_CTX *ctx, char *section, X509_REQ *req); -OPENSSL_EXPORT int X509V3_EXT_CRL_add_nconf(CONF *conf, X509V3_CTX *ctx, char *section, X509_CRL *crl); - -OPENSSL_EXPORT int X509V3_EXT_CRL_add_conf(LHASH_OF(CONF_VALUE) *conf, X509V3_CTX *ctx, - char *section, X509_CRL *crl); - -OPENSSL_EXPORT int X509V3_add_value_bool_nf(char *name, int asn1_bool, - STACK_OF(CONF_VALUE) **extlist); -OPENSSL_EXPORT int X509V3_get_value_bool(CONF_VALUE *value, int *asn1_bool); -OPENSSL_EXPORT int X509V3_get_value_int(CONF_VALUE *value, ASN1_INTEGER **aint); -OPENSSL_EXPORT void X509V3_set_nconf(X509V3_CTX *ctx, CONF *conf); - -OPENSSL_EXPORT char * X509V3_get_string(X509V3_CTX *ctx, char *name, char *section); -OPENSSL_EXPORT STACK_OF(CONF_VALUE) * X509V3_get_section(X509V3_CTX *ctx, char *section); -OPENSSL_EXPORT void X509V3_string_free(X509V3_CTX *ctx, char *str); -OPENSSL_EXPORT void X509V3_section_free( X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *section); -OPENSSL_EXPORT void X509V3_set_ctx(X509V3_CTX *ctx, X509 *issuer, X509 *subject, - X509_REQ *req, X509_CRL *crl, int flags); - -OPENSSL_EXPORT int X509V3_add_value(const char *name, const char *value, - STACK_OF(CONF_VALUE) **extlist); -OPENSSL_EXPORT int X509V3_add_value_uchar(const char *name, const unsigned char *value, - STACK_OF(CONF_VALUE) **extlist); -OPENSSL_EXPORT int X509V3_add_value_bool(const char *name, int asn1_bool, - STACK_OF(CONF_VALUE) **extlist); -OPENSSL_EXPORT int X509V3_add_value_int(const char *name, ASN1_INTEGER *aint, - STACK_OF(CONF_VALUE) **extlist); -OPENSSL_EXPORT char * i2s_ASN1_INTEGER(X509V3_EXT_METHOD *meth, ASN1_INTEGER *aint); -OPENSSL_EXPORT ASN1_INTEGER * s2i_ASN1_INTEGER(X509V3_EXT_METHOD *meth, char *value); -OPENSSL_EXPORT char * i2s_ASN1_ENUMERATED(X509V3_EXT_METHOD *meth, ASN1_ENUMERATED *aint); -OPENSSL_EXPORT char * i2s_ASN1_ENUMERATED_TABLE(X509V3_EXT_METHOD *meth, ASN1_ENUMERATED *aint); -OPENSSL_EXPORT int X509V3_EXT_add(X509V3_EXT_METHOD *ext); -OPENSSL_EXPORT int X509V3_EXT_add_list(X509V3_EXT_METHOD *extlist); -OPENSSL_EXPORT int X509V3_EXT_add_alias(int nid_to, int nid_from); -OPENSSL_EXPORT void X509V3_EXT_cleanup(void); - -OPENSSL_EXPORT const X509V3_EXT_METHOD *X509V3_EXT_get(X509_EXTENSION *ext); -OPENSSL_EXPORT const X509V3_EXT_METHOD *X509V3_EXT_get_nid(int nid); -OPENSSL_EXPORT int X509V3_add_standard_extensions(void); -OPENSSL_EXPORT STACK_OF(CONF_VALUE) *X509V3_parse_list(const char *line); -OPENSSL_EXPORT void *X509V3_EXT_d2i(X509_EXTENSION *ext); -OPENSSL_EXPORT void *X509V3_get_d2i(STACK_OF(X509_EXTENSION) *x, int nid, int *crit, int *idx); - - -OPENSSL_EXPORT X509_EXTENSION *X509V3_EXT_i2d(int ext_nid, int crit, void *ext_struc); -OPENSSL_EXPORT int X509V3_add1_i2d(STACK_OF(X509_EXTENSION) **x, int nid, void *value, int crit, unsigned long flags); - -char *hex_to_string(const unsigned char *buffer, long len); -unsigned char *string_to_hex(const char *str, long *len); -int name_cmp(const char *name, const char *cmp); - -OPENSSL_EXPORT void X509V3_EXT_val_prn(BIO *out, STACK_OF(CONF_VALUE) *val, int indent, - int ml); -OPENSSL_EXPORT int X509V3_EXT_print(BIO *out, X509_EXTENSION *ext, unsigned long flag, int indent); -OPENSSL_EXPORT int X509V3_EXT_print_fp(FILE *out, X509_EXTENSION *ext, int flag, int indent); - -OPENSSL_EXPORT int X509V3_extensions_print(BIO *out, const char *title, STACK_OF(X509_EXTENSION) *exts, unsigned long flag, int indent); - -OPENSSL_EXPORT int X509_check_ca(X509 *x); -OPENSSL_EXPORT int X509_check_purpose(X509 *x, int id, int ca); -OPENSSL_EXPORT int X509_supported_extension(X509_EXTENSION *ex); -OPENSSL_EXPORT int X509_PURPOSE_set(int *p, int purpose); -OPENSSL_EXPORT int X509_check_issued(X509 *issuer, X509 *subject); -OPENSSL_EXPORT int X509_check_akid(X509 *issuer, AUTHORITY_KEYID *akid); -OPENSSL_EXPORT int X509_PURPOSE_get_count(void); -OPENSSL_EXPORT X509_PURPOSE * X509_PURPOSE_get0(int idx); -OPENSSL_EXPORT int X509_PURPOSE_get_by_sname(char *sname); -OPENSSL_EXPORT int X509_PURPOSE_get_by_id(int id); -OPENSSL_EXPORT int X509_PURPOSE_add(int id, int trust, int flags, - int (*ck)(const X509_PURPOSE *, const X509 *, int), - char *name, char *sname, void *arg); -OPENSSL_EXPORT char *X509_PURPOSE_get0_name(X509_PURPOSE *xp); -OPENSSL_EXPORT char *X509_PURPOSE_get0_sname(X509_PURPOSE *xp); -OPENSSL_EXPORT int X509_PURPOSE_get_trust(X509_PURPOSE *xp); -OPENSSL_EXPORT void X509_PURPOSE_cleanup(void); -OPENSSL_EXPORT int X509_PURPOSE_get_id(X509_PURPOSE *); - -OPENSSL_EXPORT STACK_OF(OPENSSL_STRING) *X509_get1_email(X509 *x); -OPENSSL_EXPORT STACK_OF(OPENSSL_STRING) *X509_REQ_get1_email(X509_REQ *x); -OPENSSL_EXPORT void X509_email_free(STACK_OF(OPENSSL_STRING) *sk); -OPENSSL_EXPORT STACK_OF(OPENSSL_STRING) *X509_get1_ocsp(X509 *x); -/* Flags for X509_check_* functions */ - -/* Always check subject name for host match even if subject alt names present */ -#define X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT 0x1 -/* Disable wildcard matching for dnsName fields and common name. */ -#define X509_CHECK_FLAG_NO_WILDCARDS 0x2 -/* Wildcards must not match a partial label. */ -#define X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS 0x4 -/* Allow (non-partial) wildcards to match multiple labels. */ -#define X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS 0x8 -/* Constraint verifier subdomain patterns to match a single labels. */ -#define X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS 0x10 -/* - * Match reference identifiers starting with "." to any sub-domain. - * This is a non-public flag, turned on implicitly when the subject - * reference identity is a DNS name. - */ -#define _X509_CHECK_FLAG_DOT_SUBDOMAINS 0x8000 - -OPENSSL_EXPORT int X509_check_host(X509 *x, const char *chk, size_t chklen, - unsigned int flags, char **peername); -OPENSSL_EXPORT int X509_check_email(X509 *x, const char *chk, size_t chklen, - unsigned int flags); -OPENSSL_EXPORT int X509_check_ip(X509 *x, const unsigned char *chk, size_t chklen, - unsigned int flags); -OPENSSL_EXPORT int X509_check_ip_asc(X509 *x, const char *ipasc, unsigned int flags); - -OPENSSL_EXPORT ASN1_OCTET_STRING *a2i_IPADDRESS(const char *ipasc); -OPENSSL_EXPORT ASN1_OCTET_STRING *a2i_IPADDRESS_NC(const char *ipasc); -OPENSSL_EXPORT int a2i_ipadd(unsigned char *ipout, const char *ipasc); -OPENSSL_EXPORT int X509V3_NAME_from_section(X509_NAME *nm, STACK_OF(CONF_VALUE)*dn_sk, - unsigned long chtype); - -OPENSSL_EXPORT void X509_POLICY_NODE_print(BIO *out, X509_POLICY_NODE *node, int indent); -DECLARE_STACK_OF(X509_POLICY_NODE) - -/* BEGIN ERROR CODES */ -/* The following lines are auto generated by the script mkerr.pl. Any changes - * made after this point may be overwritten when the script is next run. - */ -void ERR_load_X509V3_strings(void); - - -#ifdef __cplusplus -} -#endif -#define X509V3_F_SXNET_add_id_INTEGER 100 -#define X509V3_F_SXNET_add_id_asc 101 -#define X509V3_F_SXNET_add_id_ulong 102 -#define X509V3_F_SXNET_get_id_asc 103 -#define X509V3_F_SXNET_get_id_ulong 104 -#define X509V3_F_X509V3_EXT_add 105 -#define X509V3_F_X509V3_EXT_add_alias 106 -#define X509V3_F_X509V3_EXT_free 107 -#define X509V3_F_X509V3_EXT_i2d 108 -#define X509V3_F_X509V3_EXT_nconf 109 -#define X509V3_F_X509V3_add1_i2d 110 -#define X509V3_F_X509V3_add_value 111 -#define X509V3_F_X509V3_get_section 112 -#define X509V3_F_X509V3_get_string 113 -#define X509V3_F_X509V3_get_value_bool 114 -#define X509V3_F_X509V3_parse_list 115 -#define X509V3_F_X509_PURPOSE_add 116 -#define X509V3_F_X509_PURPOSE_set 117 -#define X509V3_F_a2i_GENERAL_NAME 118 -#define X509V3_F_copy_email 119 -#define X509V3_F_copy_issuer 120 -#define X509V3_F_do_dirname 121 -#define X509V3_F_do_ext_i2d 122 -#define X509V3_F_do_ext_nconf 123 -#define X509V3_F_gnames_from_sectname 124 -#define X509V3_F_hex_to_string 125 -#define X509V3_F_i2s_ASN1_ENUMERATED 126 -#define X509V3_F_i2s_ASN1_IA5STRING 127 -#define X509V3_F_i2s_ASN1_INTEGER 128 -#define X509V3_F_i2v_AUTHORITY_INFO_ACCESS 129 -#define X509V3_F_notice_section 130 -#define X509V3_F_nref_nos 131 -#define X509V3_F_policy_section 132 -#define X509V3_F_process_pci_value 133 -#define X509V3_F_r2i_certpol 134 -#define X509V3_F_r2i_pci 135 -#define X509V3_F_s2i_ASN1_IA5STRING 136 -#define X509V3_F_s2i_ASN1_INTEGER 137 -#define X509V3_F_s2i_ASN1_OCTET_STRING 138 -#define X509V3_F_s2i_skey_id 139 -#define X509V3_F_set_dist_point_name 140 -#define X509V3_F_string_to_hex 141 -#define X509V3_F_v2i_ASN1_BIT_STRING 142 -#define X509V3_F_v2i_AUTHORITY_INFO_ACCESS 143 -#define X509V3_F_v2i_AUTHORITY_KEYID 144 -#define X509V3_F_v2i_BASIC_CONSTRAINTS 145 -#define X509V3_F_v2i_EXTENDED_KEY_USAGE 146 -#define X509V3_F_v2i_GENERAL_NAMES 147 -#define X509V3_F_v2i_GENERAL_NAME_ex 148 -#define X509V3_F_v2i_NAME_CONSTRAINTS 149 -#define X509V3_F_v2i_POLICY_CONSTRAINTS 150 -#define X509V3_F_v2i_POLICY_MAPPINGS 151 -#define X509V3_F_v2i_crld 152 -#define X509V3_F_v2i_idp 153 -#define X509V3_F_v2i_issuer_alt 154 -#define X509V3_F_v2i_subject_alt 155 -#define X509V3_F_v3_generic_extension 156 -#define X509V3_R_BAD_IP_ADDRESS 100 -#define X509V3_R_BAD_OBJECT 101 -#define X509V3_R_BN_DEC2BN_ERROR 102 -#define X509V3_R_BN_TO_ASN1_INTEGER_ERROR 103 -#define X509V3_R_CANNOT_FIND_FREE_FUNCTION 104 -#define X509V3_R_DIRNAME_ERROR 105 -#define X509V3_R_DISTPOINT_ALREADY_SET 106 -#define X509V3_R_DUPLICATE_ZONE_ID 107 -#define X509V3_R_ERROR_CONVERTING_ZONE 108 -#define X509V3_R_ERROR_CREATING_EXTENSION 109 -#define X509V3_R_ERROR_IN_EXTENSION 110 -#define X509V3_R_EXPECTED_A_SECTION_NAME 111 -#define X509V3_R_EXTENSION_EXISTS 112 -#define X509V3_R_EXTENSION_NAME_ERROR 113 -#define X509V3_R_EXTENSION_NOT_FOUND 114 -#define X509V3_R_EXTENSION_SETTING_NOT_SUPPORTED 115 -#define X509V3_R_EXTENSION_VALUE_ERROR 116 -#define X509V3_R_ILLEGAL_EMPTY_EXTENSION 117 -#define X509V3_R_ILLEGAL_HEX_DIGIT 118 -#define X509V3_R_INCORRECT_POLICY_SYNTAX_TAG 119 -#define X509V3_R_INVALID_BOOLEAN_STRING 120 -#define X509V3_R_INVALID_EXTENSION_STRING 121 -#define X509V3_R_INVALID_MULTIPLE_RDNS 122 -#define X509V3_R_INVALID_NAME 123 -#define X509V3_R_INVALID_NULL_ARGUMENT 124 -#define X509V3_R_INVALID_NULL_NAME 125 -#define X509V3_R_INVALID_NULL_VALUE 126 -#define X509V3_R_INVALID_NUMBER 127 -#define X509V3_R_INVALID_NUMBERS 128 -#define X509V3_R_INVALID_OBJECT_IDENTIFIER 129 -#define X509V3_R_INVALID_OPTION 130 -#define X509V3_R_INVALID_POLICY_IDENTIFIER 131 -#define X509V3_R_INVALID_PROXY_POLICY_SETTING 132 -#define X509V3_R_INVALID_PURPOSE 133 -#define X509V3_R_INVALID_SECTION 134 -#define X509V3_R_INVALID_SYNTAX 135 -#define X509V3_R_ISSUER_DECODE_ERROR 136 -#define X509V3_R_MISSING_VALUE 137 -#define X509V3_R_NEED_ORGANIZATION_AND_NUMBERS 138 -#define X509V3_R_NO_CONFIG_DATABASE 139 -#define X509V3_R_NO_ISSUER_CERTIFICATE 140 -#define X509V3_R_NO_ISSUER_DETAILS 141 -#define X509V3_R_NO_POLICY_IDENTIFIER 142 -#define X509V3_R_NO_PROXY_CERT_POLICY_LANGUAGE_DEFINED 143 -#define X509V3_R_NO_PUBLIC_KEY 144 -#define X509V3_R_NO_SUBJECT_DETAILS 145 -#define X509V3_R_ODD_NUMBER_OF_DIGITS 146 -#define X509V3_R_OPERATION_NOT_DEFINED 147 -#define X509V3_R_OTHERNAME_ERROR 148 -#define X509V3_R_POLICY_LANGUAGE_ALREADY_DEFINED 149 -#define X509V3_R_POLICY_PATH_LENGTH 150 -#define X509V3_R_POLICY_PATH_LENGTH_ALREADY_DEFINED 151 -#define X509V3_R_POLICY_WHEN_PROXY_LANGUAGE_REQUIRES_NO_POLICY 152 -#define X509V3_R_SECTION_NOT_FOUND 153 -#define X509V3_R_UNABLE_TO_GET_ISSUER_DETAILS 154 -#define X509V3_R_UNABLE_TO_GET_ISSUER_KEYID 155 -#define X509V3_R_UNKNOWN_BIT_STRING_ARGUMENT 156 -#define X509V3_R_UNKNOWN_EXTENSION 157 -#define X509V3_R_UNKNOWN_EXTENSION_NAME 158 -#define X509V3_R_UNKNOWN_OPTION 159 -#define X509V3_R_UNSUPPORTED_OPTION 160 -#define X509V3_R_UNSUPPORTED_TYPE 161 -#define X509V3_R_USER_TOO_LONG 162 - -#endif diff --git a/third_party/boringssl/lib/libssl_static.a b/third_party/boringssl/lib/libssl_static.a deleted file mode 100644 index b6c52d03a0..0000000000 Binary files a/third_party/boringssl/lib/libssl_static.a and /dev/null differ diff --git a/third_party/bzip2/LICENSE b/third_party/bzip2/LICENSE deleted file mode 100644 index cc614178cf..0000000000 --- a/third_party/bzip2/LICENSE +++ /dev/null @@ -1,42 +0,0 @@ - --------------------------------------------------------------------------- - -This program, "bzip2", the associated library "libbzip2", and all -documentation, are copyright (C) 1996-2010 Julian R Seward. All -rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -2. The origin of this software must not be misrepresented; you must - not claim that you wrote the original software. If you use this - software in a product, an acknowledgment in the product - documentation would be appreciated but is not required. - -3. Altered source versions must be plainly marked as such, and must - not be misrepresented as being the original software. - -4. The name of the author may not be used to endorse or promote - products derived from this software without specific prior written - permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS -OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. - -Julian Seward, jseward@bzip.org -bzip2/libbzip2 version 1.0.6 of 6 September 2010 - --------------------------------------------------------------------------- diff --git a/third_party/bzip2/build.txt b/third_party/bzip2/build.txt deleted file mode 100644 index ceb3226210..0000000000 --- a/third_party/bzip2/build.txt +++ /dev/null @@ -1,6 +0,0 @@ -git clone https://github.com/enthought/bzip2-1.0.6.git -cd bzip2-1.0.6 -git reset --hard 288acf97a15d558f96c24c89f578b724d6e06b0c - -make libbz2.a -cp libbz2.a ../ diff --git a/third_party/bzip2/bzlib.h b/third_party/bzip2/bzlib.h deleted file mode 100644 index 8277123da8..0000000000 --- a/third_party/bzip2/bzlib.h +++ /dev/null @@ -1,282 +0,0 @@ - -/*-------------------------------------------------------------*/ -/*--- Public header file for the library. ---*/ -/*--- bzlib.h ---*/ -/*-------------------------------------------------------------*/ - -/* ------------------------------------------------------------------ - This file is part of bzip2/libbzip2, a program and library for - lossless, block-sorting data compression. - - bzip2/libbzip2 version 1.0.6 of 6 September 2010 - Copyright (C) 1996-2010 Julian Seward - - Please read the WARNING, DISCLAIMER and PATENTS sections in the - README file. - - This program is released under the terms of the license contained - in the file LICENSE. - ------------------------------------------------------------------ */ - - -#ifndef _BZLIB_H -#define _BZLIB_H - -#ifdef __cplusplus -extern "C" { -#endif - -#define BZ_RUN 0 -#define BZ_FLUSH 1 -#define BZ_FINISH 2 - -#define BZ_OK 0 -#define BZ_RUN_OK 1 -#define BZ_FLUSH_OK 2 -#define BZ_FINISH_OK 3 -#define BZ_STREAM_END 4 -#define BZ_SEQUENCE_ERROR (-1) -#define BZ_PARAM_ERROR (-2) -#define BZ_MEM_ERROR (-3) -#define BZ_DATA_ERROR (-4) -#define BZ_DATA_ERROR_MAGIC (-5) -#define BZ_IO_ERROR (-6) -#define BZ_UNEXPECTED_EOF (-7) -#define BZ_OUTBUFF_FULL (-8) -#define BZ_CONFIG_ERROR (-9) - -typedef - struct { - char *next_in; - unsigned int avail_in; - unsigned int total_in_lo32; - unsigned int total_in_hi32; - - char *next_out; - unsigned int avail_out; - unsigned int total_out_lo32; - unsigned int total_out_hi32; - - void *state; - - void *(*bzalloc)(void *,int,int); - void (*bzfree)(void *,void *); - void *opaque; - } - bz_stream; - - -#ifndef BZ_IMPORT -#define BZ_EXPORT -#endif - -#ifndef BZ_NO_STDIO -/* Need a definitition for FILE */ -#include -#endif - -#ifdef _WIN32 -# include -# ifdef small - /* windows.h define small to char */ -# undef small -# endif -# ifdef BZ_EXPORT -# define BZ_API(func) WINAPI func -# define BZ_EXTERN extern -# else - /* import windows dll dynamically */ -# define BZ_API(func) (WINAPI * func) -# define BZ_EXTERN -# endif -#else -# define BZ_API(func) func -# define BZ_EXTERN extern -#endif - - -/*-- Core (low-level) library functions --*/ - -BZ_EXTERN int BZ_API(BZ2_bzCompressInit) ( - bz_stream* strm, - int blockSize100k, - int verbosity, - int workFactor - ); - -BZ_EXTERN int BZ_API(BZ2_bzCompress) ( - bz_stream* strm, - int action - ); - -BZ_EXTERN int BZ_API(BZ2_bzCompressEnd) ( - bz_stream* strm - ); - -BZ_EXTERN int BZ_API(BZ2_bzDecompressInit) ( - bz_stream *strm, - int verbosity, - int small - ); - -BZ_EXTERN int BZ_API(BZ2_bzDecompress) ( - bz_stream* strm - ); - -BZ_EXTERN int BZ_API(BZ2_bzDecompressEnd) ( - bz_stream *strm - ); - - - -/*-- High(er) level library functions --*/ - -#ifndef BZ_NO_STDIO -#define BZ_MAX_UNUSED 5000 - -typedef void BZFILE; - -BZ_EXTERN BZFILE* BZ_API(BZ2_bzReadOpen) ( - int* bzerror, - FILE* f, - int verbosity, - int small, - void* unused, - int nUnused - ); - -BZ_EXTERN void BZ_API(BZ2_bzReadClose) ( - int* bzerror, - BZFILE* b - ); - -BZ_EXTERN void BZ_API(BZ2_bzReadGetUnused) ( - int* bzerror, - BZFILE* b, - void** unused, - int* nUnused - ); - -BZ_EXTERN int BZ_API(BZ2_bzRead) ( - int* bzerror, - BZFILE* b, - void* buf, - int len - ); - -BZ_EXTERN BZFILE* BZ_API(BZ2_bzWriteOpen) ( - int* bzerror, - FILE* f, - int blockSize100k, - int verbosity, - int workFactor - ); - -BZ_EXTERN void BZ_API(BZ2_bzWrite) ( - int* bzerror, - BZFILE* b, - void* buf, - int len - ); - -BZ_EXTERN void BZ_API(BZ2_bzWriteClose) ( - int* bzerror, - BZFILE* b, - int abandon, - unsigned int* nbytes_in, - unsigned int* nbytes_out - ); - -BZ_EXTERN void BZ_API(BZ2_bzWriteClose64) ( - int* bzerror, - BZFILE* b, - int abandon, - unsigned int* nbytes_in_lo32, - unsigned int* nbytes_in_hi32, - unsigned int* nbytes_out_lo32, - unsigned int* nbytes_out_hi32 - ); -#endif - - -/*-- Utility functions --*/ - -BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffCompress) ( - char* dest, - unsigned int* destLen, - char* source, - unsigned int sourceLen, - int blockSize100k, - int verbosity, - int workFactor - ); - -BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffDecompress) ( - char* dest, - unsigned int* destLen, - char* source, - unsigned int sourceLen, - int small, - int verbosity - ); - - -/*-- - Code contributed by Yoshioka Tsuneo (tsuneo@rr.iij4u.or.jp) - to support better zlib compatibility. - This code is not _officially_ part of libbzip2 (yet); - I haven't tested it, documented it, or considered the - threading-safeness of it. - If this code breaks, please contact both Yoshioka and me. ---*/ - -BZ_EXTERN const char * BZ_API(BZ2_bzlibVersion) ( - void - ); - -#ifndef BZ_NO_STDIO -BZ_EXTERN BZFILE * BZ_API(BZ2_bzopen) ( - const char *path, - const char *mode - ); - -BZ_EXTERN BZFILE * BZ_API(BZ2_bzdopen) ( - int fd, - const char *mode - ); - -BZ_EXTERN int BZ_API(BZ2_bzread) ( - BZFILE* b, - void* buf, - int len - ); - -BZ_EXTERN int BZ_API(BZ2_bzwrite) ( - BZFILE* b, - void* buf, - int len - ); - -BZ_EXTERN int BZ_API(BZ2_bzflush) ( - BZFILE* b - ); - -BZ_EXTERN void BZ_API(BZ2_bzclose) ( - BZFILE* b - ); - -BZ_EXTERN const char * BZ_API(BZ2_bzerror) ( - BZFILE *b, - int *errnum - ); -#endif - -#ifdef __cplusplus -} -#endif - -#endif - -/*-------------------------------------------------------------*/ -/*--- end bzlib.h ---*/ -/*-------------------------------------------------------------*/ diff --git a/third_party/bzip2/libbz2.a b/third_party/bzip2/libbz2.a deleted file mode 100644 index 0efccceb17..0000000000 Binary files a/third_party/bzip2/libbz2.a and /dev/null differ diff --git a/third_party/catch2/include/catch2/catch.hpp b/third_party/catch2/include/catch2/catch.hpp index cf1fae15aa..d2a12427b2 100644 --- a/third_party/catch2/include/catch2/catch.hpp +++ b/third_party/catch2/include/catch2/catch.hpp @@ -1,9 +1,9 @@ /* - * Catch v2.13.0 - * Generated: 2020-07-12 20:07:49.015950 + * Catch v2.13.9 + * Generated: 2022-04-12 22:37:23.260201 * ---------------------------------------------------------- * This file has been merged from multiple headers. Please don't edit it directly - * Copyright (c) 2020 Two Blue Cubes Ltd. All rights reserved. + * Copyright (c) 2022 Two Blue Cubes Ltd. All rights reserved. * * Distributed under the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) @@ -15,7 +15,7 @@ #define CATCH_VERSION_MAJOR 2 #define CATCH_VERSION_MINOR 13 -#define CATCH_VERSION_PATCH 0 +#define CATCH_VERSION_PATCH 9 #ifdef __clang__ # pragma clang system_header @@ -66,13 +66,16 @@ #if !defined(CATCH_CONFIG_IMPL_ONLY) // start catch_platform.h +// See e.g.: +// https://opensource.apple.com/source/CarbonHeaders/CarbonHeaders-18.1/TargetConditionals.h.auto.html #ifdef __APPLE__ -# include -# if TARGET_OS_OSX == 1 -# define CATCH_PLATFORM_MAC -# elif TARGET_OS_IPHONE == 1 -# define CATCH_PLATFORM_IPHONE -# endif +# include +# if (defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1) || \ + (defined(TARGET_OS_MAC) && TARGET_OS_MAC == 1) +# define CATCH_PLATFORM_MAC +# elif (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1) +# define CATCH_PLATFORM_IPHONE +# endif #elif defined(linux) || defined(__linux) || defined(__linux__) # define CATCH_PLATFORM_LINUX @@ -132,13 +135,9 @@ namespace Catch { #endif -#if defined(__cpp_lib_uncaught_exceptions) -# define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS -#endif - -// We have to avoid both ICC and Clang, because they try to mask themselves -// as gcc, and we want only GCC in this block -#if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) +// Only GCC compiler should be used in this block, so other compilers trying to +// mask themselves as GCC should be ignored. +#if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__) && !defined(__LCC__) # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic push" ) # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic pop" ) @@ -162,7 +161,7 @@ namespace Catch { // ``` // // Therefore, `CATCH_INTERNAL_IGNORE_BUT_WARN` is not implemented. -# if !defined(__ibmxl__) +# if !defined(__ibmxl__) && !defined(__CUDACC__) # define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) /* NOLINT(cppcoreguidelines-pro-type-vararg, hicpp-vararg) */ # endif @@ -241,13 +240,6 @@ namespace Catch { // Visual C++ #if defined(_MSC_VER) -# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) ) -# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) ) - -# if _MSC_VER >= 1900 // Visual Studio 2015 or newer -# define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS -# endif - // Universal Windows platform does not support SEH // Or console colours (or console at all...) # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) @@ -256,13 +248,18 @@ namespace Catch { # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH # endif +# if !defined(__clang__) // Handle Clang masquerading for msvc + // MSVC traditional preprocessor needs some workaround for __VA_ARGS__ // _MSVC_TRADITIONAL == 0 means new conformant preprocessor // _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor -# if !defined(__clang__) // Handle Clang masquerading for msvc # if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL) # define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR # endif // MSVC_TRADITIONAL + +// Only do this if we're not using clang on Windows, which uses `diagnostic push` & `diagnostic pop` +# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) ) +# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) ) # endif // __clang__ #endif // _MSC_VER @@ -330,7 +327,10 @@ namespace Catch { // Check if byte is available and usable # if __has_include() && defined(CATCH_CPP17_OR_GREATER) - # define CATCH_INTERNAL_CONFIG_CPP17_BYTE + # include + # if defined(__cpp_lib_byte) && (__cpp_lib_byte > 0) + # define CATCH_INTERNAL_CONFIG_CPP17_BYTE + # endif # endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) // Check if variant is available and usable @@ -373,10 +373,6 @@ namespace Catch { # define CATCH_CONFIG_CPP17_OPTIONAL #endif -#if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) -# define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS -#endif - #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW) # define CATCH_CONFIG_CPP17_STRING_VIEW #endif @@ -1016,34 +1012,34 @@ struct AutoReg : NonCopyable { #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \ - INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) + INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, typename TestType, __VA_ARGS__ ) #else #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \ - INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) ) + INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, typename TestType, __VA_ARGS__ ) ) #endif #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \ - INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) + INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, Signature, __VA_ARGS__ ) #else #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \ - INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) ) + INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, Signature, __VA_ARGS__ ) ) #endif #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \ - INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) #else #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \ - INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) ) + INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) ) #endif #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \ - INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) #else #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \ - INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) ) + INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) ) #endif #endif @@ -1056,7 +1052,7 @@ struct AutoReg : NonCopyable { CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ static void TestName() #define INTERNAL_CATCH_TESTCASE( ... ) \ - INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ ) + INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ), __VA_ARGS__ ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \ @@ -1078,7 +1074,7 @@ struct AutoReg : NonCopyable { CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ void TestName::test() #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \ - INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ ) + INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ), ClassName, __VA_ARGS__ ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \ @@ -1105,7 +1101,7 @@ struct AutoReg : NonCopyable { int index = 0; \ constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\ using expander = int[];\ - (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++, 0)... };/* NOLINT */ \ + (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \ }\ };\ static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ @@ -1119,18 +1115,18 @@ struct AutoReg : NonCopyable { #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \ - INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) + INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, typename TestType, __VA_ARGS__ ) #else #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \ - INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) ) + INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, typename TestType, __VA_ARGS__ ) ) #endif #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \ - INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) + INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, Signature, __VA_ARGS__ ) #else #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \ - INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) ) + INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, Signature, __VA_ARGS__ ) ) #endif #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \ @@ -1151,7 +1147,7 @@ struct AutoReg : NonCopyable { constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\ constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\ constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\ - (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFuncName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++, 0)... };/* NOLINT */\ + (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFuncName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++)... };/* NOLINT */\ } \ }; \ static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \ @@ -1168,18 +1164,18 @@ struct AutoReg : NonCopyable { #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\ - INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename T,__VA_ARGS__) + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, typename T,__VA_ARGS__) #else #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\ - INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename T, __VA_ARGS__ ) ) + INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, typename T, __VA_ARGS__ ) ) #endif #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\ - INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__) + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, Signature, __VA_ARGS__) #else #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\ - INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) ) + INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, Signature, __VA_ARGS__ ) ) #endif #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\ @@ -1195,7 +1191,7 @@ struct AutoReg : NonCopyable { void reg_tests() { \ int index = 0; \ using expander = int[]; \ - (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFunc ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++, 0)... };/* NOLINT */\ + (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFunc ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++)... };/* NOLINT */\ } \ };\ static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \ @@ -1210,7 +1206,7 @@ struct AutoReg : NonCopyable { static void TestFunc() #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \ - INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, TmplList ) + INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, TmplList ) #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \ CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ @@ -1229,7 +1225,7 @@ struct AutoReg : NonCopyable { int index = 0; \ constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\ using expander = int[];\ - (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++, 0)... };/* NOLINT */ \ + (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \ }\ };\ static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ @@ -1243,18 +1239,18 @@ struct AutoReg : NonCopyable { #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \ - INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) #else #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \ - INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) ) + INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) ) #endif #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \ - INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) #else #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \ - INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) ) + INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) ) #endif #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\ @@ -1278,7 +1274,7 @@ struct AutoReg : NonCopyable { constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\ constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\ constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\ - (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++, 0)... };/* NOLINT */ \ + (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++)... };/* NOLINT */ \ }\ };\ static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ @@ -1295,18 +1291,18 @@ struct AutoReg : NonCopyable { #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\ - INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, typename T, __VA_ARGS__ ) + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), ClassName, Name, Tags, typename T, __VA_ARGS__ ) #else #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\ - INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, typename T,__VA_ARGS__ ) ) + INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), ClassName, Name, Tags, typename T,__VA_ARGS__ ) ) #endif #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\ - INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, Signature, __VA_ARGS__ ) + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), ClassName, Name, Tags, Signature, __VA_ARGS__ ) #else #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\ - INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, Signature,__VA_ARGS__ ) ) + INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), ClassName, Name, Tags, Signature,__VA_ARGS__ ) ) #endif #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \ @@ -1325,7 +1321,7 @@ struct AutoReg : NonCopyable { void reg_tests(){\ int index = 0;\ using expander = int[];\ - (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++, 0)... };/* NOLINT */ \ + (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++)... };/* NOLINT */ \ }\ };\ static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ @@ -1340,7 +1336,7 @@ struct AutoReg : NonCopyable { void TestName::test() #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \ - INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, TmplList ) + INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), ClassName, Name, Tags, TmplList ) // end catch_test_registry.h // start catch_capture.hpp @@ -1829,8 +1825,8 @@ namespace Catch { #endif namespace Detail { - template - std::string rangeToString(InputIterator first, InputIterator last) { + template + std::string rangeToString(InputIterator first, Sentinel last) { ReusableStringStream rss; rss << "{ "; if (first != last) { @@ -3097,7 +3093,7 @@ namespace Detail { Approx operator-() const; template ::value>::type> - Approx operator()( T const& value ) { + Approx operator()( T const& value ) const { Approx approx( static_cast(value) ); approx.m_epsilon = m_epsilon; approx.m_margin = m_margin; @@ -4169,7 +4165,7 @@ namespace Generators { if (!m_predicate(m_generator.get())) { // It might happen that there are no values that pass the // filter. In that case we throw an exception. - auto has_initial_value = next(); + auto has_initial_value = nextImpl(); if (!has_initial_value) { Catch::throw_exception(GeneratorException("No valid value found in filtered generator")); } @@ -4181,6 +4177,11 @@ namespace Generators { } bool next() override { + return nextImpl(); + } + + private: + bool nextImpl() { bool success = m_generator.next(); if (!success) { return false; @@ -5464,6 +5465,8 @@ namespace Catch { } // namespace Catch // end catch_outlier_classification.hpp + +#include #endif // CATCH_CONFIG_ENABLE_BENCHMARKING #include @@ -6348,9 +6351,10 @@ namespace Catch { void writeTestCase(TestCaseNode const& testCaseNode); - void writeSection(std::string const& className, - std::string const& rootName, - SectionNode const& sectionNode); + void writeSection( std::string const& className, + std::string const& rootName, + SectionNode const& sectionNode, + bool testOkToFail ); void writeAssertions(SectionNode const& sectionNode); void writeAssertion(AssertionStats const& stats); @@ -6885,7 +6889,7 @@ namespace Catch { } iters *= 2; } - throw optimized_away_error{}; + Catch::throw_exception(optimized_away_error{}); } } // namespace Detail } // namespace Benchmark @@ -6893,6 +6897,7 @@ namespace Catch { // end catch_run_for_at_least.hpp #include +#include namespace Catch { namespace Benchmark { @@ -7063,8 +7068,8 @@ namespace Catch { double b2 = bias - z1; double a1 = a(b1); double a2 = a(b2); - auto lo = std::max(cumn(a1), 0); - auto hi = std::min(cumn(a2), n - 1); + auto lo = (std::max)(cumn(a1), 0); + auto hi = (std::min)(cumn(a2), n - 1); return { point, resample[lo], resample[hi], confidence_level }; } @@ -7133,7 +7138,9 @@ namespace Catch { } template EnvironmentEstimate> estimate_clock_cost(FloatDuration resolution) { - auto time_limit = std::min(resolution * clock_cost_estimation_tick_limit, FloatDuration(clock_cost_estimation_time_limit)); + auto time_limit = (std::min)( + resolution * clock_cost_estimation_tick_limit, + FloatDuration(clock_cost_estimation_time_limit)); auto time_clock = [](int k) { return Detail::measure([k] { for (int i = 0; i < k; ++i) { @@ -7611,6 +7618,10 @@ namespace TestCaseTracking { void addInitialFilters( std::vector const& filters ); void addNextFilters( std::vector const& filters ); + //! Returns filters active in this tracker + std::vector const& getFilters() const; + //! Returns whitespace-trimmed name of the tracked section + std::string const& trimmedName() const; }; } // namespace TestCaseTracking @@ -7776,7 +7787,7 @@ namespace Catch { double sb = stddev.point; double mn = mean.point / n; double mg_min = mn / 2.; - double sg = std::min(mg_min / 4., sb / std::sqrt(n)); + double sg = (std::min)(mg_min / 4., sb / std::sqrt(n)); double sg2 = sg * sg; double sb2 = sb * sb; @@ -7795,7 +7806,7 @@ namespace Catch { return (nc / n) * (sb2 - nc * sg2); }; - return std::min(var_out(1), var_out(std::min(c_max(0.), c_max(mg_min)))) / sb2; + return (std::min)(var_out(1), var_out((std::min)(c_max(0.), c_max(mg_min)))) / sb2; } bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector::iterator first, std::vector::iterator last) { @@ -7985,86 +7996,58 @@ namespace Catch { // start catch_fatal_condition.h -// start catch_windows_h_proxy.h - - -#if defined(CATCH_PLATFORM_WINDOWS) - -#if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX) -# define CATCH_DEFINED_NOMINMAX -# define NOMINMAX -#endif -#if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN) -# define CATCH_DEFINED_WIN32_LEAN_AND_MEAN -# define WIN32_LEAN_AND_MEAN -#endif - -#ifdef __AFXDLL -#include -#else -#include -#endif - -#ifdef CATCH_DEFINED_NOMINMAX -# undef NOMINMAX -#endif -#ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN -# undef WIN32_LEAN_AND_MEAN -#endif - -#endif // defined(CATCH_PLATFORM_WINDOWS) - -// end catch_windows_h_proxy.h -#if defined( CATCH_CONFIG_WINDOWS_SEH ) +#include namespace Catch { - struct FatalConditionHandler { - - static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo); + // Wrapper for platform-specific fatal error (signals/SEH) handlers + // + // Tries to be cooperative with other handlers, and not step over + // other handlers. This means that unknown structured exceptions + // are passed on, previous signal handlers are called, and so on. + // + // Can only be instantiated once, and assumes that once a signal + // is caught, the binary will end up terminating. Thus, there + class FatalConditionHandler { + bool m_started = false; + + // Install/disengage implementation for specific platform. + // Should be if-defed to work on current platform, can assume + // engage-disengage 1:1 pairing. + void engage_platform(); + void disengage_platform(); + public: + // Should also have platform-specific implementations as needed FatalConditionHandler(); - static void reset(); ~FatalConditionHandler(); - private: - static bool isSet; - static ULONG guaranteeSize; - static PVOID exceptionHandlerHandle; - }; - -} // namespace Catch - -#elif defined ( CATCH_CONFIG_POSIX_SIGNALS ) - -#include - -namespace Catch { - - struct FatalConditionHandler { - - static bool isSet; - static struct sigaction oldSigActions[]; - static stack_t oldSigStack; - static char altStackMem[]; - - static void handleSignal( int sig ); + void engage() { + assert(!m_started && "Handler cannot be installed twice."); + m_started = true; + engage_platform(); + } - FatalConditionHandler(); - ~FatalConditionHandler(); - static void reset(); + void disengage() { + assert(m_started && "Handler cannot be uninstalled without being installed first"); + m_started = false; + disengage_platform(); + } }; -} // namespace Catch - -#else - -namespace Catch { - struct FatalConditionHandler { - void reset(); + //! Simple RAII guard for (dis)engaging the FatalConditionHandler + class FatalConditionHandlerGuard { + FatalConditionHandler* m_handler; + public: + FatalConditionHandlerGuard(FatalConditionHandler* handler): + m_handler(handler) { + m_handler->engage(); + } + ~FatalConditionHandlerGuard() { + m_handler->disengage(); + } }; -} -#endif +} // end namespace Catch // end catch_fatal_condition.h #include @@ -8190,6 +8173,7 @@ namespace Catch { std::vector m_unfinishedSections; std::vector m_activeSections; TrackerContext m_trackerContext; + FatalConditionHandler m_fatalConditionhandler; bool m_lastAssertionPassed = false; bool m_shouldReportUnexpected = true; bool m_includeSuccessfulResults; @@ -10062,6 +10046,36 @@ namespace Catch { } // end catch_errno_guard.h +// start catch_windows_h_proxy.h + + +#if defined(CATCH_PLATFORM_WINDOWS) + +#if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX) +# define CATCH_DEFINED_NOMINMAX +# define NOMINMAX +#endif +#if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN) +# define CATCH_DEFINED_WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +#endif + +#ifdef __AFXDLL +#include +#else +#include +#endif + +#ifdef CATCH_DEFINED_NOMINMAX +# undef NOMINMAX +#endif +#ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN +# undef WIN32_LEAN_AND_MEAN +#endif + +#endif // defined(CATCH_PLATFORM_WINDOWS) + +// end catch_windows_h_proxy.h #include namespace Catch { @@ -10578,7 +10592,7 @@ namespace Catch { // Extracts the actual name part of an enum instance // In other words, it returns the Blue part of Bikeshed::Colour::Blue StringRef extractInstanceName(StringRef enumInstance) { - // Find last occurence of ":" + // Find last occurrence of ":" size_t name_start = enumInstance.size(); while (name_start > 0 && enumInstance[name_start - 1] != ':') { --name_start; @@ -10740,25 +10754,47 @@ namespace Catch { // end catch_exception_translator_registry.cpp // start catch_fatal_condition.cpp -#if defined(__GNUC__) -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wmissing-field-initializers" -#endif +#include + +#if !defined( CATCH_CONFIG_WINDOWS_SEH ) && !defined( CATCH_CONFIG_POSIX_SIGNALS ) + +namespace Catch { + + // If neither SEH nor signal handling is required, the handler impls + // do not have to do anything, and can be empty. + void FatalConditionHandler::engage_platform() {} + void FatalConditionHandler::disengage_platform() {} + FatalConditionHandler::FatalConditionHandler() = default; + FatalConditionHandler::~FatalConditionHandler() = default; + +} // end namespace Catch + +#endif // !CATCH_CONFIG_WINDOWS_SEH && !CATCH_CONFIG_POSIX_SIGNALS + +#if defined( CATCH_CONFIG_WINDOWS_SEH ) && defined( CATCH_CONFIG_POSIX_SIGNALS ) +#error "Inconsistent configuration: Windows' SEH handling and POSIX signals cannot be enabled at the same time" +#endif // CATCH_CONFIG_WINDOWS_SEH && CATCH_CONFIG_POSIX_SIGNALS #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS ) namespace { - // Report the error condition + //! Signals fatal error message to the run context void reportFatal( char const * const message ) { Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message ); } -} -#endif // signals/SEH handling + //! Minimal size Catch2 needs for its own fatal error handling. + //! Picked anecdotally, so it might not be sufficient on all + //! platforms, and for all configurations. + constexpr std::size_t minStackSizeForErrors = 32 * 1024; +} // end unnamed namespace + +#endif // CATCH_CONFIG_WINDOWS_SEH || CATCH_CONFIG_POSIX_SIGNALS #if defined( CATCH_CONFIG_WINDOWS_SEH ) namespace Catch { + struct SignalDefs { DWORD id; const char* name; }; // There is no 1-1 mapping between signals and windows exceptions. @@ -10771,7 +10807,7 @@ namespace Catch { { static_cast(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error" }, }; - LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) { + static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) { for (auto const& def : signalDefs) { if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) { reportFatal(def.name); @@ -10782,38 +10818,50 @@ namespace Catch { return EXCEPTION_CONTINUE_SEARCH; } + // Since we do not support multiple instantiations, we put these + // into global variables and rely on cleaning them up in outlined + // constructors/destructors + static PVOID exceptionHandlerHandle = nullptr; + + // For MSVC, we reserve part of the stack memory for handling + // memory overflow structured exception. FatalConditionHandler::FatalConditionHandler() { - isSet = true; - // 32k seems enough for Catch to handle stack overflow, - // but the value was found experimentally, so there is no strong guarantee - guaranteeSize = 32 * 1024; - exceptionHandlerHandle = nullptr; + ULONG guaranteeSize = static_cast(minStackSizeForErrors); + if (!SetThreadStackGuarantee(&guaranteeSize)) { + // We do not want to fully error out, because needing + // the stack reserve should be rare enough anyway. + Catch::cerr() + << "Failed to reserve piece of stack." + << " Stack overflows will not be reported successfully."; + } + } + + // We do not attempt to unset the stack guarantee, because + // Windows does not support lowering the stack size guarantee. + FatalConditionHandler::~FatalConditionHandler() = default; + + void FatalConditionHandler::engage_platform() { // Register as first handler in current chain exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException); - // Pass in guarantee size to be filled - SetThreadStackGuarantee(&guaranteeSize); + if (!exceptionHandlerHandle) { + CATCH_RUNTIME_ERROR("Could not register vectored exception handler"); + } } - void FatalConditionHandler::reset() { - if (isSet) { - RemoveVectoredExceptionHandler(exceptionHandlerHandle); - SetThreadStackGuarantee(&guaranteeSize); - exceptionHandlerHandle = nullptr; - isSet = false; + void FatalConditionHandler::disengage_platform() { + if (!RemoveVectoredExceptionHandler(exceptionHandlerHandle)) { + CATCH_RUNTIME_ERROR("Could not unregister vectored exception handler"); } + exceptionHandlerHandle = nullptr; } - FatalConditionHandler::~FatalConditionHandler() { - reset(); - } +} // end namespace Catch -bool FatalConditionHandler::isSet = false; -ULONG FatalConditionHandler::guaranteeSize = 0; -PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr; +#endif // CATCH_CONFIG_WINDOWS_SEH -} // namespace Catch +#if defined( CATCH_CONFIG_POSIX_SIGNALS ) -#elif defined( CATCH_CONFIG_POSIX_SIGNALS ) +#include namespace Catch { @@ -10822,10 +10870,6 @@ namespace Catch { const char* name; }; - // 32kb for the alternate stack seems to be sufficient. However, this value - // is experimentally determined, so that's not guaranteed. - static constexpr std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ; - static SignalDefs signalDefs[] = { { SIGINT, "SIGINT - Terminal interrupt signal" }, { SIGILL, "SIGILL - Illegal instruction signal" }, @@ -10835,7 +10879,32 @@ namespace Catch { { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" } }; - void FatalConditionHandler::handleSignal( int sig ) { +// Older GCCs trigger -Wmissing-field-initializers for T foo = {} +// which is zero initialization, but not explicit. We want to avoid +// that. +#if defined(__GNUC__) +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wmissing-field-initializers" +#endif + + static char* altStackMem = nullptr; + static std::size_t altStackSize = 0; + static stack_t oldSigStack{}; + static struct sigaction oldSigActions[sizeof(signalDefs) / sizeof(SignalDefs)]{}; + + static void restorePreviousSignalHandlers() { + // We set signal handlers back to the previous ones. Hopefully + // nobody overwrote them in the meantime, and doesn't expect + // their signal handlers to live past ours given that they + // installed them after ours.. + for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) { + sigaction(signalDefs[i].id, &oldSigActions[i], nullptr); + } + // Return the old stack + sigaltstack(&oldSigStack, nullptr); + } + + static void handleSignal( int sig ) { char const * name = ""; for (auto const& def : signalDefs) { if (sig == def.id) { @@ -10843,16 +10912,33 @@ namespace Catch { break; } } - reset(); - reportFatal(name); + // We need to restore previous signal handlers and let them do + // their thing, so that the users can have the debugger break + // when a signal is raised, and so on. + restorePreviousSignalHandlers(); + reportFatal( name ); raise( sig ); } FatalConditionHandler::FatalConditionHandler() { - isSet = true; + assert(!altStackMem && "Cannot initialize POSIX signal handler when one already exists"); + if (altStackSize == 0) { + altStackSize = std::max(static_cast(SIGSTKSZ), minStackSizeForErrors); + } + altStackMem = new char[altStackSize](); + } + + FatalConditionHandler::~FatalConditionHandler() { + delete[] altStackMem; + // We signal that another instance can be constructed by zeroing + // out the pointer. + altStackMem = nullptr; + } + + void FatalConditionHandler::engage_platform() { stack_t sigStack; sigStack.ss_sp = altStackMem; - sigStack.ss_size = sigStackSize; + sigStack.ss_size = altStackSize; sigStack.ss_flags = 0; sigaltstack(&sigStack, &oldSigStack); struct sigaction sa = { }; @@ -10864,40 +10950,17 @@ namespace Catch { } } - FatalConditionHandler::~FatalConditionHandler() { - reset(); - } +#if defined(__GNUC__) +# pragma GCC diagnostic pop +#endif - void FatalConditionHandler::reset() { - if( isSet ) { - // Set signals back to previous values -- hopefully nobody overwrote them in the meantime - for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) { - sigaction(signalDefs[i].id, &oldSigActions[i], nullptr); - } - // Return the old stack - sigaltstack(&oldSigStack, nullptr); - isSet = false; - } + void FatalConditionHandler::disengage_platform() { + restorePreviousSignalHandlers(); } - bool FatalConditionHandler::isSet = false; - struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {}; - stack_t FatalConditionHandler::oldSigStack = {}; - char FatalConditionHandler::altStackMem[sigStackSize] = {}; - -} // namespace Catch - -#else - -namespace Catch { - void FatalConditionHandler::reset() {} -} - -#endif // signals/SEH handling +} // end namespace Catch -#if defined(__GNUC__) -# pragma GCC diagnostic pop -#endif +#endif // CATCH_CONFIG_POSIX_SIGNALS // end catch_fatal_condition.cpp // start catch_generators.cpp @@ -11452,7 +11515,8 @@ namespace { return lhs == rhs; } - auto ulpDiff = std::abs(lc - rc); + // static cast as a workaround for IBM XLC + auto ulpDiff = std::abs(static_cast(lc - rc)); return static_cast(ulpDiff) <= maxUlpDiff; } @@ -11626,7 +11690,6 @@ Floating::WithinRelMatcher WithinRel(float target) { } // namespace Matchers } // namespace Catch - // end catch_matchers_floating.cpp // start catch_matchers_generic.cpp @@ -12042,7 +12105,7 @@ namespace Catch { if (tmpnam_s(m_buffer)) { CATCH_RUNTIME_ERROR("Could not get a temp filename"); } - if (fopen_s(&m_file, m_buffer, "w")) { + if (fopen_s(&m_file, m_buffer, "w+")) { char buffer[100]; if (strerror_s(buffer, errno)) { CATCH_RUNTIME_ERROR("Could not translate errno to a string"); @@ -12580,13 +12643,53 @@ namespace Catch { // `SECTION`s. // **The check for m_children.empty cannot be removed**. // doing so would break `GENERATE` _not_ followed by `SECTION`s. - const bool should_wait_for_child = - !m_children.empty() && - std::find_if( m_children.begin(), - m_children.end(), - []( TestCaseTracking::ITrackerPtr tracker ) { - return tracker->hasStarted(); - } ) == m_children.end(); + const bool should_wait_for_child = [&]() { + // No children -> nobody to wait for + if ( m_children.empty() ) { + return false; + } + // If at least one child started executing, don't wait + if ( std::find_if( + m_children.begin(), + m_children.end(), + []( TestCaseTracking::ITrackerPtr tracker ) { + return tracker->hasStarted(); + } ) != m_children.end() ) { + return false; + } + + // No children have started. We need to check if they _can_ + // start, and thus we should wait for them, or they cannot + // start (due to filters), and we shouldn't wait for them + auto* parent = m_parent; + // This is safe: there is always at least one section + // tracker in a test case tracking tree + while ( !parent->isSectionTracker() ) { + parent = &( parent->parent() ); + } + assert( parent && + "Missing root (test case) level section" ); + + auto const& parentSection = + static_cast( *parent ); + auto const& filters = parentSection.getFilters(); + // No filters -> no restrictions on running sections + if ( filters.empty() ) { + return true; + } + + for ( auto const& child : m_children ) { + if ( child->isSectionTracker() && + std::find( filters.begin(), + filters.end(), + static_cast( *child ) + .trimmedName() ) != + filters.end() ) { + return true; + } + } + return false; + }(); // This check is a bit tricky, because m_generator->next() // has a side-effect, where it consumes generator's current @@ -12920,9 +13023,8 @@ namespace Catch { } void RunContext::invokeActiveTestCase() { - FatalConditionHandler fatalConditionHandler; // Handle signals + FatalConditionHandlerGuard _(&m_fatalConditionhandler); m_activeTestCase->invoke(); - fatalConditionHandler.reset(); } void RunContext::handleUnfinishedSections() { @@ -13290,6 +13392,10 @@ namespace Catch { filename.erase(0, lastSlash); filename[0] = '#'; } + else + { + filename.insert(0, "#"); + } auto lastDot = filename.find_last_of('.'); if (lastDot != std::string::npos) { @@ -14091,24 +14197,28 @@ namespace Catch { namespace { struct TestHasher { - explicit TestHasher(Catch::SimplePcg32& rng) { - basis = rng(); - basis <<= 32; - basis |= rng(); - } + using hash_t = uint64_t; - uint64_t basis; + explicit TestHasher( hash_t hashSuffix ): + m_hashSuffix{ hashSuffix } {} - uint64_t operator()(TestCase const& t) const { - // Modified FNV-1a hash - static constexpr uint64_t prime = 1099511628211; - uint64_t hash = basis; - for (const char c : t.name) { + uint32_t operator()( TestCase const& t ) const { + // FNV-1a hash with multiplication fold. + const hash_t prime = 1099511628211u; + hash_t hash = 14695981039346656037u; + for ( const char c : t.name ) { hash ^= c; hash *= prime; } - return hash; + hash ^= m_hashSuffix; + hash *= prime; + const uint32_t low{ static_cast( hash ) }; + const uint32_t high{ static_cast( hash >> 32 ) }; + return low * high; } + + private: + hash_t m_hashSuffix; }; } // end unnamed namespace @@ -14126,9 +14236,9 @@ namespace Catch { case RunTests::InRandomOrder: { seedRng( config ); - TestHasher h( rng() ); + TestHasher h{ config.rngSeed() }; - using hashedTest = std::pair; + using hashedTest = std::pair; std::vector indexed_tests; indexed_tests.reserve( unsortedTestCases.size() ); @@ -14458,6 +14568,14 @@ namespace TestCaseTracking { m_filters.insert( m_filters.end(), filters.begin()+1, filters.end() ); } + std::vector const& SectionTracker::getFilters() const { + return m_filters; + } + + std::string const& SectionTracker::trimmedName() const { + return m_trimmed_name; + } + } // namespace TestCaseTracking using TestCaseTracking::ITracker; @@ -15192,6 +15310,41 @@ namespace Catch { // end catch_totals.cpp // start catch_uncaught_exceptions.cpp +// start catch_config_uncaught_exceptions.hpp + +// Copyright Catch2 Authors +// Distributed under the Boost Software License, Version 1.0. +// (See accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// SPDX-License-Identifier: BSL-1.0 + +#ifndef CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP +#define CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP + +#if defined(_MSC_VER) +# if _MSC_VER >= 1900 // Visual Studio 2015 or newer +# define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS +# endif +#endif + +#include + +#if defined(__cpp_lib_uncaught_exceptions) \ + && !defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) + +# define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS +#endif // __cpp_lib_uncaught_exceptions + +#if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) \ + && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) \ + && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) + +# define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS +#endif + +#endif // CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP +// end catch_config_uncaught_exceptions.hpp #include namespace Catch { @@ -15238,7 +15391,7 @@ namespace Catch { } Version const& libraryVersion() { - static Version version( 2, 13, 0, "", 0 ); + static Version version( 2, 13, 9, "", 0 ); return version; } @@ -16651,6 +16804,7 @@ CATCH_REGISTER_REPORTER("console", ConsoleReporter) #include #include #include +#include namespace Catch { @@ -16678,7 +16832,7 @@ namespace Catch { #else std::strftime(timeStamp, timeStampSize, fmt, timeInfo); #endif - return std::string(timeStamp); + return std::string(timeStamp, timeStampSize-1); } std::string fileNameTag(const std::vector &tags) { @@ -16689,6 +16843,17 @@ namespace Catch { return it->substr(1); return std::string(); } + + // Formats the duration in seconds to 3 decimal places. + // This is done because some genius defined Maven Surefire schema + // in a way that only accepts 3 decimal places, and tools like + // Jenkins use that schema for validation JUnit reporter output. + std::string formatDuration( double seconds ) { + ReusableStringStream rss; + rss << std::fixed << std::setprecision( 3 ) << seconds; + return rss.str(); + } + } // anonymous namespace JunitReporter::JunitReporter( ReporterConfig const& _config ) @@ -16758,7 +16923,7 @@ namespace Catch { if( m_config->showDurations() == ShowDurations::Never ) xml.writeAttribute( "time", "" ); else - xml.writeAttribute( "time", suiteTime ); + xml.writeAttribute( "time", formatDuration( suiteTime ) ); xml.writeAttribute( "timestamp", getCurrentTimestamp() ); // Write properties if there are any @@ -16803,12 +16968,13 @@ namespace Catch { if ( !m_config->name().empty() ) className = m_config->name() + "." + className; - writeSection( className, "", rootSection ); + writeSection( className, "", rootSection, stats.testInfo.okToFail() ); } - void JunitReporter::writeSection( std::string const& className, - std::string const& rootName, - SectionNode const& sectionNode ) { + void JunitReporter::writeSection( std::string const& className, + std::string const& rootName, + SectionNode const& sectionNode, + bool testOkToFail) { std::string name = trim( sectionNode.stats.sectionInfo.name ); if( !rootName.empty() ) name = rootName + '/' + name; @@ -16825,13 +16991,18 @@ namespace Catch { xml.writeAttribute( "classname", className ); xml.writeAttribute( "name", name ); } - xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) ); + xml.writeAttribute( "time", formatDuration( sectionNode.stats.durationInSeconds ) ); // This is not ideal, but it should be enough to mimic gtest's // junit output. // Ideally the JUnit reporter would also handle `skipTest` // events and write those out appropriately. xml.writeAttribute( "status", "run" ); + if (sectionNode.stats.assertions.failedButOk) { + xml.scopedElement("skipped") + .writeAttribute("message", "TEST_CASE tagged with !mayfail"); + } + writeAssertions( sectionNode ); if( !sectionNode.stdOut.empty() ) @@ -16841,9 +17012,9 @@ namespace Catch { } for( auto const& childNode : sectionNode.childSections ) if( className.empty() ) - writeSection( name, "", *childNode ); + writeSection( name, "", *childNode, testOkToFail ); else - writeSection( className, name, *childNode ); + writeSection( className, name, *childNode, testOkToFail ); } void JunitReporter::writeAssertions( SectionNode const& sectionNode ) { @@ -17488,9 +17659,9 @@ int main (int argc, char * const argv[]) { #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) #define CATCH_BENCHMARK(...) \ - INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,)) + INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_B_E_N_C_H_), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,)) #define CATCH_BENCHMARK_ADVANCED(name) \ - INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name) + INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_B_E_N_C_H_), name) #endif // CATCH_CONFIG_ENABLE_BENCHMARKING // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required @@ -17592,9 +17763,9 @@ int main (int argc, char * const argv[]) { #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) #define BENCHMARK(...) \ - INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,)) + INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_B_E_N_C_H_), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,)) #define BENCHMARK_ADVANCED(name) \ - INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name) + INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_B_E_N_C_H_), name) #endif // CATCH_CONFIG_ENABLE_BENCHMARKING using Catch::Detail::Approx; @@ -17641,8 +17812,8 @@ using Catch::Detail::Approx; #define CATCH_WARN( msg ) (void)(0) #define CATCH_CAPTURE( msg ) (void)(0) -#define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) -#define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) +#define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ )) +#define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ )) #define CATCH_METHOD_AS_TEST_CASE( method, ... ) #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0) #define CATCH_SECTION( ... ) @@ -17651,7 +17822,7 @@ using Catch::Detail::Approx; #define CATCH_FAIL_CHECK( ... ) (void)(0) #define CATCH_SUCCEED( ... ) (void)(0) -#define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) +#define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ )) #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) @@ -17674,8 +17845,8 @@ using Catch::Detail::Approx; #endif // "BDD-style" convenience wrappers -#define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) -#define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className ) +#define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ )) +#define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ), className ) #define CATCH_GIVEN( desc ) #define CATCH_AND_GIVEN( desc ) #define CATCH_WHEN( desc ) @@ -17723,10 +17894,10 @@ using Catch::Detail::Approx; #define INFO( msg ) (void)(0) #define UNSCOPED_INFO( msg ) (void)(0) #define WARN( msg ) (void)(0) -#define CAPTURE( msg ) (void)(0) +#define CAPTURE( ... ) (void)(0) -#define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) -#define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) +#define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ )) +#define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ )) #define METHOD_AS_TEST_CASE( method, ... ) #define REGISTER_TEST_CASE( Function, ... ) (void)(0) #define SECTION( ... ) @@ -17734,7 +17905,7 @@ using Catch::Detail::Approx; #define FAIL( ... ) (void)(0) #define FAIL_CHECK( ... ) (void)(0) #define SUCCEED( ... ) (void)(0) -#define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) +#define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ )) #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) @@ -17764,8 +17935,8 @@ using Catch::Detail::Approx; #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature ) // "BDD-style" convenience wrappers -#define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) ) -#define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className ) +#define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ) ) +#define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ), className ) #define GIVEN( desc ) #define AND_GIVEN( desc ) diff --git a/third_party/catch2/include/catch2/catch_reporter_automake.hpp b/third_party/catch2/include/catch2/catch_reporter_automake.hpp index dbebe97516..ba6f67f310 100644 --- a/third_party/catch2/include/catch2/catch_reporter_automake.hpp +++ b/third_party/catch2/include/catch2/catch_reporter_automake.hpp @@ -1,62 +1,62 @@ -/* - * Created by Justin R. Wilson on 2/19/2017. - * Copyright 2017 Justin R. Wilson. All rights reserved. - * - * Distributed under the Boost Software License, Version 1.0. (See accompanying - * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - */ -#ifndef TWOBLUECUBES_CATCH_REPORTER_AUTOMAKE_HPP_INCLUDED -#define TWOBLUECUBES_CATCH_REPORTER_AUTOMAKE_HPP_INCLUDED - -// Don't #include any Catch headers here - we can assume they are already -// included before this header. -// This is not good practice in general but is necessary in this case so this -// file can be distributed as a single header that works with the main -// Catch single header. - -namespace Catch { - - struct AutomakeReporter : StreamingReporterBase { - AutomakeReporter( ReporterConfig const& _config ) - : StreamingReporterBase( _config ) - {} - - ~AutomakeReporter() override; - - static std::string getDescription() { - return "Reports test results in the format of Automake .trs files"; - } - - void assertionStarting( AssertionInfo const& ) override {} - - bool assertionEnded( AssertionStats const& /*_assertionStats*/ ) override { return true; } - - void testCaseEnded( TestCaseStats const& _testCaseStats ) override { - // Possible values to emit are PASS, XFAIL, SKIP, FAIL, XPASS and ERROR. - stream << ":test-result: "; - if (_testCaseStats.totals.assertions.allPassed()) { - stream << "PASS"; - } else if (_testCaseStats.totals.assertions.allOk()) { - stream << "XFAIL"; - } else { - stream << "FAIL"; - } - stream << ' ' << _testCaseStats.testInfo.name << '\n'; - StreamingReporterBase::testCaseEnded( _testCaseStats ); - } - - void skipTest( TestCaseInfo const& testInfo ) override { - stream << ":test-result: SKIP " << testInfo.name << '\n'; - } - - }; - -#ifdef CATCH_IMPL - AutomakeReporter::~AutomakeReporter() {} -#endif - - CATCH_REGISTER_REPORTER( "automake", AutomakeReporter) - -} // end namespace Catch - -#endif // TWOBLUECUBES_CATCH_REPORTER_AUTOMAKE_HPP_INCLUDED +/* + * Created by Justin R. Wilson on 2/19/2017. + * Copyright 2017 Justin R. Wilson. All rights reserved. + * + * Distributed under the Boost Software License, Version 1.0. (See accompanying + * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + */ +#ifndef TWOBLUECUBES_CATCH_REPORTER_AUTOMAKE_HPP_INCLUDED +#define TWOBLUECUBES_CATCH_REPORTER_AUTOMAKE_HPP_INCLUDED + +// Don't #include any Catch headers here - we can assume they are already +// included before this header. +// This is not good practice in general but is necessary in this case so this +// file can be distributed as a single header that works with the main +// Catch single header. + +namespace Catch { + + struct AutomakeReporter : StreamingReporterBase { + AutomakeReporter( ReporterConfig const& _config ) + : StreamingReporterBase( _config ) + {} + + ~AutomakeReporter() override; + + static std::string getDescription() { + return "Reports test results in the format of Automake .trs files"; + } + + void assertionStarting( AssertionInfo const& ) override {} + + bool assertionEnded( AssertionStats const& /*_assertionStats*/ ) override { return true; } + + void testCaseEnded( TestCaseStats const& _testCaseStats ) override { + // Possible values to emit are PASS, XFAIL, SKIP, FAIL, XPASS and ERROR. + stream << ":test-result: "; + if (_testCaseStats.totals.assertions.allPassed()) { + stream << "PASS"; + } else if (_testCaseStats.totals.assertions.allOk()) { + stream << "XFAIL"; + } else { + stream << "FAIL"; + } + stream << ' ' << _testCaseStats.testInfo.name << '\n'; + StreamingReporterBase::testCaseEnded( _testCaseStats ); + } + + void skipTest( TestCaseInfo const& testInfo ) override { + stream << ":test-result: SKIP " << testInfo.name << '\n'; + } + + }; + +#ifdef CATCH_IMPL + AutomakeReporter::~AutomakeReporter() {} +#endif + + CATCH_REGISTER_REPORTER( "automake", AutomakeReporter) + +} // end namespace Catch + +#endif // TWOBLUECUBES_CATCH_REPORTER_AUTOMAKE_HPP_INCLUDED diff --git a/third_party/catch2/include/catch2/catch_reporter_sonarqube.hpp b/third_party/catch2/include/catch2/catch_reporter_sonarqube.hpp index bf7d9299a5..06056f154f 100644 --- a/third_party/catch2/include/catch2/catch_reporter_sonarqube.hpp +++ b/third_party/catch2/include/catch2/catch_reporter_sonarqube.hpp @@ -1,181 +1,181 @@ -/* - * Created by Daniel Garcia on 2018-12-04. - * Copyright Social Point SL. All rights reserved. - * - * Distributed under the Boost Software License, Version 1.0. (See accompanying - * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - */ -#ifndef CATCH_REPORTER_SONARQUBE_HPP_INCLUDED -#define CATCH_REPORTER_SONARQUBE_HPP_INCLUDED - - -// Don't #include any Catch headers here - we can assume they are already -// included before this header. -// This is not good practice in general but is necessary in this case so this -// file can be distributed as a single header that works with the main -// Catch single header. - -#include - -namespace Catch { - - struct SonarQubeReporter : CumulativeReporterBase { - - SonarQubeReporter(ReporterConfig const& config) - : CumulativeReporterBase(config) - , xml(config.stream()) { - m_reporterPrefs.shouldRedirectStdOut = true; - m_reporterPrefs.shouldReportAllAssertions = true; - } - - ~SonarQubeReporter() override; - - static std::string getDescription() { - return "Reports test results in the Generic Test Data SonarQube XML format"; - } - - static std::set getSupportedVerbosities() { - return { Verbosity::Normal }; - } - - void noMatchingTestCases(std::string const& /*spec*/) override {} - - void testRunStarting(TestRunInfo const& testRunInfo) override { - CumulativeReporterBase::testRunStarting(testRunInfo); - xml.startElement("testExecutions"); - xml.writeAttribute("version", "1"); - } - - void testGroupEnded(TestGroupStats const& testGroupStats) override { - CumulativeReporterBase::testGroupEnded(testGroupStats); - writeGroup(*m_testGroups.back()); - } - - void testRunEndedCumulative() override { - xml.endElement(); - } - - void writeGroup(TestGroupNode const& groupNode) { - std::map testsPerFile; - for(auto const& child : groupNode.children) - testsPerFile[child->value.testInfo.lineInfo.file].push_back(child); - - for(auto const& kv : testsPerFile) - writeTestFile(kv.first.c_str(), kv.second); - } - - void writeTestFile(const char* filename, TestGroupNode::ChildNodes const& testCaseNodes) { - XmlWriter::ScopedElement e = xml.scopedElement("file"); - xml.writeAttribute("path", filename); - - for(auto const& child : testCaseNodes) - writeTestCase(*child); - } - - void writeTestCase(TestCaseNode const& testCaseNode) { - // All test cases have exactly one section - which represents the - // test case itself. That section may have 0-n nested sections - assert(testCaseNode.children.size() == 1); - SectionNode const& rootSection = *testCaseNode.children.front(); - writeSection("", rootSection, testCaseNode.value.testInfo.okToFail()); - } - - void writeSection(std::string const& rootName, SectionNode const& sectionNode, bool okToFail) { - std::string name = trim(sectionNode.stats.sectionInfo.name); - if(!rootName.empty()) - name = rootName + '/' + name; - - if(!sectionNode.assertions.empty() || !sectionNode.stdOut.empty() || !sectionNode.stdErr.empty()) { - XmlWriter::ScopedElement e = xml.scopedElement("testCase"); - xml.writeAttribute("name", name); - xml.writeAttribute("duration", static_cast(sectionNode.stats.durationInSeconds * 1000)); - - writeAssertions(sectionNode, okToFail); - } - - for(auto const& childNode : sectionNode.childSections) - writeSection(name, *childNode, okToFail); - } - - void writeAssertions(SectionNode const& sectionNode, bool okToFail) { - for(auto const& assertion : sectionNode.assertions) - writeAssertion( assertion, okToFail); - } - - void writeAssertion(AssertionStats const& stats, bool okToFail) { - AssertionResult const& result = stats.assertionResult; - if(!result.isOk()) { - std::string elementName; - if(okToFail) { - elementName = "skipped"; - } - else { - switch(result.getResultType()) { - case ResultWas::ThrewException: - case ResultWas::FatalErrorCondition: - elementName = "error"; - break; - case ResultWas::ExplicitFailure: - elementName = "failure"; - break; - case ResultWas::ExpressionFailed: - elementName = "failure"; - break; - case ResultWas::DidntThrowException: - elementName = "failure"; - break; - - // We should never see these here: - case ResultWas::Info: - case ResultWas::Warning: - case ResultWas::Ok: - case ResultWas::Unknown: - case ResultWas::FailureBit: - case ResultWas::Exception: - elementName = "internalError"; - break; - } - } - - XmlWriter::ScopedElement e = xml.scopedElement(elementName); - - ReusableStringStream messageRss; - messageRss << result.getTestMacroName() << "(" << result.getExpression() << ")"; - xml.writeAttribute("message", messageRss.str()); - - ReusableStringStream textRss; - if (stats.totals.assertions.total() > 0) { - textRss << "FAILED:\n"; - if (result.hasExpression()) { - textRss << "\t" << result.getExpressionInMacro() << "\n"; - } - if (result.hasExpandedExpression()) { - textRss << "with expansion:\n\t" << result.getExpandedExpression() << "\n"; - } - } - - if(!result.getMessage().empty()) - textRss << result.getMessage() << "\n"; - - for(auto const& msg : stats.infoMessages) - if(msg.type == ResultWas::Info) - textRss << msg.message << "\n"; - - textRss << "at " << result.getSourceInfo(); - xml.writeText(textRss.str(), XmlFormatting::Newline); - } - } - - private: - XmlWriter xml; - }; - -#ifdef CATCH_IMPL - SonarQubeReporter::~SonarQubeReporter() {} -#endif - - CATCH_REGISTER_REPORTER( "sonarqube", SonarQubeReporter ) - -} // end namespace Catch - +/* + * Created by Daniel Garcia on 2018-12-04. + * Copyright Social Point SL. All rights reserved. + * + * Distributed under the Boost Software License, Version 1.0. (See accompanying + * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + */ +#ifndef CATCH_REPORTER_SONARQUBE_HPP_INCLUDED +#define CATCH_REPORTER_SONARQUBE_HPP_INCLUDED + + +// Don't #include any Catch headers here - we can assume they are already +// included before this header. +// This is not good practice in general but is necessary in this case so this +// file can be distributed as a single header that works with the main +// Catch single header. + +#include + +namespace Catch { + + struct SonarQubeReporter : CumulativeReporterBase { + + SonarQubeReporter(ReporterConfig const& config) + : CumulativeReporterBase(config) + , xml(config.stream()) { + m_reporterPrefs.shouldRedirectStdOut = true; + m_reporterPrefs.shouldReportAllAssertions = true; + } + + ~SonarQubeReporter() override; + + static std::string getDescription() { + return "Reports test results in the Generic Test Data SonarQube XML format"; + } + + static std::set getSupportedVerbosities() { + return { Verbosity::Normal }; + } + + void noMatchingTestCases(std::string const& /*spec*/) override {} + + void testRunStarting(TestRunInfo const& testRunInfo) override { + CumulativeReporterBase::testRunStarting(testRunInfo); + xml.startElement("testExecutions"); + xml.writeAttribute("version", "1"); + } + + void testGroupEnded(TestGroupStats const& testGroupStats) override { + CumulativeReporterBase::testGroupEnded(testGroupStats); + writeGroup(*m_testGroups.back()); + } + + void testRunEndedCumulative() override { + xml.endElement(); + } + + void writeGroup(TestGroupNode const& groupNode) { + std::map testsPerFile; + for(auto const& child : groupNode.children) + testsPerFile[child->value.testInfo.lineInfo.file].push_back(child); + + for(auto const& kv : testsPerFile) + writeTestFile(kv.first.c_str(), kv.second); + } + + void writeTestFile(const char* filename, TestGroupNode::ChildNodes const& testCaseNodes) { + XmlWriter::ScopedElement e = xml.scopedElement("file"); + xml.writeAttribute("path", filename); + + for(auto const& child : testCaseNodes) + writeTestCase(*child); + } + + void writeTestCase(TestCaseNode const& testCaseNode) { + // All test cases have exactly one section - which represents the + // test case itself. That section may have 0-n nested sections + assert(testCaseNode.children.size() == 1); + SectionNode const& rootSection = *testCaseNode.children.front(); + writeSection("", rootSection, testCaseNode.value.testInfo.okToFail()); + } + + void writeSection(std::string const& rootName, SectionNode const& sectionNode, bool okToFail) { + std::string name = trim(sectionNode.stats.sectionInfo.name); + if(!rootName.empty()) + name = rootName + '/' + name; + + if(!sectionNode.assertions.empty() || !sectionNode.stdOut.empty() || !sectionNode.stdErr.empty()) { + XmlWriter::ScopedElement e = xml.scopedElement("testCase"); + xml.writeAttribute("name", name); + xml.writeAttribute("duration", static_cast(sectionNode.stats.durationInSeconds * 1000)); + + writeAssertions(sectionNode, okToFail); + } + + for(auto const& childNode : sectionNode.childSections) + writeSection(name, *childNode, okToFail); + } + + void writeAssertions(SectionNode const& sectionNode, bool okToFail) { + for(auto const& assertion : sectionNode.assertions) + writeAssertion( assertion, okToFail); + } + + void writeAssertion(AssertionStats const& stats, bool okToFail) { + AssertionResult const& result = stats.assertionResult; + if(!result.isOk()) { + std::string elementName; + if(okToFail) { + elementName = "skipped"; + } + else { + switch(result.getResultType()) { + case ResultWas::ThrewException: + case ResultWas::FatalErrorCondition: + elementName = "error"; + break; + case ResultWas::ExplicitFailure: + elementName = "failure"; + break; + case ResultWas::ExpressionFailed: + elementName = "failure"; + break; + case ResultWas::DidntThrowException: + elementName = "failure"; + break; + + // We should never see these here: + case ResultWas::Info: + case ResultWas::Warning: + case ResultWas::Ok: + case ResultWas::Unknown: + case ResultWas::FailureBit: + case ResultWas::Exception: + elementName = "internalError"; + break; + } + } + + XmlWriter::ScopedElement e = xml.scopedElement(elementName); + + ReusableStringStream messageRss; + messageRss << result.getTestMacroName() << "(" << result.getExpression() << ")"; + xml.writeAttribute("message", messageRss.str()); + + ReusableStringStream textRss; + if (stats.totals.assertions.total() > 0) { + textRss << "FAILED:\n"; + if (result.hasExpression()) { + textRss << "\t" << result.getExpressionInMacro() << "\n"; + } + if (result.hasExpandedExpression()) { + textRss << "with expansion:\n\t" << result.getExpandedExpression() << "\n"; + } + } + + if(!result.getMessage().empty()) + textRss << result.getMessage() << "\n"; + + for(auto const& msg : stats.infoMessages) + if(msg.type == ResultWas::Info) + textRss << msg.message << "\n"; + + textRss << "at " << result.getSourceInfo(); + xml.writeText(textRss.str(), XmlFormatting::Newline); + } + } + + private: + XmlWriter xml; + }; + +#ifdef CATCH_IMPL + SonarQubeReporter::~SonarQubeReporter() {} +#endif + + CATCH_REGISTER_REPORTER( "sonarqube", SonarQubeReporter ) + +} // end namespace Catch + #endif // CATCH_REPORTER_SONARQUBE_HPP_INCLUDED \ No newline at end of file diff --git a/third_party/catch2/include/catch2/catch_reporter_tap.hpp b/third_party/catch2/include/catch2/catch_reporter_tap.hpp index 5ac8524ce7..3acab5f39d 100644 --- a/third_party/catch2/include/catch2/catch_reporter_tap.hpp +++ b/third_party/catch2/include/catch2/catch_reporter_tap.hpp @@ -1,254 +1,254 @@ -/* - * Created by Colton Wolkins on 2015-08-15. - * Copyright 2015 Martin Moene. All rights reserved. - * - * Distributed under the Boost Software License, Version 1.0. (See accompanying - * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - */ -#ifndef TWOBLUECUBES_CATCH_REPORTER_TAP_HPP_INCLUDED -#define TWOBLUECUBES_CATCH_REPORTER_TAP_HPP_INCLUDED - - -// Don't #include any Catch headers here - we can assume they are already -// included before this header. -// This is not good practice in general but is necessary in this case so this -// file can be distributed as a single header that works with the main -// Catch single header. - -#include - -namespace Catch { - - struct TAPReporter : StreamingReporterBase { - - using StreamingReporterBase::StreamingReporterBase; - - TAPReporter( ReporterConfig const& config ): - StreamingReporterBase( config ) { - m_reporterPrefs.shouldReportAllAssertions = true; - } - - ~TAPReporter() override; - - static std::string getDescription() { - return "Reports test results in TAP format, suitable for test harnesses"; - } - - void noMatchingTestCases( std::string const& spec ) override { - stream << "# No test cases matched '" << spec << "'" << std::endl; - } - - void assertionStarting( AssertionInfo const& ) override {} - - bool assertionEnded( AssertionStats const& _assertionStats ) override { - ++counter; - - stream << "# " << currentTestCaseInfo->name << std::endl; - AssertionPrinter printer( stream, _assertionStats, counter ); - printer.print(); - - stream << std::endl; - return true; - } - - void testRunEnded( TestRunStats const& _testRunStats ) override { - printTotals( _testRunStats.totals ); - stream << "\n" << std::endl; - StreamingReporterBase::testRunEnded( _testRunStats ); - } - - private: - std::size_t counter = 0; - class AssertionPrinter { - public: - AssertionPrinter& operator= ( AssertionPrinter const& ) = delete; - AssertionPrinter( AssertionPrinter const& ) = delete; - AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, std::size_t _counter ) - : stream( _stream ) - , result( _stats.assertionResult ) - , messages( _stats.infoMessages ) - , itMessage( _stats.infoMessages.begin() ) - , printInfoMessages( true ) - , counter(_counter) - {} - - void print() { - itMessage = messages.begin(); - - switch( result.getResultType() ) { - case ResultWas::Ok: - printResultType( passedString() ); - printOriginalExpression(); - printReconstructedExpression(); - if ( ! result.hasExpression() ) - printRemainingMessages( Colour::None ); - else - printRemainingMessages(); - break; - case ResultWas::ExpressionFailed: - if (result.isOk()) { - printResultType(passedString()); - } else { - printResultType(failedString()); - } - printOriginalExpression(); - printReconstructedExpression(); - if (result.isOk()) { - printIssue(" # TODO"); - } - printRemainingMessages(); - break; - case ResultWas::ThrewException: - printResultType( failedString() ); - printIssue( "unexpected exception with message:" ); - printMessage(); - printExpressionWas(); - printRemainingMessages(); - break; - case ResultWas::FatalErrorCondition: - printResultType( failedString() ); - printIssue( "fatal error condition with message:" ); - printMessage(); - printExpressionWas(); - printRemainingMessages(); - break; - case ResultWas::DidntThrowException: - printResultType( failedString() ); - printIssue( "expected exception, got none" ); - printExpressionWas(); - printRemainingMessages(); - break; - case ResultWas::Info: - printResultType( "info" ); - printMessage(); - printRemainingMessages(); - break; - case ResultWas::Warning: - printResultType( "warning" ); - printMessage(); - printRemainingMessages(); - break; - case ResultWas::ExplicitFailure: - printResultType( failedString() ); - printIssue( "explicitly" ); - printRemainingMessages( Colour::None ); - break; - // These cases are here to prevent compiler warnings - case ResultWas::Unknown: - case ResultWas::FailureBit: - case ResultWas::Exception: - printResultType( "** internal error **" ); - break; - } - } - - private: - static Colour::Code dimColour() { return Colour::FileName; } - - static const char* failedString() { return "not ok"; } - static const char* passedString() { return "ok"; } - - void printSourceInfo() const { - Colour colourGuard( dimColour() ); - stream << result.getSourceInfo() << ":"; - } - - void printResultType( std::string const& passOrFail ) const { - if( !passOrFail.empty() ) { - stream << passOrFail << ' ' << counter << " -"; - } - } - - void printIssue( std::string const& issue ) const { - stream << " " << issue; - } - - void printExpressionWas() { - if( result.hasExpression() ) { - stream << ";"; - { - Colour colour( dimColour() ); - stream << " expression was:"; - } - printOriginalExpression(); - } - } - - void printOriginalExpression() const { - if( result.hasExpression() ) { - stream << " " << result.getExpression(); - } - } - - void printReconstructedExpression() const { - if( result.hasExpandedExpression() ) { - { - Colour colour( dimColour() ); - stream << " for: "; - } - std::string expr = result.getExpandedExpression(); - std::replace( expr.begin(), expr.end(), '\n', ' '); - stream << expr; - } - } - - void printMessage() { - if ( itMessage != messages.end() ) { - stream << " '" << itMessage->message << "'"; - ++itMessage; - } - } - - void printRemainingMessages( Colour::Code colour = dimColour() ) { - if (itMessage == messages.end()) { - return; - } - - const auto itEnd = messages.cend(); - const auto N = static_cast( std::distance( itMessage, itEnd ) ); - - { - Colour colourGuard( colour ); - stream << " with " << pluralise( N, "message" ) << ":"; - } - - while( itMessage != itEnd ) { - // If this assertion is a warning ignore any INFO messages - if( printInfoMessages || itMessage->type != ResultWas::Info ) { - stream << " '" << itMessage->message << "'"; - if ( ++itMessage != itEnd ) { - Colour colourGuard( dimColour() ); - stream << " and"; - } - continue; - } - ++itMessage; - } - } - - private: - std::ostream& stream; - AssertionResult const& result; - std::vector messages; - std::vector::const_iterator itMessage; - bool printInfoMessages; - std::size_t counter; - }; - - void printTotals( const Totals& totals ) const { - stream << "1.." << totals.assertions.total(); - if( totals.testCases.total() == 0 ) { - stream << " # Skipped: No tests ran."; - } - } - }; - -#ifdef CATCH_IMPL - TAPReporter::~TAPReporter() {} -#endif - - CATCH_REGISTER_REPORTER( "tap", TAPReporter ) - -} // end namespace Catch - -#endif // TWOBLUECUBES_CATCH_REPORTER_TAP_HPP_INCLUDED +/* + * Created by Colton Wolkins on 2015-08-15. + * Copyright 2015 Martin Moene. All rights reserved. + * + * Distributed under the Boost Software License, Version 1.0. (See accompanying + * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + */ +#ifndef TWOBLUECUBES_CATCH_REPORTER_TAP_HPP_INCLUDED +#define TWOBLUECUBES_CATCH_REPORTER_TAP_HPP_INCLUDED + + +// Don't #include any Catch headers here - we can assume they are already +// included before this header. +// This is not good practice in general but is necessary in this case so this +// file can be distributed as a single header that works with the main +// Catch single header. + +#include + +namespace Catch { + + struct TAPReporter : StreamingReporterBase { + + using StreamingReporterBase::StreamingReporterBase; + + TAPReporter( ReporterConfig const& config ): + StreamingReporterBase( config ) { + m_reporterPrefs.shouldReportAllAssertions = true; + } + + ~TAPReporter() override; + + static std::string getDescription() { + return "Reports test results in TAP format, suitable for test harnesses"; + } + + void noMatchingTestCases( std::string const& spec ) override { + stream << "# No test cases matched '" << spec << "'" << std::endl; + } + + void assertionStarting( AssertionInfo const& ) override {} + + bool assertionEnded( AssertionStats const& _assertionStats ) override { + ++counter; + + stream << "# " << currentTestCaseInfo->name << std::endl; + AssertionPrinter printer( stream, _assertionStats, counter ); + printer.print(); + + stream << std::endl; + return true; + } + + void testRunEnded( TestRunStats const& _testRunStats ) override { + printTotals( _testRunStats.totals ); + stream << "\n" << std::endl; + StreamingReporterBase::testRunEnded( _testRunStats ); + } + + private: + std::size_t counter = 0; + class AssertionPrinter { + public: + AssertionPrinter& operator= ( AssertionPrinter const& ) = delete; + AssertionPrinter( AssertionPrinter const& ) = delete; + AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, std::size_t _counter ) + : stream( _stream ) + , result( _stats.assertionResult ) + , messages( _stats.infoMessages ) + , itMessage( _stats.infoMessages.begin() ) + , printInfoMessages( true ) + , counter(_counter) + {} + + void print() { + itMessage = messages.begin(); + + switch( result.getResultType() ) { + case ResultWas::Ok: + printResultType( passedString() ); + printOriginalExpression(); + printReconstructedExpression(); + if ( ! result.hasExpression() ) + printRemainingMessages( Colour::None ); + else + printRemainingMessages(); + break; + case ResultWas::ExpressionFailed: + if (result.isOk()) { + printResultType(passedString()); + } else { + printResultType(failedString()); + } + printOriginalExpression(); + printReconstructedExpression(); + if (result.isOk()) { + printIssue(" # TODO"); + } + printRemainingMessages(); + break; + case ResultWas::ThrewException: + printResultType( failedString() ); + printIssue( "unexpected exception with message:" ); + printMessage(); + printExpressionWas(); + printRemainingMessages(); + break; + case ResultWas::FatalErrorCondition: + printResultType( failedString() ); + printIssue( "fatal error condition with message:" ); + printMessage(); + printExpressionWas(); + printRemainingMessages(); + break; + case ResultWas::DidntThrowException: + printResultType( failedString() ); + printIssue( "expected exception, got none" ); + printExpressionWas(); + printRemainingMessages(); + break; + case ResultWas::Info: + printResultType( "info" ); + printMessage(); + printRemainingMessages(); + break; + case ResultWas::Warning: + printResultType( "warning" ); + printMessage(); + printRemainingMessages(); + break; + case ResultWas::ExplicitFailure: + printResultType( failedString() ); + printIssue( "explicitly" ); + printRemainingMessages( Colour::None ); + break; + // These cases are here to prevent compiler warnings + case ResultWas::Unknown: + case ResultWas::FailureBit: + case ResultWas::Exception: + printResultType( "** internal error **" ); + break; + } + } + + private: + static Colour::Code dimColour() { return Colour::FileName; } + + static const char* failedString() { return "not ok"; } + static const char* passedString() { return "ok"; } + + void printSourceInfo() const { + Colour colourGuard( dimColour() ); + stream << result.getSourceInfo() << ":"; + } + + void printResultType( std::string const& passOrFail ) const { + if( !passOrFail.empty() ) { + stream << passOrFail << ' ' << counter << " -"; + } + } + + void printIssue( std::string const& issue ) const { + stream << " " << issue; + } + + void printExpressionWas() { + if( result.hasExpression() ) { + stream << ";"; + { + Colour colour( dimColour() ); + stream << " expression was:"; + } + printOriginalExpression(); + } + } + + void printOriginalExpression() const { + if( result.hasExpression() ) { + stream << " " << result.getExpression(); + } + } + + void printReconstructedExpression() const { + if( result.hasExpandedExpression() ) { + { + Colour colour( dimColour() ); + stream << " for: "; + } + std::string expr = result.getExpandedExpression(); + std::replace( expr.begin(), expr.end(), '\n', ' '); + stream << expr; + } + } + + void printMessage() { + if ( itMessage != messages.end() ) { + stream << " '" << itMessage->message << "'"; + ++itMessage; + } + } + + void printRemainingMessages( Colour::Code colour = dimColour() ) { + if (itMessage == messages.end()) { + return; + } + + const auto itEnd = messages.cend(); + const auto N = static_cast( std::distance( itMessage, itEnd ) ); + + { + Colour colourGuard( colour ); + stream << " with " << pluralise( N, "message" ) << ":"; + } + + while( itMessage != itEnd ) { + // If this assertion is a warning ignore any INFO messages + if( printInfoMessages || itMessage->type != ResultWas::Info ) { + stream << " '" << itMessage->message << "'"; + if ( ++itMessage != itEnd ) { + Colour colourGuard( dimColour() ); + stream << " and"; + } + continue; + } + ++itMessage; + } + } + + private: + std::ostream& stream; + AssertionResult const& result; + std::vector messages; + std::vector::const_iterator itMessage; + bool printInfoMessages; + std::size_t counter; + }; + + void printTotals( const Totals& totals ) const { + stream << "1.." << totals.assertions.total(); + if( totals.testCases.total() == 0 ) { + stream << " # Skipped: No tests ran."; + } + } + }; + +#ifdef CATCH_IMPL + TAPReporter::~TAPReporter() {} +#endif + + CATCH_REGISTER_REPORTER( "tap", TAPReporter ) + +} // end namespace Catch + +#endif // TWOBLUECUBES_CATCH_REPORTER_TAP_HPP_INCLUDED diff --git a/third_party/catch2/include/catch2/catch_reporter_teamcity.hpp b/third_party/catch2/include/catch2/catch_reporter_teamcity.hpp index 47b7e4aac3..5c985d2cc1 100644 --- a/third_party/catch2/include/catch2/catch_reporter_teamcity.hpp +++ b/third_party/catch2/include/catch2/catch_reporter_teamcity.hpp @@ -1,219 +1,219 @@ -/* - * Created by Phil Nash on 19th December 2014 - * Copyright 2014 Two Blue Cubes Ltd. All rights reserved. - * - * Distributed under the Boost Software License, Version 1.0. (See accompanying - * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - */ -#ifndef TWOBLUECUBES_CATCH_REPORTER_TEAMCITY_HPP_INCLUDED -#define TWOBLUECUBES_CATCH_REPORTER_TEAMCITY_HPP_INCLUDED - -// Don't #include any Catch headers here - we can assume they are already -// included before this header. -// This is not good practice in general but is necessary in this case so this -// file can be distributed as a single header that works with the main -// Catch single header. - -#include - -#ifdef __clang__ -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wpadded" -#endif - -namespace Catch { - - struct TeamCityReporter : StreamingReporterBase { - TeamCityReporter( ReporterConfig const& _config ) - : StreamingReporterBase( _config ) - { - m_reporterPrefs.shouldRedirectStdOut = true; - } - - static std::string escape( std::string const& str ) { - std::string escaped = str; - replaceInPlace( escaped, "|", "||" ); - replaceInPlace( escaped, "'", "|'" ); - replaceInPlace( escaped, "\n", "|n" ); - replaceInPlace( escaped, "\r", "|r" ); - replaceInPlace( escaped, "[", "|[" ); - replaceInPlace( escaped, "]", "|]" ); - return escaped; - } - ~TeamCityReporter() override; - - static std::string getDescription() { - return "Reports test results as TeamCity service messages"; - } - - void skipTest( TestCaseInfo const& /* testInfo */ ) override { - } - - void noMatchingTestCases( std::string const& /* spec */ ) override {} - - void testGroupStarting( GroupInfo const& groupInfo ) override { - StreamingReporterBase::testGroupStarting( groupInfo ); - stream << "##teamcity[testSuiteStarted name='" - << escape( groupInfo.name ) << "']\n"; - } - void testGroupEnded( TestGroupStats const& testGroupStats ) override { - StreamingReporterBase::testGroupEnded( testGroupStats ); - stream << "##teamcity[testSuiteFinished name='" - << escape( testGroupStats.groupInfo.name ) << "']\n"; - } - - - void assertionStarting( AssertionInfo const& ) override {} - - bool assertionEnded( AssertionStats const& assertionStats ) override { - AssertionResult const& result = assertionStats.assertionResult; - if( !result.isOk() ) { - - ReusableStringStream msg; - if( !m_headerPrintedForThisSection ) - printSectionHeader( msg.get() ); - m_headerPrintedForThisSection = true; - - msg << result.getSourceInfo() << "\n"; - - switch( result.getResultType() ) { - case ResultWas::ExpressionFailed: - msg << "expression failed"; - break; - case ResultWas::ThrewException: - msg << "unexpected exception"; - break; - case ResultWas::FatalErrorCondition: - msg << "fatal error condition"; - break; - case ResultWas::DidntThrowException: - msg << "no exception was thrown where one was expected"; - break; - case ResultWas::ExplicitFailure: - msg << "explicit failure"; - break; - - // We shouldn't get here because of the isOk() test - case ResultWas::Ok: - case ResultWas::Info: - case ResultWas::Warning: - CATCH_ERROR( "Internal error in TeamCity reporter" ); - // These cases are here to prevent compiler warnings - case ResultWas::Unknown: - case ResultWas::FailureBit: - case ResultWas::Exception: - CATCH_ERROR( "Not implemented" ); - } - if( assertionStats.infoMessages.size() == 1 ) - msg << " with message:"; - if( assertionStats.infoMessages.size() > 1 ) - msg << " with messages:"; - for( auto const& messageInfo : assertionStats.infoMessages ) - msg << "\n \"" << messageInfo.message << "\""; - - - if( result.hasExpression() ) { - msg << - "\n " << result.getExpressionInMacro() << "\n" - "with expansion:\n" << - " " << result.getExpandedExpression() << "\n"; - } - - if( currentTestCaseInfo->okToFail() ) { - msg << "- failure ignore as test marked as 'ok to fail'\n"; - stream << "##teamcity[testIgnored" - << " name='" << escape( currentTestCaseInfo->name )<< "'" - << " message='" << escape( msg.str() ) << "'" - << "]\n"; - } - else { - stream << "##teamcity[testFailed" - << " name='" << escape( currentTestCaseInfo->name )<< "'" - << " message='" << escape( msg.str() ) << "'" - << "]\n"; - } - } - stream.flush(); - return true; - } - - void sectionStarting( SectionInfo const& sectionInfo ) override { - m_headerPrintedForThisSection = false; - StreamingReporterBase::sectionStarting( sectionInfo ); - } - - void testCaseStarting( TestCaseInfo const& testInfo ) override { - m_testTimer.start(); - StreamingReporterBase::testCaseStarting( testInfo ); - stream << "##teamcity[testStarted name='" - << escape( testInfo.name ) << "']\n"; - stream.flush(); - } - - void testCaseEnded( TestCaseStats const& testCaseStats ) override { - StreamingReporterBase::testCaseEnded( testCaseStats ); - if( !testCaseStats.stdOut.empty() ) - stream << "##teamcity[testStdOut name='" - << escape( testCaseStats.testInfo.name ) - << "' out='" << escape( testCaseStats.stdOut ) << "']\n"; - if( !testCaseStats.stdErr.empty() ) - stream << "##teamcity[testStdErr name='" - << escape( testCaseStats.testInfo.name ) - << "' out='" << escape( testCaseStats.stdErr ) << "']\n"; - stream << "##teamcity[testFinished name='" - << escape( testCaseStats.testInfo.name ) << "' duration='" - << m_testTimer.getElapsedMilliseconds() << "']\n"; - stream.flush(); - } - - private: - void printSectionHeader( std::ostream& os ) { - assert( !m_sectionStack.empty() ); - - if( m_sectionStack.size() > 1 ) { - os << getLineOfChars<'-'>() << "\n"; - - std::vector::const_iterator - it = m_sectionStack.begin()+1, // Skip first section (test case) - itEnd = m_sectionStack.end(); - for( ; it != itEnd; ++it ) - printHeaderString( os, it->name ); - os << getLineOfChars<'-'>() << "\n"; - } - - SourceLineInfo lineInfo = m_sectionStack.front().lineInfo; - - os << lineInfo << "\n"; - os << getLineOfChars<'.'>() << "\n\n"; - } - - // if string has a : in first line will set indent to follow it on - // subsequent lines - static void printHeaderString( std::ostream& os, std::string const& _string, std::size_t indent = 0 ) { - std::size_t i = _string.find( ": " ); - if( i != std::string::npos ) - i+=2; - else - i = 0; - os << Column( _string ) - .indent( indent+i) - .initialIndent( indent ) << "\n"; - } - private: - bool m_headerPrintedForThisSection = false; - Timer m_testTimer; - }; - -#ifdef CATCH_IMPL - TeamCityReporter::~TeamCityReporter() {} -#endif - - CATCH_REGISTER_REPORTER( "teamcity", TeamCityReporter ) - -} // end namespace Catch - -#ifdef __clang__ -# pragma clang diagnostic pop -#endif - -#endif // TWOBLUECUBES_CATCH_REPORTER_TEAMCITY_HPP_INCLUDED +/* + * Created by Phil Nash on 19th December 2014 + * Copyright 2014 Two Blue Cubes Ltd. All rights reserved. + * + * Distributed under the Boost Software License, Version 1.0. (See accompanying + * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + */ +#ifndef TWOBLUECUBES_CATCH_REPORTER_TEAMCITY_HPP_INCLUDED +#define TWOBLUECUBES_CATCH_REPORTER_TEAMCITY_HPP_INCLUDED + +// Don't #include any Catch headers here - we can assume they are already +// included before this header. +// This is not good practice in general but is necessary in this case so this +// file can be distributed as a single header that works with the main +// Catch single header. + +#include + +#ifdef __clang__ +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wpadded" +#endif + +namespace Catch { + + struct TeamCityReporter : StreamingReporterBase { + TeamCityReporter( ReporterConfig const& _config ) + : StreamingReporterBase( _config ) + { + m_reporterPrefs.shouldRedirectStdOut = true; + } + + static std::string escape( std::string const& str ) { + std::string escaped = str; + replaceInPlace( escaped, "|", "||" ); + replaceInPlace( escaped, "'", "|'" ); + replaceInPlace( escaped, "\n", "|n" ); + replaceInPlace( escaped, "\r", "|r" ); + replaceInPlace( escaped, "[", "|[" ); + replaceInPlace( escaped, "]", "|]" ); + return escaped; + } + ~TeamCityReporter() override; + + static std::string getDescription() { + return "Reports test results as TeamCity service messages"; + } + + void skipTest( TestCaseInfo const& /* testInfo */ ) override { + } + + void noMatchingTestCases( std::string const& /* spec */ ) override {} + + void testGroupStarting( GroupInfo const& groupInfo ) override { + StreamingReporterBase::testGroupStarting( groupInfo ); + stream << "##teamcity[testSuiteStarted name='" + << escape( groupInfo.name ) << "']\n"; + } + void testGroupEnded( TestGroupStats const& testGroupStats ) override { + StreamingReporterBase::testGroupEnded( testGroupStats ); + stream << "##teamcity[testSuiteFinished name='" + << escape( testGroupStats.groupInfo.name ) << "']\n"; + } + + + void assertionStarting( AssertionInfo const& ) override {} + + bool assertionEnded( AssertionStats const& assertionStats ) override { + AssertionResult const& result = assertionStats.assertionResult; + if( !result.isOk() ) { + + ReusableStringStream msg; + if( !m_headerPrintedForThisSection ) + printSectionHeader( msg.get() ); + m_headerPrintedForThisSection = true; + + msg << result.getSourceInfo() << "\n"; + + switch( result.getResultType() ) { + case ResultWas::ExpressionFailed: + msg << "expression failed"; + break; + case ResultWas::ThrewException: + msg << "unexpected exception"; + break; + case ResultWas::FatalErrorCondition: + msg << "fatal error condition"; + break; + case ResultWas::DidntThrowException: + msg << "no exception was thrown where one was expected"; + break; + case ResultWas::ExplicitFailure: + msg << "explicit failure"; + break; + + // We shouldn't get here because of the isOk() test + case ResultWas::Ok: + case ResultWas::Info: + case ResultWas::Warning: + CATCH_ERROR( "Internal error in TeamCity reporter" ); + // These cases are here to prevent compiler warnings + case ResultWas::Unknown: + case ResultWas::FailureBit: + case ResultWas::Exception: + CATCH_ERROR( "Not implemented" ); + } + if( assertionStats.infoMessages.size() == 1 ) + msg << " with message:"; + if( assertionStats.infoMessages.size() > 1 ) + msg << " with messages:"; + for( auto const& messageInfo : assertionStats.infoMessages ) + msg << "\n \"" << messageInfo.message << "\""; + + + if( result.hasExpression() ) { + msg << + "\n " << result.getExpressionInMacro() << "\n" + "with expansion:\n" << + " " << result.getExpandedExpression() << "\n"; + } + + if( currentTestCaseInfo->okToFail() ) { + msg << "- failure ignore as test marked as 'ok to fail'\n"; + stream << "##teamcity[testIgnored" + << " name='" << escape( currentTestCaseInfo->name )<< "'" + << " message='" << escape( msg.str() ) << "'" + << "]\n"; + } + else { + stream << "##teamcity[testFailed" + << " name='" << escape( currentTestCaseInfo->name )<< "'" + << " message='" << escape( msg.str() ) << "'" + << "]\n"; + } + } + stream.flush(); + return true; + } + + void sectionStarting( SectionInfo const& sectionInfo ) override { + m_headerPrintedForThisSection = false; + StreamingReporterBase::sectionStarting( sectionInfo ); + } + + void testCaseStarting( TestCaseInfo const& testInfo ) override { + m_testTimer.start(); + StreamingReporterBase::testCaseStarting( testInfo ); + stream << "##teamcity[testStarted name='" + << escape( testInfo.name ) << "']\n"; + stream.flush(); + } + + void testCaseEnded( TestCaseStats const& testCaseStats ) override { + StreamingReporterBase::testCaseEnded( testCaseStats ); + if( !testCaseStats.stdOut.empty() ) + stream << "##teamcity[testStdOut name='" + << escape( testCaseStats.testInfo.name ) + << "' out='" << escape( testCaseStats.stdOut ) << "']\n"; + if( !testCaseStats.stdErr.empty() ) + stream << "##teamcity[testStdErr name='" + << escape( testCaseStats.testInfo.name ) + << "' out='" << escape( testCaseStats.stdErr ) << "']\n"; + stream << "##teamcity[testFinished name='" + << escape( testCaseStats.testInfo.name ) << "' duration='" + << m_testTimer.getElapsedMilliseconds() << "']\n"; + stream.flush(); + } + + private: + void printSectionHeader( std::ostream& os ) { + assert( !m_sectionStack.empty() ); + + if( m_sectionStack.size() > 1 ) { + os << getLineOfChars<'-'>() << "\n"; + + std::vector::const_iterator + it = m_sectionStack.begin()+1, // Skip first section (test case) + itEnd = m_sectionStack.end(); + for( ; it != itEnd; ++it ) + printHeaderString( os, it->name ); + os << getLineOfChars<'-'>() << "\n"; + } + + SourceLineInfo lineInfo = m_sectionStack.front().lineInfo; + + os << lineInfo << "\n"; + os << getLineOfChars<'.'>() << "\n\n"; + } + + // if string has a : in first line will set indent to follow it on + // subsequent lines + static void printHeaderString( std::ostream& os, std::string const& _string, std::size_t indent = 0 ) { + std::size_t i = _string.find( ": " ); + if( i != std::string::npos ) + i+=2; + else + i = 0; + os << Column( _string ) + .indent( indent+i) + .initialIndent( indent ) << "\n"; + } + private: + bool m_headerPrintedForThisSection = false; + Timer m_testTimer; + }; + +#ifdef CATCH_IMPL + TeamCityReporter::~TeamCityReporter() {} +#endif + + CATCH_REGISTER_REPORTER( "teamcity", TeamCityReporter ) + +} // end namespace Catch + +#ifdef __clang__ +# pragma clang diagnostic pop +#endif + +#endif // TWOBLUECUBES_CATCH_REPORTER_TEAMCITY_HPP_INCLUDED diff --git a/third_party/libgralloc/include/gralloc_priv.h b/third_party/libgralloc/include/gralloc_priv.h deleted file mode 100644 index 4aa47541b0..0000000000 --- a/third_party/libgralloc/include/gralloc_priv.h +++ /dev/null @@ -1,296 +0,0 @@ -/* - * Copyright (C) 2008 The Android Open Source Project - * Copyright (c) 2011-2015, The Linux Foundation. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef GRALLOC_PRIV_H_ -#define GRALLOC_PRIV_H_ - -#include -#include -#include -#include -#include -#include -#include - -#include - -#include - -#define ROUND_UP_PAGESIZE(x) ( (((unsigned long)(x)) + PAGE_SIZE-1) & \ - (~(PAGE_SIZE-1)) ) - -/* Gralloc usage bits indicating the type of allocation that should be used */ -/* SYSTEM heap comes from kernel vmalloc (ION_SYSTEM_HEAP_ID) - * is cached by default and - * is not secured */ - -/* GRALLOC_USAGE_PRIVATE_0 is unused */ - -/* Non linear, Universal Bandwidth Compression */ -#define GRALLOC_USAGE_PRIVATE_ALLOC_UBWC GRALLOC_USAGE_PRIVATE_1 - -/* IOMMU heap comes from manually allocated pages, can be cached/uncached, - * is not secured */ -#define GRALLOC_USAGE_PRIVATE_IOMMU_HEAP GRALLOC_USAGE_PRIVATE_2 - -/* MM heap is a carveout heap for video, can be secured */ -#define GRALLOC_USAGE_PRIVATE_MM_HEAP GRALLOC_USAGE_PRIVATE_3 - -/* ADSP heap is a carveout heap, is not secured */ -#define GRALLOC_USAGE_PRIVATE_ADSP_HEAP 0x01000000 - -/* Set this for allocating uncached memory (using O_DSYNC), - * cannot be used with noncontiguous heaps */ -#define GRALLOC_USAGE_PRIVATE_UNCACHED 0x02000000 - -/* Buffer content should be displayed on an primary display only */ -#define GRALLOC_USAGE_PRIVATE_INTERNAL_ONLY 0x04000000 - -/* Buffer content should be displayed on an external display only */ -#define GRALLOC_USAGE_PRIVATE_EXTERNAL_ONLY 0x08000000 - -/* This flag is set for WFD usecase */ -#define GRALLOC_USAGE_PRIVATE_WFD 0x00200000 - -/* CAMERA heap is a carveout heap for camera, is not secured */ -#define GRALLOC_USAGE_PRIVATE_CAMERA_HEAP 0x00400000 - -/* This flag is used for SECURE display usecase */ -#define GRALLOC_USAGE_PRIVATE_SECURE_DISPLAY 0x00800000 - -/* define Gralloc perform */ -#define GRALLOC_MODULE_PERFORM_CREATE_HANDLE_FROM_BUFFER 1 -// This will be used by the graphics drivers to know if certain features -// are defined in this display HAL. -// Ex: Newer GFX libraries + Older Display HAL -#define GRALLOC_MODULE_PERFORM_GET_STRIDE 2 -#define GRALLOC_MODULE_PERFORM_GET_CUSTOM_STRIDE_FROM_HANDLE 3 -#define GRALLOC_MODULE_PERFORM_GET_CUSTOM_STRIDE_AND_HEIGHT_FROM_HANDLE 4 -#define GRALLOC_MODULE_PERFORM_GET_ATTRIBUTES 5 -#define GRALLOC_MODULE_PERFORM_GET_COLOR_SPACE_FROM_HANDLE 6 -#define GRALLOC_MODULE_PERFORM_GET_YUV_PLANE_INFO 7 -#define GRALLOC_MODULE_PERFORM_GET_MAP_SECURE_BUFFER_INFO 8 -#define GRALLOC_MODULE_PERFORM_GET_UBWC_FLAG 9 -#define GRALLOC_MODULE_PERFORM_GET_RGB_DATA_ADDRESS 10 -#define GRALLOC_MODULE_PERFORM_GET_IGC 11 -#define GRALLOC_MODULE_PERFORM_SET_IGC 12 -#define GRALLOC_MODULE_PERFORM_SET_SINGLE_BUFFER_MODE 13 - -/* OEM specific HAL formats */ - -#define HAL_PIXEL_FORMAT_RGBA_5551 6 -#define HAL_PIXEL_FORMAT_RGBA_4444 7 -#define HAL_PIXEL_FORMAT_NV12_ENCODEABLE 0x102 -#define HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS 0x7FA30C04 -#define HAL_PIXEL_FORMAT_YCbCr_420_SP_TILED 0x7FA30C03 -#define HAL_PIXEL_FORMAT_YCbCr_420_SP 0x109 -#define HAL_PIXEL_FORMAT_YCrCb_420_SP_ADRENO 0x7FA30C01 -#define HAL_PIXEL_FORMAT_YCrCb_422_SP 0x10B -#define HAL_PIXEL_FORMAT_R_8 0x10D -#define HAL_PIXEL_FORMAT_RG_88 0x10E -#define HAL_PIXEL_FORMAT_YCbCr_444_SP 0x10F -#define HAL_PIXEL_FORMAT_YCrCb_444_SP 0x110 -#define HAL_PIXEL_FORMAT_YCrCb_422_I 0x111 -#define HAL_PIXEL_FORMAT_BGRX_8888 0x112 -#define HAL_PIXEL_FORMAT_NV21_ZSL 0x113 -#define HAL_PIXEL_FORMAT_YCrCb_420_SP_VENUS 0x114 -#define HAL_PIXEL_FORMAT_BGR_565 0x115 -#define HAL_PIXEL_FORMAT_INTERLACE 0x180 - -//v4l2_fourcc('Y', 'U', 'Y', 'L'). 24 bpp YUYV 4:2:2 10 bit per component -#define HAL_PIXEL_FORMAT_YCbCr_422_I_10BIT 0x4C595559 - -//v4l2_fourcc('Y', 'B', 'W', 'C'). 10 bit per component. This compressed -//format reduces the memory access bandwidth -#define HAL_PIXEL_FORMAT_YCbCr_422_I_10BIT_COMPRESSED 0x43574259 - -// UBWC aligned Venus format -#define HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS_UBWC 0x7FA30C06 - -//Khronos ASTC formats -#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_4x4_KHR 0x93B0 -#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_5x4_KHR 0x93B1 -#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_5x5_KHR 0x93B2 -#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_6x5_KHR 0x93B3 -#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_6x6_KHR 0x93B4 -#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_8x5_KHR 0x93B5 -#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_8x6_KHR 0x93B6 -#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_8x8_KHR 0x93B7 -#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_10x5_KHR 0x93B8 -#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_10x6_KHR 0x93B9 -#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_10x8_KHR 0x93BA -#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_10x10_KHR 0x93BB -#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_12x10_KHR 0x93BC -#define HAL_PIXEL_FORMAT_COMPRESSED_RGBA_ASTC_12x12_KHR 0x93BD -#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR 0x93D0 -#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR 0x93D1 -#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR 0x93D2 -#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR 0x93D3 -#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR 0x93D4 -#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR 0x93D5 -#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR 0x93D6 -#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR 0x93D7 -#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR 0x93D8 -#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR 0x93D9 -#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR 0x93DA -#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR 0x93DB -#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR 0x93DC -#define HAL_PIXEL_FORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR 0x93DD - -/* possible values for inverse gamma correction */ -#define HAL_IGC_NOT_SPECIFIED 0 -#define HAL_IGC_s_RGB 1 - -/* possible formats for 3D content*/ -enum { - HAL_NO_3D = 0x0, - HAL_3D_SIDE_BY_SIDE_L_R = 0x1, - HAL_3D_SIDE_BY_SIDE_R_L = 0x2, - HAL_3D_TOP_BOTTOM = 0x4, - HAL_3D_IN_SIDE_BY_SIDE_L_R = 0x10000, //unused legacy format -}; - -enum { - BUFFER_TYPE_UI = 0, - BUFFER_TYPE_VIDEO -}; - -#ifdef __cplusplus -struct private_handle_t : public native_handle { -#else - struct private_handle_t { - native_handle_t nativeHandle; -#endif - enum { - PRIV_FLAGS_FRAMEBUFFER = 0x00000001, - PRIV_FLAGS_USES_ION = 0x00000008, - PRIV_FLAGS_USES_ASHMEM = 0x00000010, - PRIV_FLAGS_NEEDS_FLUSH = 0x00000020, - PRIV_FLAGS_INTERNAL_ONLY = 0x00000040, - PRIV_FLAGS_NON_CPU_WRITER = 0x00000080, - PRIV_FLAGS_NONCONTIGUOUS_MEM = 0x00000100, - PRIV_FLAGS_CACHED = 0x00000200, - PRIV_FLAGS_SECURE_BUFFER = 0x00000400, - // Display on external only - PRIV_FLAGS_EXTERNAL_ONLY = 0x00002000, - // Set by HWC for protected non secure buffers - PRIV_FLAGS_PROTECTED_BUFFER = 0x00004000, - PRIV_FLAGS_VIDEO_ENCODER = 0x00010000, - PRIV_FLAGS_CAMERA_WRITE = 0x00020000, - PRIV_FLAGS_CAMERA_READ = 0x00040000, - PRIV_FLAGS_HW_COMPOSER = 0x00080000, - PRIV_FLAGS_HW_TEXTURE = 0x00100000, - PRIV_FLAGS_ITU_R_601 = 0x00200000, //Unused from display - PRIV_FLAGS_ITU_R_601_FR = 0x00400000, //Unused from display - PRIV_FLAGS_ITU_R_709 = 0x00800000, //Unused from display - PRIV_FLAGS_SECURE_DISPLAY = 0x01000000, - // Buffer is rendered in Tile Format - PRIV_FLAGS_TILE_RENDERED = 0x02000000, - // Buffer rendered using CPU/SW renderer - PRIV_FLAGS_CPU_RENDERED = 0x04000000, - // Buffer is allocated with UBWC alignment - PRIV_FLAGS_UBWC_ALIGNED = 0x08000000, - // Buffer allocated will be consumed by SF/HWC - PRIV_FLAGS_DISP_CONSUMER = 0x10000000 - }; - - // file-descriptors - int fd; - int fd_metadata; // fd for the meta-data - // ints - int magic; - int flags; - unsigned int size; - unsigned int offset; - int bufferType; - uint64_t base __attribute__((aligned(8))); - unsigned int offset_metadata; - // The gpu address mapped into the mmu. - uint64_t gpuaddr __attribute__((aligned(8))); - int format; - int width; // specifies aligned width - int height; // specifies aligned height - int real_width; - int real_height; - uint64_t base_metadata __attribute__((aligned(8))); - -#ifdef __cplusplus - static const int sNumFds = 2; - static inline int sNumInts() { - return ((sizeof(private_handle_t) - sizeof(native_handle_t)) / - sizeof(int)) - sNumFds; - } - static const int sMagic = 'gmsm'; - - private_handle_t(int fd, unsigned int size, int flags, int bufferType, - int format, int aligned_width, int aligned_height, - int width, int height, int eFd = -1, - unsigned int eOffset = 0, uint64_t eBase = 0) : - fd(fd), fd_metadata(eFd), magic(sMagic), - flags(flags), size(size), offset(0), bufferType(bufferType), - base(0), offset_metadata(eOffset), gpuaddr(0), - format(format), width(aligned_width), height(aligned_height), - real_width(width), real_height(height), base_metadata(eBase) - { - version = (int) sizeof(native_handle); - numInts = sNumInts(); - numFds = sNumFds; - } - ~private_handle_t() { - magic = 0; - } - - static int validate(const native_handle* h) { - const private_handle_t* hnd = (const private_handle_t*)h; - if (!h || h->version != sizeof(native_handle) || - h->numInts != sNumInts() || h->numFds != sNumFds || - hnd->magic != sMagic) - { - ALOGD("Invalid gralloc handle (at %p): " - "ver(%d/%zu) ints(%d/%d) fds(%d/%d)" - "magic(%c%c%c%c/%c%c%c%c)", - h, - h ? h->version : -1, sizeof(native_handle), - h ? h->numInts : -1, sNumInts(), - h ? h->numFds : -1, sNumFds, - hnd ? (((hnd->magic >> 24) & 0xFF)? - ((hnd->magic >> 24) & 0xFF) : '-') : '?', - hnd ? (((hnd->magic >> 16) & 0xFF)? - ((hnd->magic >> 16) & 0xFF) : '-') : '?', - hnd ? (((hnd->magic >> 8) & 0xFF)? - ((hnd->magic >> 8) & 0xFF) : '-') : '?', - hnd ? (((hnd->magic >> 0) & 0xFF)? - ((hnd->magic >> 0) & 0xFF) : '-') : '?', - (sMagic >> 24) & 0xFF, - (sMagic >> 16) & 0xFF, - (sMagic >> 8) & 0xFF, - (sMagic >> 0) & 0xFF); - return -EINVAL; - } - return 0; - } - - static private_handle_t* dynamicCast(const native_handle* in) { - if (validate(in) == 0) { - return (private_handle_t*) in; - } - return NULL; - } -#endif - }; - -#endif /* GRALLOC_PRIV_H_ */ diff --git a/third_party/libyuv/x64/lib/libyuv.a b/third_party/libyuv/x64/lib/libyuv.a index c6afc56433..ef786b1172 100644 Binary files a/third_party/libyuv/x64/lib/libyuv.a and b/third_party/libyuv/x64/lib/libyuv.a differ diff --git a/selfdrive/loggerd/include/msm_media_info.h b/third_party/linux/include/msm_media_info.h similarity index 100% rename from selfdrive/loggerd/include/msm_media_info.h rename to third_party/linux/include/msm_media_info.h diff --git a/third_party/linux/include/v4l2-controls.h b/third_party/linux/include/v4l2-controls.h new file mode 100644 index 0000000000..d14cd8fabe --- /dev/null +++ b/third_party/linux/include/v4l2-controls.h @@ -0,0 +1,1696 @@ +/* + * Video for Linux Two controls header file + * + * Copyright (C) 1999-2012 the contributors + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program 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 General Public License for more details. + * + * Alternatively you can redistribute this file under the terms of the + * BSD license as stated below: + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. 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. + * 3. The names of its contributors may not 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 AND FITNESS FOR + * A PARTICULAR PURPOSE 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. + * + * The contents of this header was split off from videodev2.h. All control + * definitions should be added to this header, which is included by + * videodev2.h. + */ + +#ifndef __LINUX_V4L2_CONTROLS_H +#define __LINUX_V4L2_CONTROLS_H + +/* Control classes */ +#define V4L2_CTRL_CLASS_USER 0x00980000 /* Old-style 'user' controls */ +#define V4L2_CTRL_CLASS_MPEG 0x00990000 /* MPEG-compression controls */ +#define V4L2_CTRL_CLASS_CAMERA 0x009a0000 /* Camera class controls */ +#define V4L2_CTRL_CLASS_FM_TX 0x009b0000 /* FM Modulator controls */ +#define V4L2_CTRL_CLASS_FLASH 0x009c0000 /* Camera flash controls */ +#define V4L2_CTRL_CLASS_JPEG 0x009d0000 /* JPEG-compression controls */ +#define V4L2_CTRL_CLASS_IMAGE_SOURCE 0x009e0000 /* Image source controls */ +#define V4L2_CTRL_CLASS_IMAGE_PROC 0x009f0000 /* Image processing controls */ +#define V4L2_CTRL_CLASS_DV 0x00a00000 /* Digital Video controls */ +#define V4L2_CTRL_CLASS_FM_RX 0x00a10000 /* FM Receiver controls */ +#define V4L2_CTRL_CLASS_RF_TUNER 0x00a20000 /* RF tuner controls */ +#define V4L2_CTRL_CLASS_DETECT 0x00a30000 /* Detection controls */ + +/* User-class control IDs */ + +#define V4L2_CID_BASE (V4L2_CTRL_CLASS_USER | 0x900) +#define V4L2_CID_USER_BASE V4L2_CID_BASE +#define V4L2_CID_USER_CLASS (V4L2_CTRL_CLASS_USER | 1) +#define V4L2_CID_BRIGHTNESS (V4L2_CID_BASE+0) +#define V4L2_CID_CONTRAST (V4L2_CID_BASE+1) +#define V4L2_CID_SATURATION (V4L2_CID_BASE+2) +#define V4L2_CID_HUE (V4L2_CID_BASE+3) +#define V4L2_CID_AUDIO_VOLUME (V4L2_CID_BASE+5) +#define V4L2_CID_AUDIO_BALANCE (V4L2_CID_BASE+6) +#define V4L2_CID_AUDIO_BASS (V4L2_CID_BASE+7) +#define V4L2_CID_AUDIO_TREBLE (V4L2_CID_BASE+8) +#define V4L2_CID_AUDIO_MUTE (V4L2_CID_BASE+9) +#define V4L2_CID_AUDIO_LOUDNESS (V4L2_CID_BASE+10) +#define V4L2_CID_BLACK_LEVEL (V4L2_CID_BASE+11) /* Deprecated */ +#define V4L2_CID_AUTO_WHITE_BALANCE (V4L2_CID_BASE+12) +#define V4L2_CID_DO_WHITE_BALANCE (V4L2_CID_BASE+13) +#define V4L2_CID_RED_BALANCE (V4L2_CID_BASE+14) +#define V4L2_CID_BLUE_BALANCE (V4L2_CID_BASE+15) +#define V4L2_CID_GAMMA (V4L2_CID_BASE+16) +#define V4L2_CID_WHITENESS (V4L2_CID_GAMMA) /* Deprecated */ +#define V4L2_CID_EXPOSURE (V4L2_CID_BASE+17) +#define V4L2_CID_AUTOGAIN (V4L2_CID_BASE+18) +#define V4L2_CID_GAIN (V4L2_CID_BASE+19) +#define V4L2_CID_HFLIP (V4L2_CID_BASE+20) +#define V4L2_CID_VFLIP (V4L2_CID_BASE+21) + +#define V4L2_CID_POWER_LINE_FREQUENCY (V4L2_CID_BASE+24) +enum v4l2_power_line_frequency { + V4L2_CID_POWER_LINE_FREQUENCY_DISABLED = 0, + V4L2_CID_POWER_LINE_FREQUENCY_50HZ = 1, + V4L2_CID_POWER_LINE_FREQUENCY_60HZ = 2, + V4L2_CID_POWER_LINE_FREQUENCY_AUTO = 3, +}; +#define V4L2_CID_HUE_AUTO (V4L2_CID_BASE+25) +#define V4L2_CID_WHITE_BALANCE_TEMPERATURE (V4L2_CID_BASE+26) +#define V4L2_CID_SHARPNESS (V4L2_CID_BASE+27) +#define V4L2_CID_BACKLIGHT_COMPENSATION (V4L2_CID_BASE+28) +#define V4L2_CID_CHROMA_AGC (V4L2_CID_BASE+29) +#define V4L2_CID_COLOR_KILLER (V4L2_CID_BASE+30) +#define V4L2_CID_COLORFX (V4L2_CID_BASE+31) +enum v4l2_colorfx { + V4L2_COLORFX_NONE = 0, + V4L2_COLORFX_BW = 1, + V4L2_COLORFX_SEPIA = 2, + V4L2_COLORFX_NEGATIVE = 3, + V4L2_COLORFX_EMBOSS = 4, + V4L2_COLORFX_SKETCH = 5, + V4L2_COLORFX_SKY_BLUE = 6, + V4L2_COLORFX_GRASS_GREEN = 7, + V4L2_COLORFX_SKIN_WHITEN = 8, + V4L2_COLORFX_VIVID = 9, + V4L2_COLORFX_AQUA = 10, + V4L2_COLORFX_ART_FREEZE = 11, + V4L2_COLORFX_SILHOUETTE = 12, + V4L2_COLORFX_SOLARIZATION = 13, + V4L2_COLORFX_ANTIQUE = 14, + V4L2_COLORFX_SET_CBCR = 15, +}; +#define V4L2_CID_AUTOBRIGHTNESS (V4L2_CID_BASE+32) +#define V4L2_CID_BAND_STOP_FILTER (V4L2_CID_BASE+33) + +#define V4L2_CID_ROTATE (V4L2_CID_BASE+34) +#define V4L2_CID_BG_COLOR (V4L2_CID_BASE+35) + +#define V4L2_CID_CHROMA_GAIN (V4L2_CID_BASE+36) + +#define V4L2_CID_ILLUMINATORS_1 (V4L2_CID_BASE+37) +#define V4L2_CID_ILLUMINATORS_2 (V4L2_CID_BASE+38) + +#define V4L2_CID_MIN_BUFFERS_FOR_CAPTURE (V4L2_CID_BASE+39) +#define V4L2_CID_MIN_BUFFERS_FOR_OUTPUT (V4L2_CID_BASE+40) + +#define V4L2_CID_ALPHA_COMPONENT (V4L2_CID_BASE+41) +#define V4L2_CID_COLORFX_CBCR (V4L2_CID_BASE+42) + +/* last CID + 1 */ +#define V4L2_CID_LASTP1 (V4L2_CID_BASE+43) + +/* USER-class private control IDs */ + +/* The base for the meye driver controls. See linux/meye.h for the list + * of controls. We reserve 16 controls for this driver. */ +#define V4L2_CID_USER_MEYE_BASE (V4L2_CID_USER_BASE + 0x1000) + +/* The base for the bttv driver controls. + * We reserve 32 controls for this driver. */ +#define V4L2_CID_USER_BTTV_BASE (V4L2_CID_USER_BASE + 0x1010) + + +/* The base for the s2255 driver controls. + * We reserve 16 controls for this driver. */ +#define V4L2_CID_USER_S2255_BASE (V4L2_CID_USER_BASE + 0x1030) + +/* + * The base for the si476x driver controls. See include/media/drv-intf/si476x.h + * for the list of controls. Total of 16 controls is reserved for this driver + */ +#define V4L2_CID_USER_SI476X_BASE (V4L2_CID_USER_BASE + 0x1040) + +/* The base for the TI VPE driver controls. Total of 16 controls is reserved for + * this driver */ +#define V4L2_CID_USER_TI_VPE_BASE (V4L2_CID_USER_BASE + 0x1050) + +/* The base for the saa7134 driver controls. + * We reserve 16 controls for this driver. */ +#define V4L2_CID_USER_SAA7134_BASE (V4L2_CID_USER_BASE + 0x1060) + +/* The base for the adv7180 driver controls. + * We reserve 16 controls for this driver. */ +#define V4L2_CID_USER_ADV7180_BASE (V4L2_CID_USER_BASE + 0x1070) + +/* The base for the tc358743 driver controls. + * We reserve 16 controls for this driver. */ +#define V4L2_CID_USER_TC358743_BASE (V4L2_CID_USER_BASE + 0x1080) + +/* MPEG-class control IDs */ +/* The MPEG controls are applicable to all codec controls + * and the 'MPEG' part of the define is historical */ + +#define V4L2_CID_MPEG_BASE (V4L2_CTRL_CLASS_MPEG | 0x900) +#define V4L2_CID_MPEG_CLASS (V4L2_CTRL_CLASS_MPEG | 1) + +/* MPEG streams, specific to multiplexed streams */ +#define V4L2_CID_MPEG_STREAM_TYPE (V4L2_CID_MPEG_BASE+0) +enum v4l2_mpeg_stream_type { + V4L2_MPEG_STREAM_TYPE_MPEG2_PS = 0, /* MPEG-2 program stream */ + V4L2_MPEG_STREAM_TYPE_MPEG2_TS = 1, /* MPEG-2 transport stream */ + V4L2_MPEG_STREAM_TYPE_MPEG1_SS = 2, /* MPEG-1 system stream */ + V4L2_MPEG_STREAM_TYPE_MPEG2_DVD = 3, /* MPEG-2 DVD-compatible stream */ + V4L2_MPEG_STREAM_TYPE_MPEG1_VCD = 4, /* MPEG-1 VCD-compatible stream */ + V4L2_MPEG_STREAM_TYPE_MPEG2_SVCD = 5, /* MPEG-2 SVCD-compatible stream */ +}; +#define V4L2_CID_MPEG_STREAM_PID_PMT (V4L2_CID_MPEG_BASE+1) +#define V4L2_CID_MPEG_STREAM_PID_AUDIO (V4L2_CID_MPEG_BASE+2) +#define V4L2_CID_MPEG_STREAM_PID_VIDEO (V4L2_CID_MPEG_BASE+3) +#define V4L2_CID_MPEG_STREAM_PID_PCR (V4L2_CID_MPEG_BASE+4) +#define V4L2_CID_MPEG_STREAM_PES_ID_AUDIO (V4L2_CID_MPEG_BASE+5) +#define V4L2_CID_MPEG_STREAM_PES_ID_VIDEO (V4L2_CID_MPEG_BASE+6) +#define V4L2_CID_MPEG_STREAM_VBI_FMT (V4L2_CID_MPEG_BASE+7) +enum v4l2_mpeg_stream_vbi_fmt { + V4L2_MPEG_STREAM_VBI_FMT_NONE = 0, /* No VBI in the MPEG stream */ + V4L2_MPEG_STREAM_VBI_FMT_IVTV = 1, /* VBI in private packets, IVTV format */ +}; + +/* MPEG audio controls specific to multiplexed streams */ +#define V4L2_CID_MPEG_AUDIO_SAMPLING_FREQ (V4L2_CID_MPEG_BASE+100) +enum v4l2_mpeg_audio_sampling_freq { + V4L2_MPEG_AUDIO_SAMPLING_FREQ_44100 = 0, + V4L2_MPEG_AUDIO_SAMPLING_FREQ_48000 = 1, + V4L2_MPEG_AUDIO_SAMPLING_FREQ_32000 = 2, +}; +#define V4L2_CID_MPEG_AUDIO_ENCODING (V4L2_CID_MPEG_BASE+101) +enum v4l2_mpeg_audio_encoding { + V4L2_MPEG_AUDIO_ENCODING_LAYER_1 = 0, + V4L2_MPEG_AUDIO_ENCODING_LAYER_2 = 1, + V4L2_MPEG_AUDIO_ENCODING_LAYER_3 = 2, + V4L2_MPEG_AUDIO_ENCODING_AAC = 3, + V4L2_MPEG_AUDIO_ENCODING_AC3 = 4, +}; +#define V4L2_CID_MPEG_AUDIO_L1_BITRATE (V4L2_CID_MPEG_BASE+102) +enum v4l2_mpeg_audio_l1_bitrate { + V4L2_MPEG_AUDIO_L1_BITRATE_32K = 0, + V4L2_MPEG_AUDIO_L1_BITRATE_64K = 1, + V4L2_MPEG_AUDIO_L1_BITRATE_96K = 2, + V4L2_MPEG_AUDIO_L1_BITRATE_128K = 3, + V4L2_MPEG_AUDIO_L1_BITRATE_160K = 4, + V4L2_MPEG_AUDIO_L1_BITRATE_192K = 5, + V4L2_MPEG_AUDIO_L1_BITRATE_224K = 6, + V4L2_MPEG_AUDIO_L1_BITRATE_256K = 7, + V4L2_MPEG_AUDIO_L1_BITRATE_288K = 8, + V4L2_MPEG_AUDIO_L1_BITRATE_320K = 9, + V4L2_MPEG_AUDIO_L1_BITRATE_352K = 10, + V4L2_MPEG_AUDIO_L1_BITRATE_384K = 11, + V4L2_MPEG_AUDIO_L1_BITRATE_416K = 12, + V4L2_MPEG_AUDIO_L1_BITRATE_448K = 13, +}; +#define V4L2_CID_MPEG_AUDIO_L2_BITRATE (V4L2_CID_MPEG_BASE+103) +enum v4l2_mpeg_audio_l2_bitrate { + V4L2_MPEG_AUDIO_L2_BITRATE_32K = 0, + V4L2_MPEG_AUDIO_L2_BITRATE_48K = 1, + V4L2_MPEG_AUDIO_L2_BITRATE_56K = 2, + V4L2_MPEG_AUDIO_L2_BITRATE_64K = 3, + V4L2_MPEG_AUDIO_L2_BITRATE_80K = 4, + V4L2_MPEG_AUDIO_L2_BITRATE_96K = 5, + V4L2_MPEG_AUDIO_L2_BITRATE_112K = 6, + V4L2_MPEG_AUDIO_L2_BITRATE_128K = 7, + V4L2_MPEG_AUDIO_L2_BITRATE_160K = 8, + V4L2_MPEG_AUDIO_L2_BITRATE_192K = 9, + V4L2_MPEG_AUDIO_L2_BITRATE_224K = 10, + V4L2_MPEG_AUDIO_L2_BITRATE_256K = 11, + V4L2_MPEG_AUDIO_L2_BITRATE_320K = 12, + V4L2_MPEG_AUDIO_L2_BITRATE_384K = 13, +}; +#define V4L2_CID_MPEG_AUDIO_L3_BITRATE (V4L2_CID_MPEG_BASE+104) +enum v4l2_mpeg_audio_l3_bitrate { + V4L2_MPEG_AUDIO_L3_BITRATE_32K = 0, + V4L2_MPEG_AUDIO_L3_BITRATE_40K = 1, + V4L2_MPEG_AUDIO_L3_BITRATE_48K = 2, + V4L2_MPEG_AUDIO_L3_BITRATE_56K = 3, + V4L2_MPEG_AUDIO_L3_BITRATE_64K = 4, + V4L2_MPEG_AUDIO_L3_BITRATE_80K = 5, + V4L2_MPEG_AUDIO_L3_BITRATE_96K = 6, + V4L2_MPEG_AUDIO_L3_BITRATE_112K = 7, + V4L2_MPEG_AUDIO_L3_BITRATE_128K = 8, + V4L2_MPEG_AUDIO_L3_BITRATE_160K = 9, + V4L2_MPEG_AUDIO_L3_BITRATE_192K = 10, + V4L2_MPEG_AUDIO_L3_BITRATE_224K = 11, + V4L2_MPEG_AUDIO_L3_BITRATE_256K = 12, + V4L2_MPEG_AUDIO_L3_BITRATE_320K = 13, +}; +#define V4L2_CID_MPEG_AUDIO_MODE (V4L2_CID_MPEG_BASE+105) +enum v4l2_mpeg_audio_mode { + V4L2_MPEG_AUDIO_MODE_STEREO = 0, + V4L2_MPEG_AUDIO_MODE_JOINT_STEREO = 1, + V4L2_MPEG_AUDIO_MODE_DUAL = 2, + V4L2_MPEG_AUDIO_MODE_MONO = 3, +}; +#define V4L2_CID_MPEG_AUDIO_MODE_EXTENSION (V4L2_CID_MPEG_BASE+106) +enum v4l2_mpeg_audio_mode_extension { + V4L2_MPEG_AUDIO_MODE_EXTENSION_BOUND_4 = 0, + V4L2_MPEG_AUDIO_MODE_EXTENSION_BOUND_8 = 1, + V4L2_MPEG_AUDIO_MODE_EXTENSION_BOUND_12 = 2, + V4L2_MPEG_AUDIO_MODE_EXTENSION_BOUND_16 = 3, +}; +#define V4L2_CID_MPEG_AUDIO_EMPHASIS (V4L2_CID_MPEG_BASE+107) +enum v4l2_mpeg_audio_emphasis { + V4L2_MPEG_AUDIO_EMPHASIS_NONE = 0, + V4L2_MPEG_AUDIO_EMPHASIS_50_DIV_15_uS = 1, + V4L2_MPEG_AUDIO_EMPHASIS_CCITT_J17 = 2, +}; +#define V4L2_CID_MPEG_AUDIO_CRC (V4L2_CID_MPEG_BASE+108) +enum v4l2_mpeg_audio_crc { + V4L2_MPEG_AUDIO_CRC_NONE = 0, + V4L2_MPEG_AUDIO_CRC_CRC16 = 1, +}; +#define V4L2_CID_MPEG_AUDIO_MUTE (V4L2_CID_MPEG_BASE+109) +#define V4L2_CID_MPEG_AUDIO_AAC_BITRATE (V4L2_CID_MPEG_BASE+110) +#define V4L2_CID_MPEG_AUDIO_AC3_BITRATE (V4L2_CID_MPEG_BASE+111) +enum v4l2_mpeg_audio_ac3_bitrate { + V4L2_MPEG_AUDIO_AC3_BITRATE_32K = 0, + V4L2_MPEG_AUDIO_AC3_BITRATE_40K = 1, + V4L2_MPEG_AUDIO_AC3_BITRATE_48K = 2, + V4L2_MPEG_AUDIO_AC3_BITRATE_56K = 3, + V4L2_MPEG_AUDIO_AC3_BITRATE_64K = 4, + V4L2_MPEG_AUDIO_AC3_BITRATE_80K = 5, + V4L2_MPEG_AUDIO_AC3_BITRATE_96K = 6, + V4L2_MPEG_AUDIO_AC3_BITRATE_112K = 7, + V4L2_MPEG_AUDIO_AC3_BITRATE_128K = 8, + V4L2_MPEG_AUDIO_AC3_BITRATE_160K = 9, + V4L2_MPEG_AUDIO_AC3_BITRATE_192K = 10, + V4L2_MPEG_AUDIO_AC3_BITRATE_224K = 11, + V4L2_MPEG_AUDIO_AC3_BITRATE_256K = 12, + V4L2_MPEG_AUDIO_AC3_BITRATE_320K = 13, + V4L2_MPEG_AUDIO_AC3_BITRATE_384K = 14, + V4L2_MPEG_AUDIO_AC3_BITRATE_448K = 15, + V4L2_MPEG_AUDIO_AC3_BITRATE_512K = 16, + V4L2_MPEG_AUDIO_AC3_BITRATE_576K = 17, + V4L2_MPEG_AUDIO_AC3_BITRATE_640K = 18, +}; +#define V4L2_CID_MPEG_AUDIO_DEC_PLAYBACK (V4L2_CID_MPEG_BASE+112) +enum v4l2_mpeg_audio_dec_playback { + V4L2_MPEG_AUDIO_DEC_PLAYBACK_AUTO = 0, + V4L2_MPEG_AUDIO_DEC_PLAYBACK_STEREO = 1, + V4L2_MPEG_AUDIO_DEC_PLAYBACK_LEFT = 2, + V4L2_MPEG_AUDIO_DEC_PLAYBACK_RIGHT = 3, + V4L2_MPEG_AUDIO_DEC_PLAYBACK_MONO = 4, + V4L2_MPEG_AUDIO_DEC_PLAYBACK_SWAPPED_STEREO = 5, +}; +#define V4L2_CID_MPEG_AUDIO_DEC_MULTILINGUAL_PLAYBACK (V4L2_CID_MPEG_BASE+113) + +/* MPEG video controls specific to multiplexed streams */ +#define V4L2_CID_MPEG_VIDEO_ENCODING (V4L2_CID_MPEG_BASE+200) +enum v4l2_mpeg_video_encoding { + V4L2_MPEG_VIDEO_ENCODING_MPEG_1 = 0, + V4L2_MPEG_VIDEO_ENCODING_MPEG_2 = 1, + V4L2_MPEG_VIDEO_ENCODING_MPEG_4_AVC = 2, +}; +#define V4L2_CID_MPEG_VIDEO_ASPECT (V4L2_CID_MPEG_BASE+201) +enum v4l2_mpeg_video_aspect { + V4L2_MPEG_VIDEO_ASPECT_1x1 = 0, + V4L2_MPEG_VIDEO_ASPECT_4x3 = 1, + V4L2_MPEG_VIDEO_ASPECT_16x9 = 2, + V4L2_MPEG_VIDEO_ASPECT_221x100 = 3, +}; +#define V4L2_CID_MPEG_VIDEO_B_FRAMES (V4L2_CID_MPEG_BASE+202) +#define V4L2_CID_MPEG_VIDEO_GOP_SIZE (V4L2_CID_MPEG_BASE+203) +#define V4L2_CID_MPEG_VIDEO_GOP_CLOSURE (V4L2_CID_MPEG_BASE+204) +#define V4L2_CID_MPEG_VIDEO_PULLDOWN (V4L2_CID_MPEG_BASE+205) +#define V4L2_CID_MPEG_VIDEO_BITRATE_MODE (V4L2_CID_MPEG_BASE+206) +enum v4l2_mpeg_video_bitrate_mode { + V4L2_MPEG_VIDEO_BITRATE_MODE_VBR = 0, + V4L2_MPEG_VIDEO_BITRATE_MODE_CBR = 1, +}; +#define V4L2_CID_MPEG_VIDEO_BITRATE (V4L2_CID_MPEG_BASE+207) +#define V4L2_CID_MPEG_VIDEO_BITRATE_PEAK (V4L2_CID_MPEG_BASE+208) +#define V4L2_CID_MPEG_VIDEO_TEMPORAL_DECIMATION (V4L2_CID_MPEG_BASE+209) +#define V4L2_CID_MPEG_VIDEO_MUTE (V4L2_CID_MPEG_BASE+210) +#define V4L2_CID_MPEG_VIDEO_MUTE_YUV (V4L2_CID_MPEG_BASE+211) +#define V4L2_CID_MPEG_VIDEO_DECODER_SLICE_INTERFACE (V4L2_CID_MPEG_BASE+212) +#define V4L2_CID_MPEG_VIDEO_DECODER_MPEG4_DEBLOCK_FILTER (V4L2_CID_MPEG_BASE+213) +#define V4L2_CID_MPEG_VIDEO_CYCLIC_INTRA_REFRESH_MB (V4L2_CID_MPEG_BASE+214) +#define V4L2_CID_MPEG_VIDEO_FRAME_RC_ENABLE (V4L2_CID_MPEG_BASE+215) +#define V4L2_CID_MPEG_VIDEO_HEADER_MODE (V4L2_CID_MPEG_BASE+216) +enum v4l2_mpeg_video_header_mode { + V4L2_MPEG_VIDEO_HEADER_MODE_SEPARATE = 0, + V4L2_MPEG_VIDEO_HEADER_MODE_JOINED_WITH_1ST_FRAME = 1, + V4L2_MPEG_VIDEO_HEADER_MODE_JOINED_WITH_I_FRAME = 2, +}; +#define V4L2_CID_MPEG_VIDEO_MAX_REF_PIC (V4L2_CID_MPEG_BASE+217) +#define V4L2_CID_MPEG_VIDEO_MB_RC_ENABLE (V4L2_CID_MPEG_BASE+218) +#define V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_BYTES (V4L2_CID_MPEG_BASE+219) +#define V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_MB (V4L2_CID_MPEG_BASE+220) +#define V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE (V4L2_CID_MPEG_BASE+221) +enum v4l2_mpeg_video_multi_slice_mode { + V4L2_MPEG_VIDEO_MULTI_SLICE_MODE_SINGLE = 0, + V4L2_MPEG_VIDEO_MULTI_SICE_MODE_MAX_MB = 1, + V4L2_MPEG_VIDEO_MULTI_SICE_MODE_MAX_BYTES = 2, + V4L2_MPEG_VIDEO_MULTI_SLICE_GOB = 3, +}; +#define V4L2_CID_MPEG_VIDEO_VBV_SIZE (V4L2_CID_MPEG_BASE+222) +#define V4L2_CID_MPEG_VIDEO_DEC_PTS (V4L2_CID_MPEG_BASE+223) +#define V4L2_CID_MPEG_VIDEO_DEC_FRAME (V4L2_CID_MPEG_BASE+224) +#define V4L2_CID_MPEG_VIDEO_VBV_DELAY (V4L2_CID_MPEG_BASE+225) +#define V4L2_CID_MPEG_VIDEO_REPEAT_SEQ_HEADER (V4L2_CID_MPEG_BASE+226) +#define V4L2_CID_MPEG_VIDEO_MV_H_SEARCH_RANGE (V4L2_CID_MPEG_BASE+227) +#define V4L2_CID_MPEG_VIDEO_MV_V_SEARCH_RANGE (V4L2_CID_MPEG_BASE+228) +#define V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME (V4L2_CID_MPEG_BASE+229) + +#define V4L2_CID_MPEG_VIDEO_H263_I_FRAME_QP (V4L2_CID_MPEG_BASE+300) +#define V4L2_CID_MPEG_VIDEO_H263_P_FRAME_QP (V4L2_CID_MPEG_BASE+301) +#define V4L2_CID_MPEG_VIDEO_H263_B_FRAME_QP (V4L2_CID_MPEG_BASE+302) +#define V4L2_CID_MPEG_VIDEO_H263_MIN_QP (V4L2_CID_MPEG_BASE+303) +#define V4L2_CID_MPEG_VIDEO_H263_MAX_QP (V4L2_CID_MPEG_BASE+304) +#define V4L2_CID_MPEG_VIDEO_H264_I_FRAME_QP (V4L2_CID_MPEG_BASE+350) +#define V4L2_CID_MPEG_VIDEO_H264_P_FRAME_QP (V4L2_CID_MPEG_BASE+351) +#define V4L2_CID_MPEG_VIDEO_H264_B_FRAME_QP (V4L2_CID_MPEG_BASE+352) +#define V4L2_CID_MPEG_VIDEO_H264_MIN_QP (V4L2_CID_MPEG_BASE+353) +#define V4L2_CID_MPEG_VIDEO_H264_MAX_QP (V4L2_CID_MPEG_BASE+354) +#define V4L2_CID_MPEG_VIDEO_H264_8X8_TRANSFORM (V4L2_CID_MPEG_BASE+355) +#define V4L2_CID_MPEG_VIDEO_H264_CPB_SIZE (V4L2_CID_MPEG_BASE+356) +#define V4L2_CID_MPEG_VIDEO_H264_ENTROPY_MODE (V4L2_CID_MPEG_BASE+357) +enum v4l2_mpeg_video_h264_entropy_mode { + V4L2_MPEG_VIDEO_H264_ENTROPY_MODE_CAVLC = 0, + V4L2_MPEG_VIDEO_H264_ENTROPY_MODE_CABAC = 1, +}; +#define V4L2_CID_MPEG_VIDEO_H264_I_PERIOD (V4L2_CID_MPEG_BASE+358) +#define V4L2_CID_MPEG_VIDEO_H264_LEVEL (V4L2_CID_MPEG_BASE+359) +enum v4l2_mpeg_video_h264_level { + V4L2_MPEG_VIDEO_H264_LEVEL_1_0 = 0, + V4L2_MPEG_VIDEO_H264_LEVEL_1B = 1, + V4L2_MPEG_VIDEO_H264_LEVEL_1_1 = 2, + V4L2_MPEG_VIDEO_H264_LEVEL_1_2 = 3, + V4L2_MPEG_VIDEO_H264_LEVEL_1_3 = 4, + V4L2_MPEG_VIDEO_H264_LEVEL_2_0 = 5, + V4L2_MPEG_VIDEO_H264_LEVEL_2_1 = 6, + V4L2_MPEG_VIDEO_H264_LEVEL_2_2 = 7, + V4L2_MPEG_VIDEO_H264_LEVEL_3_0 = 8, + V4L2_MPEG_VIDEO_H264_LEVEL_3_1 = 9, + V4L2_MPEG_VIDEO_H264_LEVEL_3_2 = 10, + V4L2_MPEG_VIDEO_H264_LEVEL_4_0 = 11, + V4L2_MPEG_VIDEO_H264_LEVEL_4_1 = 12, + V4L2_MPEG_VIDEO_H264_LEVEL_4_2 = 13, + V4L2_MPEG_VIDEO_H264_LEVEL_5_0 = 14, + V4L2_MPEG_VIDEO_H264_LEVEL_5_1 = 15, + V4L2_MPEG_VIDEO_H264_LEVEL_5_2 = 16, +#define V4L2_MPEG_VIDEO_H264_LEVEL_UNKNOWN \ + V4L2_MPEG_VIDEO_H264_LEVEL_UNKNOWN + V4L2_MPEG_VIDEO_H264_LEVEL_UNKNOWN = 17, +}; +#define V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_ALPHA (V4L2_CID_MPEG_BASE+360) +#define V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_BETA (V4L2_CID_MPEG_BASE+361) +#define V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_MODE (V4L2_CID_MPEG_BASE+362) +enum v4l2_mpeg_video_h264_loop_filter_mode { + V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_ENABLED = 0, + V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_DISABLED = 1, + V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_DISABLED_AT_SLICE_BOUNDARY = 2, +}; +#define V4L2_CID_MPEG_VIDEO_H264_PROFILE (V4L2_CID_MPEG_BASE+363) +enum v4l2_mpeg_video_h264_profile { + V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE = 0, + V4L2_MPEG_VIDEO_H264_PROFILE_CONSTRAINED_BASELINE = 1, + V4L2_MPEG_VIDEO_H264_PROFILE_MAIN = 2, + V4L2_MPEG_VIDEO_H264_PROFILE_EXTENDED = 3, + V4L2_MPEG_VIDEO_H264_PROFILE_HIGH = 4, + V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_10 = 5, + V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_422 = 6, + V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_444_PREDICTIVE = 7, + V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_10_INTRA = 8, + V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_422_INTRA = 9, + V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_444_INTRA = 10, + V4L2_MPEG_VIDEO_H264_PROFILE_CAVLC_444_INTRA = 11, + V4L2_MPEG_VIDEO_H264_PROFILE_SCALABLE_BASELINE = 12, + V4L2_MPEG_VIDEO_H264_PROFILE_SCALABLE_HIGH = 13, + V4L2_MPEG_VIDEO_H264_PROFILE_SCALABLE_HIGH_INTRA = 14, + V4L2_MPEG_VIDEO_H264_PROFILE_STEREO_HIGH = 15, + V4L2_MPEG_VIDEO_H264_PROFILE_MULTIVIEW_HIGH = 16, + V4L2_MPEG_VIDEO_H264_PROFILE_CONSTRAINED_HIGH = 17, +}; +#define V4L2_CID_MPEG_VIDEO_H264_VUI_EXT_SAR_HEIGHT (V4L2_CID_MPEG_BASE+364) +#define V4L2_CID_MPEG_VIDEO_H264_VUI_EXT_SAR_WIDTH (V4L2_CID_MPEG_BASE+365) +#define V4L2_CID_MPEG_VIDEO_H264_VUI_SAR_ENABLE (V4L2_CID_MPEG_BASE+366) +#define V4L2_CID_MPEG_VIDEO_H264_VUI_SAR_IDC (V4L2_CID_MPEG_BASE+367) +enum v4l2_mpeg_video_h264_vui_sar_idc { + V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_UNSPECIFIED = 0, + V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_1x1 = 1, + V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_12x11 = 2, + V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_10x11 = 3, + V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_16x11 = 4, + V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_40x33 = 5, + V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_24x11 = 6, + V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_20x11 = 7, + V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_32x11 = 8, + V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_80x33 = 9, + V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_18x11 = 10, + V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_15x11 = 11, + V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_64x33 = 12, + V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_160x99 = 13, + V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_4x3 = 14, + V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_3x2 = 15, + V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_2x1 = 16, + V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_EXTENDED = 17, +}; +#define V4L2_CID_MPEG_VIDEO_H264_SEI_FRAME_PACKING (V4L2_CID_MPEG_BASE+368) +#define V4L2_CID_MPEG_VIDEO_H264_SEI_FP_CURRENT_FRAME_0 (V4L2_CID_MPEG_BASE+369) +#define V4L2_CID_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE (V4L2_CID_MPEG_BASE+370) +enum v4l2_mpeg_video_h264_sei_fp_arrangement_type { + V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_CHECKERBOARD = 0, + V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_COLUMN = 1, + V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_ROW = 2, + V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_SIDE_BY_SIDE = 3, + V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_TOP_BOTTOM = 4, + V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_TEMPORAL = 5, +}; +#define V4L2_CID_MPEG_VIDEO_H264_FMO (V4L2_CID_MPEG_BASE+371) +#define V4L2_CID_MPEG_VIDEO_H264_FMO_MAP_TYPE (V4L2_CID_MPEG_BASE+372) +enum v4l2_mpeg_video_h264_fmo_map_type { + V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_INTERLEAVED_SLICES = 0, + V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_SCATTERED_SLICES = 1, + V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_FOREGROUND_WITH_LEFT_OVER = 2, + V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_BOX_OUT = 3, + V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_RASTER_SCAN = 4, + V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_WIPE_SCAN = 5, + V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_EXPLICIT = 6, +}; +#define V4L2_CID_MPEG_VIDEO_H264_FMO_SLICE_GROUP (V4L2_CID_MPEG_BASE+373) +#define V4L2_CID_MPEG_VIDEO_H264_FMO_CHANGE_DIRECTION (V4L2_CID_MPEG_BASE+374) +enum v4l2_mpeg_video_h264_fmo_change_dir { + V4L2_MPEG_VIDEO_H264_FMO_CHANGE_DIR_RIGHT = 0, + V4L2_MPEG_VIDEO_H264_FMO_CHANGE_DIR_LEFT = 1, +}; +#define V4L2_CID_MPEG_VIDEO_H264_FMO_CHANGE_RATE (V4L2_CID_MPEG_BASE+375) +#define V4L2_CID_MPEG_VIDEO_H264_FMO_RUN_LENGTH (V4L2_CID_MPEG_BASE+376) +#define V4L2_CID_MPEG_VIDEO_H264_ASO (V4L2_CID_MPEG_BASE+377) +#define V4L2_CID_MPEG_VIDEO_H264_ASO_SLICE_ORDER (V4L2_CID_MPEG_BASE+378) +#define V4L2_CID_MPEG_VIDEO_H264_HIERARCHICAL_CODING (V4L2_CID_MPEG_BASE+379) +#define V4L2_CID_MPEG_VIDEO_H264_HIERARCHICAL_CODING_TYPE (V4L2_CID_MPEG_BASE+380) +enum v4l2_mpeg_video_h264_hierarchical_coding_type { + V4L2_MPEG_VIDEO_H264_HIERARCHICAL_CODING_B = 0, + V4L2_MPEG_VIDEO_H264_HIERARCHICAL_CODING_P = 1, +}; +#define V4L2_CID_MPEG_VIDEO_H264_HIERARCHICAL_CODING_LAYER (V4L2_CID_MPEG_BASE+381) +#define V4L2_CID_MPEG_VIDEO_H264_HIERARCHICAL_CODING_LAYER_QP (V4L2_CID_MPEG_BASE+382) +#define V4L2_CID_MPEG_VIDEO_MPEG4_I_FRAME_QP (V4L2_CID_MPEG_BASE+400) +#define V4L2_CID_MPEG_VIDEO_MPEG4_P_FRAME_QP (V4L2_CID_MPEG_BASE+401) +#define V4L2_CID_MPEG_VIDEO_MPEG4_B_FRAME_QP (V4L2_CID_MPEG_BASE+402) +#define V4L2_CID_MPEG_VIDEO_MPEG4_MIN_QP (V4L2_CID_MPEG_BASE+403) +#define V4L2_CID_MPEG_VIDEO_MPEG4_MAX_QP (V4L2_CID_MPEG_BASE+404) +#define V4L2_CID_MPEG_VIDEO_MPEG4_LEVEL (V4L2_CID_MPEG_BASE+405) +enum v4l2_mpeg_video_mpeg4_level { + V4L2_MPEG_VIDEO_MPEG4_LEVEL_0 = 0, + V4L2_MPEG_VIDEO_MPEG4_LEVEL_0B = 1, + V4L2_MPEG_VIDEO_MPEG4_LEVEL_1 = 2, + V4L2_MPEG_VIDEO_MPEG4_LEVEL_2 = 3, + V4L2_MPEG_VIDEO_MPEG4_LEVEL_3 = 4, + V4L2_MPEG_VIDEO_MPEG4_LEVEL_3B = 5, + V4L2_MPEG_VIDEO_MPEG4_LEVEL_4 = 6, + V4L2_MPEG_VIDEO_MPEG4_LEVEL_5 = 7, +}; +#define V4L2_CID_MPEG_VIDEO_MPEG4_PROFILE (V4L2_CID_MPEG_BASE+406) +enum v4l2_mpeg_video_mpeg4_profile { + V4L2_MPEG_VIDEO_MPEG4_PROFILE_SIMPLE = 0, + V4L2_MPEG_VIDEO_MPEG4_PROFILE_ADVANCED_SIMPLE = 1, + V4L2_MPEG_VIDEO_MPEG4_PROFILE_CORE = 2, + V4L2_MPEG_VIDEO_MPEG4_PROFILE_SIMPLE_SCALABLE = 3, + V4L2_MPEG_VIDEO_MPEG4_PROFILE_ADVANCED_CODING_EFFICIENCY = 4, +}; +#define V4L2_CID_MPEG_VIDEO_MPEG4_QPEL (V4L2_CID_MPEG_BASE+407) + +/* Control IDs for VP8 streams + * Although VP8 is not part of MPEG we add these controls to the MPEG class + * as that class is already handling other video compression standards + */ +#define V4L2_CID_MPEG_VIDEO_VPX_NUM_PARTITIONS (V4L2_CID_MPEG_BASE+500) +enum v4l2_vp8_num_partitions { + V4L2_CID_MPEG_VIDEO_VPX_1_PARTITION = 0, + V4L2_CID_MPEG_VIDEO_VPX_2_PARTITIONS = 1, + V4L2_CID_MPEG_VIDEO_VPX_4_PARTITIONS = 2, + V4L2_CID_MPEG_VIDEO_VPX_8_PARTITIONS = 3, +}; +#define V4L2_CID_MPEG_VIDEO_VPX_IMD_DISABLE_4X4 (V4L2_CID_MPEG_BASE+501) +#define V4L2_CID_MPEG_VIDEO_VPX_NUM_REF_FRAMES (V4L2_CID_MPEG_BASE+502) +enum v4l2_vp8_num_ref_frames { + V4L2_CID_MPEG_VIDEO_VPX_1_REF_FRAME = 0, + V4L2_CID_MPEG_VIDEO_VPX_2_REF_FRAME = 1, + V4L2_CID_MPEG_VIDEO_VPX_3_REF_FRAME = 2, +}; +#define V4L2_CID_MPEG_VIDEO_VPX_FILTER_LEVEL (V4L2_CID_MPEG_BASE+503) +#define V4L2_CID_MPEG_VIDEO_VPX_FILTER_SHARPNESS (V4L2_CID_MPEG_BASE+504) +#define V4L2_CID_MPEG_VIDEO_VPX_GOLDEN_FRAME_REF_PERIOD (V4L2_CID_MPEG_BASE+505) +#define V4L2_CID_MPEG_VIDEO_VPX_GOLDEN_FRAME_SEL (V4L2_CID_MPEG_BASE+506) +enum v4l2_vp8_golden_frame_sel { + V4L2_CID_MPEG_VIDEO_VPX_GOLDEN_FRAME_USE_PREV = 0, + V4L2_CID_MPEG_VIDEO_VPX_GOLDEN_FRAME_USE_REF_PERIOD = 1, +}; +#define V4L2_CID_MPEG_VIDEO_VPX_MIN_QP (V4L2_CID_MPEG_BASE+507) +#define V4L2_CID_MPEG_VIDEO_VPX_MAX_QP (V4L2_CID_MPEG_BASE+508) +#define V4L2_CID_MPEG_VIDEO_VPX_I_FRAME_QP (V4L2_CID_MPEG_BASE+509) +#define V4L2_CID_MPEG_VIDEO_VPX_P_FRAME_QP (V4L2_CID_MPEG_BASE+510) +#define V4L2_CID_MPEG_VIDEO_VPX_PROFILE (V4L2_CID_MPEG_BASE+511) + +/* MPEG-class control IDs specific to the CX2341x driver as defined by V4L2 */ +#define V4L2_CID_MPEG_CX2341X_BASE (V4L2_CTRL_CLASS_MPEG | 0x1000) +#define V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER_MODE (V4L2_CID_MPEG_CX2341X_BASE+0) +enum v4l2_mpeg_cx2341x_video_spatial_filter_mode { + V4L2_MPEG_CX2341X_VIDEO_SPATIAL_FILTER_MODE_MANUAL = 0, + V4L2_MPEG_CX2341X_VIDEO_SPATIAL_FILTER_MODE_AUTO = 1, +}; +#define V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER (V4L2_CID_MPEG_CX2341X_BASE+1) +#define V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE (V4L2_CID_MPEG_CX2341X_BASE+2) +enum v4l2_mpeg_cx2341x_video_luma_spatial_filter_type { + V4L2_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE_OFF = 0, + V4L2_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE_1D_HOR = 1, + V4L2_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE_1D_VERT = 2, + V4L2_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE_2D_HV_SEPARABLE = 3, + V4L2_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE_2D_SYM_NON_SEPARABLE = 4, +}; +#define V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_SPATIAL_FILTER_TYPE (V4L2_CID_MPEG_CX2341X_BASE+3) +enum v4l2_mpeg_cx2341x_video_chroma_spatial_filter_type { + V4L2_MPEG_CX2341X_VIDEO_CHROMA_SPATIAL_FILTER_TYPE_OFF = 0, + V4L2_MPEG_CX2341X_VIDEO_CHROMA_SPATIAL_FILTER_TYPE_1D_HOR = 1, +}; +#define V4L2_CID_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER_MODE (V4L2_CID_MPEG_CX2341X_BASE+4) +enum v4l2_mpeg_cx2341x_video_temporal_filter_mode { + V4L2_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER_MODE_MANUAL = 0, + V4L2_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER_MODE_AUTO = 1, +}; +#define V4L2_CID_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER (V4L2_CID_MPEG_CX2341X_BASE+5) +#define V4L2_CID_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE (V4L2_CID_MPEG_CX2341X_BASE+6) +enum v4l2_mpeg_cx2341x_video_median_filter_type { + V4L2_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE_OFF = 0, + V4L2_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE_HOR = 1, + V4L2_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE_VERT = 2, + V4L2_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE_HOR_VERT = 3, + V4L2_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE_DIAG = 4, +}; +#define V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_MEDIAN_FILTER_BOTTOM (V4L2_CID_MPEG_CX2341X_BASE+7) +#define V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_MEDIAN_FILTER_TOP (V4L2_CID_MPEG_CX2341X_BASE+8) +#define V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_MEDIAN_FILTER_BOTTOM (V4L2_CID_MPEG_CX2341X_BASE+9) +#define V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_MEDIAN_FILTER_TOP (V4L2_CID_MPEG_CX2341X_BASE+10) +#define V4L2_CID_MPEG_CX2341X_STREAM_INSERT_NAV_PACKETS (V4L2_CID_MPEG_CX2341X_BASE+11) + +/* MPEG-class control IDs specific to the Samsung MFC 5.1 driver as defined by V4L2 */ +#define V4L2_CID_MPEG_MFC51_BASE (V4L2_CTRL_CLASS_MPEG | 0x1100) + +#define V4L2_CID_MPEG_MFC51_VIDEO_DECODER_H264_DISPLAY_DELAY (V4L2_CID_MPEG_MFC51_BASE+0) +#define V4L2_CID_MPEG_MFC51_VIDEO_DECODER_H264_DISPLAY_DELAY_ENABLE (V4L2_CID_MPEG_MFC51_BASE+1) +#define V4L2_CID_MPEG_MFC51_VIDEO_FRAME_SKIP_MODE (V4L2_CID_MPEG_MFC51_BASE+2) +enum v4l2_mpeg_mfc51_video_frame_skip_mode { + V4L2_MPEG_MFC51_VIDEO_FRAME_SKIP_MODE_DISABLED = 0, + V4L2_MPEG_MFC51_VIDEO_FRAME_SKIP_MODE_LEVEL_LIMIT = 1, + V4L2_MPEG_MFC51_VIDEO_FRAME_SKIP_MODE_BUF_LIMIT = 2, +}; +#define V4L2_CID_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE (V4L2_CID_MPEG_MFC51_BASE+3) +enum v4l2_mpeg_mfc51_video_force_frame_type { + V4L2_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE_DISABLED = 0, + V4L2_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE_I_FRAME = 1, + V4L2_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE_NOT_CODED = 2, +}; +#define V4L2_CID_MPEG_MFC51_VIDEO_PADDING (V4L2_CID_MPEG_MFC51_BASE+4) +#define V4L2_CID_MPEG_MFC51_VIDEO_PADDING_YUV (V4L2_CID_MPEG_MFC51_BASE+5) +#define V4L2_CID_MPEG_MFC51_VIDEO_RC_FIXED_TARGET_BIT (V4L2_CID_MPEG_MFC51_BASE+6) +#define V4L2_CID_MPEG_MFC51_VIDEO_RC_REACTION_COEFF (V4L2_CID_MPEG_MFC51_BASE+7) +#define V4L2_CID_MPEG_MFC51_VIDEO_H264_ADAPTIVE_RC_ACTIVITY (V4L2_CID_MPEG_MFC51_BASE+50) +#define V4L2_CID_MPEG_MFC51_VIDEO_H264_ADAPTIVE_RC_DARK (V4L2_CID_MPEG_MFC51_BASE+51) +#define V4L2_CID_MPEG_MFC51_VIDEO_H264_ADAPTIVE_RC_SMOOTH (V4L2_CID_MPEG_MFC51_BASE+52) +#define V4L2_CID_MPEG_MFC51_VIDEO_H264_ADAPTIVE_RC_STATIC (V4L2_CID_MPEG_MFC51_BASE+53) +#define V4L2_CID_MPEG_MFC51_VIDEO_H264_NUM_REF_PIC_FOR_P (V4L2_CID_MPEG_MFC51_BASE+54) + +/* MPEG-class control IDs specific to the msm_vidc driver */ +#define V4L2_CID_MPEG_MSM_VIDC_BASE (V4L2_CTRL_CLASS_MPEG | 0x2000) + +#define V4L2_CID_MPEG_VIDC_VIDEO_PICTYPE_DEC_MODE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE+0) +enum v4l2_mpeg_vidc_video_pictype_dec_mode { + V4L2_MPEG_VIDC_VIDEO_PICTYPE_DECODE_OFF = 0, + V4L2_MPEG_VIDC_VIDEO_PICTYPE_DECODE_ON = 1, +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_KEEP_ASPECT_RATIO \ + (V4L2_CID_MPEG_MSM_VIDC_BASE+1) + +#define V4L2_CID_MPEG_VIDC_VIDEO_STREAM_FORMAT (V4L2_CID_MPEG_MSM_VIDC_BASE+2) +enum v4l2_mpeg_vidc_video_stream_format { + V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_STARTCODES = 0, + V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_ONE_NAL_PER_BUFFER = 1, + V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_ONE_BYTE_LENGTH = 2, + V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_TWO_BYTE_LENGTH = 3, + V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_FOUR_BYTE_LENGTH = 4, +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_OUTPUT_ORDER (V4L2_CID_MPEG_MSM_VIDC_BASE+3) +enum v4l2_mpeg_vidc_video_output_order { + V4L2_MPEG_VIDC_VIDEO_OUTPUT_ORDER_DISPLAY = 0, + V4L2_MPEG_VIDC_VIDEO_OUTPUT_ORDER_DECODE = 1, +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_FRAME_RATE (V4L2_CID_MPEG_MSM_VIDC_BASE+4) +#define V4L2_CID_MPEG_VIDC_VIDEO_IDR_PERIOD (V4L2_CID_MPEG_MSM_VIDC_BASE+5) +#define V4L2_CID_MPEG_VIDC_VIDEO_NUM_P_FRAMES (V4L2_CID_MPEG_MSM_VIDC_BASE+6) +#define V4L2_CID_MPEG_VIDC_VIDEO_NUM_B_FRAMES (V4L2_CID_MPEG_MSM_VIDC_BASE+7) +#define V4L2_CID_MPEG_VIDC_VIDEO_REQUEST_IFRAME (V4L2_CID_MPEG_MSM_VIDC_BASE+8) + +#define V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL (V4L2_CID_MPEG_MSM_VIDC_BASE+9) +enum v4l2_mpeg_vidc_video_rate_control { + V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_OFF = 0, + V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_VBR_VFR = 1, + V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_VBR_CFR = 2, + V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_CBR_VFR = 3, + V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_CBR_CFR = 4, + V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_MBR_CFR = 5, + V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_MBR_VFR = 6, + V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_CQ = 7, +}; +#define V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_MBR_CFR \ + V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_MBR_CFR +#define V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_MBR_VFR \ + V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_MBR_VFR + +#define V4L2_CID_MPEG_VIDC_VIDEO_ROTATION (V4L2_CID_MPEG_MSM_VIDC_BASE+10) +enum v4l2_mpeg_vidc_video_rotation { + V4L2_CID_MPEG_VIDC_VIDEO_ROTATION_NONE = 0, + V4L2_CID_MPEG_VIDC_VIDEO_ROTATION_90 = 1, + V4L2_CID_MPEG_VIDC_VIDEO_ROTATION_180 = 2, + V4L2_CID_MPEG_VIDC_VIDEO_ROTATION_270 = 3, +}; +#define V4L2_CID_MPEG_VIDC_VIDEO_H264_CABAC_MODEL \ + (V4L2_CID_MPEG_MSM_VIDC_BASE+11) +enum v4l2_mpeg_vidc_h264_cabac_model { + V4L2_CID_MPEG_VIDC_VIDEO_H264_CABAC_MODEL_0 = 0, + V4L2_CID_MPEG_VIDC_VIDEO_H264_CABAC_MODEL_1 = 1, + V4L2_CID_MPEG_VIDC_VIDEO_H264_CABAC_MODEL_2 = 2, +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_INTRA_REFRESH_MODE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE+12) +enum v4l2_mpeg_vidc_video_intra_refresh_mode { + V4L2_CID_MPEG_VIDC_VIDEO_INTRA_REFRESH_NONE = 0, + V4L2_CID_MPEG_VIDC_VIDEO_INTRA_REFRESH_CYCLIC = 1, + V4L2_CID_MPEG_VIDC_VIDEO_INTRA_REFRESH_RANDOM = 2, + V4L2_CID_MPEG_VIDC_VIDEO_INTRA_REFRESH_ADAPTIVE = 3, + V4L2_CID_MPEG_VIDC_VIDEO_INTRA_REFRESH_CYCLIC_ADAPTIVE = 4, +}; +#define V4L2_CID_MPEG_VIDC_VIDEO_IR_MBS (V4L2_CID_MPEG_MSM_VIDC_BASE+13) + +#define V4L2_CID_MPEG_VIDC_VIDEO_AU_DELIMITER \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 14) +enum v4l2_mpeg_vidc_video_au_delimiter { + V4L2_MPEG_VIDC_VIDEO_AU_DELIMITER_DISABLED = 0, + V4L2_MPEG_VIDC_VIDEO_AU_DELIMITER_ENABLED = 1 +}; +#define V4L2_CID_MPEG_VIDC_VIDEO_SYNC_FRAME_DECODE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 15) +enum v4l2_mpeg_vidc_video_sync_frame_decode { + V4L2_MPEG_VIDC_VIDEO_SYNC_FRAME_DECODE_DISABLE = 0, + V4L2_MPEG_VIDC_VIDEO_SYNC_FRAME_DECODE_ENABLE = 1 +}; +#define V4L2_CID_MPEG_VIDC_VIDEO_SECURE (V4L2_CID_MPEG_MSM_VIDC_BASE+16) +#define V4L2_CID_MPEG_VIDC_VIDEO_EXTRADATA \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 17) +enum v4l2_mpeg_vidc_extradata { + V4L2_MPEG_VIDC_EXTRADATA_NONE = 0, + V4L2_MPEG_VIDC_EXTRADATA_MB_QUANTIZATION = 1, + V4L2_MPEG_VIDC_EXTRADATA_INTERLACE_VIDEO = 2, + V4L2_MPEG_VIDC_EXTRADATA_VC1_FRAMEDISP = 3, + V4L2_MPEG_VIDC_EXTRADATA_VC1_SEQDISP = 4, + V4L2_MPEG_VIDC_EXTRADATA_TIMESTAMP = 5, + V4L2_MPEG_VIDC_EXTRADATA_S3D_FRAME_PACKING = 6, + V4L2_MPEG_VIDC_EXTRADATA_FRAME_RATE = 7, + V4L2_MPEG_VIDC_EXTRADATA_PANSCAN_WINDOW = 8, + V4L2_MPEG_VIDC_EXTRADATA_RECOVERY_POINT_SEI = 9, + V4L2_MPEG_VIDC_EXTRADATA_MULTISLICE_INFO = 10, + V4L2_MPEG_VIDC_EXTRADATA_NUM_CONCEALED_MB = 11, + V4L2_MPEG_VIDC_EXTRADATA_METADATA_FILLER = 12, + V4L2_MPEG_VIDC_EXTRADATA_INPUT_CROP = 13, + V4L2_MPEG_VIDC_EXTRADATA_DIGITAL_ZOOM = 14, + V4L2_MPEG_VIDC_EXTRADATA_ASPECT_RATIO = 15, + V4L2_MPEG_VIDC_EXTRADATA_MPEG2_SEQDISP = 16, + V4L2_MPEG_VIDC_EXTRADATA_STREAM_USERDATA = 17, + V4L2_MPEG_VIDC_EXTRADATA_FRAME_QP = 18, + V4L2_MPEG_VIDC_EXTRADATA_FRAME_BITS_INFO = 19, + V4L2_MPEG_VIDC_EXTRADATA_LTR = 20, + V4L2_MPEG_VIDC_EXTRADATA_METADATA_MBI = 21, + V4L2_MPEG_VIDC_EXTRADATA_VQZIP_SEI = 22, + V4L2_MPEG_VIDC_EXTRADATA_YUV_STATS = 23, + V4L2_MPEG_VIDC_EXTRADATA_ROI_QP = 24, +#define V4L2_MPEG_VIDC_EXTRADATA_OUTPUT_CROP \ + V4L2_MPEG_VIDC_EXTRADATA_OUTPUT_CROP + V4L2_MPEG_VIDC_EXTRADATA_OUTPUT_CROP = 25, +#define V4L2_MPEG_VIDC_EXTRADATA_DISPLAY_COLOUR_SEI \ + V4L2_MPEG_VIDC_EXTRADATA_DISPLAY_COLOUR_SEI + V4L2_MPEG_VIDC_EXTRADATA_DISPLAY_COLOUR_SEI = 26, +#define V4L2_MPEG_VIDC_EXTRADATA_CONTENT_LIGHT_LEVEL_SEI \ + V4L2_MPEG_VIDC_EXTRADATA_CONTENT_LIGHT_LEVEL_SEI + V4L2_MPEG_VIDC_EXTRADATA_CONTENT_LIGHT_LEVEL_SEI = 27, +#define V4L2_MPEG_VIDC_EXTRADATA_PQ_INFO \ + V4L2_MPEG_VIDC_EXTRADATA_PQ_INFO + V4L2_MPEG_VIDC_EXTRADATA_PQ_INFO = 28, +#define V4L2_MPEG_VIDC_EXTRADATA_VUI_DISPLAY \ + V4L2_MPEG_VIDC_EXTRADATA_VUI_DISPLAY + V4L2_MPEG_VIDC_EXTRADATA_VUI_DISPLAY = 29, +#define V4L2_MPEG_VIDC_EXTRADATA_VPX_COLORSPACE \ + V4L2_MPEG_VIDC_EXTRADATA_VPX_COLORSPACE + V4L2_MPEG_VIDC_EXTRADATA_VPX_COLORSPACE = 30, +#define V4L2_MPEG_VIDC_EXTRADATA_UBWC_CR_STATS_INFO \ + V4L2_MPEG_VIDC_EXTRADATA_UBWC_CR_STATS_INFO + V4L2_MPEG_VIDC_EXTRADATA_UBWC_CR_STATS_INFO = 31, +#define V4L2_MPEG_VIDC_EXTRADATA_ENC_FRAME_QP \ + V4L2_MPEG_VIDC_EXTRADATA_ENC_FRAME_QP + V4L2_MPEG_VIDC_EXTRADATA_ENC_FRAME_QP = 32, +}; + +#define V4L2_CID_MPEG_VIDEO_MULTI_SLICE_DELIVERY_MODE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 18) + +#define V4L2_CID_MPEG_VIDC_VIDEO_VUI_TIMING_INFO \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 19) +enum v4l2_mpeg_vidc_video_vui_timing_info { + V4L2_MPEG_VIDC_VIDEO_VUI_TIMING_INFO_DISABLED = 0, + V4L2_MPEG_VIDC_VIDEO_VUI_TIMING_INFO_ENABLED = 1 +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_VP8_PROFILE_LEVEL \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 20) +enum v4l2_mpeg_vidc_video_vp8_profile_level { + V4L2_MPEG_VIDC_VIDEO_VP8_UNUSED, + V4L2_MPEG_VIDC_VIDEO_VP8_VERSION_0, + V4L2_MPEG_VIDC_VIDEO_VP8_VERSION_1, + V4L2_MPEG_VIDC_VIDEO_VP8_VERSION_2, + V4L2_MPEG_VIDC_VIDEO_VP8_VERSION_3, +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_PRESERVE_TEXT_QUALITY \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 21) +enum v4l2_mpeg_vidc_video_preserve_text_quality { + V4L2_MPEG_VIDC_VIDEO_PRESERVE_TEXT_QUALITY_DISABLED = 0, + V4L2_MPEG_VIDC_VIDEO_PRESERVE_TEXT_QUALITY_ENABLED = 1 +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_STREAM_OUTPUT_MODE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 22) +enum v4l2_mpeg_vidc_video_decoder_multi_stream { + V4L2_CID_MPEG_VIDC_VIDEO_STREAM_OUTPUT_PRIMARY = 0, + V4L2_CID_MPEG_VIDC_VIDEO_STREAM_OUTPUT_SECONDARY = 1, +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_MPEG2_LEVEL (V4L2_CID_MPEG_MSM_VIDC_BASE+23) +enum v4l2_mpeg_vidc_video_mpeg2_level { + V4L2_MPEG_VIDC_VIDEO_MPEG2_LEVEL_0 = 0, + V4L2_MPEG_VIDC_VIDEO_MPEG2_LEVEL_1 = 1, + V4L2_MPEG_VIDC_VIDEO_MPEG2_LEVEL_2 = 2, + V4L2_MPEG_VIDC_VIDEO_MPEG2_LEVEL_3 = 3, +}; +#define V4L2_CID_MPEG_VIDC_VIDEO_MPEG2_PROFILE (V4L2_CID_MPEG_MSM_VIDC_BASE+24) +enum v4l2_mpeg_vidc_video_mpeg2_profile { + V4L2_MPEG_VIDC_VIDEO_MPEG2_PROFILE_SIMPLE = 0, + V4L2_MPEG_VIDC_VIDEO_MPEG2_PROFILE_MAIN = 1, + V4L2_MPEG_VIDC_VIDEO_MPEG2_PROFILE_422 = 2, + V4L2_MPEG_VIDC_VIDEO_MPEG2_PROFILE_SNR_SCALABLE = 3, + V4L2_MPEG_VIDC_VIDEO_MPEG2_PROFILE_SPATIAL_SCALABLE = 4, + V4L2_MPEG_VIDC_VIDEO_MPEG2_PROFILE_HIGH = 5, +}; + +enum v4l2_mpeg_vidc_video_mvc_layout { + V4L2_MPEG_VIDC_VIDEO_MVC_SEQUENTIAL = 0, + V4L2_MPEG_VIDC_VIDEO_MVC_TOP_BOTTOM = 1 +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_CONCEAL_COLOR \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 25) + +#define V4L2_CID_MPEG_VIDC_VIDEO_LTRMODE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 26) + +enum v4l2_mpeg_vidc_video_ltrmode { + V4L2_MPEG_VIDC_VIDEO_LTR_MODE_DISABLE = 0, + V4L2_MPEG_VIDC_VIDEO_LTR_MODE_MANUAL = 1, + V4L2_MPEG_VIDC_VIDEO_LTR_MODE_PERIODIC = 2 +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_LTRCOUNT \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 27) + +#define V4L2_CID_MPEG_VIDC_VIDEO_USELTRFRAME \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 28) + +#define V4L2_CID_MPEG_VIDC_VIDEO_MARKLTRFRAME \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 29) + +#define V4L2_CID_MPEG_VIDC_VIDEO_HIER_P_NUM_LAYERS \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 30) + +#define V4L2_CID_MPEG_VIDC_VIDEO_ALLOC_MODE_OUTPUT \ + (V4L2_CID_MPEG_MSM_VIDC_BASE+31) +enum v4l2_mpeg_vidc_video_alloc_mode_type { + V4L2_MPEG_VIDC_VIDEO_STATIC = 0, + V4L2_MPEG_VIDC_VIDEO_RING = 1, + V4L2_MPEG_VIDC_VIDEO_DYNAMIC = 2, +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_IFRAME_X_RANGE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 32) + +#define V4L2_CID_MPEG_VIDC_VIDEO_PFRAME_X_RANGE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 33) + +#define V4L2_CID_MPEG_VIDC_VIDEO_BFRAME_X_RANGE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 34) + +#define V4L2_CID_MPEG_VIDC_VIDEO_IFRAME_Y_RANGE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 35) + +#define V4L2_CID_MPEG_VIDC_VIDEO_PFRAME_Y_RANGE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 36) + +#define V4L2_CID_MPEG_VIDC_VIDEO_BFRAME_Y_RANGE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 37) + +#define V4L2_CID_MPEG_VIDC_VIDEO_VPX_ERROR_RESILIENCE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 38) + +#define V4L2_CID_MPEG_VIDC_VIDEO_BUFFER_SIZE_LIMIT \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 39) + +enum vl42_mpeg_vidc_video_vpx_error_resilience { + V4L2_MPEG_VIDC_VIDEO_VPX_ERROR_RESILIENCE_DISABLED = 0, + V4L2_MPEG_VIDC_VIDEO_VPX_ERROR_RESILIENCE_ENABLED = 1, +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_HEVC_PROFILE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 40) +enum v4l2_mpeg_video_hevc_profile { + V4L2_MPEG_VIDC_VIDEO_HEVC_PROFILE_MAIN = 0, + V4L2_MPEG_VIDC_VIDEO_HEVC_PROFILE_MAIN10 = 1, + V4L2_MPEG_VIDC_VIDEO_HEVC_PROFILE_MAIN_STILL_PIC = 2, +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_HEVC_TIER_LEVEL \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 41) +enum v4l2_mpeg_video_hevc_level { + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_1 = 0, + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_1 = 1, + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_2 = 2, + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_2 = 3, + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_2_1 = 4, + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_2_1 = 5, + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_3 = 6, + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_3 = 7, + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_3_1 = 8, + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_3_1 = 9, + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_4 = 10, + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_4 = 11, + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_4_1 = 12, + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_4_1 = 13, + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_5 = 14, + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_5 = 15, + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_5_1 = 16, + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_5_1 = 17, + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_5_2 = 18, + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_5_2 = 19, + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_6 = 20, + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_6 = 21, + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_6_1 = 22, + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_6_1 = 23, + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_6_2 = 24, + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_6_2 = 25, +#define V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_UNKNOWN \ + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_UNKNOWN + V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_UNKNOWN = 26, +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_HIER_B_NUM_LAYERS \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 42) + +#define V4L2_CID_MPEG_VIDC_VIDEO_HYBRID_HIERP_MODE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 43) + +#define V4L2_CID_MPEG_VIDC_VIDEO_DPB_COLOR_FORMAT \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 44) + +enum v4l2_mpeg_vidc_video_dpb_color_format { + V4L2_MPEG_VIDC_VIDEO_DPB_COLOR_FMT_NONE = 0, + V4L2_MPEG_VIDC_VIDEO_DPB_COLOR_FMT_UBWC = 1, + V4L2_MPEG_VIDC_VIDEO_DPB_COLOR_FMT_TP10_UBWC = 2 +}; + +#define V4L2_CID_VIDC_QBUF_MODE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 45) +enum v4l2_vidc_qbuf_mode { + V4L2_VIDC_QBUF_STANDARD = 0, + V4L2_VIDC_QBUF_BATCHED = 1, +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_MAX_HIERP_LAYERS \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 46) + +#define V4L2_CID_MPEG_VIDC_VIDEO_BASELAYER_ID \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 47) + +#define V4L2_CID_MPEG_VIDC_VENC_PARAM_SAR_WIDTH \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 48) + +#define V4L2_CID_MPEG_VIDC_VENC_PARAM_SAR_HEIGHT \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 49) + +#define V4L2_CID_MPEG_VIDC_VIDEO_VQZIP_SEI \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 50) + +enum v4l2_mpeg_vidc_video_vqzip_sei_enable { + V4L2_CID_MPEG_VIDC_VIDEO_VQZIP_SEI_DISABLE = 0, + V4L2_CID_MPEG_VIDC_VIDEO_VQZIP_SEI_ENABLE = 1 +}; + +#define V4L2_CID_MPEG_VIDC_VENC_PARAM_LAYER_BITRATE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 51) + +#define V4L2_CID_MPEG_VIDC_VIDEO_PRIORITY \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 52) + +enum v4l2_mpeg_vidc_video_priority { + V4L2_MPEG_VIDC_VIDEO_PRIORITY_REALTIME_ENABLE = 0, + V4L2_MPEG_VIDC_VIDEO_PRIORITY_REALTIME_DISABLE = 1, +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_OPERATING_RATE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 53) + +#define V4L2_CID_MPEG_VIDC_VIDEO_VENC_BITRATE_TYPE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 54) + +enum v4l2_mpeg_vidc_video_venc_bitrate_type_enable { + V4L2_CID_MPEG_VIDC_VIDEO_VENC_BITRATE_DISABLE = 0, + V4L2_CID_MPEG_VIDC_VIDEO_VENC_BITRATE_ENABLE = 1 +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_VPE_CSC \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 55) + +enum v4l2_cid_mpeg_vidc_video_vpe_csc_type_enable { + V4L2_CID_MPEG_VIDC_VIDEO_VPE_CSC_DISABLE = 0, + V4L2_CID_MPEG_VIDC_VIDEO_VPE_CSC_ENABLE = 1 +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_LOWLATENCY_MODE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 56) + +enum v4l2_mpeg_vidc_video_lowlatency_mode { + V4L2_CID_MPEG_VIDC_VIDEO_LOWLATENCY_DISABLE = 0, + V4L2_CID_MPEG_VIDC_VIDEO_LOWLATENCY_ENABLE = 1, +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_BLUR_WIDTH \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 57) + +#define V4L2_CID_MPEG_VIDC_VIDEO_BLUR_HEIGHT \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 58) + +#define V4L2_CID_MPEG_VIDC_VIDEO_H264_TRANSFORM_8x8 \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 59) +enum v4l2_mpeg_vidc_video_h264_transform_8x8 { + V4L2_MPEG_VIDC_VIDEO_H264_TRANSFORM_8x8_DISABLE = 0, + V4L2_MPEG_VIDC_VIDEO_H264_TRANSFORM_8x8_ENABLE = 1, +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_COLOR_SPACE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 60) + +#define V4L2_CID_MPEG_VIDC_VIDEO_FULL_RANGE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 61) + +enum v4l2_cid_mpeg_vidc_video_full_range { + V4L2_CID_MPEG_VIDC_VIDEO_FULL_RANGE_DISABLE = 0, + V4L2_CID_MPEG_VIDC_VIDEO_FULL_RANGE_ENABLE = 1, +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_TRANSFER_CHARS \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 62) + +#define V4L2_CID_MPEG_VIDC_VIDEO_MATRIX_COEFFS \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 63) + +#define V4L2_CID_MPEG_VIDC_VIDEO_IFRAME_SIZE_TYPE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 64) + +#define V4L2_CID_MPEG_VIDC_VIDEO_LAYER_ID \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 65) + +#define V4L2_CID_MPEG_VIDC_VIDEO_VP9_PROFILE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 66) +enum v4l2_mpeg_vidc_video_vp9_profile { + V4L2_MPEG_VIDC_VIDEO_VP9_PROFILE_UNUSED = 0, + V4L2_MPEG_VIDC_VIDEO_VP9_PROFILE_P0 = 1, + V4L2_MPEG_VIDC_VIDEO_VP9_PROFILE_P2_10 = 2, +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_VP9_LEVEL \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 67) +enum v4l2_mpeg_vidc_video_vp9_level { + V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_UNUSED = 0, + V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_1 = 1, + V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_11 = 2, + V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_2 = 3, + V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_21 = 4, + V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_3 = 5, + V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_31 = 6, + V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_4 = 7, + V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_41 = 8, + V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_5 = 9, + V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_51 = 10, +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_MB_ERROR_MAP_REPORTING \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 68) +#define V4L2_CID_MPEG_VIDC_VIDEO_CONTINUE_DATA_TRANSFER \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 69) + +#define V4L2_CID_MPEG_VIDC_VIDEO_ALLOC_MODE_INPUT \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 70) + +#define V4L2_CID_MPEG_VIDC_VIDEO_FRAME_ASSEMBLY \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 71) +enum v4l2_mpeg_vidc_video_assembly { + V4L2_MPEG_VIDC_FRAME_ASSEMBLY_DISABLE = 0, + V4L2_MPEG_VIDC_FRAME_ASSEMBLY_ENABLE = 1, +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_H263_PROFILE\ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 72) +enum v4l2_mpeg_vidc_video_h263_profile { + V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_BASELINE = 0, + V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_H320CODING = 1, + V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_BACKWARDCOMPATIBLE = 2, + V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_ISWV2 = 3, + V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_ISWV3 = 4, + V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_HIGHCOMPRESSION = 5, + V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_INTERNET = 6, + V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_INTERLACE = 7, + V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_HIGHLATENCY = 8, +}; + +#define V4L2_CID_MPEG_VIDEO_MIN_QP_PACKED \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 97) +#define V4L2_CID_MPEG_VIDEO_MAX_QP_PACKED \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 98) +#define V4L2_CID_MPEG_VIDC_VIDEO_I_FRAME_QP \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 99) +#define V4L2_CID_MPEG_VIDC_VIDEO_P_FRAME_QP \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 100) +#define V4L2_CID_MPEG_VIDC_VIDEO_B_FRAME_QP \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 101) +#define V4L2_CID_MPEG_VIDC_VIDEO_I_FRAME_QP_MIN \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 102) +#define V4L2_CID_MPEG_VIDC_VIDEO_P_FRAME_QP_MIN \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 103) +#define V4L2_CID_MPEG_VIDC_VIDEO_B_FRAME_QP_MIN \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 104) +#define V4L2_CID_MPEG_VIDC_VIDEO_I_FRAME_QP_MAX \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 105) +#define V4L2_CID_MPEG_VIDC_VIDEO_P_FRAME_QP_MAX \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 106) +#define V4L2_CID_MPEG_VIDC_VIDEO_B_FRAME_QP_MAX \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 107) +#define V4L2_CID_MPEG_VIDC_VIDEO_QP_MASK \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 108) + +enum v4l2_mpeg_vidc_video_venc_iframesize_type { + V4L2_CID_MPEG_VIDC_VIDEO_IFRAME_SIZE_DEFAULT, + V4L2_CID_MPEG_VIDC_VIDEO_IFRAME_SIZE_MEDIUM, + V4L2_CID_MPEG_VIDC_VIDEO_IFRAME_SIZE_HUGE, + V4L2_CID_MPEG_VIDC_VIDEO_IFRAME_SIZE_UNLIMITED, +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_CONCEAL_COLOR_8BIT \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 109) +#define V4L2_CID_MPEG_VIDC_VIDEO_CONCEAL_COLOR_10BIT \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 110) + +#define V4L2_CID_MPEG_VIDC_VIDEO_TME_PROFILE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 111) + +enum v4l2_mpeg_vidc_video_tme_profile { + V4L2_MPEG_VIDC_VIDEO_TME_PROFILE_0 = 0, + V4L2_MPEG_VIDC_VIDEO_TME_PROFILE_1 = 1, + V4L2_MPEG_VIDC_VIDEO_TME_PROFILE_2 = 2, + V4L2_MPEG_VIDC_VIDEO_TME_PROFILE_3 = 3, +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_TME_LEVEL \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 112) + +enum v4l2_mpeg_vidc_video_tme_level { + V4L2_MPEG_VIDC_VIDEO_TME_LEVEL_INTEGER = 0, +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_TME_PAYLOAD_VERSION \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 113) + +#define V4L2_CID_MPEG_VIDC_VIDEO_VPE_CSC_CUSTOM_MATRIX \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 114) + +#define V4L2_CID_MPEG_VIDC_VIDEO_FLIP (V4L2_CID_MPEG_MSM_VIDC_BASE + 115) +enum v4l2_mpeg_vidc_video_flip { + V4L2_CID_MPEG_VIDC_VIDEO_FLIP_NONE = 0, + V4L2_CID_MPEG_VIDC_VIDEO_FLIP_HORI = 1, + V4L2_CID_MPEG_VIDC_VIDEO_FLIP_VERT = 2, + V4L2_CID_MPEG_VIDC_VIDEO_FLIP_BOTH = 3, +}; + +/* HDR SEI INFO related control IDs and definitions*/ +#define V4L2_MPEG_VIDC_VENC_HDR_INFO_ENABLED 1 +#define V4L2_MPEG_VIDC_VENC_HDR_INFO_DISABLED 0 + +#define V4L2_CID_MPEG_VIDC_VENC_HDR_INFO \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 116) +#define V4L2_CID_MPEG_VIDC_VENC_RGB_PRIMARY_00 \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 117) +#define V4L2_CID_MPEG_VIDC_VENC_RGB_PRIMARY_01 \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 118) +#define V4L2_CID_MPEG_VIDC_VENC_RGB_PRIMARY_10 \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 119) +#define V4L2_CID_MPEG_VIDC_VENC_RGB_PRIMARY_11 \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 120) +#define V4L2_CID_MPEG_VIDC_VENC_RGB_PRIMARY_20 \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 121) +#define V4L2_CID_MPEG_VIDC_VENC_RGB_PRIMARY_21 \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 122) +#define V4L2_CID_MPEG_VIDC_VENC_WHITEPOINT_X \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 123) +#define V4L2_CID_MPEG_VIDC_VENC_WHITEPOINT_Y \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 124) +#define V4L2_CID_MPEG_VIDC_VENC_MAX_DISP_LUM \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 125) +#define V4L2_CID_MPEG_VIDC_VENC_MIN_DISP_LUM \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 126) +#define V4L2_CID_MPEG_VIDC_VENC_MAX_CLL \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 127) +#define V4L2_CID_MPEG_VIDC_VENC_MAX_FLL \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 128) + +#define V4L2_CID_MPEG_VIDC_SET_PERF_LEVEL \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 129) +enum v4l2_mpeg_vidc_perf_level { + V4L2_CID_MPEG_VIDC_PERF_LEVEL_NOMINAL = 0, + V4L2_CID_MPEG_VIDC_PERF_LEVEL_PERFORMANCE = 1, + V4L2_CID_MPEG_VIDC_PERF_LEVEL_TURBO = 2, +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_AIR_MBS (V4L2_CID_MPEG_MSM_VIDC_BASE + 130) +#define V4L2_CID_MPEG_VIDC_VIDEO_AIR_REF (V4L2_CID_MPEG_MSM_VIDC_BASE + 131) +#define V4L2_CID_MPEG_VIDC_VIDEO_CIR_MBS (V4L2_CID_MPEG_MSM_VIDC_BASE + 132) + +#define V4L2_CID_MPEG_VIDC_VIDEO_H264_VUI_TIMING_INFO \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 135) + +#define V4L2_CID_MPEG_VIDEO_MULTI_SLICE_GOB \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 136) + +#define V4L2_CID_MPEG_VIDC_VIDEO_H264_VUI_BITSTREAM_RESTRICT \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 137) +enum v4l2_mpeg_vidc_video_h264_vui_bitstream_restrict { + V4L2_MPEG_VIDC_VIDEO_H264_VUI_BITSTREAM_RESTRICT_DISABLED = 0, + V4L2_MPEG_VIDC_VIDEO_H264_VUI_BITSTREAM_RESTRICT_ENABLED = 1 +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_DEINTERLACE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 138) +enum v4l2_mpeg_vidc_video_deinterlace { + V4L2_CID_MPEG_VIDC_VIDEO_DEINTERLACE_DISABLED = 0, + V4L2_CID_MPEG_VIDC_VIDEO_DEINTERLACE_ENABLED = 1 +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_MPEG4_TIME_RESOLUTION \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 139) + +#define V4L2_CID_MPEG_VIDC_VIDEO_REQUEST_SEQ_HEADER \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 140) + +#define V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_TIMESTAMP_MODE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 141) +enum v4l2_mpeg_vidc_video_rate_control_timestamp_mode { + V4L2_MPEG_VIDC_VIDEO_RATE_CONTROL_TIMESTAMP_MODE_HONOR = 0, + V4L2_MPEG_VIDC_VIDEO_RATE_CONTROL_TIMESTAMP_MODE_IGNORE = 1, +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_ENABLE_INITIAL_QP \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 142) +enum vl42_mpeg_vidc_video_enable_initial_qp { + V4L2_CID_MPEG_VIDC_VIDEO_ENABLE_INITIAL_QP_IFRAME = 0x1, + V4L2_CID_MPEG_VIDC_VIDEO_ENABLE_INITIAL_QP_PFRAME = 0x2, + V4L2_CID_MPEG_VIDC_VIDEO_ENABLE_INITIAL_QP_BFRAME = 0x4, +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_INITIAL_I_FRAME_QP \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 143) + +#define V4L2_CID_MPEG_VIDC_VIDEO_INITIAL_P_FRAME_QP \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 144) + +#define V4L2_CID_MPEG_VIDC_VIDEO_INITIAL_B_FRAME_QP \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 145) + +#define V4L2_CID_MPEG_VIDC_VIDEO_H264_NAL_SVC \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 146) + +#define V4L2_CID_MPEG_VIDC_VIDEO_PERF_MODE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 147) +enum v4l2_mpeg_vidc_video_perf_mode { + V4L2_MPEG_VIDC_VIDEO_PERF_MAX_QUALITY = 1, + V4L2_MPEG_VIDC_VIDEO_PERF_POWER_SAVE = 2 +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_MBI_STATISTICS_MODE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 148) + +#define V4L2_CID_MPEG_VIDC_VIDEO_CONFIG_QP \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 149) + +#define V4L2_CID_MPEG_VIDC_VIDEO_H264_PIC_ORDER_CNT \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 150) + +#define V4L2_CID_MPEG_VIDC_VIDEO_SCS_THRESHOLD \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 151) + +#define V4L2_CID_MPEG_VIDC_VIDEO_MVC_BUFFER_LAYOUT \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 152) + + +#define V4L2_CID_MPEG_VIDC_VIDEO_SECURE_SCALING_THRESHOLD \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 153) + +#define V4L2_CID_MPEG_VIDC_VIDEO_NON_SECURE_OUTPUT2 \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 154) + +#define V4L2_CID_MPEG_VIDC_VIDEO_VP8_MIN_QP (V4L2_CID_MPEG_MSM_VIDC_BASE + 155) +#define V4L2_CID_MPEG_VIDC_VIDEO_VP8_MAX_QP (V4L2_CID_MPEG_MSM_VIDC_BASE + 156) + +#define V4L2_CID_MPEG_VIDC_VIDEO_H263_LEVEL (V4L2_CID_MPEG_MSM_VIDC_BASE + 157) +enum v4l2_mpeg_vidc_video_h263_level { + V4L2_MPEG_VIDC_VIDEO_H263_LEVEL_1_0 = 0, + V4L2_MPEG_VIDC_VIDEO_H263_LEVEL_2_0 = 1, + V4L2_MPEG_VIDC_VIDEO_H263_LEVEL_3_0 = 2, + V4L2_MPEG_VIDC_VIDEO_H263_LEVEL_4_0 = 3, + V4L2_MPEG_VIDC_VIDEO_H263_LEVEL_4_5 = 4, + V4L2_MPEG_VIDC_VIDEO_H263_LEVEL_5_0 = 5, + V4L2_MPEG_VIDC_VIDEO_H263_LEVEL_6_0 = 6, + V4L2_MPEG_VIDC_VIDEO_H263_LEVEL_7_0 = 7, +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_POST_LOOP_DEBLOCKER_MODE \ + (V4L2_CID_MPEG_MSM_VIDC_BASE + 158) + + +#define V4L2_CID_MPEG_VIDC_VIDEO_DIVX_FORMAT (V4L2_CID_MPEG_MSM_VIDC_BASE+159) + +enum v4l2_mpeg_vidc_video_divx_format_type { + V4L2_MPEG_VIDC_VIDEO_DIVX_FORMAT_4 = 0, + V4L2_MPEG_VIDC_VIDEO_DIVX_FORMAT_5 = 1, + V4L2_MPEG_VIDC_VIDEO_DIVX_FORMAT_6 = 2, +}; + +#define V4L2_CID_MPEG_VIDC_VIDEO_FRAME_QUALITY \ + (V4L2_CID_MPEG_MSM_VIDC_BASE+160) + +#define V4L2_CID_MPEG_VIDC_IMG_GRID_DIMENSION \ + (V4L2_CID_MPEG_MSM_VIDC_BASE+161) + +enum v4l2_mpeg_vidc_video_mbi_statistics_mode { + V4L2_CID_MPEG_VIDC_VIDEO_MBI_MODE_DEFAULT = 0, + V4L2_CID_MPEG_VIDC_VIDEO_MBI_MODE_1 = 1, + V4L2_CID_MPEG_VIDC_VIDEO_MBI_MODE_2 = 2, + V4L2_CID_MPEG_VIDC_VIDEO_MBI_MODE_3 = 3, +}; + +enum vl42_mpeg_vidc_video_h264_svc_nal { + V4L2_CID_MPEG_VIDC_VIDEO_H264_NAL_SVC_DISABLED = 0, + V4L2_CID_MPEG_VIDC_VIDEO_H264_NAL_SVC_ENABLED = 1, +}; + +enum v4l2_mpeg_vidc_video_h264_vui_timing_info { + V4L2_MPEG_VIDC_VIDEO_H264_VUI_TIMING_INFO_DISABLED = 0, + V4L2_MPEG_VIDC_VIDEO_H264_VUI_TIMING_INFO_ENABLED = 1 +}; + +/* Camera class control IDs */ + +#define V4L2_CID_CAMERA_CLASS_BASE (V4L2_CTRL_CLASS_CAMERA | 0x900) +#define V4L2_CID_CAMERA_CLASS (V4L2_CTRL_CLASS_CAMERA | 1) + +#define V4L2_CID_EXPOSURE_AUTO (V4L2_CID_CAMERA_CLASS_BASE+1) +enum v4l2_exposure_auto_type { + V4L2_EXPOSURE_AUTO = 0, + V4L2_EXPOSURE_MANUAL = 1, + V4L2_EXPOSURE_SHUTTER_PRIORITY = 2, + V4L2_EXPOSURE_APERTURE_PRIORITY = 3 +}; +#define V4L2_CID_EXPOSURE_ABSOLUTE (V4L2_CID_CAMERA_CLASS_BASE+2) +#define V4L2_CID_EXPOSURE_AUTO_PRIORITY (V4L2_CID_CAMERA_CLASS_BASE+3) + +#define V4L2_CID_PAN_RELATIVE (V4L2_CID_CAMERA_CLASS_BASE+4) +#define V4L2_CID_TILT_RELATIVE (V4L2_CID_CAMERA_CLASS_BASE+5) +#define V4L2_CID_PAN_RESET (V4L2_CID_CAMERA_CLASS_BASE+6) +#define V4L2_CID_TILT_RESET (V4L2_CID_CAMERA_CLASS_BASE+7) + +#define V4L2_CID_PAN_ABSOLUTE (V4L2_CID_CAMERA_CLASS_BASE+8) +#define V4L2_CID_TILT_ABSOLUTE (V4L2_CID_CAMERA_CLASS_BASE+9) + +#define V4L2_CID_FOCUS_ABSOLUTE (V4L2_CID_CAMERA_CLASS_BASE+10) +#define V4L2_CID_FOCUS_RELATIVE (V4L2_CID_CAMERA_CLASS_BASE+11) +#define V4L2_CID_FOCUS_AUTO (V4L2_CID_CAMERA_CLASS_BASE+12) + +#define V4L2_CID_ZOOM_ABSOLUTE (V4L2_CID_CAMERA_CLASS_BASE+13) +#define V4L2_CID_ZOOM_RELATIVE (V4L2_CID_CAMERA_CLASS_BASE+14) +#define V4L2_CID_ZOOM_CONTINUOUS (V4L2_CID_CAMERA_CLASS_BASE+15) + +#define V4L2_CID_PRIVACY (V4L2_CID_CAMERA_CLASS_BASE+16) + +#define V4L2_CID_IRIS_ABSOLUTE (V4L2_CID_CAMERA_CLASS_BASE+17) +#define V4L2_CID_IRIS_RELATIVE (V4L2_CID_CAMERA_CLASS_BASE+18) + +#define V4L2_CID_AUTO_EXPOSURE_BIAS (V4L2_CID_CAMERA_CLASS_BASE+19) + +#define V4L2_CID_AUTO_N_PRESET_WHITE_BALANCE (V4L2_CID_CAMERA_CLASS_BASE+20) +enum v4l2_auto_n_preset_white_balance { + V4L2_WHITE_BALANCE_MANUAL = 0, + V4L2_WHITE_BALANCE_AUTO = 1, + V4L2_WHITE_BALANCE_INCANDESCENT = 2, + V4L2_WHITE_BALANCE_FLUORESCENT = 3, + V4L2_WHITE_BALANCE_FLUORESCENT_H = 4, + V4L2_WHITE_BALANCE_HORIZON = 5, + V4L2_WHITE_BALANCE_DAYLIGHT = 6, + V4L2_WHITE_BALANCE_FLASH = 7, + V4L2_WHITE_BALANCE_CLOUDY = 8, + V4L2_WHITE_BALANCE_SHADE = 9, +}; + +#define V4L2_CID_WIDE_DYNAMIC_RANGE (V4L2_CID_CAMERA_CLASS_BASE+21) +#define V4L2_CID_IMAGE_STABILIZATION (V4L2_CID_CAMERA_CLASS_BASE+22) + +#define V4L2_CID_ISO_SENSITIVITY (V4L2_CID_CAMERA_CLASS_BASE+23) +#define V4L2_CID_ISO_SENSITIVITY_AUTO (V4L2_CID_CAMERA_CLASS_BASE+24) +enum v4l2_iso_sensitivity_auto_type { + V4L2_ISO_SENSITIVITY_MANUAL = 0, + V4L2_ISO_SENSITIVITY_AUTO = 1, +}; + +#define V4L2_CID_EXPOSURE_METERING (V4L2_CID_CAMERA_CLASS_BASE+25) +enum v4l2_exposure_metering { + V4L2_EXPOSURE_METERING_AVERAGE = 0, + V4L2_EXPOSURE_METERING_CENTER_WEIGHTED = 1, + V4L2_EXPOSURE_METERING_SPOT = 2, + V4L2_EXPOSURE_METERING_MATRIX = 3, +}; + +#define V4L2_CID_SCENE_MODE (V4L2_CID_CAMERA_CLASS_BASE+26) +enum v4l2_scene_mode { + V4L2_SCENE_MODE_NONE = 0, + V4L2_SCENE_MODE_BACKLIGHT = 1, + V4L2_SCENE_MODE_BEACH_SNOW = 2, + V4L2_SCENE_MODE_CANDLE_LIGHT = 3, + V4L2_SCENE_MODE_DAWN_DUSK = 4, + V4L2_SCENE_MODE_FALL_COLORS = 5, + V4L2_SCENE_MODE_FIREWORKS = 6, + V4L2_SCENE_MODE_LANDSCAPE = 7, + V4L2_SCENE_MODE_NIGHT = 8, + V4L2_SCENE_MODE_PARTY_INDOOR = 9, + V4L2_SCENE_MODE_PORTRAIT = 10, + V4L2_SCENE_MODE_SPORTS = 11, + V4L2_SCENE_MODE_SUNSET = 12, + V4L2_SCENE_MODE_TEXT = 13, +}; + +#define V4L2_CID_3A_LOCK (V4L2_CID_CAMERA_CLASS_BASE+27) +#define V4L2_LOCK_EXPOSURE (1 << 0) +#define V4L2_LOCK_WHITE_BALANCE (1 << 1) +#define V4L2_LOCK_FOCUS (1 << 2) + +#define V4L2_CID_AUTO_FOCUS_START (V4L2_CID_CAMERA_CLASS_BASE+28) +#define V4L2_CID_AUTO_FOCUS_STOP (V4L2_CID_CAMERA_CLASS_BASE+29) +#define V4L2_CID_AUTO_FOCUS_STATUS (V4L2_CID_CAMERA_CLASS_BASE+30) +#define V4L2_AUTO_FOCUS_STATUS_IDLE (0 << 0) +#define V4L2_AUTO_FOCUS_STATUS_BUSY (1 << 0) +#define V4L2_AUTO_FOCUS_STATUS_REACHED (1 << 1) +#define V4L2_AUTO_FOCUS_STATUS_FAILED (1 << 2) + +#define V4L2_CID_AUTO_FOCUS_RANGE (V4L2_CID_CAMERA_CLASS_BASE+31) +enum v4l2_auto_focus_range { + V4L2_AUTO_FOCUS_RANGE_AUTO = 0, + V4L2_AUTO_FOCUS_RANGE_NORMAL = 1, + V4L2_AUTO_FOCUS_RANGE_MACRO = 2, + V4L2_AUTO_FOCUS_RANGE_INFINITY = 3, +}; + +#define V4L2_CID_PAN_SPEED (V4L2_CID_CAMERA_CLASS_BASE+32) +#define V4L2_CID_TILT_SPEED (V4L2_CID_CAMERA_CLASS_BASE+33) + +/* FM Modulator class control IDs */ + +#define V4L2_CID_FM_TX_CLASS_BASE (V4L2_CTRL_CLASS_FM_TX | 0x900) +#define V4L2_CID_FM_TX_CLASS (V4L2_CTRL_CLASS_FM_TX | 1) + +#define V4L2_CID_RDS_TX_DEVIATION (V4L2_CID_FM_TX_CLASS_BASE + 1) +#define V4L2_CID_RDS_TX_PI (V4L2_CID_FM_TX_CLASS_BASE + 2) +#define V4L2_CID_RDS_TX_PTY (V4L2_CID_FM_TX_CLASS_BASE + 3) +#define V4L2_CID_RDS_TX_PS_NAME (V4L2_CID_FM_TX_CLASS_BASE + 5) +#define V4L2_CID_RDS_TX_RADIO_TEXT (V4L2_CID_FM_TX_CLASS_BASE + 6) +#define V4L2_CID_RDS_TX_MONO_STEREO (V4L2_CID_FM_TX_CLASS_BASE + 7) +#define V4L2_CID_RDS_TX_ARTIFICIAL_HEAD (V4L2_CID_FM_TX_CLASS_BASE + 8) +#define V4L2_CID_RDS_TX_COMPRESSED (V4L2_CID_FM_TX_CLASS_BASE + 9) +#define V4L2_CID_RDS_TX_DYNAMIC_PTY (V4L2_CID_FM_TX_CLASS_BASE + 10) +#define V4L2_CID_RDS_TX_TRAFFIC_ANNOUNCEMENT (V4L2_CID_FM_TX_CLASS_BASE + 11) +#define V4L2_CID_RDS_TX_TRAFFIC_PROGRAM (V4L2_CID_FM_TX_CLASS_BASE + 12) +#define V4L2_CID_RDS_TX_MUSIC_SPEECH (V4L2_CID_FM_TX_CLASS_BASE + 13) +#define V4L2_CID_RDS_TX_ALT_FREQS_ENABLE (V4L2_CID_FM_TX_CLASS_BASE + 14) +#define V4L2_CID_RDS_TX_ALT_FREQS (V4L2_CID_FM_TX_CLASS_BASE + 15) + +#define V4L2_CID_AUDIO_LIMITER_ENABLED (V4L2_CID_FM_TX_CLASS_BASE + 64) +#define V4L2_CID_AUDIO_LIMITER_RELEASE_TIME (V4L2_CID_FM_TX_CLASS_BASE + 65) +#define V4L2_CID_AUDIO_LIMITER_DEVIATION (V4L2_CID_FM_TX_CLASS_BASE + 66) + +#define V4L2_CID_AUDIO_COMPRESSION_ENABLED (V4L2_CID_FM_TX_CLASS_BASE + 80) +#define V4L2_CID_AUDIO_COMPRESSION_GAIN (V4L2_CID_FM_TX_CLASS_BASE + 81) +#define V4L2_CID_AUDIO_COMPRESSION_THRESHOLD (V4L2_CID_FM_TX_CLASS_BASE + 82) +#define V4L2_CID_AUDIO_COMPRESSION_ATTACK_TIME (V4L2_CID_FM_TX_CLASS_BASE + 83) +#define V4L2_CID_AUDIO_COMPRESSION_RELEASE_TIME (V4L2_CID_FM_TX_CLASS_BASE + 84) + +#define V4L2_CID_PILOT_TONE_ENABLED (V4L2_CID_FM_TX_CLASS_BASE + 96) +#define V4L2_CID_PILOT_TONE_DEVIATION (V4L2_CID_FM_TX_CLASS_BASE + 97) +#define V4L2_CID_PILOT_TONE_FREQUENCY (V4L2_CID_FM_TX_CLASS_BASE + 98) + +#define V4L2_CID_TUNE_PREEMPHASIS (V4L2_CID_FM_TX_CLASS_BASE + 112) +enum v4l2_preemphasis { + V4L2_PREEMPHASIS_DISABLED = 0, + V4L2_PREEMPHASIS_50_uS = 1, + V4L2_PREEMPHASIS_75_uS = 2, +}; +#define V4L2_CID_TUNE_POWER_LEVEL (V4L2_CID_FM_TX_CLASS_BASE + 113) +#define V4L2_CID_TUNE_ANTENNA_CAPACITOR (V4L2_CID_FM_TX_CLASS_BASE + 114) + + +/* Flash and privacy (indicator) light controls */ + +#define V4L2_CID_FLASH_CLASS_BASE (V4L2_CTRL_CLASS_FLASH | 0x900) +#define V4L2_CID_FLASH_CLASS (V4L2_CTRL_CLASS_FLASH | 1) + +#define V4L2_CID_FLASH_LED_MODE (V4L2_CID_FLASH_CLASS_BASE + 1) +enum v4l2_flash_led_mode { + V4L2_FLASH_LED_MODE_NONE, + V4L2_FLASH_LED_MODE_FLASH, + V4L2_FLASH_LED_MODE_TORCH, +}; + +#define V4L2_CID_FLASH_STROBE_SOURCE (V4L2_CID_FLASH_CLASS_BASE + 2) +enum v4l2_flash_strobe_source { + V4L2_FLASH_STROBE_SOURCE_SOFTWARE, + V4L2_FLASH_STROBE_SOURCE_EXTERNAL, +}; + +#define V4L2_CID_FLASH_STROBE (V4L2_CID_FLASH_CLASS_BASE + 3) +#define V4L2_CID_FLASH_STROBE_STOP (V4L2_CID_FLASH_CLASS_BASE + 4) +#define V4L2_CID_FLASH_STROBE_STATUS (V4L2_CID_FLASH_CLASS_BASE + 5) + +#define V4L2_CID_FLASH_TIMEOUT (V4L2_CID_FLASH_CLASS_BASE + 6) +#define V4L2_CID_FLASH_INTENSITY (V4L2_CID_FLASH_CLASS_BASE + 7) +#define V4L2_CID_FLASH_TORCH_INTENSITY (V4L2_CID_FLASH_CLASS_BASE + 8) +#define V4L2_CID_FLASH_INDICATOR_INTENSITY (V4L2_CID_FLASH_CLASS_BASE + 9) + +#define V4L2_CID_FLASH_FAULT (V4L2_CID_FLASH_CLASS_BASE + 10) +#define V4L2_FLASH_FAULT_OVER_VOLTAGE (1 << 0) +#define V4L2_FLASH_FAULT_TIMEOUT (1 << 1) +#define V4L2_FLASH_FAULT_OVER_TEMPERATURE (1 << 2) +#define V4L2_FLASH_FAULT_SHORT_CIRCUIT (1 << 3) +#define V4L2_FLASH_FAULT_OVER_CURRENT (1 << 4) +#define V4L2_FLASH_FAULT_INDICATOR (1 << 5) +#define V4L2_FLASH_FAULT_UNDER_VOLTAGE (1 << 6) +#define V4L2_FLASH_FAULT_INPUT_VOLTAGE (1 << 7) +#define V4L2_FLASH_FAULT_LED_OVER_TEMPERATURE (1 << 8) + +#define V4L2_CID_FLASH_CHARGE (V4L2_CID_FLASH_CLASS_BASE + 11) +#define V4L2_CID_FLASH_READY (V4L2_CID_FLASH_CLASS_BASE + 12) + + +/* JPEG-class control IDs */ + +#define V4L2_CID_JPEG_CLASS_BASE (V4L2_CTRL_CLASS_JPEG | 0x900) +#define V4L2_CID_JPEG_CLASS (V4L2_CTRL_CLASS_JPEG | 1) + +#define V4L2_CID_JPEG_CHROMA_SUBSAMPLING (V4L2_CID_JPEG_CLASS_BASE + 1) +enum v4l2_jpeg_chroma_subsampling { + V4L2_JPEG_CHROMA_SUBSAMPLING_444 = 0, + V4L2_JPEG_CHROMA_SUBSAMPLING_422 = 1, + V4L2_JPEG_CHROMA_SUBSAMPLING_420 = 2, + V4L2_JPEG_CHROMA_SUBSAMPLING_411 = 3, + V4L2_JPEG_CHROMA_SUBSAMPLING_410 = 4, + V4L2_JPEG_CHROMA_SUBSAMPLING_GRAY = 5, +}; +#define V4L2_CID_JPEG_RESTART_INTERVAL (V4L2_CID_JPEG_CLASS_BASE + 2) +#define V4L2_CID_JPEG_COMPRESSION_QUALITY (V4L2_CID_JPEG_CLASS_BASE + 3) + +#define V4L2_CID_JPEG_ACTIVE_MARKER (V4L2_CID_JPEG_CLASS_BASE + 4) +#define V4L2_JPEG_ACTIVE_MARKER_APP0 (1 << 0) +#define V4L2_JPEG_ACTIVE_MARKER_APP1 (1 << 1) +#define V4L2_JPEG_ACTIVE_MARKER_COM (1 << 16) +#define V4L2_JPEG_ACTIVE_MARKER_DQT (1 << 17) +#define V4L2_JPEG_ACTIVE_MARKER_DHT (1 << 18) + + +/* Image source controls */ +#define V4L2_CID_IMAGE_SOURCE_CLASS_BASE (V4L2_CTRL_CLASS_IMAGE_SOURCE | 0x900) +#define V4L2_CID_IMAGE_SOURCE_CLASS (V4L2_CTRL_CLASS_IMAGE_SOURCE | 1) + +#define V4L2_CID_VBLANK (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 1) +#define V4L2_CID_HBLANK (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 2) +#define V4L2_CID_ANALOGUE_GAIN (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 3) +#define V4L2_CID_TEST_PATTERN_RED (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 4) +#define V4L2_CID_TEST_PATTERN_GREENR (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 5) +#define V4L2_CID_TEST_PATTERN_BLUE (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 6) +#define V4L2_CID_TEST_PATTERN_GREENB (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 7) + + +/* Image processing controls */ + +#define V4L2_CID_IMAGE_PROC_CLASS_BASE (V4L2_CTRL_CLASS_IMAGE_PROC | 0x900) +#define V4L2_CID_IMAGE_PROC_CLASS (V4L2_CTRL_CLASS_IMAGE_PROC | 1) + +#define V4L2_CID_LINK_FREQ (V4L2_CID_IMAGE_PROC_CLASS_BASE + 1) +#define V4L2_CID_PIXEL_RATE (V4L2_CID_IMAGE_PROC_CLASS_BASE + 2) +#define V4L2_CID_TEST_PATTERN (V4L2_CID_IMAGE_PROC_CLASS_BASE + 3) + + +/* DV-class control IDs defined by V4L2 */ +#define V4L2_CID_DV_CLASS_BASE (V4L2_CTRL_CLASS_DV | 0x900) +#define V4L2_CID_DV_CLASS (V4L2_CTRL_CLASS_DV | 1) + +#define V4L2_CID_DV_TX_HOTPLUG (V4L2_CID_DV_CLASS_BASE + 1) +#define V4L2_CID_DV_TX_RXSENSE (V4L2_CID_DV_CLASS_BASE + 2) +#define V4L2_CID_DV_TX_EDID_PRESENT (V4L2_CID_DV_CLASS_BASE + 3) +#define V4L2_CID_DV_TX_MODE (V4L2_CID_DV_CLASS_BASE + 4) +enum v4l2_dv_tx_mode { + V4L2_DV_TX_MODE_DVI_D = 0, + V4L2_DV_TX_MODE_HDMI = 1, +}; +#define V4L2_CID_DV_TX_RGB_RANGE (V4L2_CID_DV_CLASS_BASE + 5) +enum v4l2_dv_rgb_range { + V4L2_DV_RGB_RANGE_AUTO = 0, + V4L2_DV_RGB_RANGE_LIMITED = 1, + V4L2_DV_RGB_RANGE_FULL = 2, +}; + +#define V4L2_CID_DV_TX_IT_CONTENT_TYPE (V4L2_CID_DV_CLASS_BASE + 6) +enum v4l2_dv_it_content_type { + V4L2_DV_IT_CONTENT_TYPE_GRAPHICS = 0, + V4L2_DV_IT_CONTENT_TYPE_PHOTO = 1, + V4L2_DV_IT_CONTENT_TYPE_CINEMA = 2, + V4L2_DV_IT_CONTENT_TYPE_GAME = 3, + V4L2_DV_IT_CONTENT_TYPE_NO_ITC = 4, +}; + +#define V4L2_CID_DV_RX_POWER_PRESENT (V4L2_CID_DV_CLASS_BASE + 100) +#define V4L2_CID_DV_RX_RGB_RANGE (V4L2_CID_DV_CLASS_BASE + 101) +#define V4L2_CID_DV_RX_IT_CONTENT_TYPE (V4L2_CID_DV_CLASS_BASE + 102) + +#define V4L2_CID_FM_RX_CLASS_BASE (V4L2_CTRL_CLASS_FM_RX | 0x900) +#define V4L2_CID_FM_RX_CLASS (V4L2_CTRL_CLASS_FM_RX | 1) + +#define V4L2_CID_TUNE_DEEMPHASIS (V4L2_CID_FM_RX_CLASS_BASE + 1) +enum v4l2_deemphasis { + V4L2_DEEMPHASIS_DISABLED = V4L2_PREEMPHASIS_DISABLED, + V4L2_DEEMPHASIS_50_uS = V4L2_PREEMPHASIS_50_uS, + V4L2_DEEMPHASIS_75_uS = V4L2_PREEMPHASIS_75_uS, +}; + +#define V4L2_CID_RDS_RECEPTION (V4L2_CID_FM_RX_CLASS_BASE + 2) +#define V4L2_CID_RDS_RX_PTY (V4L2_CID_FM_RX_CLASS_BASE + 3) +#define V4L2_CID_RDS_RX_PS_NAME (V4L2_CID_FM_RX_CLASS_BASE + 4) +#define V4L2_CID_RDS_RX_RADIO_TEXT (V4L2_CID_FM_RX_CLASS_BASE + 5) +#define V4L2_CID_RDS_RX_TRAFFIC_ANNOUNCEMENT (V4L2_CID_FM_RX_CLASS_BASE + 6) +#define V4L2_CID_RDS_RX_TRAFFIC_PROGRAM (V4L2_CID_FM_RX_CLASS_BASE + 7) +#define V4L2_CID_RDS_RX_MUSIC_SPEECH (V4L2_CID_FM_RX_CLASS_BASE + 8) + +#define V4L2_CID_RF_TUNER_CLASS_BASE (V4L2_CTRL_CLASS_RF_TUNER | 0x900) +#define V4L2_CID_RF_TUNER_CLASS (V4L2_CTRL_CLASS_RF_TUNER | 1) + +#define V4L2_CID_RF_TUNER_BANDWIDTH_AUTO (V4L2_CID_RF_TUNER_CLASS_BASE + 11) +#define V4L2_CID_RF_TUNER_BANDWIDTH (V4L2_CID_RF_TUNER_CLASS_BASE + 12) +#define V4L2_CID_RF_TUNER_RF_GAIN (V4L2_CID_RF_TUNER_CLASS_BASE + 32) +#define V4L2_CID_RF_TUNER_LNA_GAIN_AUTO (V4L2_CID_RF_TUNER_CLASS_BASE + 41) +#define V4L2_CID_RF_TUNER_LNA_GAIN (V4L2_CID_RF_TUNER_CLASS_BASE + 42) +#define V4L2_CID_RF_TUNER_MIXER_GAIN_AUTO (V4L2_CID_RF_TUNER_CLASS_BASE + 51) +#define V4L2_CID_RF_TUNER_MIXER_GAIN (V4L2_CID_RF_TUNER_CLASS_BASE + 52) +#define V4L2_CID_RF_TUNER_IF_GAIN_AUTO (V4L2_CID_RF_TUNER_CLASS_BASE + 61) +#define V4L2_CID_RF_TUNER_IF_GAIN (V4L2_CID_RF_TUNER_CLASS_BASE + 62) +#define V4L2_CID_RF_TUNER_PLL_LOCK (V4L2_CID_RF_TUNER_CLASS_BASE + 91) + + +/* Detection-class control IDs defined by V4L2 */ +#define V4L2_CID_DETECT_CLASS_BASE (V4L2_CTRL_CLASS_DETECT | 0x900) +#define V4L2_CID_DETECT_CLASS (V4L2_CTRL_CLASS_DETECT | 1) + +#define V4L2_CID_DETECT_MD_MODE (V4L2_CID_DETECT_CLASS_BASE + 1) +enum v4l2_detect_md_mode { + V4L2_DETECT_MD_MODE_DISABLED = 0, + V4L2_DETECT_MD_MODE_GLOBAL = 1, + V4L2_DETECT_MD_MODE_THRESHOLD_GRID = 2, + V4L2_DETECT_MD_MODE_REGION_GRID = 3, +}; +#define V4L2_CID_DETECT_MD_GLOBAL_THRESHOLD (V4L2_CID_DETECT_CLASS_BASE + 2) +#define V4L2_CID_DETECT_MD_THRESHOLD_GRID (V4L2_CID_DETECT_CLASS_BASE + 3) +#define V4L2_CID_DETECT_MD_REGION_GRID (V4L2_CID_DETECT_CLASS_BASE + 4) + +#endif diff --git a/third_party/openmax/include/OMX_Audio.h b/third_party/openmax/include/OMX_Audio.h deleted file mode 100644 index 0d455766c5..0000000000 --- a/third_party/openmax/include/OMX_Audio.h +++ /dev/null @@ -1,1312 +0,0 @@ -/* - * 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/third_party/openmax/include/OMX_Component.h b/third_party/openmax/include/OMX_Component.h deleted file mode 100644 index d5956405e2..0000000000 --- a/third_party/openmax/include/OMX_Component.h +++ /dev/null @@ -1,579 +0,0 @@ -/* - * 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/third_party/openmax/include/OMX_ContentPipe.h b/third_party/openmax/include/OMX_ContentPipe.h deleted file mode 100644 index 5f6310c28a..0000000000 --- a/third_party/openmax/include/OMX_ContentPipe.h +++ /dev/null @@ -1,195 +0,0 @@ -/* - * 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/third_party/openmax/include/OMX_Core.h b/third_party/openmax/include/OMX_Core.h deleted file mode 100644 index 52d211f0dc..0000000000 --- a/third_party/openmax/include/OMX_Core.h +++ /dev/null @@ -1,1440 +0,0 @@ -/* - * 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/third_party/openmax/include/OMX_CoreExt.h b/third_party/openmax/include/OMX_CoreExt.h deleted file mode 100644 index 3ec14b05f3..0000000000 --- a/third_party/openmax/include/OMX_CoreExt.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - * 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/third_party/openmax/include/OMX_IVCommon.h b/third_party/openmax/include/OMX_IVCommon.h deleted file mode 100644 index ec717565a0..0000000000 --- a/third_party/openmax/include/OMX_IVCommon.h +++ /dev/null @@ -1,933 +0,0 @@ -/** - * 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/third_party/openmax/include/OMX_Index.h b/third_party/openmax/include/OMX_Index.h deleted file mode 100644 index a1f17487d3..0000000000 --- a/third_party/openmax/include/OMX_Index.h +++ /dev/null @@ -1,259 +0,0 @@ -/* - * 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/third_party/openmax/include/OMX_Other.h b/third_party/openmax/include/OMX_Other.h deleted file mode 100644 index caf7f38448..0000000000 --- a/third_party/openmax/include/OMX_Other.h +++ /dev/null @@ -1,337 +0,0 @@ -/* - * 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 CCs current wall - * time - * OMX_IndexConfigTimeCurrentMediaTime: query of the CCs 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. - * - * Its 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_CLOCKSTATETYPEs 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/third_party/openmax/include/OMX_QCOMExtns.h b/third_party/openmax/include/OMX_QCOMExtns.h deleted file mode 100644 index 20917932be..0000000000 --- a/third_party/openmax/include/OMX_QCOMExtns.h +++ /dev/null @@ -1,1888 +0,0 @@ -/*-------------------------------------------------------------------------- -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 2Each 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 3Each 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/third_party/openmax/include/OMX_Skype_VideoExtensions.h b/third_party/openmax/include/OMX_Skype_VideoExtensions.h deleted file mode 100644 index 5cc832930f..0000000000 --- a/third_party/openmax/include/OMX_Skype_VideoExtensions.h +++ /dev/null @@ -1,155 +0,0 @@ -/*@@@+++@@@@****************************************************************** - - 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/third_party/openmax/include/OMX_Types.h b/third_party/openmax/include/OMX_Types.h deleted file mode 100644 index 3b9fab4fc2..0000000000 --- a/third_party/openmax/include/OMX_Types.h +++ /dev/null @@ -1,359 +0,0 @@ -/* - * 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/third_party/openmax/include/OMX_Video.h b/third_party/openmax/include/OMX_Video.h deleted file mode 100644 index 64dbe87b43..0000000000 --- a/third_party/openmax/include/OMX_Video.h +++ /dev/null @@ -1,1082 +0,0 @@ -/** - * 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/third_party/openmax/include/OMX_VideoExt.h b/third_party/openmax/include/OMX_VideoExt.h deleted file mode 100644 index 5bf6fd4878..0000000000 --- a/third_party/openmax/include/OMX_VideoExt.h +++ /dev/null @@ -1,166 +0,0 @@ -/* - * 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/third_party/qt-plugins/build_qtlocation.sh b/third_party/qt-plugins/build_qtlocation.sh deleted file mode 100755 index 09e6182d1f..0000000000 --- a/third_party/qt-plugins/build_qtlocation.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env sh - -# Qtlocation plugin with extra fields parsed from api response -cd /tmp -git clone https://github.com/commaai/qtlocation.git -cd qtlocation -qmake -make -j$(nproc) diff --git a/third_party/qt-plugins/x86_64/geoservices/.gitattributes b/third_party/qt-plugins/x86_64/geoservices/.gitattributes deleted file mode 100644 index 51b1d333fe..0000000000 --- a/third_party/qt-plugins/x86_64/geoservices/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -libqtgeoservices_mapbox.so filter=lfs diff=lfs merge=lfs -text diff --git a/third_party/qt-plugins/x86_64/geoservices/libqtgeoservices_mapbox.so b/third_party/qt-plugins/x86_64/geoservices/libqtgeoservices_mapbox.so deleted file mode 100755 index 375fc0e012..0000000000 --- a/third_party/qt-plugins/x86_64/geoservices/libqtgeoservices_mapbox.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5c8bda321dc524e753f67823cb5353358e756cfc1c5328e22e32920e80dd9e9b -size 12166248 diff --git a/third_party/qt5/larch64/bin/lrelease b/third_party/qt5/larch64/bin/lrelease new file mode 100755 index 0000000000..5c0195d29a Binary files /dev/null and b/third_party/qt5/larch64/bin/lrelease differ diff --git a/third_party/qt5/larch64/bin/lupdate b/third_party/qt5/larch64/bin/lupdate new file mode 100755 index 0000000000..67b7ea5cb5 Binary files /dev/null and b/third_party/qt5/larch64/bin/lupdate differ diff --git a/third_party/snpe/aarch64 b/third_party/snpe/aarch64 deleted file mode 120000 index baf4e9cb6e..0000000000 --- a/third_party/snpe/aarch64 +++ /dev/null @@ -1 +0,0 @@ -aarch64-android-clang6.0 \ No newline at end of file diff --git a/third_party/snpe/aarch64-android-clang6.0/libPlatformValidatorShared.so b/third_party/snpe/aarch64-android-clang6.0/libPlatformValidatorShared.so deleted file mode 100644 index 5df5b07b18..0000000000 Binary files a/third_party/snpe/aarch64-android-clang6.0/libPlatformValidatorShared.so and /dev/null differ diff --git a/third_party/snpe/aarch64-android-clang6.0/libSNPE.so b/third_party/snpe/aarch64-android-clang6.0/libSNPE.so deleted file mode 100644 index 6ef777e15b..0000000000 Binary files a/third_party/snpe/aarch64-android-clang6.0/libSNPE.so and /dev/null differ diff --git a/third_party/snpe/aarch64-android-clang6.0/libSNPE_G.so b/third_party/snpe/aarch64-android-clang6.0/libSNPE_G.so deleted file mode 100644 index 565c80bb68..0000000000 Binary files a/third_party/snpe/aarch64-android-clang6.0/libSNPE_G.so and /dev/null differ diff --git a/third_party/snpe/aarch64-android-clang6.0/libc++_shared.so b/third_party/snpe/aarch64-android-clang6.0/libc++_shared.so deleted file mode 100644 index 5b9a9cff61..0000000000 Binary files a/third_party/snpe/aarch64-android-clang6.0/libc++_shared.so and /dev/null differ diff --git a/third_party/snpe/aarch64-android-clang6.0/libcalculator.so b/third_party/snpe/aarch64-android-clang6.0/libcalculator.so deleted file mode 100644 index 3aa1ec3ac2..0000000000 Binary files a/third_party/snpe/aarch64-android-clang6.0/libcalculator.so and /dev/null differ diff --git a/third_party/snpe/aarch64-android-clang6.0/libcalculator_domains.so b/third_party/snpe/aarch64-android-clang6.0/libcalculator_domains.so deleted file mode 100644 index bef3fc2019..0000000000 Binary files a/third_party/snpe/aarch64-android-clang6.0/libcalculator_domains.so and /dev/null differ diff --git a/third_party/snpe/aarch64-android-clang6.0/libhta.so b/third_party/snpe/aarch64-android-clang6.0/libhta.so deleted file mode 100644 index bfd3554cf7..0000000000 Binary files a/third_party/snpe/aarch64-android-clang6.0/libhta.so and /dev/null differ diff --git a/third_party/snpe/aarch64-android-clang6.0/libsnpe_adsp.so b/third_party/snpe/aarch64-android-clang6.0/libsnpe_adsp.so deleted file mode 100644 index 8a6b4e3fc5..0000000000 Binary files a/third_party/snpe/aarch64-android-clang6.0/libsnpe_adsp.so and /dev/null differ diff --git a/third_party/snpe/aarch64-android-clang6.0/libsnpe_dsp_domains.so b/third_party/snpe/aarch64-android-clang6.0/libsnpe_dsp_domains.so deleted file mode 100644 index 0663d25e33..0000000000 Binary files a/third_party/snpe/aarch64-android-clang6.0/libsnpe_dsp_domains.so and /dev/null differ diff --git a/third_party/snpe/aarch64-android-clang6.0/libsnpe_dsp_domains_system.so b/third_party/snpe/aarch64-android-clang6.0/libsnpe_dsp_domains_system.so deleted file mode 100644 index 33d354ff7d..0000000000 Binary files a/third_party/snpe/aarch64-android-clang6.0/libsnpe_dsp_domains_system.so and /dev/null differ diff --git a/third_party/snpe/aarch64-android-clang6.0/libsnpe_dsp_domains_v2.so b/third_party/snpe/aarch64-android-clang6.0/libsnpe_dsp_domains_v2.so deleted file mode 100644 index 5a63344590..0000000000 Binary files a/third_party/snpe/aarch64-android-clang6.0/libsnpe_dsp_domains_v2.so and /dev/null differ diff --git a/third_party/snpe/aarch64-android-clang6.0/libsnpe_dsp_domains_v2_system.so b/third_party/snpe/aarch64-android-clang6.0/libsnpe_dsp_domains_v2_system.so deleted file mode 100644 index 2d74ae0f05..0000000000 Binary files a/third_party/snpe/aarch64-android-clang6.0/libsnpe_dsp_domains_v2_system.so and /dev/null differ diff --git a/third_party/snpe/aarch64-android-clang6.0/libsymphony-cpu.so b/third_party/snpe/aarch64-android-clang6.0/libsymphony-cpu.so deleted file mode 100644 index 8dd26fb266..0000000000 Binary files a/third_party/snpe/aarch64-android-clang6.0/libsymphony-cpu.so and /dev/null differ diff --git a/third_party/snpe/aarch64-linux-gcc4.9/libPlatformValidatorShared.so b/third_party/snpe/aarch64-linux-gcc4.9/libPlatformValidatorShared.so deleted file mode 100644 index 32f8e2f60e..0000000000 Binary files a/third_party/snpe/aarch64-linux-gcc4.9/libPlatformValidatorShared.so and /dev/null differ diff --git a/third_party/snpe/aarch64-linux-gcc4.9/libSNPE.so b/third_party/snpe/aarch64-linux-gcc4.9/libSNPE.so deleted file mode 100644 index 6f497cfa08..0000000000 Binary files a/third_party/snpe/aarch64-linux-gcc4.9/libSNPE.so and /dev/null differ diff --git a/third_party/snpe/aarch64-linux-gcc4.9/libatomic.so.1 b/third_party/snpe/aarch64-linux-gcc4.9/libatomic.so.1 deleted file mode 100644 index 809fd4ef6f..0000000000 Binary files a/third_party/snpe/aarch64-linux-gcc4.9/libatomic.so.1 and /dev/null differ diff --git a/third_party/snpe/aarch64-linux-gcc4.9/libcalculator.so b/third_party/snpe/aarch64-linux-gcc4.9/libcalculator.so deleted file mode 100644 index dd3bfe5afd..0000000000 Binary files a/third_party/snpe/aarch64-linux-gcc4.9/libcalculator.so and /dev/null differ diff --git a/third_party/snpe/aarch64-linux-gcc4.9/libcalculator_domains.so b/third_party/snpe/aarch64-linux-gcc4.9/libcalculator_domains.so deleted file mode 100644 index 05cf724b7b..0000000000 Binary files a/third_party/snpe/aarch64-linux-gcc4.9/libcalculator_domains.so and /dev/null differ diff --git a/third_party/snpe/aarch64-linux-gcc4.9/libsnpe_adsp.so b/third_party/snpe/aarch64-linux-gcc4.9/libsnpe_adsp.so deleted file mode 100644 index 11db2cdf6d..0000000000 Binary files a/third_party/snpe/aarch64-linux-gcc4.9/libsnpe_adsp.so and /dev/null differ diff --git a/third_party/snpe/aarch64-linux-gcc4.9/libsnpe_dsp_domains_v2.so b/third_party/snpe/aarch64-linux-gcc4.9/libsnpe_dsp_domains_v2.so deleted file mode 100644 index cc8a8dc2ae..0000000000 Binary files a/third_party/snpe/aarch64-linux-gcc4.9/libsnpe_dsp_domains_v2.so and /dev/null differ diff --git a/third_party/snpe/aarch64-linux-gcc4.9/libsymphony-cpu.so b/third_party/snpe/aarch64-linux-gcc4.9/libsymphony-cpu.so deleted file mode 100644 index 202d7e9710..0000000000 Binary files a/third_party/snpe/aarch64-linux-gcc4.9/libsymphony-cpu.so and /dev/null differ diff --git a/third_party/snpe/aarch64-ubuntu-gcc7.5/libPlatformValidatorShared.so b/third_party/snpe/aarch64-ubuntu-gcc7.5/libPlatformValidatorShared.so new file mode 100644 index 0000000000..d3872772bc Binary files /dev/null and b/third_party/snpe/aarch64-ubuntu-gcc7.5/libPlatformValidatorShared.so differ diff --git a/third_party/snpe/aarch64-ubuntu-gcc7.5/libSNPE.so b/third_party/snpe/aarch64-ubuntu-gcc7.5/libSNPE.so new file mode 100644 index 0000000000..be23b835ab Binary files /dev/null and b/third_party/snpe/aarch64-ubuntu-gcc7.5/libSNPE.so differ diff --git a/third_party/snpe/aarch64-ubuntu-gcc7.5/libcalculator.so b/third_party/snpe/aarch64-ubuntu-gcc7.5/libcalculator.so new file mode 100644 index 0000000000..3b8c33f3f7 Binary files /dev/null and b/third_party/snpe/aarch64-ubuntu-gcc7.5/libcalculator.so differ diff --git a/third_party/snpe/aarch64-ubuntu-gcc7.5/libhta.so b/third_party/snpe/aarch64-ubuntu-gcc7.5/libhta.so new file mode 100644 index 0000000000..8358969edc Binary files /dev/null and b/third_party/snpe/aarch64-ubuntu-gcc7.5/libhta.so differ diff --git a/third_party/snpe/aarch64-ubuntu-gcc7.5/libsnpe_dsp_domains_v2.so b/third_party/snpe/aarch64-ubuntu-gcc7.5/libsnpe_dsp_domains_v2.so new file mode 100644 index 0000000000..c4f3fa67a2 Binary files /dev/null and b/third_party/snpe/aarch64-ubuntu-gcc7.5/libsnpe_dsp_domains_v2.so differ diff --git a/third_party/snpe/dsp/libcalculator_domains_skel.so b/third_party/snpe/dsp/libcalculator_domains_skel.so deleted file mode 100644 index cb8897f239..0000000000 Binary files a/third_party/snpe/dsp/libcalculator_domains_skel.so and /dev/null differ diff --git a/third_party/snpe/dsp/libcalculator_skel.so b/third_party/snpe/dsp/libcalculator_skel.so index 45515ea4f4..020dbfe869 100644 Binary files a/third_party/snpe/dsp/libcalculator_skel.so and b/third_party/snpe/dsp/libcalculator_skel.so differ diff --git a/third_party/snpe/dsp/libsnpe_dsp_domains_skel.so b/third_party/snpe/dsp/libsnpe_dsp_domains_skel.so deleted file mode 100644 index d4e341262a..0000000000 Binary files a/third_party/snpe/dsp/libsnpe_dsp_domains_skel.so and /dev/null differ diff --git a/third_party/snpe/dsp/libsnpe_dsp_skel.so b/third_party/snpe/dsp/libsnpe_dsp_skel.so deleted file mode 100644 index cb37356a98..0000000000 Binary files a/third_party/snpe/dsp/libsnpe_dsp_skel.so and /dev/null differ diff --git a/third_party/snpe/dsp/libsnpe_dsp_v65_domains_v2_skel.so b/third_party/snpe/dsp/libsnpe_dsp_v65_domains_v2_skel.so index 97a1499a04..c1eb88fc6a 100644 Binary files a/third_party/snpe/dsp/libsnpe_dsp_v65_domains_v2_skel.so and b/third_party/snpe/dsp/libsnpe_dsp_v65_domains_v2_skel.so differ diff --git a/third_party/snpe/dsp/libsnpe_dsp_v66_domains_v2_skel.so b/third_party/snpe/dsp/libsnpe_dsp_v66_domains_v2_skel.so index 008e9e9780..eeeb447c60 100644 Binary files a/third_party/snpe/dsp/libsnpe_dsp_v66_domains_v2_skel.so and b/third_party/snpe/dsp/libsnpe_dsp_v66_domains_v2_skel.so differ diff --git a/third_party/snpe/dsp/libsnpe_dsp_v68_domains_v3_skel.so b/third_party/snpe/dsp/libsnpe_dsp_v68_domains_v3_skel.so new file mode 100644 index 0000000000..028979f11f Binary files /dev/null and b/third_party/snpe/dsp/libsnpe_dsp_v68_domains_v3_skel.so differ diff --git a/third_party/snpe/include/DlSystem/DlEnums.hpp b/third_party/snpe/include/DlSystem/DlEnums.hpp index 1447063553..c9b3ef970a 100644 --- a/third_party/snpe/include/DlSystem/DlEnums.hpp +++ b/third_party/snpe/include/DlSystem/DlEnums.hpp @@ -1,6 +1,6 @@ //============================================================================== // -// Copyright (c) 2014-2020 Qualcomm Technologies, Inc. +// Copyright (c) 2014-2021 Qualcomm Technologies, Inc. // All Rights Reserved. // Confidential and Proprietary - Qualcomm Technologies, Inc. // @@ -76,6 +76,8 @@ enum class RuntimeCheckOption_t NORMAL_CHECK = 0, /// Perform basic runtime available check, may be runtime specific BASIC_CHECK = 1, + /// Perform unsignedPD runtime available check + UNSIGNEDPD_CHECK = 2, }; /** @@ -196,6 +198,36 @@ enum class ImageEncoding_t BGR = 6 }; +/** + * Enumeration that lists the supported LogLevels that can be set by users. + */ +enum class LogLevel_t +{ + /// Enumeration variable to be used by user to set logging level to FATAL. + LOG_FATAL = 0, + + /// Enumeration variable to be used by user to set logging level to ERROR. + LOG_ERROR = 1, + + /// Enumeration variable to be used by user to set logging level to WARN. + LOG_WARN = 2, + + /// Enumeration variable to be used by user to set logging level to INFO. + LOG_INFO = 3, + + /// Enumeration variable to be used by user to set logging level to VERBOSE. + LOG_VERBOSE = 4 +}; + +typedef enum : int +{ + UNSPECIFIED = 0, + FLOATING_POINT_32 = 1, + FLOATING_POINT_16 = 2, + FIXED_POINT_8 = 3, + FIXED_POINT_16 = 4 +} IOBufferDataType_t; + }} // namespaces end diff --git a/third_party/snpe/include/DlSystem/DlError.hpp b/third_party/snpe/include/DlSystem/DlError.hpp index f0a66e8e45..57592f01ba 100644 --- a/third_party/snpe/include/DlSystem/DlError.hpp +++ b/third_party/snpe/include/DlSystem/DlError.hpp @@ -1,6 +1,6 @@ //============================================================================== // -// Copyright (c) 2016-2020 Qualcomm Technologies, Inc. +// Copyright (c) 2016-2021 Qualcomm Technologies, Inc. // All Rights Reserved. // Confidential and Proprietary - Qualcomm Technologies, Inc. // @@ -59,6 +59,7 @@ enum class ZDL_EXPORT ErrorCode : uint32_t { SNPE_DLSYSTEM_BUFFER_CAST_FAILED = 216, SNPE_DLSYSTEM_WRONG_TRANSITION_TYPE = 217, SNPE_DLSYSTEM_LAYER_ALREADY_REGISTERED = 218, + SNPE_DLSYSTEM_TENSOR_DIM_INVALID = 219, SNPE_DLSYSTEM_BUFFERENCODING_UNKNOWN = 240, SNPE_DLSYSTEM_BUFFER_INVALID_PARAM = 241, @@ -89,6 +90,7 @@ enum class ZDL_EXPORT ErrorCode : uint32_t { SNPE_NETWORK_MISMATCH_BETWEEN_NAMES_AND_DIMS = 404, SNPE_NETWORK_MISSING_INPUT_NAMES = 405, SNPE_NETWORK_MISSING_OUTPUT_NAMES = 406, + SNPE_NETWORK_EXECUTION_FAILED = 407, // Host runtime errors SNPE_HOST_RUNTIME_TARGET_UNAVAILABLE = 500, @@ -140,6 +142,13 @@ enum class ZDL_EXPORT ErrorCode : uint32_t { SNPE_DSP_RUNTIME_INVALID_PARAM_ERROR = 909, SNPE_DSP_RUNTIME_SYSTEM_ERROR = 910, SNPE_DSP_RUNTIME_CRASHED_ERROR = 911, + SNPE_DSP_BUFFER_SIZE_ERROR = 912, + SNPE_DSP_UDO_EXECUTE_ERROR = 913, + SNPE_DSP_UDO_LIB_NOT_REGISTERED_ERROR = 914, + SNPE_DSP_UDO_INVALID_QUANTIZATION_TYPE_ERROR = 915, + SNPE_DSP_RUNTIME_INVALID_RPC_DRIVER = 916, + SNPE_DSP_RUNTIME_RPC_PERMISSION_ERROR = 917, + SNPE_DSP_RUNTIME_DSP_FILE_OPEN_ERROR = 918, // Model validataion errors SNPE_MODEL_VALIDATION_LAYER_NOT_SUPPORTED = 1000, @@ -196,7 +205,10 @@ enum class ZDL_EXPORT ErrorCode : uint32_t { // Infrastructure Errors SNPE_INFRA_CLUSTERMGR_INSTANCE_INVALID = 1600, - SNPE_INFRA_CLUSTERMGR_EXECUTE_SYNC_FAILED = 1601 + SNPE_INFRA_CLUSTERMGR_EXECUTE_SYNC_FAILED = 1601, + + // Memory Errors + SNPE_MEMORY_CORRUPTION_ERROR = 1700 }; diff --git a/third_party/snpe/include/DlSystem/IOBufferDataTypeMap.hpp b/third_party/snpe/include/DlSystem/IOBufferDataTypeMap.hpp new file mode 100644 index 0000000000..e36b1fbd7e --- /dev/null +++ b/third_party/snpe/include/DlSystem/IOBufferDataTypeMap.hpp @@ -0,0 +1,127 @@ +//============================================================================= +// +// Copyright (c) 2021-2022 Qualcomm Technologies, Inc. +// All Rights Reserved. +// Confidential and Proprietary - Qualcomm Technologies, Inc. +// +//============================================================================= + + +#ifndef DL_SYSTEM_IOBUFFER_DATATYPE_MAP_HPP +#define DL_SYSTEM_IOBUFFER_DATATYPE_MAP_HPP + +#include +#include +#include "DlSystem/DlEnums.hpp" + +namespace DlSystem +{ + // Forward declaration of IOBufferDataTypeMapImpl implementation. + class IOBufferDataTypeMapImpl; +} + +namespace zdl +{ +namespace DlSystem +{ +/** @addtogroup c_plus_plus_apis C++ +@{ */ + +/** + * @brief . + * + * The IoBufferDataTypeMap class definition + */ +class ZDL_EXPORT IOBufferDataTypeMap final +{ +public: + + /** + * @brief . + * + * Creates a new Buffer Data type map + * + */ + IOBufferDataTypeMap(); + + /** + * @brief Adds a name and the corresponding buffer data type + * to the map + * + * @param[name] name The name of the buffer + * @param[bufferDataType] buffer Data Type of the buffer + * + * @note If a buffer with the same name already exists, no new + * buffer is added. + */ + void add(const char* name, zdl::DlSystem::IOBufferDataType_t bufferDataType); + + /** + * @brief Removes a buffer name from the map + * + * @param[name] name The name of the buffer + * + */ + void remove(const char* name); + + /** + * @brief Returns the type of the named buffer + * + * @param[name] name The name of the buffer + * + * @return The type of the buffer, or UNSPECIFIED if the buffer does not exist + * + */ + zdl::DlSystem::IOBufferDataType_t getBufferDataType(const char* name); + + /** + * @brief Returns the type of the first buffer + * + * @return The type of the first buffer, or UNSPECIFIED if the map is empty. + * + */ + zdl::DlSystem::IOBufferDataType_t getBufferDataType(); + + /** + * @brief Returns the size of the buffer type map. + * + * @return The size of the map + * + */ + size_t size(); + + /** + * @brief Checks the existence of the named buffer in the map + * + * @return True if the named buffer exists, false otherwise. + * + */ + bool find(const char* name); + + /** + * @brief Resets the map + * + */ + void clear(); + + /** + * @brief Checks whether the map is empty + * + * @return True if the map is empty, false otherwise. + * + */ + bool empty(); + + /** + * @brief Destroys the map + * + */ + ~IOBufferDataTypeMap(); + +private: + std::shared_ptr<::DlSystem::IOBufferDataTypeMapImpl> m_IOBufferDataTypeMapImpl; +}; +} + +} +#endif diff --git a/third_party/snpe/include/DlSystem/IUDL.hpp b/third_party/snpe/include/DlSystem/IUDL.hpp index 2e9dddc48f..a171ac7e81 100644 --- a/third_party/snpe/include/DlSystem/IUDL.hpp +++ b/third_party/snpe/include/DlSystem/IUDL.hpp @@ -1,6 +1,6 @@ //============================================================================= // -// Copyright (c) 2016-2017 Qualcomm Technologies, Inc. +// Copyright (c) 2016-2021 Qualcomm Technologies, Inc. // All Rights Reserved. // Confidential and Proprietary - Qualcomm Technologies, Inc. // @@ -13,10 +13,10 @@ namespace zdl { namespace DlSystem { -/** @addtogroup c_plus_plus_apis C++ -@{ */ /** + * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. + * * @brief . * * Base class user concrete UDL implementation. @@ -32,6 +32,8 @@ namespace DlSystem { class ZDL_EXPORT IUDL { public: /** + * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. + * * @brief . * * Destructor @@ -39,6 +41,8 @@ public: virtual ~IUDL() = default; /** + * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. + * * @brief Sets up the user's environment. * This is called by the SNPE framework to allow the user the * opportunity to setup anything which is needed for running @@ -66,6 +70,8 @@ public: size_t outsz, const size_t **outdim, const size_t *outdimsz) = 0; /** + * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. + * * @brief Close the instance. Invoked by the SNPE * framework to allow the user the opportunity to release any resources * allocated during setup. @@ -75,6 +81,8 @@ public: virtual void close(void *cookie) noexcept = 0; /** + * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. + * * @brief Execute the user defined layer * * @param cookie User provided opaque data returned by the SNPE @@ -89,7 +97,6 @@ public: */ virtual bool execute(void *cookie, const float **input, float **output) = 0; }; -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ } // ns DlSystem diff --git a/third_party/snpe/include/DlSystem/IUserBuffer.hpp b/third_party/snpe/include/DlSystem/IUserBuffer.hpp index 5e5731dd83..ea491a545b 100644 --- a/third_party/snpe/include/DlSystem/IUserBuffer.hpp +++ b/third_party/snpe/include/DlSystem/IUserBuffer.hpp @@ -151,101 +151,6 @@ public: * An encoding type where each element is represented by tf8, which is an * 8-bit quantizd value, which has an exact representation of 0.0 */ - -class ZDL_EXPORT UserBufferEncodingTf8 : public UserBufferEncodingUnsigned8Bit { -public: - UserBufferEncodingTf8() = delete; - UserBufferEncodingTf8(unsigned char stepFor0, float stepSize) : - UserBufferEncodingUnsigned8Bit(ElementType_t::TF8), - m_StepExactly0(stepFor0), - m_QuantizedStepSize(stepSize) {}; - - UserBufferEncodingTf8(const zdl::DlSystem::UserBufferEncoding &ubEncoding) : UserBufferEncodingUnsigned8Bit(ubEncoding.getElementType()){ - const zdl::DlSystem::UserBufferEncodingTf8* ubEncodingTf8 - = dynamic_cast (&ubEncoding); - if (ubEncodingTf8) { - m_StepExactly0 = ubEncodingTf8->getStepExactly0(); - m_QuantizedStepSize = ubEncodingTf8->getQuantizedStepSize(); - } - } - -/** - * @brief Sets the step value that represents 0 - * - * @param[in] stepExactly0 The step value that represents 0 - * - */ - - void setStepExactly0(const unsigned char stepExactly0) { - m_StepExactly0 = stepExactly0; - } - - -/** - * @brief Sets the float value that each step represents - * - * @param[in] quantizedStepSize The float value of each step size - * - */ - - void setQuantizedStepSize(const float quantizedStepSize) { - m_QuantizedStepSize = quantizedStepSize; - } - - -/** - * @brief Retrieves the step that represents 0.0 - * - * @return Step value - */ - - unsigned char getStepExactly0() const { - return m_StepExactly0; - } - - -/** - * Calculates the minimum floating point value that - * can be represented with this encoding. - * - * @return Minimum representable floating point value - */ - - float getMin() const { - return m_QuantizedStepSize * (0 - m_StepExactly0); - } - - -/** - * Calculates the maximum floating point value that - * can be represented with this encoding. - * - * @return Maximum representable floating point value - */ - - float getMax() const { - return m_QuantizedStepSize * (255 - m_StepExactly0); - } - - -/** - * @brief Retrieves the step size - * - * @return Step size - */ - - float getQuantizedStepSize() const { - return m_QuantizedStepSize; - } - -private: - unsigned char m_StepExactly0; - - float m_QuantizedStepSize; -}; - - - class ZDL_EXPORT UserBufferEncodingTfN : public UserBufferEncoding { public: UserBufferEncodingTfN() = delete; @@ -327,12 +232,44 @@ public: ElementType_t getTypeFromWidth(uint8_t width); uint8_t bitWidth; -private: +protected: uint64_t m_StepExactly0; float m_QuantizedStepSize; }; +class ZDL_EXPORT UserBufferEncodingTf8 : public UserBufferEncodingTfN { +public: + UserBufferEncodingTf8() = delete; + UserBufferEncodingTf8(unsigned char stepFor0, float stepSize) : + UserBufferEncodingTfN(stepFor0, stepSize) {}; + + UserBufferEncodingTf8(const zdl::DlSystem::UserBufferEncoding &ubEncoding) : UserBufferEncodingTfN(ubEncoding){} + +/** + * @brief Sets the step value that represents 0 + * + * @param[in] stepExactly0 The step value that represents 0 + * + */ + + void setStepExactly0(const unsigned char stepExactly0) { + UserBufferEncodingTfN::m_StepExactly0 = stepExactly0; + } + +/** + * @brief Retrieves the step that represents 0.0 + * + * @return Step value + */ + + unsigned char getStepExactly0() const { + return UserBufferEncodingTfN::m_StepExactly0; + } + +}; + + /** * @brief UserBuffer contains a pointer and info on how to walk it and interpret its content. */ diff --git a/third_party/snpe/include/DlSystem/PlatformConfig.hpp b/third_party/snpe/include/DlSystem/PlatformConfig.hpp index 3f15f177e3..c7b85f43c1 100644 --- a/third_party/snpe/include/DlSystem/PlatformConfig.hpp +++ b/third_party/snpe/include/DlSystem/PlatformConfig.hpp @@ -1,6 +1,6 @@ //============================================================================= // -// Copyright (c) 2017-2018 Qualcomm Technologies, Inc. +// Copyright (c) 2017-2018,2021 Qualcomm Technologies, Inc. // All Rights Reserved. // Confidential and Proprietary - Qualcomm Technologies, Inc. // @@ -190,10 +190,37 @@ public: */ std::string getPlatformOptions() const { return m_PlatformOptions; } + /** + * @brief Sets the platform options + * + * @param[in] optionName Name of platform options" + * @param[in] value Value of specified optionName + * + * @return If true, add "optionName:value" to platform options if optionName don't exist, otherwise update the + * value of specified optionName. + * If false, the platform options will not be changed. + */ + bool setPlatformOptionValue(const std::string& optionName, const std::string& value); + + /** + * @brief Removes the platform options + * + * @param[in] optionName Name of platform options" + * @param[in] value Value of specified optionName + * + * @return If true, removed "optionName:value" to platform options if optionName don't exist, do nothing. + * If false, the platform options will not be changed. + */ + bool removePlatformOptionValue(const std::string& optionName, const std::string& value); + + static void SetIsUserGLBuffer(bool isUserGLBuffer); + static bool GetIsUserGLBuffer(); + private: PlatformType_t m_PlatformType; PlatformConfigInfo m_PlatformConfigInfo; std::string m_PlatformOptions; + static bool m_IsUserGLBuffer; }; /** @} */ /* end_addtogroup c_plus_plus_apis C++ */ diff --git a/third_party/snpe/include/DlSystem/UDLContext.hpp b/third_party/snpe/include/DlSystem/UDLContext.hpp index 6b7c07d3eb..21fce1b04a 100644 --- a/third_party/snpe/include/DlSystem/UDLContext.hpp +++ b/third_party/snpe/include/DlSystem/UDLContext.hpp @@ -1,6 +1,6 @@ //============================================================================== // -// Copyright (c) 2016 Qualcomm Technologies, Inc. +// Copyright (c) 2016-2021 Qualcomm Technologies, Inc. // All Rights Reserved. // Confidential and Proprietary - Qualcomm Technologies, Inc. // @@ -15,10 +15,10 @@ #include "ZdlExportDefine.hpp" namespace zdl { namespace DlSystem { -/** @addtogroup c_plus_plus_apis C++ -@{ */ /** + * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. + * * @brief . * * UDLContext holds the user defined layer context which @@ -237,7 +237,6 @@ private: size_t m_Size = 0; int32_t m_Id = -1; }; -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ }} diff --git a/third_party/snpe/include/DlSystem/UDLFunc.hpp b/third_party/snpe/include/DlSystem/UDLFunc.hpp index 633ce985bf..6a95eef170 100644 --- a/third_party/snpe/include/DlSystem/UDLFunc.hpp +++ b/third_party/snpe/include/DlSystem/UDLFunc.hpp @@ -1,6 +1,6 @@ //============================================================================== // -// Copyright (c) 2015 Qualcomm Technologies, Inc. +// Copyright (c) 2015-2021 Qualcomm Technologies, Inc. // All Rights Reserved. // Confidential and Proprietary - Qualcomm Technologies, Inc. // @@ -21,9 +21,9 @@ namespace zdl { } namespace zdl { namespace DlSystem { -/** @addtogroup c_plus_plus_apis C++ -@{ */ /** + * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. + * * @brief . * * Definition of UDLFactoyFunc, using/typedef and default FactoryFunction @@ -47,6 +47,8 @@ namespace zdl { namespace DlSystem { using UDLFactoryFunc = std::function; /** + * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. + * * @brief . * * default UDL factory implementation @@ -65,6 +67,8 @@ using UDLFactoryFunc = std::function +#include "ZdlExportDefine.hpp" +#include "StringList.hpp" + +#ifndef DL_SYSTEM_USER_MEMORY_MAP_HPP +#define DL_SYSTEM_USER_MEMORY_MAP_HPP + +namespace DlSystem +{ + // Forward declaration of UserMemory map implementation. + class UserMemoryMapImpl; +} + +namespace zdl +{ +namespace DlSystem +{ +class IUserBuffer; + +/** @addtogroup c_plus_plus_apis C++ +@{ */ + +/** + * @brief . + * + * A class representing the map of UserMemory. + */ +class ZDL_EXPORT UserMemoryMap final +{ +public: + + /** + * @brief . + * + * Creates a new empty UserMemory map + */ + UserMemoryMap(); + + /** + * copy constructor. + * @param[in] other object to copy. + */ + UserMemoryMap(const UserMemoryMap& other); + + /** + * assignment operator. + */ + UserMemoryMap& operator=(const UserMemoryMap& other); + + /** + * @brief Adds a name and the corresponding buffer address + * to the map + * + * @param[in] name The name of the UserMemory + * @param[in] address The pointer to the Buffer Memory + * + * @note If a UserBuffer with the same name already exists, the new + * address would be updated. + */ + void add(const char *name, void *address); + + /** + * @brief Removes a mapping of one Buffer address and its name by its name + * + * @param[in] name The name of Memory address to be removed + * + * @note If no UserBuffer with the specified name is found, nothing + * is done. + */ + void remove(const char *name) noexcept; + + /** + * @brief Returns the number of User Memory addresses in the map + */ + size_t size() const noexcept; + + /** + * @brief . + * + * Removes all User Memory from the map + */ + void clear() noexcept; + + /** + * @brief . + * + * Returns the names of all User Memory + * + * @return A list of Buffer names. + */ + zdl::DlSystem::StringList getUserBufferNames() const; + + /** + * @brief Returns the no of UserMemory addresses mapped to the buffer + * + * @param[in] name The name of the UserMemory + * + */ + size_t getUserMemoryAddressCount(const char *name) const noexcept; + + /** + * @brief Returns address at a specified index corresponding to a UserMemory buffer name + * + * @param[in] name The name of the buffer + * @param[in] index The index in the list of addresses + * + */ + void* getUserMemoryAddressAtIndex(const char *name, uint32_t index) const noexcept; + + ~UserMemoryMap(); +private: + void swap(const UserMemoryMap &other); + std::unique_ptr<::DlSystem::UserMemoryMapImpl> m_UserMemoryMapImpl; +}; +/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ + +} // DlSystem namespace +} // zdl namespace + + +#endif // DL_SYSTEM_TENSOR_MAP_HPP + diff --git a/third_party/snpe/include/PlatformValidator/PlatformValidator.hpp b/third_party/snpe/include/PlatformValidator/PlatformValidator.hpp index e74278ead7..66097ba569 100644 --- a/third_party/snpe/include/PlatformValidator/PlatformValidator.hpp +++ b/third_party/snpe/include/PlatformValidator/PlatformValidator.hpp @@ -1,6 +1,6 @@ // ============================================================================= // -// Copyright (c) 2018-2019 Qualcomm Technologies, Inc. +// Copyright (c) 2018-2020 Qualcomm Technologies, Inc. // All Rights Reserved. // Confidential and Proprietary - Qualcomm Technologies, Inc. // @@ -10,7 +10,32 @@ #define SNPE_PLATFORMVALIDATOR_HPP #include "DlSystem/DlEnums.hpp" -#include "DlSystem/DlMacros.hpp" +#include "DlSystem/ZdlExportDefine.hpp" + +#define DO_PRAGMA(s) _Pragma(#s) +#define NO_WARNING "-Wunused-variable" + +#ifdef __clang__ +#define SNPE_DISABLE_WARNINGS(clang_warning,gcc_warning) \ +_Pragma("clang diagnostic push") \ +DO_PRAGMA(clang diagnostic ignored clang_warning) + +#define SNPE_ENABLE_WARNINGS \ +_Pragma("clang diagnostic pop") + +#elif defined __GNUC__ +#define SNPE_DISABLE_WARNINGS(clang_warning,gcc_warning) \ +_Pragma("GCC diagnostic push") \ +DO_PRAGMA(GCC diagnostic ignored gcc_warning) + +#define SNPE_ENABLE_WARNINGS \ +_Pragma("GCC diagnostic pop") + +#else +#define SNPE_DISABLE_WARNINGS(...) +#define SNPE_ENABLE_WARNINGS +#endif + SNPE_DISABLE_WARNINGS("-Wdelete-non-virtual-dtor","-Wdelete-non-virtual-dtor") #include #include @@ -34,7 +59,7 @@ namespace zdl * */ -class zdl::SNPE::PlatformValidator +class ZDL_EXPORT zdl::SNPE::PlatformValidator { public: /** diff --git a/third_party/snpe/include/SNPE/PSNPE.hpp b/third_party/snpe/include/SNPE/PSNPE.hpp index c0a6fb55d6..a823c0c7fa 100644 --- a/third_party/snpe/include/SNPE/PSNPE.hpp +++ b/third_party/snpe/include/SNPE/PSNPE.hpp @@ -1,6 +1,6 @@ // ============================================================================= // -// Copyright (c) 2019-2020 Qualcomm Technologies, Inc. +// Copyright (c) 2019-2021 Qualcomm Technologies, Inc. // All Rights Reserved. // Confidential and Proprietary - Qualcomm Technologies, Inc. // @@ -54,8 +54,9 @@ struct ZDL_EXPORT OutputAsyncCallbackParam { size_t dataIndex; bool executeStatus; - OutputAsyncCallbackParam(size_t _index,bool _status) - : dataIndex(_index),executeStatus(_status){}; + std::string errorMsg; + OutputAsyncCallbackParam(size_t _index,bool _status, const std::string& _errorMsg = std::string()) + : dataIndex(_index),executeStatus(_status), errorMsg(_errorMsg){}; }; /** * @brief A structure representing parameters of callback function of Async Input/Output mode @@ -65,12 +66,13 @@ struct ZDL_EXPORT InputOutputAsyncCallbackParam size_t dataIndex; const ApplicationBufferMap& outputMap; bool executeStatus; - InputOutputAsyncCallbackParam(size_t _index, const ApplicationBufferMap& output_map,bool _status) + std::string errorMsg; + InputOutputAsyncCallbackParam(size_t _index, const ApplicationBufferMap& output_map,bool _status, + const std::string _ErrorMsg = std::string()) : dataIndex(_index) , outputMap(output_map) - ,executeStatus(_status){ - - }; + , executeStatus(_status) + , errorMsg(_ErrorMsg){}; }; /** * @brief This callback is called when the output data is ready, only use for Output Async mode @@ -96,6 +98,7 @@ struct ZDL_EXPORT BuildConfig final BuildMode buildMode = BuildMode::SERIAL; ///< Specify build in serial mode or parallel mode zdl::DlContainer::IDlContainer* container;///< The opened container ptr zdl::DlSystem::StringList outputBufferNames;///< Specify the output layer name + zdl::DlSystem::StringList outputTensors;///< Specify the output layer name RuntimeConfigList runtimeConfigList;///< The runtime config list for PSNPE, @see RuntimeConfig size_t inputThreadNumbers = 1;///< Specify the number of threads used in the execution phase to process input data, only used in inputOutputAsync mode size_t outputThreadNumbers = 1;///< Specify the number of threads used in the execution phase to process output data, only used in inputOutputAsync and outputAsync mode @@ -106,6 +109,8 @@ struct ZDL_EXPORT BuildConfig final zdl::DlSystem::ProfilingLevel_t profilingLevel = zdl::DlSystem::ProfilingLevel_t::OFF;///< Specify profiling level for Diaglog uint64_t encode[2] = {0, 0}; bool enableInitCache = false; + std::string platformOptions; + std::string diaglogOutputDir = "./diaglogs/"; ///< Specify a diaglog output directory to save the generated Diaglog files. }; /** * @brief . @@ -170,6 +175,8 @@ class ZDL_EXPORT PSNPE final */ const zdl::DlSystem::TensorShape getInputDimensions() const noexcept; + const zdl::DlSystem::TensorShape getInputDimensions(const char *name) const noexcept; + /** * @brief Returns attributes of buffers. * @@ -180,6 +187,10 @@ class ZDL_EXPORT PSNPE final const zdl::DlSystem::TensorShape getBufferAttributesDims(const char *name) const noexcept; zdl::DlSystem::Optional getInputOutputBufferAttributes(const char *name) const noexcept; + bool registerIonBuffers(const zdl::DlSystem::UserMemoryMap& ionBufferMap) const noexcept; + bool deregisterIonBuffers(const zdl::DlSystem::StringList& ionBufferNames) const noexcept; + + const char* getLastErrorString(); private: PSNPE(const PSNPE&) = delete; diff --git a/third_party/snpe/include/SNPE/SNPE.hpp b/third_party/snpe/include/SNPE/SNPE.hpp index 239690ab2c..5ab45b82ee 100644 --- a/third_party/snpe/include/SNPE/SNPE.hpp +++ b/third_party/snpe/include/SNPE/SNPE.hpp @@ -1,6 +1,6 @@ //============================================================================== // -// Copyright (c) 2015-2020 Qualcomm Technologies, Inc. +// Copyright (c) 2015-2021 Qualcomm Technologies, Inc. // All Rights Reserved. // Confidential and Proprietary - Qualcomm Technologies, Inc. // @@ -19,6 +19,7 @@ #include "DlSystem/StringList.hpp" #include "DlSystem/IUserBuffer.hpp" #include "DlSystem/UserBufferMap.hpp" +#include "DlSystem/UserMemoryMap.hpp" #include "DlSystem/ZdlExportDefine.hpp" namespace zdl { @@ -147,6 +148,21 @@ public: bool execute(const zdl::DlSystem::UserBufferMap &input, const zdl::DlSystem::UserBufferMap &output) noexcept; + + /** + * @brief Regiter Client ION Buffers + * @param[in] A UserMemoryMap of virtual addresses + * + */ + bool registerIonBuffers(const zdl::DlSystem::UserMemoryMap& ionBufferMap) noexcept; + + /** + * @brief Regiter Client ION Buffers + * @param[in] A StringList of ION Buffer names + * + */ + bool deregisterIonBuffers(const zdl::DlSystem::StringList& ionBufferNames) noexcept; + /** * @brief Returns the version string embedded at model conversion * time. @@ -215,8 +231,6 @@ public: */ zdl::DlSystem::Optional getInputOutputBufferAttributes(const char *name) const noexcept; - zdl::DlSystem::Optional getInputOutputBufferAttributesTf8(const char *name) const noexcept; - /** * @brief . * diff --git a/third_party/snpe/include/SNPE/SNPEBuilder.hpp b/third_party/snpe/include/SNPE/SNPEBuilder.hpp index f314d88bcf..5fc7846ced 100644 --- a/third_party/snpe/include/SNPE/SNPEBuilder.hpp +++ b/third_party/snpe/include/SNPE/SNPEBuilder.hpp @@ -1,6 +1,6 @@ //============================================================================== // -// Copyright (c) 2017-2019 Qualcomm Technologies, Inc. +// Copyright (c) 2017-2021 Qualcomm Technologies, Inc. // All Rights Reserved. // Confidential and Proprietary - Qualcomm Technologies, Inc. // @@ -15,6 +15,7 @@ #include "DlSystem/DlOptional.hpp" #include "DlSystem/TensorShapeMap.hpp" #include "DlSystem/PlatformConfig.hpp" +#include "DlSystem/IOBufferDataTypeMap.hpp" #include "DlSystem/RuntimeList.hpp" namespace zdl { @@ -275,6 +276,28 @@ public: SNPEBuilder& setUnconsumedTensorsAsOutputs( bool setOutput); + /** + * @brief Execution terminated when exceeding time limit. + * Only valid for dsp runtime currently. + * + * @param[in] timeout Time limit value + * + * @return The current instance of SNPEBuilder. + */ + SNPEBuilder& setTimeOut( + uint64_t timeout); + + + /** + * @brief Sets the datatype of the buffer. + * Only valid for dsp runtime currently. + * + * @param[in] Map of the buffer names and the datatype that needs to be set. + * + * @return The current instance of SNPEBuilder. + */ + SNPEBuilder& setBufferDataType(const zdl::DlSystem::IOBufferDataTypeMap& dataTypeMap); + }; /** @} */ /* end_addtogroup c_plus_plus_apis C++ */ diff --git a/third_party/snpe/include/SNPE/SNPEFactory.hpp b/third_party/snpe/include/SNPE/SNPEFactory.hpp index 7bef45d877..2d78e81b17 100644 --- a/third_party/snpe/include/SNPE/SNPEFactory.hpp +++ b/third_party/snpe/include/SNPE/SNPEFactory.hpp @@ -1,6 +1,6 @@ //============================================================================== // -// Copyright (c) 2015-2020 Qualcomm Technologies, Inc. +// Copyright (c) 2015-2021 Qualcomm Technologies, Inc. // All Rights Reserved. // Confidential and Proprietary - Qualcomm Technologies, Inc. // @@ -47,8 +47,6 @@ public: * * @param[in] runtime The target runtime to check. * - * @param[in] option Extent to perform runtime available check. - * * @return True if the supplied runtime is available; false, * otherwise. */ @@ -122,6 +120,97 @@ public: * otherwise. */ static bool isGLCLInteropSupported(); + + static const char* getLastError(); + + /** + * Initializes logging with the specified log level. + * initializeLogging with level, is used on Android platforms + * and after successful initialization, SNPE + * logs are printed in android logcat logs. + * + * It is recommended to initializeLogging before creating any + * SNPE instances, in order to capture information related to + * core initialization. If this is called again after first + * time initialization, subsequent calls are ignored. + * Also, Logging can be re-initialized after a call to + * terminateLogging API by calling initializeLogging again. + * + * A typical usage of Logging life cycle can be + * initializeLogging() + * any other SNPE API like isRuntimeAvailable() + * * setLogLevel() - optional - can be called anytime + * between initializeLogging & terminateLogging + * SNPE instance creation, inference, destroy + * terminateLogging(). + * + * Please note, enabling logging can have performance impact. + * + * @param[in] LogLevel_t Log level (LOG_INFO, LOG_WARN, etc.). + * + * @return True if successful, False otherwise. + */ + static bool initializeLogging(const zdl::DlSystem::LogLevel_t& level); + + /** + * Initializes logging with the specified log level and log path. + * initializeLogging with level & log path, is used on non Android + * platforms and after successful initialization, SNPE + * logs are printed in std output & into log files created in the + * log path. + * + * It is recommended to initializeLogging before creating any + * SNPE instances, in order to capture information related to + * core initialization. If this is called again after first + * time initialization, subsequent calls are ignored. + * Also, Logging can be re-initialized after a call to + * terminateLogging API by calling initializeLogging again. + * + * A typical usage of Logging life cycle can be + * initializeLogging() + * any other SNPE API like isRuntimeAvailable() + * * setLogLevel() - optional - can be called anytime + * between initializeLogging & terminateLogging + * SNPE instance creation, inference, destroy + * terminateLogging() + * + * Please note, enabling logging can have performance impact + * + * @param[in] LogLevel_t Log level (LOG_INFO, LOG_WARN, etc.). + * + * @param[in] Path of directory to store logs. + * If path is empty, the default path is "./Log". + * For android, the log path is ignored. + * + * @return True if successful, False otherwise. + */ + static bool initializeLogging(const zdl::DlSystem::LogLevel_t& level, const std::string& logPath); + + /** + * Updates the current logging level with the specified level. + * setLogLevel is optional, called anytime after initializeLogging + * and before terminateLogging, to update the log level set. + * Log levels can be updated multiple times by calling setLogLevel + * A call to setLogLevel() is ignored if it is made before + * initializeLogging() or after terminateLogging() + * + * @param[in] LogLevel_t Log level (LOG_INFO, LOG_WARN, etc.). + * + * @return True if successful, False otherwise. + */ + static bool setLogLevel(const zdl::DlSystem::LogLevel_t& level); + + /** + * Terminates logging. + * + * It is recommended to terminateLogging after initializeLogging + * in order to disable logging information. + * If this is called before initialization or after first time termination, + * calls are ignored. + * + * @return True if successful, False otherwise. + */ + static bool terminateLogging(void); }; /** @} */ /* end_addtogroup c_plus_plus_apis C++ */ diff --git a/third_party/snpe/include/SnpeUdo/UdoBase.h b/third_party/snpe/include/SnpeUdo/UdoBase.h index be370e1ac5..7b2567920e 100644 --- a/third_party/snpe/include/SnpeUdo/UdoBase.h +++ b/third_party/snpe/include/SnpeUdo/UdoBase.h @@ -1,6 +1,6 @@ //============================================================================== // -// Copyright (c) 2019-2020 Qualcomm Technologies, Inc. +// Copyright (c) 2019-2021 Qualcomm Technologies, Inc. // All Rights Reserved. // Confidential and Proprietary - Qualcomm Technologies, Inc. // @@ -13,7 +13,7 @@ // Provide values to use for API version. #define API_VERSION_MAJOR 1 -#define API_VERSION_MINOR 5 +#define API_VERSION_MINOR 6 #define API_VERSION_TEENY 0 /** @addtogroup c_plus_plus_apis C++ @@ -21,10 +21,12 @@ // Defines a bitmask of enum values. typedef uint32_t SnpeUdo_Bitmask_t; +typedef SnpeUdo_Bitmask_t Udo_Bitmask_t; // A string of characters, rather than an array of bytes. // Assumed to be UTF-8. typedef char* SnpeUdo_String_t; +typedef SnpeUdo_String_t Udo_String_t; // The maximum allowable length of a SnpeUdo_String_t in bytes, // including null terminator. SNPE will truncate strings longer @@ -41,32 +43,34 @@ typedef char* SnpeUdo_String_t; typedef enum { /// No Error - SNPE_UDO_NO_ERROR = 0, + SNPE_UDO_NO_ERROR = 0, UDO_NO_ERROR = 0, /// Unsupported value for core type - SNPE_UDO_WRONG_CORE = 1, + SNPE_UDO_WRONG_CORE = 1, UDO_WRONG_CORE = 1, /// Invalid attribute/argument passed into UDO API - SNPE_UDO_INVALID_ARGUMENT = 2, + SNPE_UDO_INVALID_ARGUMENT = 2, UDO_INVALID_ARGUMENT = 2, /// Unsupported feature error - SNPE_UDO_UNSUPPORTED_FEATURE = 3, + SNPE_UDO_UNSUPPORTED_FEATURE = 3, UDO_UNSUPPORTED_FEATURE = 3, /// Error relating to memory allocation - SNPE_UDO_MEM_ALLOC_ERROR = 4, + SNPE_UDO_MEM_ALLOC_ERROR = 4, UDO_MEM_ALLOC_ERROR = 4, /* Configuration Specific errors */ /// No op with given attributes available in library - SNPE_UDO_WRONG_OPERATION = 100, + SNPE_UDO_WRONG_OPERATION = 100, UDO_WRONG_OPERATION = 100, /// Unsupported value for core type in UDO configuration - SNPE_UDO_WRONG_CORE_TYPE = 101, + SNPE_UDO_WRONG_CORE_TYPE = 101, UDO_WRONG_CORE_TYPE = 101, /// Wrong number of params in UDO definition - SNPE_UDO_WRONG_NUM_OF_PARAMS = 102, + SNPE_UDO_WRONG_NUM_OF_PARAMS = 102, UDO_WRONG_NUM_OF_PARAMS = 102, /// Wrong number of dimensions for tensor(s) in UDO definition - SNPE_UDO_WRONG_NUM_OF_DIMENSIONS = 103, + SNPE_UDO_WRONG_NUM_OF_DIMENSIONS = 103, UDO_WRONG_NUM_OF_DIMENSIONS = 103, /// Wrong number of input tensors in UDO definition - SNPE_UDO_WRONG_NUM_OF_INPUTS = 104, + SNPE_UDO_WRONG_NUM_OF_INPUTS = 104, UDO_WRONG_NUM_OF_INPUTS = 104, /// Wrong number of output tensors in UDO definition - SNPE_UDO_WRONG_NUM_OF_OUTPUTS = 105, - SNPE_UDO_PROGRAM_CACHE_NOT_FOUND = 106, - SNPE_UDO_UNKNOWN_ERROR = 0xFFFFFFFF + SNPE_UDO_WRONG_NUM_OF_OUTPUTS = 105, UDO_WRONG_NUM_OF_OUTPUTS = 105, + SNPE_UDO_PROGRAM_CACHE_NOT_FOUND = 106, UDO_PROGRAM_CACHE_NOT_FOUND = 106, + SNPE_UDO_UNKNOWN_ERROR = 0xFFFFFFFF, UDO_UNKNOWN_ERROR = 0xFFFFFFFF } SnpeUdo_ErrorType_t; +typedef SnpeUdo_ErrorType_t Udo_ErrorType_t; + /** * An enum which holds the various data types. * Designed to be used as single values or combined into a bitfield parameter @@ -77,32 +81,34 @@ typedef enum typedef enum { /// data type: 16-bit floating point - SNPE_UDO_DATATYPE_FLOAT_16 = 0x01, + SNPE_UDO_DATATYPE_FLOAT_16 = 0x01, UDO_DATATYPE_FLOAT_16 = 0x01, /// data type: 32-bit floating point - SNPE_UDO_DATATYPE_FLOAT_32 = 0x02, + SNPE_UDO_DATATYPE_FLOAT_32 = 0x02, UDO_DATATYPE_FLOAT_32 = 0x02, /// data type: 4-bit fixed point - SNPE_UDO_DATATYPE_FIXED_4 = 0x04, + SNPE_UDO_DATATYPE_FIXED_4 = 0x04, UDO_DATATYPE_FIXED_4 = 0x04, /// data type: 8-bit fixed point - SNPE_UDO_DATATYPE_FIXED_8 = 0x08, + SNPE_UDO_DATATYPE_FIXED_8 = 0x08, UDO_DATATYPE_FIXED_8 = 0x08, /// data type: 16-bit fixed point - SNPE_UDO_DATATYPE_FIXED_16 = 0x10, + SNPE_UDO_DATATYPE_FIXED_16 = 0x10, UDO_DATATYPE_FIXED_16 = 0x10, /// data type: 32-bit fixed point - SNPE_UDO_DATATYPE_FIXED_32 = 0x20, + SNPE_UDO_DATATYPE_FIXED_32 = 0x20, UDO_DATATYPE_FIXED_32 = 0x20, /// data type: 8-bit unsigned integer - SNPE_UDO_DATATYPE_UINT_8 = 0x100, + SNPE_UDO_DATATYPE_UINT_8 = 0x100, UDO_DATATYPE_UINT_8 = 0x100, /// data type: 16-bit unsigned integer - SNPE_UDO_DATATYPE_UINT_16 = 0x200, + SNPE_UDO_DATATYPE_UINT_16 = 0x200, UDO_DATATYPE_UINT_16 = 0x200, /// data type: 32-bit unsigned integer - SNPE_UDO_DATATYPE_UINT_32 = 0x400, + SNPE_UDO_DATATYPE_UINT_32 = 0x400, UDO_DATATYPE_UINT_32 = 0x400, /// data type: 8-bit signed integer - SNPE_UDO_DATATYPE_INT_8 = 0x1000, + SNPE_UDO_DATATYPE_INT_8 = 0x1000, UDO_DATATYPE_INT_8 = 0x1000, /// data type: 16-bit signed integer - SNPE_UDO_DATATYPE_INT_16 = 0x2000, + SNPE_UDO_DATATYPE_INT_16 = 0x2000, UDO_DATATYPE_INT_16 = 0x2000, /// data type: 32-bit signed integer - SNPE_UDO_DATATYPE_INT_32 = 0x4000, - SNPE_UDO_DATATYPE_LAST = 0xFFFFFFFF + SNPE_UDO_DATATYPE_INT_32 = 0x4000, UDO_DATATYPE_INT_32 = 0x4000, + SNPE_UDO_DATATYPE_LAST = 0xFFFFFFFF, UDO_DATATYPE_LAST = 0xFFFFFFFF } SnpeUdo_DataType_t; +typedef SnpeUdo_DataType_t Udo_DataType_t; + /** * An enum which holds the various layouts. * Designed to be used as single values or combined into a bitfield parameter @@ -111,21 +117,23 @@ typedef enum typedef enum { /// data layout (4D): NHWC (batch-height-width-channel) - SNPE_UDO_LAYOUT_NHWC = 0x01, + SNPE_UDO_LAYOUT_NHWC = 0x01, UDO_LAYOUT_NHWC = 0x01, /// data layout (4D): NCHW (batch-channel-height-width) - SNPE_UDO_LAYOUT_NCHW = 0x02, + SNPE_UDO_LAYOUT_NCHW = 0x02, UDO_LAYOUT_NCHW = 0x02, /// data layout (5D): NDHWC (batch-dimension-height-width-channel) - SNPE_UDO_LAYOUT_NDHWC = 0x04, - SNPE_UDO_LAYOUT_GPU_OPTIMAL1 = 0x08, - SNPE_UDO_LAYOUT_GPU_OPTIMAL2 = 0x10, - SNPE_UDO_LAYOUT_DSP_OPTIMAL1 = 0x11, - SNPE_UDO_LAYOUT_DSP_OPTIMAL2 = 0x12, + SNPE_UDO_LAYOUT_NDHWC = 0x04, UDO_LAYOUT_NDHWC = 0x04, + SNPE_UDO_LAYOUT_GPU_OPTIMAL1 = 0x08, UDO_LAYOUT_GPU_OPTIMAL1 = 0x08, + SNPE_UDO_LAYOUT_GPU_OPTIMAL2 = 0x10, UDO_LAYOUT_GPU_OPTIMAL2 = 0x10, + SNPE_UDO_LAYOUT_DSP_OPTIMAL1 = 0x11, UDO_LAYOUT_DSP_OPTIMAL1 = 0x11, + SNPE_UDO_LAYOUT_DSP_OPTIMAL2 = 0x12, UDO_LAYOUT_DSP_OPTIMAL2 = 0x12, // Indicates no data will be allocated for this tensor. // Used to specify optional inputs/outputs positionally. - SNPE_UDO_LAYOUT_NULL = 0x13, - SNPE_UDO_LAYOUT_LAST = 0xFFFFFFFF + SNPE_UDO_LAYOUT_NULL = 0x13, UDO_LAYOUT_NULL = 0x13, + SNPE_UDO_LAYOUT_LAST = 0xFFFFFFFF, UDO_LAYOUT_LAST = 0xFFFFFFFF } SnpeUdo_TensorLayout_t; +typedef SnpeUdo_TensorLayout_t Udo_TensorLayout_t; + /** * An enum which holds the UDO library Core type . * Designed to be used as single values or combined into a bitfield parameter @@ -134,43 +142,49 @@ typedef enum typedef enum { /// Library target IP Core is undefined - SNPE_UDO_CORETYPE_UNDEFINED = 0x00, + SNPE_UDO_CORETYPE_UNDEFINED = 0x00, UDO_CORETYPE_UNDEFINED = 0x00, /// Library target IP Core is CPU - SNPE_UDO_CORETYPE_CPU = 0x01, + SNPE_UDO_CORETYPE_CPU = 0x01, UDO_CORETYPE_CPU = 0x01, /// Library target IP Core is GPU - SNPE_UDO_CORETYPE_GPU = 0x02, + SNPE_UDO_CORETYPE_GPU = 0x02, UDO_CORETYPE_GPU = 0x02, /// Library target IP Core is DSP - SNPE_UDO_CORETYPE_DSP = 0x04, - SNPE_UDO_CORETYPE_LAST = 0xFFFFFFFF + SNPE_UDO_CORETYPE_DSP = 0x04, UDO_CORETYPE_DSP = 0x04, + SNPE_UDO_CORETYPE_LAST = 0xFFFFFFFF, UDO_CORETYPE_LAST = 0xFFFFFFFF } SnpeUdo_CoreType_t; +typedef SnpeUdo_CoreType_t Udo_CoreType_t; + /** * An enum to specify the parameter type : Scalar or Tensor */ typedef enum { /// UDO static param type: scalar - SNPE_UDO_PARAMTYPE_SCALAR, + SNPE_UDO_PARAMTYPE_SCALAR = 0x00, UDO_PARAMTYPE_SCALAR = 0x00, /// UDO static param type: string - SNPE_UDO_PARAMTYPE_STRING, + SNPE_UDO_PARAMTYPE_STRING = 0x01, UDO_PARAMTYPE_STRING = 0x01, /// UDO static param type: tensor - SNPE_UDO_PARAMTYPE_TENSOR, - SNPE_UDO_PARAMTYPE_LAST = 0xFFFFFFFF + SNPE_UDO_PARAMTYPE_TENSOR = 0x02, UDO_PARAMTYPE_TENSOR = 0x02, + SNPE_UDO_PARAMTYPE_LAST = 0xFFFFFFFF, UDO_PARAMTYPE_LAST = 0xFFFFFFFF } SnpeUdo_ParamType_t; +typedef SnpeUdo_ParamType_t Udo_ParamType_t; + /** * An enum to specify quantization type */ typedef enum { /// Tensor Quantization type: NONE. Signifies unquantized tensor data - SNPE_UDO_QUANTIZATION_NONE, + SNPE_UDO_QUANTIZATION_NONE = 0x00, UDO_QUANTIZATION_NONE = 0x00, /// Tensor Quantization type: Tensorflow-style - SNPE_UDO_QUANTIZATION_TF, - SNPE_UDO_QUANTIZATION_QMN, - SNPE_UDO_QUANTIZATION_LAST = 0xFFFFFFFF + SNPE_UDO_QUANTIZATION_TF = 0x01, UDO_QUANTIZATION_TF = 0x01, + SNPE_UDO_QUANTIZATION_QMN = 0x02, UDO_QUANTIZATION_QMN = 0x02, + SNPE_UDO_QUANTIZATION_LAST = 0xFFFFFFFF, UDO_QUANTIZATION_LAST = 0xFFFFFFFF } SnpeUdo_QuantizationType_t; +typedef SnpeUdo_QuantizationType_t Udo_QuantizationType_t; + /** * @brief A struct which is used to provide a version number using 3 values : major, minor, teeny * @@ -185,6 +199,8 @@ typedef struct uint32_t teeny; } SnpeUdo_Version_t; +typedef SnpeUdo_Version_t Udo_Version_t; + /** * @brief A struct returned from version query, contains the Library version and API version * @@ -197,6 +213,16 @@ typedef struct SnpeUdo_Version_t apiVersion; } SnpeUdo_LibVersion_t; +/** + * @brief A struct returned from version query, contains the package version + * + */ +typedef struct +{ + /// Version of UDO API used in package. + Udo_Version_t apiVersion; +} Udo_PkgVersion_t; + /** * @brief A union to hold the value of a generic type. Allows defining a parameter struct * in a generic way, with a "value" location that holds the data regardless of the type. @@ -220,6 +246,8 @@ typedef union int8_t int8Value; } SnpeUdo_Value_t; +typedef SnpeUdo_Value_t Udo_Value_t; + /** * @brief A struct which defines a scalar parameter : name, data type, and union of values * @@ -232,6 +260,8 @@ typedef struct SnpeUdo_Value_t dataValue; } SnpeUdo_ScalarParam_t; +typedef SnpeUdo_ScalarParam_t Udo_ScalarParam_t; + /** * @brief A struct which defines the quantization parameters in case of Tensorflow style quantization * @@ -244,6 +274,8 @@ typedef struct float maxValue; } SnpeUdo_TFQuantize_t; +typedef SnpeUdo_TFQuantize_t Udo_TFQuantize_t; + /** * @brief A struct which defines the quantization type, and union of supported quantization structs * @@ -259,6 +291,8 @@ typedef struct }; } SnpeUdo_QuantizeParams_t; +typedef SnpeUdo_QuantizeParams_t Udo_QuantizeParams_t; + /** * @brief A struct which defines the datatype associated with a specified core-type * This should be used to denote the datatypes for a single tensor info, depending @@ -273,6 +307,8 @@ typedef struct SnpeUdo_DataType_t dataType; } SnpeUdo_PerCoreDatatype_t; +typedef SnpeUdo_PerCoreDatatype_t Udo_PerCoreDatatype_t; + /** * @brief A struct which defines a tensor parameter : name, data type, layout, quantization, more. * Also holds a pointer to the tensor data. @@ -303,6 +339,8 @@ typedef struct void* tensorData; } SnpeUdo_TensorParam_t; +typedef SnpeUdo_TensorParam_t Udo_TensorParam_t; + /** * @brief A struct which defines tensor information for activation tensors only * @@ -321,9 +359,11 @@ typedef struct SnpeUdo_PerCoreDatatype_t* perCoreDatatype; /// A boolean field indicating that this tensorinfo will be repeated e.x for ops such as Concat or Split bool repeated; - + /// A boolean field indicating whether input is static or not. + bool isStatic; } SnpeUdo_TensorInfo_t; +typedef SnpeUdo_TensorInfo_t Udo_TensorInfo_t; /** * @brief struct which defines a UDO parameter - a union of scalar, tensor and string parameters @@ -346,6 +386,8 @@ typedef struct }; } SnpeUdo_Param_t; +typedef SnpeUdo_Param_t Udo_Param_t; + /** * @brief A struct which defines Operation information which is specific for IP core (CPU, GPU, DSP ...) * @@ -359,6 +401,8 @@ typedef struct SnpeUdo_Bitmask_t operationCalculationTypes; } SnpeUdo_OpCoreInfo_t; +typedef SnpeUdo_OpCoreInfo_t Udo_OpCoreInfo_t; + /** * @brief A struct which defines the common and core-specific Operation information * @@ -392,6 +436,8 @@ typedef struct SnpeUdo_TensorInfo_t* outputInfos; } SnpeUdo_OperationInfo_t; +typedef SnpeUdo_OperationInfo_t Udo_OperationInfo_t; + /** * @brief A struct which provides the implementation library info : type, name * @@ -404,6 +450,8 @@ typedef struct SnpeUdo_String_t libraryName; } SnpeUdo_LibraryInfo_t; +typedef SnpeUdo_LibraryInfo_t Udo_LibraryInfo_t; + /** * @brief A struct returned by the registration library and contains information on the UDO package : * name, operations, libraries, etc. @@ -429,6 +477,8 @@ typedef struct SnpeUdo_OperationInfo_t* operationsInfo; } SnpeUdo_RegInfo_t; +typedef SnpeUdo_RegInfo_t Udo_RegInfo_t; + /** * @brief A struct returned by the implementation library and contains information on the * specific library: name, IP Core, operations, etc. @@ -446,6 +496,8 @@ typedef struct uint32_t numOfOperations; } SnpeUdo_ImpInfo_t; +typedef SnpeUdo_ImpInfo_t Udo_ImpInfo_t; + /** * @brief This struct defines an operation. It is used for validation * or creation of an operation. @@ -478,6 +530,8 @@ typedef struct SnpeUdo_TensorParam_t* outputs; } SnpeUdo_OpDefinition_t; +typedef SnpeUdo_OpDefinition_t Udo_OpDefinition_t; + /** @} */ /* end_addtogroup c_plus_plus_apis C++ */ #endif //SNPE_UDO_BASE_H diff --git a/third_party/snpe/include/SnpeUdo/UdoImpl.h b/third_party/snpe/include/SnpeUdo/UdoImpl.h index bd29bc251d..a0cb648cf7 100644 --- a/third_party/snpe/include/SnpeUdo/UdoImpl.h +++ b/third_party/snpe/include/SnpeUdo/UdoImpl.h @@ -1,6 +1,6 @@ //============================================================================== // -// Copyright (c) 2019-2020 Qualcomm Technologies, Inc. +// Copyright (c) 2019-2021 Qualcomm Technologies, Inc. // All Rights Reserved. // Confidential and Proprietary - Qualcomm Technologies, Inc. // @@ -24,6 +24,9 @@ extern "C" typedef struct _SnpeUdo_OpFactory_t* SnpeUdo_OpFactory_t; typedef struct _SnpeUdo_Operation_t* SnpeUdo_Operation_t; +typedef SnpeUdo_OpFactory_t Udo_OpFactory_t; +typedef SnpeUdo_Operation_t Udo_Operation_t; + /** * @brief Initialize the shared library's data structures. Calling any other * library function before this one will result in error. @@ -92,6 +95,8 @@ SnpeUdo_getImpInfo(SnpeUdo_ImpInfo_t** implementationInfo); typedef SnpeUdo_ErrorType_t (*SnpeUdo_GetImpInfoFunction_t)(SnpeUdo_ImpInfo_t** implementationInfo); +typedef SnpeUdo_GetImpInfoFunction_t Udo_GetImpInfoFunction_t; + /** * @brief A function to create an operation factory. * The function receives the operation type, and an array of static parameters, @@ -130,6 +135,7 @@ typedef SnpeUdo_ErrorType_t SnpeUdo_Param_t*, SnpeUdo_OpFactory_t*); +typedef SnpeUdo_CreateOpFactoryFunction_t Udo_CreateOpFactoryFunction_t; /** * @brief A function to release the resources allocated for an operation factory @@ -145,6 +151,8 @@ SnpeUdo_releaseOpFactory(SnpeUdo_OpFactory_t opFactory); typedef SnpeUdo_ErrorType_t (*SnpeUdo_ReleaseOpFactoryFunction_t)(SnpeUdo_OpFactory_t); +typedef SnpeUdo_ReleaseOpFactoryFunction_t Udo_ReleaseOpFactoryFunction_t; + /** * @brief A function to create an operation from the factory. * The function receives array of inputs and array of outputs, and creates an operation @@ -188,6 +196,8 @@ typedef SnpeUdo_ErrorType_t SnpeUdo_TensorParam_t*, SnpeUdo_Operation_t*); +typedef SnpeUdo_CreateOperationFunction_t Udo_CreateOperationFunction_t; + /** * @brief A pointer to notification function. * @@ -206,6 +216,8 @@ typedef SnpeUdo_ErrorType_t typedef SnpeUdo_ErrorType_t (*SnpeUdo_ExternalNotify_t)(const uint32_t ID); +typedef SnpeUdo_ExternalNotify_t Udo_ExternalNotify_t; + /** * @brief Operation execution function. * @@ -245,6 +257,8 @@ typedef SnpeUdo_ErrorType_t const uint32_t, SnpeUdo_ExternalNotify_t); +typedef SnpeUdo_ExecuteOpFunction_t Udo_ExecuteOpFunction_t; + /** * @brief A function to setting the inputs & outputs. part of SnpeUdo_Operation struct, * returned from creation of a new operation instance. @@ -277,6 +291,8 @@ typedef SnpeUdo_ErrorType_t SnpeUdo_TensorParam_t*, SnpeUdo_TensorParam_t*); +typedef SnpeUdo_SetOpIOFunction_t Udo_SetOpIOFunction_t; + /** * @brief A function to return execution times. * @@ -297,6 +313,8 @@ SnpeUdo_profileOp(SnpeUdo_Operation_t operation, uint32_t *executionTime); typedef SnpeUdo_ErrorType_t (*SnpeUdo_ProfileOpFunction_t)(SnpeUdo_Operation_t, uint32_t*); +typedef SnpeUdo_ProfileOpFunction_t Udo_ProfileOpFunction_t; + /** * @brief A function to release the operation instance * \n When it is called, the implementation library needs to release all resources @@ -314,6 +332,8 @@ SnpeUdo_releaseOp(SnpeUdo_Operation_t operation); typedef SnpeUdo_ErrorType_t (*SnpeUdo_ReleaseOpFunction_t)(SnpeUdo_Operation_t); +typedef SnpeUdo_ReleaseOpFunction_t Udo_ReleaseOpFunction_t; + /** @} */ /* end_addtogroup c_plus_plus_apis C++ */ #ifdef __cplusplus diff --git a/third_party/snpe/include/SnpeUdo/UdoImplDsp.h b/third_party/snpe/include/SnpeUdo/UdoImplDsp.h index 7e85bf15d8..b97a649320 100644 --- a/third_party/snpe/include/SnpeUdo/UdoImplDsp.h +++ b/third_party/snpe/include/SnpeUdo/UdoImplDsp.h @@ -1,6 +1,6 @@ //============================================================================== // -// Copyright (c) 2019-2020 Qualcomm Technologies, Inc. +// Copyright (c) 2019-2021 Qualcomm Technologies, Inc. // All Rights Reserved. // Confidential and Proprietary - Qualcomm Technologies, Inc. // @@ -45,13 +45,16 @@ typedef SnpeUdo_ErrorType_t (*SnpeUdo_ValidateOperationFunction_t) (SnpeUdo_Stri uint32_t, const SnpeUdo_Param_t*); +typedef SnpeUdo_ValidateOperationFunction_t Udo_ValidateOperationFunction_t; // enum used for indicating input/outout tensor data layouts on DSP, plain vs d32 typedef enum { - SNPE_UDO_DSP_TENSOR_LAYOUT_PLAIN, - SNPE_UDO_DSP_TENSOR_LAYOUT_D32 + SNPE_UDO_DSP_TENSOR_LAYOUT_PLAIN = 0x00, UDO_DSP_TENSOR_LAYOUT_PLAIN = 0x00, + SNPE_UDO_DSP_TENSOR_LAYOUT_D32 = 0x01, UDO_DSP_TENSOR_LAYOUT_D32 = 0x01 } SnpeUdo_HexNNTensorLayout_t; +typedef SnpeUdo_HexNNTensorLayout_t Udo_HexNNTensorLayout_t; + /** * @brief A function to query numbers of inputs and outputs, * quantization type of each input and each output as arrays, @@ -96,7 +99,7 @@ typedef SnpeUdo_ErrorType_t (*SnpeUdo_QueryOperationFunction_t) (SnpeUdo_String_ SnpeUdo_QuantizationType_t**, SnpeUdo_HexNNTensorLayout_t**); - +typedef SnpeUdo_QueryOperationFunction_t Udo_QueryOperationFunction_t; // Global infrastructure functions supported by Hexagon-NN v2 typedef void (*workerThread_t) (void* perOpInfrastructure, void* userData); @@ -134,12 +137,25 @@ typedef struct hexNNv2GlobalInfra { udoRunWorkerThreads_t udoRunWorkerThreads; } SnpeUdo_HexNNv2GlobalInfra_t; +typedef SnpeUdo_HexNNv2GlobalInfra_t Udo_HexNNv2GlobalInfra_t; + // hexnn types typedef enum hexnnInfraType { UDO_INFRA_HEXNN_V2, UDO_INFRA_HEXNN_V3 // reserved, do not use } SnpeUdo_HexNNInfraType_t; +typedef SnpeUdo_HexNNInfraType_t Udo_HexNNInfraType_t; + +typedef struct { + Udo_CreateOpFactoryFunction_t create_op_factory; + Udo_CreateOperationFunction_t create_operation; + Udo_ExecuteOpFunction_t execute_op; + Udo_ReleaseOpFunction_t release_op; + Udo_ReleaseOpFactoryFunction_t release_op_factory; + Udo_ValidateOperationFunction_t validate_op; + Udo_QueryOperationFunction_t query_op; +} udo_func_package_t; /** * @brief Infrastructures needed by a developer of DSP Hexnn UDO Implementation library. @@ -156,6 +172,7 @@ typedef struct dspGlobalInfrastructure { SnpeUdo_HexNNv2GlobalInfra_t hexNNv2Infra; } SnpeUdo_DspGlobalInfrastructure_t; +typedef SnpeUdo_DspGlobalInfrastructure_t Udo_DspGlobalInfrastructure_t; /** * hexnn v2 per op factory infrastructure @@ -169,6 +186,7 @@ typedef struct hexnnv2OpFactoryInfra { unsigned long graphId; } SnpeUdo_HexNNv2OpFactoryInfra_t; +typedef SnpeUdo_HexNNv2OpFactoryInfra_t Udo_HexNNv2OpFactoryInfra_t; /** * hexnn v2 per operation infrastructure @@ -182,6 +200,8 @@ typedef struct hexnnv2OpFactoryInfra { */ typedef void* SnpeUdo_HexNNv2OpInfra_t; +typedef SnpeUdo_HexNNv2OpInfra_t Udo_HexNNv2OpInfra_t; + /** @} */ /* end_addtogroup c_plus_plus_apis C++ */ #endif // SNPE_UDO_IMPL_DSP_H diff --git a/third_party/snpe/include/SnpeUdo/UdoShared.h b/third_party/snpe/include/SnpeUdo/UdoShared.h index 6fd50c318a..418d9db9e2 100644 --- a/third_party/snpe/include/SnpeUdo/UdoShared.h +++ b/third_party/snpe/include/SnpeUdo/UdoShared.h @@ -1,6 +1,6 @@ //============================================================================== // -// Copyright (c) 2019-2020 Qualcomm Technologies, Inc. +// Copyright (c) 2019-2021 Qualcomm Technologies, Inc. // All Rights Reserved. // Confidential and Proprietary - Qualcomm Technologies, Inc. // @@ -37,6 +37,8 @@ SnpeUdo_getVersion (SnpeUdo_LibVersion_t** version); typedef SnpeUdo_ErrorType_t (*SnpeUdo_GetVersionFunction_t) (SnpeUdo_LibVersion_t** version); +typedef SnpeUdo_GetVersionFunction_t Udo_GetVersionFunction_t; + #ifdef __cplusplus } // extern "C" #endif diff --git a/third_party/snpe/larch64 b/third_party/snpe/larch64 index e5c222b1c9..2e2a1c315b 120000 --- a/third_party/snpe/larch64 +++ b/third_party/snpe/larch64 @@ -1 +1 @@ -aarch64-linux-gcc4.9 \ No newline at end of file +aarch64-ubuntu-gcc7.5 \ No newline at end of file diff --git a/third_party/boringssl/lib/libcrypto_static.a b/third_party/snpe/x86_64-linux-clang/libHtpPrepare.so similarity index 56% rename from third_party/boringssl/lib/libcrypto_static.a rename to third_party/snpe/x86_64-linux-clang/libHtpPrepare.so index f683cb11d4..0b0657dd33 100644 Binary files a/third_party/boringssl/lib/libcrypto_static.a and b/third_party/snpe/x86_64-linux-clang/libHtpPrepare.so differ diff --git a/third_party/snpe/x86_64-linux-clang/libSNPE.so b/third_party/snpe/x86_64-linux-clang/libSNPE.so index 4975bff895..0cee9ac3af 100644 Binary files a/third_party/snpe/x86_64-linux-clang/libSNPE.so and b/third_party/snpe/x86_64-linux-clang/libSNPE.so differ diff --git a/third_party/snpe/x86_64-linux-clang/libomp.so b/third_party/snpe/x86_64-linux-clang/libomp.so index 38ab0c03f2..567e6ae594 100755 Binary files a/third_party/snpe/x86_64-linux-clang/libomp.so and b/third_party/snpe/x86_64-linux-clang/libomp.so differ diff --git a/third_party/snpe/x86_64-linux-clang/libsymphony-cpu.so b/third_party/snpe/x86_64-linux-clang/libsymphony-cpu.so deleted file mode 100644 index 03ebe979a5..0000000000 Binary files a/third_party/snpe/x86_64-linux-clang/libsymphony-cpu.so and /dev/null differ diff --git a/third_party/zlib/build.txt b/third_party/zlib/build.txt deleted file mode 100644 index b67f9cd57a..0000000000 --- a/third_party/zlib/build.txt +++ /dev/null @@ -1,5 +0,0 @@ -# with neos tree -cd ~/android/system -mka libz - -cp ~/android/system/out/target/product/oneplus3/obj/STATIC_LIBRARIES/libz_intermediates/libz.a lib/ diff --git a/third_party/zlib/lib/libz.a b/third_party/zlib/lib/libz.a deleted file mode 100644 index d2170d8b87..0000000000 Binary files a/third_party/zlib/lib/libz.a and /dev/null differ diff --git a/tinygrad b/tinygrad new file mode 120000 index 0000000000..cb003823c6 --- /dev/null +++ b/tinygrad @@ -0,0 +1 @@ +tinygrad_repo/tinygrad \ No newline at end of file diff --git a/tinygrad_repo b/tinygrad_repo new file mode 160000 index 0000000000..8e22d5ee67 --- /dev/null +++ b/tinygrad_repo @@ -0,0 +1 @@ +Subproject commit 8e22d5ee675277181e1eff644dde9e844fc40fce diff --git a/tools/CTF.md b/tools/CTF.md index 396e7575a4..a14a41d55d 100644 --- a/tools/CTF.md +++ b/tools/CTF.md @@ -12,7 +12,7 @@ Welcome to the first part of the comma CTF! getting started ```bash # start the route reply -cd selfdrive/ui/replay +cd tools/replay ./replay '0c7f0c7f0c7f0c7f|2021-10-13--13-00-00' --dcam --ecam # start the UI in another terminal diff --git a/tools/README.md b/tools/README.md index a61d9268d2..3969deb24d 100644 --- a/tools/README.md +++ b/tools/README.md @@ -2,17 +2,16 @@ ## System Requirements -openpilot is developed and tested on **Ubuntu 20.04**, which is the primary development target aside from the [supported embdedded hardware](https://github.com/commaai/openpilot#running-on-pc). We also have a CI test to verify that openpilot builds on macOS, but the tools are untested. For the best experience, stick to Ubuntu 20.04, otherwise openpilot and the tools should work with minimal to no modifications on macOS and other Linux systems. +openpilot is developed and tested on **Ubuntu 20.04**, which is the primary development target aside from the [supported embedded hardware](https://github.com/commaai/openpilot#running-on-pc). We also have a CI test to verify that openpilot builds on macOS, but the tools are untested. For the best experience, stick to Ubuntu 20.04, otherwise openpilot and the tools should work with minimal to no modifications on macOS and other Linux systems. ## Setup your PC - First, clone openpilot: ``` bash cd ~ git clone https://github.com/commaai/openpilot.git -cd openpilot +cd openpilot git submodule update --init ``` @@ -26,10 +25,10 @@ tools/ubuntu_setup.sh tools/mac_setup.sh ``` -Activate a shell with the install Python dependencies: +Activate a shell with the Python dependencies installed: ``` bash -cd openpilot && pipenv shell +cd openpilot && poetry shell ``` Build openpilot with this command: @@ -39,11 +38,11 @@ scons -u -j$(nproc) ### Windows -Neither openpilot nor any of the tools are developed or tested on Windows, but the [Windows Subsystem for Linux (WSL)](https://docs.microsoft.com/en-us/windows/wsl/about) should get Windows users a similiar experience to Ubuntu. [WSL 2](https://docs.microsoft.com/en-us/windows/wsl/compare-versions) specifically has been reported by several users to be a seamless experience. +Neither openpilot nor any of the tools are developed or tested on Windows, but the [Windows Subsystem for Linux (WSL)](https://docs.microsoft.com/en-us/windows/wsl/about) should get Windows users a similar experience to Ubuntu. [WSL 2](https://docs.microsoft.com/en-us/windows/wsl/compare-versions) specifically has been reported by several users to be a seamless experience. Follow [these instructions](https://docs.microsoft.com/en-us/windows/wsl/install) to setup the WSL and install the `Ubuntu-20.04` distribution. Once your Ubuntu WSL environment is setup, follow the Linux setup instructions to finish setting up your environment. -GUI applications do not work with WSL out of the box. You will have to either [upgrade your system to Windows 11](https://docs.microsoft.com/en-us/windows/wsl/tutorials/gui-apps) or [set up an Xorg server](https://techcommunity.microsoft.com/t5/windows-dev-appconsult/running-wsl-gui-apps-on-windows-10/ba-p/1493242). +GUI applications do not work with WSL out of the box. You will have to either [upgrade your system to Windows 11](https://docs.microsoft.com/en-us/windows/wsl/tutorials/gui-apps) or [set up an Xorg server](https://techcommunity.microsoft.com/t5/windows-dev-appconsult/running-wsl-gui-apps-on-windows-10/ba-p/1493242). ## CTF diff --git a/tools/cabana/.gitignore b/tools/cabana/.gitignore new file mode 100644 index 0000000000..73879ab05d --- /dev/null +++ b/tools/cabana/.gitignore @@ -0,0 +1,7 @@ +moc_* +*.moc + +_cabana +settings +car_fingerprint_to_dbc.json +tests/_test_cabana diff --git a/tools/cabana/README.md b/tools/cabana/README.md new file mode 100644 index 0000000000..dd131880a6 --- /dev/null +++ b/tools/cabana/README.md @@ -0,0 +1,24 @@ +# Cabana + + + +Cabana is a tool developed to view raw CAN data. One use for this is creating and editing [CAN Dictionaries](http://socialledge.com/sjsu/index.php/DBC_Format) (DBC files), and the tool provides direct integration with [commaai/opendbc](https://github.com/commaai/opendbc) (a collection of DBC files), allowing you to load the DBC files direct from source, and save to your fork. In addition, you can load routes from [comma connect](https://connect.comma.ai). + +## Usage Instructions + +```bash +$ ./cabana -h +Usage: ./cabana [options] route + +Options: + -h, --help Displays this help. + --demo use a demo route instead of providing your own + --qcam load qcamera + --data_dir local directory with routes + +Arguments: + route the drive to replay. find your drives at + connect.comma.ai +``` + +See [openpilot wiki](https://github.com/commaai/openpilot/wiki/Cabana) diff --git a/tools/cabana/SConscript b/tools/cabana/SConscript new file mode 100644 index 0000000000..52fe9e346d --- /dev/null +++ b/tools/cabana/SConscript @@ -0,0 +1,29 @@ +import os +Import('env', 'qt_env', 'arch', 'common', 'messaging', 'visionipc', 'replay_lib', + 'cereal', 'transformations', 'widgets', 'opendbc') + +base_frameworks = qt_env['FRAMEWORKS'] +base_libs = [common, messaging, cereal, visionipc, transformations, 'zmq', + 'capnp', 'kj', 'm', 'ssl', 'crypto', 'pthread'] + qt_env["LIBS"] + +if arch == "Darwin": + base_frameworks.append('OpenCL') +else: + base_libs.append('OpenCL') + +qt_libs = ['qt_util', 'Qt5Charts'] + base_libs +cabana_libs = [widgets, cereal, messaging, visionipc, replay_lib, opendbc,'avutil', 'avcodec', 'avformat', 'bz2', 'curl', 'yuv'] + qt_libs +cabana_env = qt_env.Clone() + +prev_moc_path = cabana_env['QT_MOCHPREFIX'] +cabana_env['QT_MOCHPREFIX'] = os.path.dirname(prev_moc_path) + '/cabana/moc_' +cabana_lib = cabana_env.Library("cabana_lib", ['mainwin.cc', 'binaryview.cc', 'chartswidget.cc', 'historylog.cc', 'videowidget.cc', 'signaledit.cc', 'dbcmanager.cc', + 'canmessages.cc', 'commands.cc', 'messageswidget.cc', 'settings.cc', 'detailwidget.cc'], LIBS=cabana_libs, FRAMEWORKS=base_frameworks) +cabana_env.Program('_cabana', ['cabana.cc', cabana_lib], LIBS=cabana_libs, FRAMEWORKS=base_frameworks) + +if GetOption('test'): + cabana_env.Program('tests/_test_cabana', ['tests/test_runner.cc', 'tests/test_cabana.cc', cabana_lib], LIBS=[cabana_libs]) + +def generate_dbc_json(target, source, env): + env.Execute('tools/cabana/generate_dbc_json.py --out tools/cabana/car_fingerprint_to_dbc.json') +cabana_env.Command('generate_dbc_json', [], generate_dbc_json) diff --git a/tools/cabana/binaryview.cc b/tools/cabana/binaryview.cc new file mode 100644 index 0000000000..bc64edbfeb --- /dev/null +++ b/tools/cabana/binaryview.cc @@ -0,0 +1,263 @@ +#include "tools/cabana/binaryview.h" + +#include +#include +#include +#include +#include + +#include "tools/cabana/canmessages.h" + +// BinaryView + +const int CELL_HEIGHT = 26; + +inline int get_bit_index(const QModelIndex &index, bool little_endian) { + return index.row() * 8 + (little_endian ? 7 - index.column() : index.column()); +} + +BinaryView::BinaryView(QWidget *parent) : QTableView(parent) { + model = new BinaryViewModel(this); + setModel(model); + delegate = new BinaryItemDelegate(this); + setItemDelegate(delegate); + horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); + verticalHeader()->setSectionsClickable(false); + verticalHeader()->setSectionResizeMode(QHeaderView::Fixed); + horizontalHeader()->hide(); + setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents); + setFrameShape(QFrame::NoFrame); + setShowGrid(false); + setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum); + setMouseTracking(true); +} + +void BinaryView::highlight(const Signal *sig) { + if (sig != hovered_sig) { + hovered_sig = sig; + model->dataChanged(model->index(0, 0), model->index(model->rowCount() - 1, model->columnCount() - 1)); + emit signalHovered(hovered_sig); + } +} + +void BinaryView::setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags flags) { + auto index = indexAt(viewport()->mapFromGlobal(QCursor::pos())); + if (!anchor_index.isValid() || !index.isValid()) + return; + + QItemSelection selection; + auto [start, size, is_lb] = getSelection(index); + for (int i = start; i < start + size; ++i) { + auto idx = model->bitIndex(i, is_lb); + selection.merge({idx, idx}, flags); + } + selectionModel()->select(selection, flags); +} + +void BinaryView::mousePressEvent(QMouseEvent *event) { + delegate->setSelectionColor(style()->standardPalette().color(QPalette::Active, QPalette::Highlight)); + if (auto index = indexAt(event->pos()); index.isValid() && index.column() != 8) { + anchor_index = index; + auto item = (const BinaryViewModel::Item *)anchor_index.internalPointer(); + int bit_idx = get_bit_index(anchor_index, true); + for (auto s : item->sigs) { + if (bit_idx == s->lsb || bit_idx == s->msb) { + anchor_index = model->bitIndex(bit_idx == s->lsb ? s->msb : s->lsb, true); + resize_sig = s; + delegate->setSelectionColor(item->bg_color); + break; + } + } + } + event->accept(); +} + +void BinaryView::highlightPosition(const QPoint &pos) { + if (auto index = indexAt(viewport()->mapFromGlobal(pos)); index.isValid()) { + auto item = (BinaryViewModel::Item *)index.internalPointer(); + const Signal *sig = item->sigs.isEmpty() ? nullptr : item->sigs.back(); + highlight(sig); + sig ? QToolTip::showText(pos, sig->name.c_str(), this, rect()) + : QToolTip::hideText(); + } +} + +void BinaryView::mouseMoveEvent(QMouseEvent *event) { + highlightPosition(event->globalPos()); + QTableView::mouseMoveEvent(event); +} + +void BinaryView::mouseReleaseEvent(QMouseEvent *event) { + QTableView::mouseReleaseEvent(event); + + auto release_index = indexAt(event->pos()); + if (release_index.isValid() && anchor_index.isValid()) { + if (selectionModel()->hasSelection()) { + auto [start_bit, size, is_lb] = getSelection(release_index); + resize_sig ? emit resizeSignal(resize_sig, start_bit, size) + : emit addSignal(start_bit, size, is_lb); + } else { + auto item = (const BinaryViewModel::Item *)anchor_index.internalPointer(); + if (item && item->sigs.size() > 0) + emit signalClicked(item->sigs.back()); + } + } + clearSelection(); + anchor_index = QModelIndex(); + resize_sig = nullptr; +} + +void BinaryView::leaveEvent(QEvent *event) { + highlight(nullptr); + QTableView::leaveEvent(event); +} + +void BinaryView::setMessage(const QString &message_id) { + model->setMessage(message_id); + clearSelection(); + anchor_index = QModelIndex(); + resize_sig = nullptr; + hovered_sig = nullptr; + highlightPosition(QCursor::pos()); + updateState(); +} + +QSet BinaryView::getOverlappingSignals() const { + QSet overlapping; + for (auto &item : model->items) { + if (item.sigs.size() > 1) + for (auto s : item.sigs) overlapping += s; + } + return overlapping; +} + +std::tuple BinaryView::getSelection(QModelIndex index) { + if (index.column() == 8) { + index = model->index(index.row(), 7); + } + bool is_lb = (resize_sig && resize_sig->is_little_endian) || (!resize_sig && index < anchor_index); + int cur_bit_idx = get_bit_index(index, is_lb); + int anchor_bit_idx = get_bit_index(anchor_index, is_lb); + auto [start_bit, end_bit] = std::minmax(cur_bit_idx, anchor_bit_idx); + return {start_bit, end_bit - start_bit + 1, is_lb}; +} + +// BinaryViewModel + +void BinaryViewModel::setMessage(const QString &message_id) { + beginResetModel(); + msg_id = message_id; + items.clear(); + if ((dbc_msg = dbc()->msg(msg_id))) { + row_count = dbc_msg->size; + items.resize(row_count * column_count); + int i = 0; + for (auto sig : dbc_msg->getSignals()) { + auto [start, end] = getSignalRange(sig); + for (int j = start; j <= end; ++j) { + int bit_index = sig->is_little_endian ? bigEndianBitIndex(j) : j; + int idx = column_count * (bit_index / 8) + bit_index % 8; + if (idx >= items.size()) { + qWarning() << "signal " << sig->name.c_str() << "out of bounds.start_bit:" << sig->start_bit << "size:" << sig->size; + break; + } + if (j == start) sig->is_little_endian ? items[idx].is_lsb = true : items[idx].is_msb = true; + if (j == end) sig->is_little_endian ? items[idx].is_msb = true : items[idx].is_lsb = true; + items[idx].bg_color = getColor(i); + items[idx].sigs.push_back(sig); + } + ++i; + } + } else { + row_count = can->lastMessage(msg_id).dat.size(); + items.resize(row_count * column_count); + } + endResetModel(); +} + +void BinaryViewModel::updateState() { + auto prev_items = items; + const auto &binary = can->lastMessage(msg_id).dat; + // data size may changed. + if (binary.size() > row_count) { + beginInsertRows({}, row_count, binary.size() - 1); + row_count = binary.size(); + items.resize(row_count * column_count); + endInsertRows(); + } + char hex[3] = {'\0'}; + for (int i = 0; i < binary.size(); ++i) { + for (int j = 0; j < column_count - 1; ++j) { + items[i * column_count + j].val = ((binary[i] >> (7 - j)) & 1) != 0 ? '1' : '0'; + } + hex[0] = toHex(binary[i] >> 4); + hex[1] = toHex(binary[i] & 0xf); + items[i * column_count + 8].val = hex; + } + for (int i = binary.size(); i < row_count; ++i) { + for (int j = 0; j < column_count; ++j) { + items[i * column_count + j].val = "-"; + } + } + + for (int i = 0; i < row_count; ++i) { + if (i >= prev_items.size() || prev_items[i].val != items[i].val) { + auto idx = index(i / column_count, i % column_count); + emit dataChanged(idx, idx); + } + } +} + +QVariant BinaryViewModel::headerData(int section, Qt::Orientation orientation, int role) const { + if (orientation == Qt::Vertical) { + switch (role) { + case Qt::DisplayRole: return section; + case Qt::SizeHintRole: return QSize(30, CELL_HEIGHT); + case Qt::TextAlignmentRole: return Qt::AlignCenter; + } + } + return {}; +} + +// BinaryItemDelegate + +BinaryItemDelegate::BinaryItemDelegate(QObject *parent) : QStyledItemDelegate(parent) { + // cache fonts and color + small_font.setPointSize(6); + hex_font = QFontDatabase::systemFont(QFontDatabase::FixedFont); + hex_font.setBold(true); + selection_color = QApplication::style()->standardPalette().color(QPalette::Active, QPalette::Highlight); +} + +QSize BinaryItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { + QSize sz = QStyledItemDelegate::sizeHint(option, index); + return {sz.width(), CELL_HEIGHT}; +} + +void BinaryItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { + auto item = (const BinaryViewModel::Item *)index.internalPointer(); + BinaryView *bin_view = (BinaryView *)parent(); + painter->save(); + + if (index.column() == 8) { + painter->setFont(hex_font); + } else if (option.state & QStyle::State_Selected) { + painter->fillRect(option.rect, selection_color); + painter->setPen(QApplication::style()->standardPalette().color(QPalette::BrightText)); + } else if (!item->sigs.isEmpty() && (!bin_view->selectionModel()->hasSelection() || !item->sigs.contains(bin_view->resize_sig))) { + painter->fillRect(option.rect, item->bg_color); + painter->setPen(item->sigs.contains(bin_view->hovered_sig) + ? QApplication::style()->standardPalette().color(QPalette::BrightText) + : Qt::black); + } + + painter->drawText(option.rect, Qt::AlignCenter, item->val); + if (item->is_msb || item->is_lsb) { + painter->setFont(small_font); + painter->drawText(option.rect, Qt::AlignHCenter | Qt::AlignBottom, item->is_msb ? "MSB" : "LSB"); + } + + painter->restore(); +} diff --git a/tools/cabana/binaryview.h b/tools/cabana/binaryview.h new file mode 100644 index 0000000000..c37b378e44 --- /dev/null +++ b/tools/cabana/binaryview.h @@ -0,0 +1,91 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include "tools/cabana/dbcmanager.h" + +class BinaryItemDelegate : public QStyledItemDelegate { + Q_OBJECT + +public: + BinaryItemDelegate(QObject *parent); + void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; + QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override; + void setSelectionColor(const QColor &color) { selection_color = color; } + +private: + QFont small_font, hex_font; + QColor selection_color; +}; + +class BinaryViewModel : public QAbstractTableModel { + Q_OBJECT + +public: + BinaryViewModel(QObject *parent) : QAbstractTableModel(parent) {} + void setMessage(const QString &message_id); + void updateState(); + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const { return {}; } + int rowCount(const QModelIndex &parent = QModelIndex()) const override { return row_count; } + int columnCount(const QModelIndex &parent = QModelIndex()) const override { return column_count; } + inline QModelIndex bitIndex(int bit, bool is_lb) const { return index(bit / 8, is_lb ? (7 - bit % 8) : bit % 8); } + QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override { + return createIndex(row, column, (void *)&items[row * column_count + column]); + } + Qt::ItemFlags flags(const QModelIndex &index) const override { + return (index.column() == column_count - 1) ? Qt::ItemIsEnabled : Qt::ItemIsEnabled | Qt::ItemIsSelectable; + } + + struct Item { + QColor bg_color = QApplication::style()->standardPalette().color(QPalette::Base); + bool is_msb = false; + bool is_lsb = false; + QString val = "0"; + QList sigs; + }; + std::vector items; + +private: + QString msg_id; + const DBCMsg *dbc_msg; + int row_count = 0; + const int column_count = 9; +}; + +class BinaryView : public QTableView { + Q_OBJECT + +public: + BinaryView(QWidget *parent = nullptr); + void setMessage(const QString &message_id); + void highlight(const Signal *sig); + QSet getOverlappingSignals() const; + inline void updateState() { model->updateState(); } + +signals: + void signalClicked(const Signal *sig); + void signalHovered(const Signal *sig); + void addSignal(int start_bit, int size, bool little_endian); + void resizeSignal(const Signal *sig, int from, int size); + +private: + std::tuple getSelection(QModelIndex index); + void setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags flags) override; + void mousePressEvent(QMouseEvent *event) override; + void mouseMoveEvent(QMouseEvent *event) override; + void mouseReleaseEvent(QMouseEvent *event) override; + void leaveEvent(QEvent *event) override; + void highlightPosition(const QPoint &pt); + + QModelIndex anchor_index; + BinaryViewModel *model; + BinaryItemDelegate *delegate; + const Signal *resize_sig = nullptr; + const Signal *hovered_sig = nullptr; + friend class BinaryItemDelegate; +}; diff --git a/tools/cabana/cabana b/tools/cabana/cabana new file mode 100755 index 0000000000..b29dd66e3d --- /dev/null +++ b/tools/cabana/cabana @@ -0,0 +1,4 @@ +#!/bin/sh +cd "$(dirname "$0")" +export LD_LIBRARY_PATH="../../opendbc/can:$LD_LIBRARY_PATH" +exec ./_cabana "$1" diff --git a/tools/cabana/cabana.cc b/tools/cabana/cabana.cc new file mode 100644 index 0000000000..3e76a3e029 --- /dev/null +++ b/tools/cabana/cabana.cc @@ -0,0 +1,43 @@ +#include +#include +#include +#include + +#include "selfdrive/ui/qt/util.h" +#include "tools/cabana/mainwin.h" + +int main(int argc, char *argv[]) { + initApp(argc, argv); + QApplication app(argc, argv); + + QCommandLineParser cmd_parser; + cmd_parser.addHelpOption(); + cmd_parser.addPositionalArgument("route", "the drive to replay. find your drives at connect.comma.ai"); + cmd_parser.addOption({"demo", "use a demo route instead of providing your own"}); + cmd_parser.addOption({"qcam", "load qcamera"}); + cmd_parser.addOption({"data_dir", "local directory with routes", "data_dir"}); + cmd_parser.process(app); + const QStringList args = cmd_parser.positionalArguments(); + if (args.empty() && !cmd_parser.isSet("demo")) { + cmd_parser.showHelp(); + } + + QString uuid = QUuid::createUuid().toString(QUuid::WithoutBraces); + QString msgq_path = "/dev/shm/" + uuid; + + QDir dir; + dir.mkdir(msgq_path); + setenv("OPENPILOT_PREFIX", qPrintable(uuid), 1); + + int ret = 0; + const QString route = args.empty() ? DEMO_ROUTE : args.first(); + CANMessages p(&app); + if (p.loadRoute(route, cmd_parser.value("data_dir"), cmd_parser.isSet("qcam"))) { + MainWindow w; + w.showMaximized(); + ret = app.exec(); + } + + dir.rmdir(msgq_path); + return ret; +} diff --git a/tools/cabana/canmessages.cc b/tools/cabana/canmessages.cc new file mode 100644 index 0000000000..a8e881c5fe --- /dev/null +++ b/tools/cabana/canmessages.cc @@ -0,0 +1,132 @@ +#include "tools/cabana/canmessages.h" + +#include + +#include "tools/cabana/dbcmanager.h" + +CANMessages *can = nullptr; + +CANMessages::CANMessages(QObject *parent) : QObject(parent) { + can = this; + QObject::connect(this, &CANMessages::received, this, &CANMessages::process, Qt::QueuedConnection); + QObject::connect(&settings, &Settings::changed, this, &CANMessages::settingChanged); +} + +CANMessages::~CANMessages() { + replay->stop(); +} + +static bool event_filter(const Event *e, void *opaque) { + CANMessages *c = (CANMessages *)opaque; + return c->eventFilter(e); +} + +bool CANMessages::loadRoute(const QString &route, const QString &data_dir, bool use_qcam) { + replay = new Replay(route, {"can", "roadEncodeIdx", "carParams"}, {}, nullptr, use_qcam ? REPLAY_FLAG_QCAMERA : 0, data_dir, this); + replay->setSegmentCacheLimit(settings.cached_segment_limit); + replay->installEventFilter(event_filter, this); + QObject::connect(replay, &Replay::segmentsMerged, this, &CANMessages::eventsMerged); + QObject::connect(replay, &Replay::streamStarted, this, &CANMessages::streamStarted); + if (replay->load()) { + replay->start(); + return true; + } + return false; +} + +QList CANMessages::findSignalValues(const QString &id, const Signal *signal, double value, FindFlags flag, int max_count) { + auto evts = events(); + if (!evts) return {}; + + QList ret; + ret.reserve(max_count); + auto [bus, address] = DBCManager::parseId(id); + for (auto &evt : *evts) { + if (evt->which != cereal::Event::Which::CAN) continue; + + for (const auto &c : evt->event.getCan()) { + if (bus == c.getSrc() && address == c.getAddress()) { + double val = get_raw_value((uint8_t *)c.getDat().begin(), c.getDat().size(), *signal); + if ((flag == EQ && val == value) || (flag == LT && val < value) || (flag == GT && val > value)) { + ret.push_back({(evt->mono_time / (double)1e9) - can->routeStartTime(), val}); + if (ret.size() >= max_count) + return ret; + } + } + } + } + return ret; +} + +void CANMessages::process(QHash *messages) { + for (auto it = messages->begin(); it != messages->end(); ++it) { + can_msgs[it.key()] = it.value(); + } + emit updated(); + emit msgsReceived(messages); + delete messages; + processing = false; +} + +bool CANMessages::eventFilter(const Event *event) { + static std::unique_ptr> new_msgs; + static double prev_update_ts = 0; + + if (event->which == cereal::Event::Which::CAN) { + if (!new_msgs) { + new_msgs.reset(new QHash); + new_msgs->reserve(1000); + } + + double current_sec = replay->currentSeconds(); + if (counters_begin_sec == 0 || counters_begin_sec >= current_sec) { + counters.clear(); + counters_begin_sec = current_sec; + } + + auto can_events = event->event.getCan(); + for (const auto &c : can_events) { + QString id = QString("%1:%2").arg(c.getSrc()).arg(c.getAddress(), 1, 16); + + std::lock_guard lk(lock); + auto &list = received_msgs[id]; + while (list.size() > settings.can_msg_log_size) { + list.pop_back(); + } + CanData &data = list.emplace_front(); + data.ts = current_sec; + data.dat.append((char *)c.getDat().begin(), c.getDat().size()); + + data.count = ++counters[id]; + if (double delta = (current_sec - counters_begin_sec); delta > 0) { + data.freq = data.count / delta; + } + (*new_msgs)[id] = data; + } + + double ts = millis_since_boot(); + if ((ts - prev_update_ts) > (1000.0 / settings.fps) && !processing) { + // delay posting CAN message if UI thread is busy + processing = true; + prev_update_ts = ts; + // use pointer to avoid data copy in queued connection. + emit received(new_msgs.release()); + } + } + return true; +} + +const std::deque CANMessages::messages(const QString &id) { + std::lock_guard lk(lock); + return received_msgs[id]; +} + +void CANMessages::seekTo(double ts) { + replay->seekTo(std::max(double(0), ts), false); + counters_begin_sec = 0; + emit updated(); +} + +void CANMessages::settingChanged() { + replay->setSegmentCacheLimit(settings.cached_segment_limit); +} diff --git a/tools/cabana/canmessages.h b/tools/cabana/canmessages.h new file mode 100644 index 0000000000..1713778af7 --- /dev/null +++ b/tools/cabana/canmessages.h @@ -0,0 +1,85 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include + +#include "opendbc/can/common_dbc.h" +#include "tools/cabana/settings.h" +#include "tools/replay/replay.h" + +struct CanData { + double ts = 0.; + uint32_t count = 0; + uint32_t freq = 0; + QByteArray dat; +}; + +class CANMessages : public QObject { + Q_OBJECT + +public: + enum FindFlags{ EQ, LT, GT }; + CANMessages(QObject *parent); + ~CANMessages(); + bool loadRoute(const QString &route, const QString &data_dir, bool use_qcam); + void seekTo(double ts); + QList findSignalValues(const QString&id, const Signal* signal, double value, FindFlags flag, int max_count); + bool eventFilter(const Event *event); + + inline QString routeName() const { return replay->route()->name(); } + inline QString carFingerprint() const { return replay->carFingerprint().c_str(); } + inline double totalSeconds() const { return replay->totalSeconds(); } + inline double routeStartTime() const { return replay->routeStartTime() / (double)1e9; } + inline double currentSec() const { return replay->currentSeconds(); } + const std::deque messages(const QString &id); + inline const CanData &lastMessage(const QString &id) { return can_msgs[id]; } + + inline const Route* route() const { return replay->route(); } + inline const std::vector *events() const { return replay->events(); } + inline void setSpeed(float speed) { replay->setSpeed(speed); } + inline bool isPaused() const { return replay->isPaused(); } + inline void pause(bool pause) { replay->pause(pause); } + inline const std::vector> getTimeline() { return replay->getTimeline(); } + +signals: + void streamStarted(); + void eventsMerged(); + void updated(); + void msgsReceived(const QHash *); + void received(QHash *); + +public: + QMap can_msgs; + +protected: + void process(QHash *); + void settingChanged(); + + Replay *replay = nullptr; + std::mutex lock; + std::atomic counters_begin_sec = 0; + std::atomic processing = false; + QHash counters; + QHash> received_msgs; +}; + +inline QString toHex(const QByteArray &dat) { + return dat.toHex(' ').toUpper(); +} +inline char toHex(uint value) { + return "0123456789ABCDEF"[value & 0xF]; +} + +inline const QString &getColor(int i) { + // TODO: add more colors + static const QString SIGNAL_COLORS[] = {"#9FE2BF", "#40E0D0", "#6495ED", "#CCCCFF", "#FF7F50", "#FFBF00"}; + return SIGNAL_COLORS[i % std::size(SIGNAL_COLORS)]; +} + +// A global pointer referring to the unique CANMessages object +extern CANMessages *can; diff --git a/tools/cabana/chartswidget.cc b/tools/cabana/chartswidget.cc new file mode 100644 index 0000000000..79b40133a5 --- /dev/null +++ b/tools/cabana/chartswidget.cc @@ -0,0 +1,595 @@ +#include "tools/cabana/chartswidget.h" + +#include +#include +#include +#include +#include +#include +#include + +// ChartsWidget + +ChartsWidget::ChartsWidget(QWidget *parent) : QWidget(parent) { + QVBoxLayout *main_layout = new QVBoxLayout(this); + main_layout->setContentsMargins(0, 0, 0, 0); + + // toolbar + QToolBar *toolbar = new QToolBar(tr("Charts"), this); + title_label = new QLabel(); + title_label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); + toolbar->addWidget(title_label); + toolbar->addWidget(range_label = new QLabel()); + reset_zoom_btn = toolbar->addAction("⟲"); + reset_zoom_btn->setToolTip(tr("Reset zoom (drag on chart to zoom X-Axis)")); + remove_all_btn = toolbar->addAction("✖"); + remove_all_btn->setToolTip(tr("Remove all charts")); + dock_btn = toolbar->addAction(""); + main_layout->addWidget(toolbar); + updateToolBar(); + + // charts + QWidget *charts_container = new QWidget(this); + charts_layout = new QVBoxLayout(charts_container); + charts_layout->addStretch(); + + QScrollArea *charts_scroll = new QScrollArea(this); + charts_scroll->setWidgetResizable(true); + charts_scroll->setWidget(charts_container); + charts_scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + + main_layout->addWidget(charts_scroll); + + use_dark_theme = palette().color(QPalette::WindowText).value() > palette().color(QPalette::Background).value(); + + QObject::connect(dbc(), &DBCManager::DBCFileChanged, this, &ChartsWidget::removeAll); + QObject::connect(can, &CANMessages::eventsMerged, this, &ChartsWidget::eventsMerged); + QObject::connect(can, &CANMessages::updated, this, &ChartsWidget::updateState); + QObject::connect(remove_all_btn, &QAction::triggered, this, &ChartsWidget::removeAll); + QObject::connect(reset_zoom_btn, &QAction::triggered, this, &ChartsWidget::zoomReset); + QObject::connect(dock_btn, &QAction::triggered, [this]() { + emit dock(!docking); + docking = !docking; + updateToolBar(); + }); +} + +void ChartsWidget::eventsMerged() { + if (auto events = can->events(); events && !events->empty()) { + event_range.first = (events->front()->mono_time / (double)1e9) - can->routeStartTime(); + event_range.second = (events->back()->mono_time / (double)1e9) - can->routeStartTime(); + updateDisplayRange(); + } +} + +void ChartsWidget::updateDisplayRange() { + auto prev_range = display_range; + double current_sec = can->currentSec(); + if (current_sec < display_range.first || current_sec >= (display_range.second - 5)) { + // reached the end, or seeked to a timestamp out of range. + display_range.first = current_sec - 5; + } + display_range.first = std::max(display_range.first, event_range.first); + display_range.second = std::min(display_range.first + settings.max_chart_x_range, event_range.second); + if (prev_range != display_range) { + QFutureSynchronizer future_synchronizer; + for (auto c : charts) + future_synchronizer.addFuture(QtConcurrent::run(c, &ChartView::setEventsRange, display_range)); + } +} + +void ChartsWidget::zoomIn(double min, double max) { + zoomed_range = {min, max}; + is_zoomed = zoomed_range != display_range; + updateToolBar(); + updateState(); + emit rangeChanged(min, max, is_zoomed); +} + +void ChartsWidget::zoomReset() { + zoomIn(display_range.first, display_range.second); +} + +void ChartsWidget::updateState() { + if (charts.isEmpty()) return; + + if (!is_zoomed) { + updateDisplayRange(); + } else if (can->currentSec() < zoomed_range.first || can->currentSec() >= zoomed_range.second) { + can->seekTo(zoomed_range.first); + } + + const auto &range = is_zoomed ? zoomed_range : display_range; + for (auto c : charts) { + c->setDisplayRange(range.first, range.second); + c->scene()->invalidate({}, QGraphicsScene::ForegroundLayer); + } +} + +void ChartsWidget::updateToolBar() { + remove_all_btn->setEnabled(!charts.isEmpty()); + reset_zoom_btn->setEnabled(is_zoomed); + range_label->setText(is_zoomed ? tr("%1 - %2").arg(zoomed_range.first, 0, 'f', 2).arg(zoomed_range.second, 0, 'f', 2) : ""); + title_label->setText(charts.size() > 0 ? tr("Charts (%1)").arg(charts.size()) : tr("Charts")); + dock_btn->setText(docking ? "⬈" : "⬋"); + dock_btn->setToolTip(docking ? tr("Undock charts") : tr("Dock charts")); +} + +ChartView *ChartsWidget::findChart(const QString &id, const Signal *sig) { + for (auto c : charts) + if (c->hasSeries(id, sig)) return c; + return nullptr; +} + +void ChartsWidget::showChart(const QString &id, const Signal *sig, bool show, bool merge) { + setUpdatesEnabled(false); + if (show) { + ChartView *chart = merge && charts.size() > 0 ? charts.back() : nullptr; + if (!chart) { + chart = new ChartView(this); + chart->chart()->setTheme(use_dark_theme ? QChart::QChart::ChartThemeDark : QChart::ChartThemeLight); + chart->setEventsRange(display_range); + auto range = is_zoomed ? zoomed_range : display_range; + chart->setDisplayRange(range.first, range.second); + QObject::connect(chart, &ChartView::remove, [=]() { removeChart(chart); }); + QObject::connect(chart, &ChartView::zoomIn, this, &ChartsWidget::zoomIn); + QObject::connect(chart, &ChartView::zoomReset, this, &ChartsWidget::zoomReset); + QObject::connect(chart, &ChartView::seriesRemoved, this, &ChartsWidget::chartClosed); + charts_layout->insertWidget(0, chart); + charts.push_back(chart); + } + chart->addSeries(id, sig); + emit chartOpened(id, sig); + } else if (ChartView *chart = findChart(id, sig)) { + chart->removeSeries(id, sig); + } + updateToolBar(); + setUpdatesEnabled(true); +} + +void ChartsWidget::removeChart(ChartView *chart) { + charts.removeOne(chart); + chart->deleteLater(); + updateToolBar(); +} + +void ChartsWidget::removeAll() { + for (auto c : charts.toVector()) + removeChart(c); +} + +bool ChartsWidget::eventFilter(QObject *obj, QEvent *event) { + if (obj != this && event->type() == QEvent::Close) { + emit dock_btn->triggered(); + return true; + } + return false; +} + +// ChartView + +ChartView::ChartView(QWidget *parent) : QChartView(nullptr, parent) { + QChart *chart = new QChart(); + chart->setBackgroundRoundness(0); + axis_x = new QValueAxis(this); + axis_y = new QValueAxis(this); + chart->addAxis(axis_x, Qt::AlignBottom); + chart->addAxis(axis_y, Qt::AlignLeft); + chart->legend()->setShowToolTips(true); + chart->layout()->setContentsMargins(0, 0, 0, 0); + chart->setMargins(QMargins(20, 11, 11, 11)); + + track_line = new QGraphicsLineItem(chart); + track_line->setPen(QPen(Qt::darkGray, 1, Qt::DashLine)); + track_ellipse = new QGraphicsEllipseItem(chart); + track_ellipse->setBrush(Qt::darkGray); + value_text = new QGraphicsTextItem(chart); + item_group = scene()->createItemGroup({track_line, track_ellipse, value_text}); + item_group->setZValue(chart->zValue() + 10); + + // title + QToolButton *remove_btn = new QToolButton(); + remove_btn->setText("X"); + remove_btn->setAutoRaise(true); + remove_btn->setToolTip(tr("Remove Chart")); + close_btn_proxy = new QGraphicsProxyWidget(chart); + close_btn_proxy->setWidget(remove_btn); + close_btn_proxy->setZValue(chart->zValue() + 11); + + QToolButton *manage_btn = new QToolButton(); + manage_btn->setText("🔧"); + manage_btn->setAutoRaise(true); + manage_btn->setToolTip(tr("Manage series")); + manage_btn_proxy = new QGraphicsProxyWidget(chart); + manage_btn_proxy->setWidget(manage_btn); + manage_btn_proxy->setZValue(chart->zValue() + 11); + + setChart(chart); + setRenderHint(QPainter::Antialiasing); + setRubberBand(QChartView::HorizontalRubberBand); + updateFromSettings(); + + QObject::connect(dbc(), &DBCManager::signalRemoved, this, &ChartView::signalRemoved); + QObject::connect(dbc(), &DBCManager::signalUpdated, this, &ChartView::signalUpdated); + QObject::connect(dbc(), &DBCManager::msgRemoved, this, &ChartView::msgRemoved); + QObject::connect(dbc(), &DBCManager::msgUpdated, this, &ChartView::msgUpdated); + QObject::connect(&settings, &Settings::changed, this, &ChartView::updateFromSettings); + QObject::connect(remove_btn, &QToolButton::clicked, this, &ChartView::remove); + QObject::connect(manage_btn, &QToolButton::clicked, this, &ChartView::manageSeries); +} + +ChartView::~ChartView() { + for (auto &s : sigs) + emit seriesRemoved(s.msg_id, s.sig); +} + +void ChartView::addSeries(const QString &msg_id, const Signal *sig) { + QLineSeries *series = new QLineSeries(this); + chart()->addSeries(series); + series->attachAxis(axis_x); + series->attachAxis(axis_y); + auto [source, address] = DBCManager::parseId(msg_id); + sigs.push_back({.msg_id = msg_id, .address = address, .source = source, .sig = sig, .series = series}); + updateTitle(); + updateSeries(sig); +} + +void ChartView::removeSeries(const QString &msg_id, const Signal *sig) { + auto it = std::find_if(sigs.begin(), sigs.end(), [&](auto &s) { return s.msg_id == msg_id && s.sig == sig; }); + if (it != sigs.end()) { + it = removeSeries(it); + } +} + +bool ChartView::hasSeries(const QString &msg_id, const Signal *sig) const { + auto it = std::find_if(sigs.begin(), sigs.end(), [&](auto &s) { return s.msg_id == msg_id && s.sig == sig; }); + return it != sigs.end(); +} + +QList::iterator ChartView::removeSeries(const QList::iterator &it) { + chart()->removeSeries(it->series); + it->series->deleteLater(); + emit seriesRemoved(it->msg_id, it->sig); + + auto ret = sigs.erase(it); + if (!sigs.isEmpty()) { + updateAxisY(); + } else { + emit remove(); + } + return ret; +} + +void ChartView::signalUpdated(const Signal *sig) { + auto it = std::find_if(sigs.begin(), sigs.end(), [=](auto &s) { return s.sig == sig; }); + if (it != sigs.end()) { + updateTitle(); + // TODO: don't update series if only name changed. + updateSeries(sig); + } +} + +void ChartView::signalRemoved(const Signal *sig) { + for (auto it = sigs.begin(); it != sigs.end(); /**/) { + it = (it->sig == sig) ? removeSeries(it) : ++it; + } +} + +void ChartView::msgUpdated(uint32_t address) { + auto it = std::find_if(sigs.begin(), sigs.end(), [=](auto &s) { return s.address == address; }); + if (it != sigs.end()) + updateTitle(); +} + +void ChartView::msgRemoved(uint32_t address) { + for (auto it = sigs.begin(); it != sigs.end(); /**/) { + it = (it->address == address) ? removeSeries(it) : ++it; + } +} + +void ChartView::manageSeries() { + SeriesSelector dlg(this); + for (auto &s : sigs) { + dlg.addSeries(s.msg_id, msgName(s.msg_id), QString::fromStdString(s.sig->name)); + } + + int ret = dlg.exec(); + if (ret == QDialog::Accepted) { + QList series_list = dlg.series(); + if (series_list.isEmpty()) { + emit remove(); + } else { + for (auto &s : series_list) { + if (auto m = dbc()->msg(s[0])) { + auto it = m->sigs.find(s[2]); + if (it != m->sigs.end() && !hasSeries(s[0], &(it->second))) { + addSeries(s[0], &(it->second)); + } + } + } + for (auto it = sigs.begin(); it != sigs.end(); /**/) { + bool exists = std::any_of(series_list.cbegin(), series_list.cend(), [&](auto &s) { + return s[0] == it->msg_id && s[2] == it->sig->name.c_str(); + }); + it = exists ? ++it : removeSeries(it); + } + } + } +} + +void ChartView::resizeEvent(QResizeEvent *event) { + QChartView::resizeEvent(event); + int x = event->size().width() - close_btn_proxy->size().width() - 11; + close_btn_proxy->setPos(x, 8); + manage_btn_proxy->setPos(x - manage_btn_proxy->size().width() - 5, 8); +} + +void ChartView::updateTitle() { + for (auto &s : sigs) { + s.series->setName(QString("%1 %2 %3").arg(s.sig->name.c_str()).arg(msgName(s.msg_id)).arg(s.msg_id)); + } +} + +void ChartView::updateFromSettings() { + setFixedHeight(settings.chart_height); +} + +void ChartView::setEventsRange(const std::pair &range) { + if (range != events_range) { + events_range = range; + updateSeries(); + } +} + +void ChartView::setDisplayRange(double min, double max) { + if (min != axis_x->min() || max != axis_x->max()) { + axis_x->setRange(min, max); + updateAxisY(); + } +} + +void ChartView::adjustChartMargins() { + // TODO: Remove hardcoded aligned_pos + const int aligned_pos = 60; + if ((int)chart()->plotArea().left() != aligned_pos) { + const float left_margin = chart()->margins().left() + aligned_pos - chart()->plotArea().left(); + chart()->setMargins(QMargins(left_margin, 11, 11, 11)); + scene()->invalidate({}, QGraphicsScene::ForegroundLayer); + } +} + +void ChartView::updateSeries(const Signal *sig) { + auto events = can->events(); + if (!events || sigs.isEmpty()) return; + + for (auto &s : sigs) { + if (!sig || s.sig == sig) { + s.vals.clear(); + s.vals.reserve((events_range.second - events_range.first) * 1000); // [n]seconds * 1000hz + s.min_y = std::numeric_limits::max(); + s.max_y = std::numeric_limits::lowest(); + + double route_start_time = can->routeStartTime(); + Event begin_event(cereal::Event::Which::INIT_DATA, (route_start_time + events_range.first) * 1e9); + auto begin = std::lower_bound(events->begin(), events->end(), &begin_event, Event::lessThan()); + double end_ns = (route_start_time + events_range.second) * 1e9; + + for (auto it = begin; it != events->end() && (*it)->mono_time <= end_ns; ++it) { + if ((*it)->which == cereal::Event::Which::CAN) { + for (const auto &c : (*it)->event.getCan()) { + if (s.source == c.getSrc() && s.address == c.getAddress()) { + auto dat = c.getDat(); + double value = get_raw_value((uint8_t *)dat.begin(), dat.size(), *s.sig); + double ts = ((*it)->mono_time / (double)1e9) - route_start_time; // seconds + s.vals.push_back({ts, value}); + + if (value < s.min_y) s.min_y = value; + if (value > s.max_y) s.max_y = value; + } + } + } + } + s.series->replace(s.vals); + } + } + updateAxisY(); +} + +// auto zoom on yaxis +void ChartView::updateAxisY() { + if (sigs.isEmpty()) return; + + double min_y = std::numeric_limits::max(); + double max_y = std::numeric_limits::lowest(); + if (events_range == std::pair{axis_x->min(), axis_x->max()}) { + for (auto &s : sigs) { + if (s.min_y < min_y) min_y = s.min_y; + if (s.max_y > max_y) max_y = s.max_y; + } + } else { + for (auto &s : sigs) { + auto begin = std::lower_bound(s.vals.begin(), s.vals.end(), axis_x->min(), [](auto &p, double x) { return p.x() < x; }); + for (auto it = begin; it != s.vals.end() && it->x() <= axis_x->max(); ++it) { + if (it->y() < min_y) min_y = it->y(); + if (it->y() > max_y) max_y = it->y(); + } + } + } + + if (min_y == std::numeric_limits::max()) min_y = 0; + if (max_y == std::numeric_limits::lowest()) max_y = 0; + if (max_y == min_y) { + axis_y->setRange(min_y - 1, max_y + 1); + } else { + double range = max_y - min_y; + axis_y->setRange(min_y - range * 0.05, max_y + range * 0.05); + axis_y->applyNiceNumbers(); + } + + QTimer::singleShot(0, this, &ChartView::adjustChartMargins); +} + +void ChartView::leaveEvent(QEvent *event) { + item_group->setVisible(false); + QChartView::leaveEvent(event); +} + +void ChartView::mouseReleaseEvent(QMouseEvent *event) { + auto rubber = findChild(); + if (event->button() == Qt::LeftButton && rubber && rubber->isVisible()) { + rubber->hide(); + QRectF rect = rubber->geometry().normalized(); + double min = std::floor(chart()->mapToValue(rect.topLeft()).x() * 10.0) / 10.0; + double max = std::floor(chart()->mapToValue(rect.bottomRight()).x() * 10.0) / 10.0; + if (rubber->width() <= 0) { + // no rubber dragged, seek to mouse position + can->seekTo(min); + } else if ((max - min) >= 0.5) { + // zoom in if selected range is greater than 0.5s + emit zoomIn(min, max); + } + event->accept(); + } else if (event->button() == Qt::RightButton) { + emit zoomReset(); + event->accept(); + } else { + QGraphicsView::mouseReleaseEvent(event); + } +} + +void ChartView::mouseMoveEvent(QMouseEvent *ev) { + auto rubber = findChild(); + bool is_zooming = rubber && rubber->isVisible(); + const auto plot_area = chart()->plotArea(); + + if (!is_zooming && plot_area.contains(ev->pos())) { + QStringList text_list; + QPointF pos = {}; + const double sec = chart()->mapToValue(ev->pos()).x(); + for (auto &s : sigs) { + QString value = "--"; + // use reverse iterator to find last item <= sec. + auto it = std::lower_bound(s.vals.rbegin(), s.vals.rend(), sec, [](auto &p, double x) { return p.x() > x; }); + if (it != s.vals.rend() && it->x() >= axis_x->min()) { + value = QString::number(it->y()); + auto value_pos = chart()->mapToPosition(*it); + if (value_pos.x() > pos.x()) pos = value_pos; + } + text_list.push_back(QString(" %1 : %2 ").arg(sigs.size() > 1 ? s.sig->name.c_str() : "Value").arg(value)); + } + if (pos.x() == 0) pos = ev->pos(); + + QString time = QString::number(chart()->mapToValue(pos).x(), 'f', 3); + value_text->setHtml(QString("
 Time: %1  
%2
") + .arg(time).arg(text_list.join("
"))); + + QRectF text_rect = value_text->boundingRect(); + int text_x = pos.x() + 8; + if ((text_x + text_rect.width()) > plot_area.right()) { + text_x = pos.x() - text_rect.width() - 8; + } + value_text->setPos(text_x, pos.y() - text_rect.height() / 2); + track_line->setLine(pos.x(), plot_area.top(), pos.x(), plot_area.bottom()); + track_ellipse->setRect(pos.x() - 5, pos.y() - 5, 10, 10); + item_group->setVisible(true); + } else { + item_group->setVisible(false); + } + QChartView::mouseMoveEvent(ev); +} + +void ChartView::drawForeground(QPainter *painter, const QRectF &rect) { + qreal x = chart()->mapToPosition(QPointF{can->currentSec(), 0}).x(); + painter->setPen(QPen(chart()->titleBrush().color(), 2)); + painter->drawLine(QPointF{x, chart()->plotArea().top() - 2}, QPointF{x, chart()->plotArea().bottom() + 2}); +} + +// SeriesSelector + +SeriesSelector::SeriesSelector(QWidget *parent) { + setWindowTitle(tr("Manage Chart Series")); + QHBoxLayout *contents_layout = new QHBoxLayout(); + + QVBoxLayout *left_layout = new QVBoxLayout(); + left_layout->addWidget(new QLabel(tr("Select Signals:"))); + msgs_combo = new QComboBox(this); + left_layout->addWidget(msgs_combo); + sig_list = new QListWidget(this); + sig_list->setSortingEnabled(true); + sig_list->setToolTip(tr("Double click on an item to add signal to chart")); + left_layout->addWidget(sig_list); + + QVBoxLayout *right_layout = new QVBoxLayout(); + right_layout->addWidget(new QLabel(tr("Chart Signals:"))); + chart_series = new QListWidget(this); + chart_series->setSortingEnabled(true); + chart_series->setToolTip(tr("Double click on an item to remove signal from chart")); + right_layout->addWidget(chart_series); + contents_layout->addLayout(left_layout); + contents_layout->addLayout(right_layout); + + auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + + QVBoxLayout *main_layout = new QVBoxLayout(this); + main_layout->addLayout(contents_layout); + main_layout->addWidget(buttonBox); + + for (auto it = can->can_msgs.cbegin(); it != can->can_msgs.cend(); ++it) { + if (auto m = dbc()->msg(it.key())) { + msgs_combo->addItem(QString("%1 (%2)").arg(m->name).arg(it.key()), it.key()); + } + } + msgs_combo->model()->sort(0); + + QObject::connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); + QObject::connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); + QObject::connect(msgs_combo, SIGNAL(currentIndexChanged(int)), SLOT(msgSelected(int))); + QObject::connect(sig_list, &QListWidget::itemDoubleClicked, this, &SeriesSelector::addSignal); + QObject::connect(chart_series, &QListWidget::itemDoubleClicked, [](QListWidgetItem *item) { delete item; }); + + if (int index = msgs_combo->currentIndex(); index >= 0) { + msgSelected(index); + } +} + +void SeriesSelector::msgSelected(int index) { + QString msg_id = msgs_combo->itemData(index).toString(); + sig_list->clear(); + if (auto m = dbc()->msg(msg_id)) { + for (auto &[name, s] : m->sigs) { + QStringList data({msg_id, m->name, name}); + QListWidgetItem *item = new QListWidgetItem(name, sig_list); + item->setData(Qt::UserRole, data); + sig_list->addItem(item); + } + } +} + +void SeriesSelector::addSignal(QListWidgetItem *item) { + QStringList data = item->data(Qt::UserRole).toStringList(); + addSeries(data[0], data[1], data[2]); +} + +void SeriesSelector::addSeries(const QString &id, const QString& msg_name, const QString &sig_name) { + QStringList data({id, msg_name, sig_name}); + for (int i = 0; i < chart_series->count(); ++i) { + if (chart_series->item(i)->data(Qt::UserRole).toStringList() == data) { + return; + } + } + QListWidgetItem *new_item = new QListWidgetItem(chart_series); + new_item->setData(Qt::UserRole, data); + chart_series->addItem(new_item); + QLabel *label = new QLabel(QString("%0 %1 %2").arg(data[2]).arg(data[1]).arg(data[0]), chart_series); + label->setContentsMargins(5, 0, 5, 0); + new_item->setSizeHint(label->sizeHint()); + chart_series->setItemWidget(new_item, label); +} + +QList SeriesSelector::series() { + QList ret; + for (int i = 0; i < chart_series->count(); ++i) { + ret.push_back(chart_series->item(i)->data(Qt::UserRole).toStringList()); + } + return ret; +} diff --git a/tools/cabana/chartswidget.h b/tools/cabana/chartswidget.h new file mode 100644 index 0000000000..3e3277c5b8 --- /dev/null +++ b/tools/cabana/chartswidget.h @@ -0,0 +1,139 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "tools/cabana/canmessages.h" +#include "tools/cabana/dbcmanager.h" + +using namespace QtCharts; + +class ChartView : public QChartView { + Q_OBJECT + +public: + ChartView(QWidget *parent = nullptr); + ~ChartView(); + void addSeries(const QString &msg_id, const Signal *sig); + void removeSeries(const QString &msg_id, const Signal *sig); + bool hasSeries(const QString &msg_id, const Signal *sig) const; + void updateSeries(const Signal *sig = nullptr); + void setEventsRange(const std::pair &range); + void setDisplayRange(double min, double max); + + struct SigItem { + QString msg_id; + uint8_t source = 0; + uint32_t address = 0; + const Signal *sig = nullptr; + QLineSeries *series = nullptr; + double min_y = 0; + double max_y = 0; + QVector vals; + }; + +signals: + void seriesRemoved(const QString &id, const Signal *sig); + void zoomIn(double min, double max); + void zoomReset(); + void remove(); + +private slots: + void msgRemoved(uint32_t address); + void msgUpdated(uint32_t address); + void signalUpdated(const Signal *sig); + void signalRemoved(const Signal *sig); + void manageSeries(); + +private: + QList::iterator removeSeries(const QList::iterator &it); + void mouseReleaseEvent(QMouseEvent *event) override; + void mouseMoveEvent(QMouseEvent *ev) override; + void leaveEvent(QEvent *event) override; + void resizeEvent(QResizeEvent *event) override; + void adjustChartMargins(); + void updateAxisY(); + void updateTitle(); + void updateFromSettings(); + void drawForeground(QPainter *painter, const QRectF &rect) override; + + QValueAxis *axis_x; + QValueAxis *axis_y; + QGraphicsItemGroup *item_group; + QGraphicsLineItem *track_line; + QGraphicsEllipseItem *track_ellipse; + QGraphicsTextItem *value_text; + QGraphicsProxyWidget *close_btn_proxy; + QGraphicsProxyWidget *manage_btn_proxy; + std::pair events_range = {0, 0}; + QList sigs; + }; + +class ChartsWidget : public QWidget { + Q_OBJECT + +public: + ChartsWidget(QWidget *parent = nullptr); + void showChart(const QString &id, const Signal *sig, bool show, bool merge); + void removeChart(ChartView *chart); + inline bool isChartOpened(const QString &id, const Signal *sig) { return findChart(id, sig) != nullptr; } + +signals: + void dock(bool floating); + void rangeChanged(double min, double max, bool is_zommed); + void chartOpened(const QString &id, const Signal *sig); + void chartClosed(const QString &id, const Signal *sig); + +private: + void eventsMerged(); + void updateState(); + void updateDisplayRange(); + void zoomIn(double min, double max); + void zoomReset(); + void updateToolBar(); + void removeAll(); + bool eventFilter(QObject *obj, QEvent *event) override; + ChartView *findChart(const QString &id, const Signal *sig); + + QLabel *title_label; + QLabel *range_label; + bool docking = true; + QAction *dock_btn; + QAction *reset_zoom_btn; + QAction *remove_all_btn; + QVBoxLayout *charts_layout; + QList charts; + bool is_zoomed = false; + std::pair event_range; + std::pair display_range; + std::pair zoomed_range; + bool use_dark_theme = false; +}; + +class SeriesSelector : public QDialog { + Q_OBJECT + +public: + SeriesSelector(QWidget *parent); + void addSeries(const QString &id, const QString& msg_name, const QString &sig_name); + QList series(); + +private slots: + void msgSelected(int index); + void addSignal(QListWidgetItem *item); + +private: + QComboBox *msgs_combo; + QListWidget *sig_list; + QListWidget *chart_series; +}; diff --git a/tools/cabana/commands.cc b/tools/cabana/commands.cc new file mode 100644 index 0000000000..b3f5cb1c66 --- /dev/null +++ b/tools/cabana/commands.cc @@ -0,0 +1,75 @@ +#include "tools/cabana/commands.h" + +// EditMsgCommand + +EditMsgCommand::EditMsgCommand(const QString &id, const QString &title, int size, QUndoCommand *parent) + : id(id), new_title(title), new_size(size), QUndoCommand(parent) { + if (auto msg = dbc()->msg(id)) { + old_title = msg->name; + old_size = msg->size; + } + setText(QObject::tr("Edit message %1:%2").arg(DBCManager::parseId(id).second).arg(title)); +} + +void EditMsgCommand::undo() { + if (old_title.isEmpty()) + dbc()->removeMsg(id); + else + dbc()->updateMsg(id, old_title, old_size); +} + +void EditMsgCommand::redo() { + dbc()->updateMsg(id, new_title, new_size); +} + +// RemoveMsgCommand + +RemoveMsgCommand::RemoveMsgCommand(const QString &id, QUndoCommand *parent) : id(id), QUndoCommand(parent) { + if (auto msg = dbc()->msg(id)) { + message = *msg; + setText(QObject::tr("Remove message %1:%2").arg(DBCManager::parseId(id).second).arg(message.name)); + } +} + +void RemoveMsgCommand::undo() { + if (!message.name.isEmpty()) { + dbc()->updateMsg(id, message.name, message.size); + for (auto &[name, s] : message.sigs) + dbc()->addSignal(id, s); + } +} + +void RemoveMsgCommand::redo() { + if (!message.name.isEmpty()) + dbc()->removeMsg(id); +} + +// AddSigCommand + +AddSigCommand::AddSigCommand(const QString &id, const Signal &sig, QUndoCommand *parent) + : id(id), signal(sig), QUndoCommand(parent) { + setText(QObject::tr("Add signal %1 to %2").arg(sig.name.c_str()).arg(DBCManager::parseId(id).second)); +} + +void AddSigCommand::undo() { dbc()->removeSignal(id, signal.name.c_str()); } +void AddSigCommand::redo() { dbc()->addSignal(id, signal); } + +// RemoveSigCommand + +RemoveSigCommand::RemoveSigCommand(const QString &id, const Signal *sig, QUndoCommand *parent) + : id(id), signal(*sig), QUndoCommand(parent) { + setText(QObject::tr("Remove signal %1 from %2").arg(signal.name.c_str()).arg(DBCManager::parseId(id).second)); +} + +void RemoveSigCommand::undo() { dbc()->addSignal(id, signal); } +void RemoveSigCommand::redo() { dbc()->removeSignal(id, signal.name.c_str()); } + +// EditSignalCommand + +EditSignalCommand::EditSignalCommand(const QString &id, const Signal *sig, const Signal &new_sig, QUndoCommand *parent) + : id(id), old_signal(*sig), new_signal(new_sig), QUndoCommand(parent) { + setText(QObject::tr("Edit signal %1").arg(old_signal.name.c_str())); +} + +void EditSignalCommand::undo() { dbc()->updateSignal(id, new_signal.name.c_str(), old_signal); } +void EditSignalCommand::redo() { dbc()->updateSignal(id, old_signal.name.c_str(), new_signal); } diff --git a/tools/cabana/commands.h b/tools/cabana/commands.h new file mode 100644 index 0000000000..7ea1f66653 --- /dev/null +++ b/tools/cabana/commands.h @@ -0,0 +1,63 @@ +#pragma once + +#include + +#include "tools/cabana/canmessages.h" +#include "tools/cabana/dbcmanager.h" + +class EditMsgCommand : public QUndoCommand { +public: + EditMsgCommand(const QString &id, const QString &title, int size, QUndoCommand *parent = nullptr); + void undo() override; + void redo() override; + +private: + const QString id; + QString old_title, new_title; + int old_size = 0, new_size = 0; +}; + +class RemoveMsgCommand : public QUndoCommand { +public: + RemoveMsgCommand(const QString &id, QUndoCommand *parent = nullptr); + void undo() override; + void redo() override; + +private: + const QString id; + DBCMsg message; +}; + +class AddSigCommand : public QUndoCommand { +public: + AddSigCommand(const QString &id, const Signal &sig, QUndoCommand *parent = nullptr); + void undo() override; + void redo() override; + +private: + const QString id; + Signal signal = {}; +}; + +class RemoveSigCommand : public QUndoCommand { +public: + RemoveSigCommand(const QString &id, const Signal *sig, QUndoCommand *parent = nullptr); + void undo() override; + void redo() override; + +private: + const QString id; + Signal signal = {}; +}; + +class EditSignalCommand : public QUndoCommand { +public: + EditSignalCommand(const QString &id, const Signal *sig, const Signal &new_sig, QUndoCommand *parent = nullptr); + void undo() override; + void redo() override; + +private: + const QString id; + Signal old_signal = {}; + Signal new_signal = {}; +}; diff --git a/tools/cabana/dbcmanager.cc b/tools/cabana/dbcmanager.cc new file mode 100644 index 0000000000..e7d3ead9c6 --- /dev/null +++ b/tools/cabana/dbcmanager.cc @@ -0,0 +1,184 @@ +#include "tools/cabana/dbcmanager.h" + +#include +#include +#include + +DBCManager::DBCManager(QObject *parent) : QObject(parent) {} + +DBCManager::~DBCManager() {} + +void DBCManager::open(const QString &dbc_file_name) { + dbc = const_cast(dbc_lookup(dbc_file_name.toStdString())); + initMsgMap(); +} + +void DBCManager::open(const QString &name, const QString &content) { + std::istringstream stream(content.toStdString()); + dbc = const_cast(dbc_parse_from_stream(name.toStdString(), stream)); + initMsgMap(); +} + +void DBCManager::initMsgMap() { + msgs.clear(); + for (auto &msg : dbc->msgs) { + auto &m = msgs[msg.address]; + m.name = msg.name.c_str(); + m.size = msg.size; + for (auto &s : msg.sigs) + m.sigs[QString::fromStdString(s.name)] = s; + } + emit DBCFileChanged(); +} + +QString DBCManager::generateDBC() { + if (!dbc) return {}; + + QString dbc_string; + for (auto &[address, m] : msgs) { + dbc_string += QString("BO_ %1 %2: %3 XXX\n").arg(address).arg(m.name).arg(m.size); + for (auto &[name, sig] : m.sigs) { + dbc_string += QString(" SG_ %1 : %2|%3@%4%5 (%6,%7) [0|0] \"\" XXX\n") + .arg(name) + .arg(sig.start_bit) + .arg(sig.size) + .arg(sig.is_little_endian ? '1' : '0') + .arg(sig.is_signed ? '-' : '+') + .arg(sig.factor, 0, 'g', std::numeric_limits::digits10) + .arg(sig.offset, 0, 'g', std::numeric_limits::digits10); + } + dbc_string += "\n"; + } + return dbc_string; +} + +void DBCManager::updateMsg(const QString &id, const QString &name, uint32_t size) { + auto [_, address] = parseId(id); + auto &m = msgs[address]; + m.name = name; + m.size = size; + emit msgUpdated(address); +} + +void DBCManager::removeMsg(const QString &id) { + uint32_t address = parseId(id).second; + msgs.erase(address); + emit msgRemoved(address); +} + +void DBCManager::addSignal(const QString &id, const Signal &sig) { + if (auto m = const_cast(msg(id))) { + auto &s = m->sigs[sig.name.c_str()]; + s = sig; + emit signalAdded(&s); + } +} + +void DBCManager::updateSignal(const QString &id, const QString &sig_name, const Signal &sig) { + if (auto m = const_cast(msg(id))) { + // change key name + QString new_name = QString::fromStdString(sig.name); + auto node = m->sigs.extract(sig_name); + node.key() = new_name; + auto it = m->sigs.insert(std::move(node)); + auto &s = m->sigs[new_name]; + s = sig; + emit signalUpdated(&s); + } +} + +void DBCManager::removeSignal(const QString &id, const QString &sig_name) { + if (auto m = const_cast(msg(id))) { + auto it = m->sigs.find(sig_name); + if (it != m->sigs.end()) { + emit signalRemoved(&(it->second)); + m->sigs.erase(it); + } + } +} + +std::pair DBCManager::parseId(const QString &id) { + const auto list = id.split(':'); + return {list[0].toInt(), list[1].toUInt(nullptr, 16)}; +} + +DBCManager *dbc() { + static DBCManager dbc_manager(nullptr); + return &dbc_manager; +} + +// DBCMsg + +std::vector DBCMsg::getSignals() const { + std::vector ret; + for (auto &[name, sig] : sigs) ret.push_back(&sig); + std::sort(ret.begin(), ret.end(), [](auto l, auto r) { return l->start_bit < r->start_bit; }); + return ret; +} + +// helper functions + +static QVector BIG_ENDIAN_START_BITS = []() { + QVector ret; + for (int i = 0; i < 64; i++) + for (int j = 7; j >= 0; j--) + ret.push_back(j + i * 8); + return ret; +}(); + +int bigEndianStartBitsIndex(int start_bit) { + return BIG_ENDIAN_START_BITS[start_bit]; +} + +int bigEndianBitIndex(int index) { + return BIG_ENDIAN_START_BITS.indexOf(index); +} + +double get_raw_value(uint8_t *data, size_t data_size, const Signal &sig) { + int64_t val = 0; + + int i = sig.msb / 8; + int bits = sig.size; + while (i >= 0 && i < data_size && bits > 0) { + int lsb = (int)(sig.lsb / 8) == i ? sig.lsb : i * 8; + int msb = (int)(sig.msb / 8) == i ? sig.msb : (i + 1) * 8 - 1; + int size = msb - lsb + 1; + + uint64_t d = (data[i] >> (lsb - (i * 8))) & ((1ULL << size) - 1); + val |= d << (bits - size); + + bits -= size; + i = sig.is_little_endian ? i - 1 : i + 1; + } + if (sig.is_signed) { + val -= ((val >> (sig.size - 1)) & 0x1) ? (1ULL << sig.size) : 0; + } + double value = val * sig.factor + sig.offset; + return value; +} + +void updateSigSizeParamsFromRange(Signal &s, int start_bit, int size) { + s.start_bit = s.is_little_endian ? start_bit : bigEndianBitIndex(start_bit); + s.size = size; + if (s.is_little_endian) { + s.lsb = s.start_bit; + s.msb = s.start_bit + s.size - 1; + } else { + s.lsb = bigEndianStartBitsIndex(bigEndianBitIndex(s.start_bit) + s.size - 1); + s.msb = s.start_bit; + } +} + +std::pair getSignalRange(const Signal *s) { + int from = s->is_little_endian ? s->start_bit : bigEndianBitIndex(s->start_bit); + int to = from + s->size - 1; + return {from, to}; +} + +bool operator==(const Signal &l, const Signal &r) { + return l.name == r.name && l.size == r.size && + l.start_bit == r.start_bit && + l.msb == r.msb && l.lsb == r.lsb && + l.is_signed == r.is_signed && l.is_little_endian == r.is_little_endian && + l.factor == r.factor && l.offset == r.offset; +} diff --git a/tools/cabana/dbcmanager.h b/tools/cabana/dbcmanager.h new file mode 100644 index 0000000000..c7675121bb --- /dev/null +++ b/tools/cabana/dbcmanager.h @@ -0,0 +1,69 @@ +#pragma once + +#include +#include +#include +#include "opendbc/can/common_dbc.h" + +struct DBCMsg { + QString name; + uint32_t size; + std::map sigs; + std::vector getSignals() const; +}; + +class DBCManager : public QObject { + Q_OBJECT + +public: + DBCManager(QObject *parent); + ~DBCManager(); + + void open(const QString &dbc_file_name); + void open(const QString &name, const QString &content); + QString generateDBC(); + void addSignal(const QString &id, const Signal &sig); + void updateSignal(const QString &id, const QString &sig_name, const Signal &sig); + void removeSignal(const QString &id, const QString &sig_name); + + static std::pair parseId(const QString &id); + inline static std::vector allDBCNames() { return get_dbc_names(); } + inline std::map &allMsgs() { return msgs; } + inline QString name() const { return dbc ? dbc->name.c_str() : ""; } + + void updateMsg(const QString &id, const QString &name, uint32_t size); + void removeMsg(const QString &id); + inline const std::map &messages() const { return msgs; } + inline const DBCMsg *msg(const QString &id) const { return msg(parseId(id).second); } + inline const DBCMsg *msg(uint32_t address) const { + auto it = msgs.find(address); + return it != msgs.end() ? &it->second : nullptr; + } + +signals: + void signalAdded(const Signal *sig); + void signalRemoved(const Signal *sig); + void signalUpdated(const Signal *sig); + void msgUpdated(uint32_t address); + void msgRemoved(uint32_t address); + void DBCFileChanged(); + +private: + void initMsgMap(); + DBC *dbc = nullptr; + std::map msgs; +}; + +// TODO: Add helper function in dbc.h +double get_raw_value(uint8_t *data, size_t data_size, const Signal &sig); +bool operator==(const Signal &l, const Signal &r); +inline bool operator!=(const Signal &l, const Signal &r) { return !(l == r); } +int bigEndianStartBitsIndex(int start_bit); +int bigEndianBitIndex(int index); +void updateSigSizeParamsFromRange(Signal &s, int start_bit, int size); +std::pair getSignalRange(const Signal *s); +DBCManager *dbc(); +inline QString msgName(const QString &id, const char *def = "untitled") { + auto msg = dbc()->msg(id); + return msg ? msg->name : def; +} diff --git a/tools/cabana/detailwidget.cc b/tools/cabana/detailwidget.cc new file mode 100644 index 0000000000..cd1057f7e1 --- /dev/null +++ b/tools/cabana/detailwidget.cc @@ -0,0 +1,337 @@ +#include "tools/cabana/detailwidget.h" + +#include +#include +#include +#include +#include +#include + +#include "selfdrive/ui/qt/util.h" +#include "tools/cabana/canmessages.h" +#include "tools/cabana/commands.h" +#include "tools/cabana/dbcmanager.h" + +// DetailWidget + +DetailWidget::DetailWidget(ChartsWidget *charts, QWidget *parent) : charts(charts), QWidget(parent) { + undo_stack = new QUndoStack(this); + setMinimumWidth(500); + QWidget *main_widget = new QWidget(this); + QVBoxLayout *main_layout = new QVBoxLayout(main_widget); + main_layout->setContentsMargins(0, 0, 0, 0); + main_layout->setSpacing(0); + + // tabbar + tabbar = new QTabBar(this); + tabbar->setTabsClosable(true); + tabbar->setUsesScrollButtons(true); + tabbar->setAutoHide(true); + tabbar->setContextMenuPolicy(Qt::CustomContextMenu); + main_layout->addWidget(tabbar); + + QFrame *title_frame = new QFrame(this); + QVBoxLayout *frame_layout = new QVBoxLayout(title_frame); + title_frame->setFrameShape(QFrame::StyledPanel); + + // message title + toolbar = new QToolBar(this); + toolbar->addWidget(new QLabel("time:")); + time_label = new QLabel(this); + time_label->setStyleSheet("font-weight:bold"); + toolbar->addWidget(time_label); + name_label = new QLabel(this); + name_label->setStyleSheet("font-weight:bold;"); + name_label->setAlignment(Qt::AlignCenter); + name_label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); + toolbar->addWidget(name_label); + toolbar->addAction("🖍", this, &DetailWidget::editMsg)->setToolTip(tr("Edit Message")); + remove_msg_act = toolbar->addAction("X", this, &DetailWidget::removeMsg); + remove_msg_act->setToolTip(tr("Remove Message")); + toolbar->setVisible(false); + frame_layout->addWidget(toolbar); + + // warning + warning_widget = new QWidget(this); + QHBoxLayout *warning_hlayout = new QHBoxLayout(warning_widget); + warning_hlayout->setContentsMargins(0, 0, 0, 0); + QLabel *warning_icon = new QLabel(this); + warning_icon->setPixmap(style()->standardPixmap(QStyle::SP_MessageBoxWarning).scaledToWidth(24, Qt::SmoothTransformation)); + warning_hlayout->addWidget(warning_icon, 0, Qt::AlignTop); + warning_label = new QLabel(this); + warning_hlayout->addWidget(warning_label, 1, Qt::AlignLeft); + warning_widget->hide(); + frame_layout->addWidget(warning_widget); + main_layout->addWidget(title_frame); + + // msg widget + QWidget *msg_widget = new QWidget(this); + QVBoxLayout *msg_layout = new QVBoxLayout(msg_widget); + msg_layout->setContentsMargins(0, 0, 0, 0); + // binary view + binary_view = new BinaryView(this); + msg_layout->addWidget(binary_view); + // signals + signals_layout = new QVBoxLayout(); + signals_layout->setSpacing(0); + msg_layout->addLayout(signals_layout); + msg_layout->addStretch(0); + + scroll = new QScrollArea(this); + scroll->setFrameShape(QFrame::NoFrame); + scroll->setWidget(msg_widget); + scroll->setWidgetResizable(true); + scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + + tab_widget = new QTabWidget(this); + tab_widget->setTabPosition(QTabWidget::South); + tab_widget->addTab(scroll, "&Msg"); + history_log = new HistoryLog(this); + tab_widget->addTab(history_log, "&Logs"); + main_layout->addWidget(tab_widget); + + stacked_layout = new QStackedLayout(this); + stacked_layout->addWidget(new WelcomeWidget(this)); + stacked_layout->addWidget(main_widget); + + QObject::connect(binary_view, &BinaryView::signalClicked, this, &DetailWidget::showForm); + QObject::connect(binary_view, &BinaryView::resizeSignal, this, &DetailWidget::resizeSignal); + QObject::connect(binary_view, &BinaryView::addSignal, this, &DetailWidget::addSignal); + QObject::connect(tab_widget, &QTabWidget::currentChanged, [this]() { updateState(); }); + QObject::connect(can, &CANMessages::msgsReceived, this, &DetailWidget::updateState); + QObject::connect(dbc(), &DBCManager::DBCFileChanged, [this]() { dbcMsgChanged(); }); + QObject::connect(tabbar, &QTabBar::customContextMenuRequested, this, &DetailWidget::showTabBarContextMenu); + QObject::connect(tabbar, &QTabBar::currentChanged, [this](int index) { + if (index != -1 && tabbar->tabText(index) != msg_id) { + setMessage(tabbar->tabText(index)); + } + }); + QObject::connect(tabbar, &QTabBar::tabCloseRequested, tabbar, &QTabBar::removeTab); + QObject::connect(charts, &ChartsWidget::chartOpened, [this](const QString &id, const Signal *sig) { updateChartState(id, sig, true); }); + QObject::connect(charts, &ChartsWidget::chartClosed, [this](const QString &id, const Signal *sig) { updateChartState(id, sig, false); }); + QObject::connect(undo_stack, &QUndoStack::indexChanged, [this]() { + if (undo_stack->count() > 0) + dbcMsgChanged(); + }); +} + +void DetailWidget::showTabBarContextMenu(const QPoint &pt) { + int index = tabbar->tabAt(pt); + if (index >= 0) { + QMenu menu(this); + menu.addAction(tr("Close Other Tabs")); + if (menu.exec(tabbar->mapToGlobal(pt))) { + tabbar->moveTab(index, 0); + tabbar->setCurrentIndex(0); + while (tabbar->count() > 1) + tabbar->removeTab(1); + } + } +} + +void DetailWidget::setMessage(const QString &message_id) { + msg_id = message_id; + int index = tabbar->count() - 1; + for (/**/; index >= 0 && tabbar->tabText(index) != msg_id; --index) { /**/ } + if (index == -1) { + index = tabbar->addTab(message_id); + tabbar->setTabToolTip(index, msgName(message_id)); + } + tabbar->setCurrentIndex(index); + dbcMsgChanged(); + scroll->verticalScrollBar()->setValue(0); + stacked_layout->setCurrentIndex(1); +} + +void DetailWidget::dbcMsgChanged(int show_form_idx) { + if (msg_id.isEmpty()) return; + + setUpdatesEnabled(false); + + binary_view->setMessage(msg_id); + history_log->setMessage(msg_id); + + int i = 0; + QStringList warnings; + const DBCMsg *msg = dbc()->msg(msg_id); + if (msg) { + for (auto sig : msg->getSignals()) { + SignalEdit *form = i < signal_list.size() ? signal_list[i] : nullptr; + if (!form) { + form = new SignalEdit(i, this); + QObject::connect(form, &SignalEdit::remove, this, &DetailWidget::removeSignal); + QObject::connect(form, &SignalEdit::save, this, &DetailWidget::saveSignal); + QObject::connect(form, &SignalEdit::showFormClicked, this, &DetailWidget::showForm); + QObject::connect(form, &SignalEdit::highlight, binary_view, &BinaryView::highlight); + QObject::connect(binary_view, &BinaryView::signalHovered, form, &SignalEdit::signalHovered); + QObject::connect(form, &SignalEdit::showChart, charts, &ChartsWidget::showChart); + signals_layout->addWidget(form); + signal_list.push_back(form); + } + form->setSignal(msg_id, sig); + form->setChartOpened(charts->isChartOpened(msg_id, sig)); + ++i; + } + if (msg->size != can->lastMessage(msg_id).dat.size()) + warnings.push_back(tr("Message size (%1) is incorrect.").arg(msg->size)); + } + for (/**/; i < signal_list.size(); ++i) + signal_list[i]->hide(); + + toolbar->setVisible(!msg_id.isEmpty()); + remove_msg_act->setEnabled(msg != nullptr); + name_label->setText(msgName(msg_id)); + + for (auto s : binary_view->getOverlappingSignals()) + warnings.push_back(tr("%1 has overlapping bits.").arg(s->name.c_str())); + + warning_label->setText(warnings.join('\n')); + warning_widget->setVisible(!warnings.isEmpty()); + setUpdatesEnabled(true); +} + +void DetailWidget::updateState(const QHash * msgs) { + time_label->setText(QString::number(can->currentSec(), 'f', 3)); + if (msg_id.isEmpty() || (msgs && !msgs->contains(msg_id))) + return; + + if (tab_widget->currentIndex() == 0) + binary_view->updateState(); + else + history_log->updateState(); +} + +void DetailWidget::showForm(const Signal *sig) { + setUpdatesEnabled(false); + for (auto f : signal_list) { + f->updateForm(f->sig == sig && !f->form->isVisible()); + if (f->sig == sig && f->form->isVisible()) { + QTimer::singleShot(0, [=]() { scroll->ensureWidgetVisible(f); }); + } + } + setUpdatesEnabled(true); +} + +void DetailWidget::updateChartState(const QString &id, const Signal *sig, bool opened) { + for (auto f : signal_list) + if (f->msg_id == id && f->sig == sig) f->setChartOpened(opened); +} + +void DetailWidget::editMsg() { + QString id = msg_id; + auto msg = dbc()->msg(id); + int size = msg ? msg->size : can->lastMessage(id).dat.size(); + EditMessageDialog dlg(id, msgName(id), size, this); + if (dlg.exec()) { + undo_stack->push(new EditMsgCommand(msg_id, dlg.name_edit->text(), dlg.size_spin->value())); + } +} + +void DetailWidget::removeMsg() { + undo_stack->push(new RemoveMsgCommand(msg_id)); +} + +void DetailWidget::addSignal(int start_bit, int size, bool little_endian) { + auto msg = dbc()->msg(msg_id); + if (!msg) { + for (int i = 1; /**/; ++i) { + QString name = QString("NEW_MSG_%1").arg(i); + auto it = std::find_if(dbc()->messages().begin(), dbc()->messages().end(), [&](auto &m) { return m.second.name == name; }); + if (it == dbc()->messages().end()) { + undo_stack->push(new EditMsgCommand(msg_id, name, can->lastMessage(msg_id).dat.size())); + msg = dbc()->msg(msg_id); + break; + } + } + } + Signal sig = {.is_little_endian = little_endian, .factor = 1}; + for (int i = 1; /**/; ++i) { + sig.name = "NEW_SIGNAL_" + std::to_string(i); + if (msg->sigs.count(sig.name.c_str()) == 0) break; + } + updateSigSizeParamsFromRange(sig, start_bit, size); + undo_stack->push(new AddSigCommand(msg_id, sig)); +} + +void DetailWidget::resizeSignal(const Signal *sig, int start_bit, int size) { + Signal s = *sig; + updateSigSizeParamsFromRange(s, start_bit, size); + saveSignal(sig, s); +} + +void DetailWidget::saveSignal(const Signal *sig, const Signal &new_sig) { + auto msg = dbc()->msg(msg_id); + if (new_sig.name != sig->name) { + auto it = msg->sigs.find(new_sig.name.c_str()); + if (it != msg->sigs.end()) { + QString warning_str = tr("There is already a signal with the same name '%1'").arg(new_sig.name.c_str()); + QMessageBox::warning(this, tr("Failed to save signal"), warning_str); + return; + } + } + auto [start, end] = getSignalRange(&new_sig); + if (start < 0 || end >= msg->size * 8) { + QString warning_str = tr("Signal size [%1] exceed limit").arg(new_sig.size); + QMessageBox::warning(this, tr("Failed to save signal"), warning_str); + return; + } + + undo_stack->push(new EditSignalCommand(msg_id, sig, new_sig)); +} + +void DetailWidget::removeSignal(const Signal *sig) { + undo_stack->push(new RemoveSigCommand(msg_id, sig)); +} + +// EditMessageDialog + +EditMessageDialog::EditMessageDialog(const QString &msg_id, const QString &title, int size, QWidget *parent) : QDialog(parent) { + setWindowTitle(tr("Edit message")); + QFormLayout *form_layout = new QFormLayout(this); + form_layout->addRow("ID", new QLabel(msg_id)); + + name_edit = new QLineEdit(title, this); + name_edit->setValidator(new QRegExpValidator(QRegExp("^(\\w+)"), name_edit)); + form_layout->addRow(tr("Name"), name_edit); + + size_spin = new QSpinBox(this); + // TODO: limit the maximum? + size_spin->setMinimum(1); + size_spin->setValue(size); + form_layout->addRow(tr("Size"), size_spin); + + auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + form_layout->addRow(buttonBox); + setFixedWidth(parent->width() * 0.9); + + connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); +} + +// WelcomeWidget + +WelcomeWidget::WelcomeWidget(QWidget *parent) : QWidget(parent) { + QVBoxLayout *main_layout = new QVBoxLayout(this); + main_layout->addStretch(0); + QLabel *logo = new QLabel("CABANA"); + logo->setAlignment(Qt::AlignCenter); + logo->setStyleSheet("font-size:50px;font-weight:bold;"); + main_layout->addWidget(logo); + + auto newShortcutRow = [](const QString &title, const QString &key) { + QHBoxLayout *hlayout = new QHBoxLayout(); + auto btn = new QToolButton(); + btn->setText(key); + btn->setEnabled(false); + hlayout->addWidget(new QLabel(title), 0, Qt::AlignRight); + hlayout->addWidget(btn, 0, Qt::AlignLeft); + return hlayout; + }; + + main_layout->addLayout(newShortcutRow("Pause", "Space")); + main_layout->addLayout(newShortcutRow("Help", "Alt + H")); + main_layout->addStretch(0); + + setStyleSheet("QLabel{color:darkGray;}"); +} + diff --git a/tools/cabana/detailwidget.h b/tools/cabana/detailwidget.h new file mode 100644 index 0000000000..91127c9b74 --- /dev/null +++ b/tools/cabana/detailwidget.h @@ -0,0 +1,62 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include "tools/cabana/binaryview.h" +#include "tools/cabana/chartswidget.h" +#include "tools/cabana/historylog.h" +#include "tools/cabana/signaledit.h" + +class EditMessageDialog : public QDialog { +public: + EditMessageDialog(const QString &msg_id, const QString &title, int size, QWidget *parent); + + QLineEdit *name_edit; + QSpinBox *size_spin; +}; + +class WelcomeWidget : public QWidget { +public: + WelcomeWidget(QWidget *parent); +}; + +class DetailWidget : public QWidget { + Q_OBJECT + +public: + DetailWidget(ChartsWidget *charts, QWidget *parent); + void setMessage(const QString &message_id); + void dbcMsgChanged(int show_form_idx = -1); + QUndoStack *undo_stack = nullptr; + +private: + void showForm(const Signal *sig); + void updateChartState(const QString &id, const Signal *sig, bool opened); + void showTabBarContextMenu(const QPoint &pt); + void addSignal(int start_bit, int size, bool little_endian); + void resizeSignal(const Signal *sig, int from, int to); + void saveSignal(const Signal *sig, const Signal &new_sig); + void removeSignal(const Signal *sig); + void editMsg(); + void removeMsg(); + void updateState(const QHash * msgs = nullptr); + + QString msg_id; + QLabel *name_label, *time_label, *warning_label; + QWidget *warning_widget; + QVBoxLayout *signals_layout; + QTabBar *tabbar; + QTabWidget *tab_widget; + QToolBar *toolbar; + QAction *remove_msg_act; + HistoryLog *history_log; + BinaryView *binary_view; + QScrollArea *scroll; + ChartsWidget *charts; + QStackedLayout *stacked_layout; + QList signal_list; +}; diff --git a/tools/cabana/generate_dbc_json.py b/tools/cabana/generate_dbc_json.py new file mode 100755 index 0000000000..cb122e2eb2 --- /dev/null +++ b/tools/cabana/generate_dbc_json.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python3 +import argparse +import json + +from selfdrive.car.car_helpers import get_interface_attr + + +def generate_dbc_json() -> str: + all_cars_by_brand = get_interface_attr("CAR_INFO") + all_dbcs_by_brand = get_interface_attr("DBC") + dbc_map = {car: all_dbcs_by_brand[brand][car]['pt'] for brand, cars in all_cars_by_brand.items() for car in cars if car != 'mock'} + return json.dumps(dict(sorted(dbc_map.items())), indent=2) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Generate mapping for all car fingerprints to DBC names and outputs json file", + formatter_class=argparse.ArgumentDefaultsHelpFormatter) + + parser.add_argument("--out", required=True, help="Generated json filepath") + args = parser.parse_args() + + with open(args.out, 'w') as f: + f.write(generate_dbc_json()) + print(f"Generated and written to {args.out}") diff --git a/tools/cabana/historylog.cc b/tools/cabana/historylog.cc new file mode 100644 index 0000000000..5457555db4 --- /dev/null +++ b/tools/cabana/historylog.cc @@ -0,0 +1,104 @@ +#include "tools/cabana/historylog.h" + +#include +#include + +// HistoryLogModel + +QVariant HistoryLogModel::data(const QModelIndex &index, int role) const { + if (role == Qt::DisplayRole) { + const auto &m = messages[index.row()]; + if (index.column() == 0) { + return QString::number(m.ts, 'f', 2); + } + return !sigs.empty() ? QString::number(get_raw_value((uint8_t *)m.dat.data(), m.dat.size(), *sigs[index.column() - 1])) + : toHex(m.dat); + } else if (role == Qt::FontRole && index.column() == 1 && sigs.empty()) { + return QFontDatabase::systemFont(QFontDatabase::FixedFont); + } + return {}; +} + +void HistoryLogModel::setMessage(const QString &message_id) { + beginResetModel(); + msg_id = message_id; + sigs.clear(); + messages.clear(); + if (auto dbc_msg = dbc()->msg(message_id)) { + sigs = dbc_msg->getSignals(); + } + endResetModel(); + updateState(); +} + +QVariant HistoryLogModel::headerData(int section, Qt::Orientation orientation, int role) const { + if (orientation == Qt::Horizontal) { + if (role == Qt::DisplayRole || role == Qt::ToolTipRole) { + if (section == 0) { + return "Time"; + } + return !sigs.empty() ? QString::fromStdString(sigs[section - 1]->name).replace('_', ' ') : "Data"; + } else if (role == Qt::BackgroundRole && section > 0 && !sigs.empty()) { + return QBrush(QColor(getColor(section - 1))); + } else if (role == Qt::ForegroundRole && section > 0 && !sigs.empty()) { + return QBrush(Qt::black); + } + } + return {}; +} + +void HistoryLogModel::updateState() { + int prev_row_count = messages.size(); + if (!msg_id.isEmpty()) { + messages = can->messages(msg_id); + } + int delta = messages.size() - prev_row_count; + if (delta > 0) { + beginInsertRows({}, prev_row_count, messages.size() - 1); + endInsertRows(); + } else if (delta < 0) { + beginRemoveRows({}, messages.size(), prev_row_count - 1); + endRemoveRows(); + } + if (!messages.empty()) { + emit dataChanged(index(0, 0), index(rowCount() - 1, columnCount() - 1), {Qt::DisplayRole}); + } +} + +// HeaderView + +QSize HeaderView::sectionSizeFromContents(int logicalIndex) const { + const QString text = model()->headerData(logicalIndex, this->orientation(), Qt::DisplayRole).toString(); + const QRect rect = fontMetrics().boundingRect(QRect(0, 0, sectionSize(logicalIndex), 1000), defaultAlignment(), text); + return rect.size() + QSize{10, 6}; +} + +void HeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const { + auto bg_role = model()->headerData(logicalIndex, Qt::Horizontal, Qt::BackgroundRole); + if (bg_role.isValid()) { + QPen pen(model()->headerData(logicalIndex, Qt::Horizontal, Qt::ForegroundRole).value(), 1); + painter->setPen(pen); + painter->fillRect(rect, bg_role.value()); + } + QString text = model()->headerData(logicalIndex, Qt::Horizontal, Qt::DisplayRole).toString(); + painter->drawText(rect.adjusted(5, 3, 5, 3), defaultAlignment(), text); +} + +// HistoryLog + +HistoryLog::HistoryLog(QWidget *parent) : QTableView(parent) { + model = new HistoryLogModel(this); + setModel(model); + setHorizontalHeader(new HeaderView(Qt::Horizontal, this)); + horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); + horizontalHeader()->setDefaultAlignment(Qt::AlignLeft | (Qt::Alignment)Qt::TextWordWrap); + horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents); + verticalHeader()->setVisible(false); + setFrameShape(QFrame::NoFrame); + setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); +} + +int HistoryLog::sizeHintForColumn(int column) const { + // sizeHintForColumn is only called for column 0 (ResizeToContents) + return itemDelegate()->sizeHint(viewOptions(), model->index(0, 0)).width() + 5; +} diff --git a/tools/cabana/historylog.h b/tools/cabana/historylog.h new file mode 100644 index 0000000000..9ca6f427c7 --- /dev/null +++ b/tools/cabana/historylog.h @@ -0,0 +1,41 @@ +#pragma once + +#include +#include + +#include "tools/cabana/canmessages.h" +#include "tools/cabana/dbcmanager.h" + +class HeaderView : public QHeaderView { +public: + HeaderView(Qt::Orientation orientation, QWidget *parent = nullptr) : QHeaderView(orientation, parent) {} + QSize sectionSizeFromContents(int logicalIndex) const override; + void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const; +}; + +class HistoryLogModel : public QAbstractTableModel { +public: + HistoryLogModel(QObject *parent) : QAbstractTableModel(parent) {} + void setMessage(const QString &message_id); + void updateState(); + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + int rowCount(const QModelIndex &parent = QModelIndex()) const override { return messages.size(); } + int columnCount(const QModelIndex &parent = QModelIndex()) const override { return std::max(1ul, sigs.size()) + 1; } + +private: + QString msg_id; + std::deque messages; + std::vector sigs; +}; + +class HistoryLog : public QTableView { +public: + HistoryLog(QWidget *parent); + void setMessage(const QString &message_id) { model->setMessage(message_id); } + void updateState() { model->updateState(); } + +private: + int sizeHintForColumn(int column) const override; + HistoryLogModel *model; +}; diff --git a/tools/cabana/mainwin.cc b/tools/cabana/mainwin.cc new file mode 100644 index 0000000000..70297f9978 --- /dev/null +++ b/tools/cabana/mainwin.cc @@ -0,0 +1,270 @@ +#include "tools/cabana/mainwin.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "tools/replay/util.h" + +static MainWindow *main_win = nullptr; +void qLogMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) { + if (type == QtDebugMsg) std::cout << msg.toStdString() << std::endl; + if (main_win) emit main_win->showMessage(msg, 0); +} + +MainWindow::MainWindow() : QMainWindow() { + setWindowTitle("Cabana"); + QWidget *central_widget = new QWidget(this); + QHBoxLayout *main_layout = new QHBoxLayout(central_widget); + main_layout->setContentsMargins(11, 11, 11, 0); + main_layout->setSpacing(0); + + splitter = new QSplitter(Qt::Horizontal, this); + splitter->setHandleWidth(11); + + // DBC file selector + QWidget *messages_container = new QWidget(this); + QVBoxLayout *messages_layout = new QVBoxLayout(messages_container); + messages_layout->setContentsMargins(0, 0, 0, 0); + dbc_combo = new QComboBox(this); + auto dbc_names = dbc()->allDBCNames(); + for (const auto &name : dbc_names) { + dbc_combo->addItem(QString::fromStdString(name)); + } + dbc_combo->model()->sort(0); + dbc_combo->setInsertPolicy(QComboBox::NoInsert); + messages_layout->addWidget(dbc_combo); + + messages_widget = new MessagesWidget(this); + messages_layout->addWidget(messages_widget); + splitter->addWidget(messages_container); + + charts_widget = new ChartsWidget(this); + detail_widget = new DetailWidget(charts_widget, this); + splitter->addWidget(detail_widget); + if (!settings.splitter_state.isEmpty()) { + splitter->restoreState(settings.splitter_state); + } + main_layout->addWidget(splitter); + + // right widgets + QWidget *right_container = new QWidget(this); + right_container->setFixedWidth(640); + r_layout = new QVBoxLayout(right_container); + r_layout->setContentsMargins(11, 0, 0, 0); + QHBoxLayout *right_hlayout = new QHBoxLayout(); + fingerprint_label = new QLabel(this); + right_hlayout->addWidget(fingerprint_label, 0, Qt::AlignLeft); + + // TODO: click to select another route. + right_hlayout->addWidget(new QLabel(can->routeName()), 0, Qt::AlignRight); + r_layout->addLayout(right_hlayout); + + video_widget = new VideoWidget(this); + r_layout->addWidget(video_widget, 0, Qt::AlignTop); + r_layout->addWidget(charts_widget, 1); + r_layout->addStretch(0); + main_layout->addWidget(right_container); + + setCentralWidget(central_widget); + createActions(); + createStatusBar(); + createShortcuts(); + + qRegisterMetaType("uint64_t"); + qRegisterMetaType("ReplyMsgType"); + installMessageHandler([this](ReplyMsgType type, const std::string msg) { + // use queued connection to recv the log messages from replay. + emit showMessage(QString::fromStdString(msg), 3000); + }); + installDownloadProgressHandler([this](uint64_t cur, uint64_t total, bool success) { + emit updateProgressBar(cur, total, success); + }); + + main_win = this; + qInstallMessageHandler(qLogMessageHandler); + QFile json_file("./car_fingerprint_to_dbc.json"); + if (json_file.open(QIODevice::ReadOnly)) { + fingerprint_to_dbc = QJsonDocument::fromJson(json_file.readAll()); + } + + QObject::connect(dbc_combo, SIGNAL(activated(const QString &)), SLOT(loadDBCFromName(const QString &))); + QObject::connect(this, &MainWindow::showMessage, statusBar(), &QStatusBar::showMessage); + QObject::connect(this, &MainWindow::updateProgressBar, this, &MainWindow::updateDownloadProgress); + QObject::connect(messages_widget, &MessagesWidget::msgSelectionChanged, detail_widget, &DetailWidget::setMessage); + QObject::connect(charts_widget, &ChartsWidget::dock, this, &MainWindow::dockCharts); + QObject::connect(charts_widget, &ChartsWidget::rangeChanged, video_widget, &VideoWidget::rangeChanged); + QObject::connect(can, &CANMessages::streamStarted, this, &MainWindow::loadDBCFromFingerprint); + QObject::connect(dbc(), &DBCManager::DBCFileChanged, [this]() { + detail_widget->undo_stack->clear(); + dbc_combo->setCurrentText(QFileInfo(dbc()->name()).baseName()); + setWindowTitle(tr("%1 - Cabana").arg(dbc()->name())); + }); + QObject::connect(detail_widget->undo_stack, &QUndoStack::indexChanged, [this](int index) { + setWindowTitle(tr("%1%2 - Cabana").arg(index > 0 ? "* " : "").arg(dbc()->name())); + }); +} + +void MainWindow::createActions() { + QMenu *file_menu = menuBar()->addMenu(tr("&File")); + file_menu->addAction(tr("Open DBC File..."), this, &MainWindow::loadDBCFromFile); + file_menu->addAction(tr("Load DBC From Clipboard"), this, &MainWindow::loadDBCFromClipboard); + file_menu->addSeparator(); + file_menu->addAction(tr("Save DBC As..."), this, &MainWindow::saveDBCToFile); + file_menu->addAction(tr("Copy DBC To Clipboard"), this, &MainWindow::saveDBCToClipboard); + file_menu->addSeparator(); + file_menu->addAction(tr("Settings..."), this, &MainWindow::setOption); + + QMenu *edit_menu = menuBar()->addMenu(tr("&Edit")); + auto undo_act = detail_widget->undo_stack->createUndoAction(this, tr("&Undo")); + undo_act->setShortcuts(QKeySequence::Undo); + edit_menu->addAction(undo_act); + auto redo_act = detail_widget->undo_stack->createRedoAction(this, tr("&Rndo")); + redo_act->setShortcuts(QKeySequence::Redo); + edit_menu->addAction(redo_act); + edit_menu->addSeparator(); + + QMenu *commands_menu = edit_menu->addMenu(tr("Command &List")); + auto undo_view = new QUndoView(detail_widget->undo_stack); + undo_view->setWindowTitle(tr("Command List")); + QWidgetAction *commands_act = new QWidgetAction(this); + commands_act->setDefaultWidget(undo_view); + commands_menu->addAction(commands_act); + + QMenu *help_menu = menuBar()->addMenu(tr("&Help")); + help_menu->addAction(tr("About &Qt"), qApp, &QApplication::aboutQt); +} + +void MainWindow::createStatusBar() { + progress_bar = new QProgressBar(); + progress_bar->setRange(0, 100); + progress_bar->setTextVisible(true); + progress_bar->setFixedSize({230, 16}); + progress_bar->setVisible(false); + statusBar()->addPermanentWidget(progress_bar); +} + +void MainWindow::createShortcuts() { + auto shortcut = new QShortcut(QKeySequence(Qt::Key_Space), this, nullptr, nullptr, Qt::ApplicationShortcut); + QObject::connect(shortcut, &QShortcut::activated, []() { can->pause(!can->isPaused()); }); + // TODO: add more shortcuts here. +} + +void MainWindow::loadDBCFromName(const QString &name) { + if (name != dbc()->name()) + dbc()->open(name); +} + +void MainWindow::loadDBCFromFile() { + QString file_name = QFileDialog::getOpenFileName(this, tr("Open File"), settings.last_dir, "DBC (*.dbc)"); + if (!file_name.isEmpty()) { + settings.last_dir = QFileInfo(file_name).absolutePath(); + QFile file(file_name); + if (file.open(QIODevice::ReadOnly)) { + auto dbc_name = QFileInfo(file_name).baseName(); + dbc()->open(dbc_name, file.readAll()); + } + } +} + +void MainWindow::loadDBCFromClipboard() { + QString dbc_str = QGuiApplication::clipboard()->text(); + dbc()->open("From Clipboard", dbc_str); + QMessageBox::information(this, tr("Load From Clipboard"), tr("DBC Successfully Loaded!")); +} + +void MainWindow::loadDBCFromFingerprint() { + auto fingerprint = can->carFingerprint(); + fingerprint_label->setText(fingerprint); + if (!fingerprint.isEmpty() && dbc()->name().isEmpty()) { + auto dbc_name = fingerprint_to_dbc[fingerprint]; + if (dbc_name != QJsonValue::Undefined) { + loadDBCFromName(dbc_name.toString()); + } + } +} + +void MainWindow::saveDBCToFile() { + QString file_name = QFileDialog::getSaveFileName(this, tr("Save File"), + QDir::cleanPath(settings.last_dir + "/untitled.dbc"), tr("DBC (*.dbc)")); + if (!file_name.isEmpty()) { + settings.last_dir = QFileInfo(file_name).absolutePath(); + QFile file(file_name); + if (file.open(QIODevice::WriteOnly)) { + file.write(dbc()->generateDBC().toUtf8()); + detail_widget->undo_stack->clear(); + } + } +} + +void MainWindow::saveDBCToClipboard() { + QGuiApplication::clipboard()->setText(dbc()->generateDBC()); + QMessageBox::information(this, tr("Copy To Clipboard"), tr("DBC Successfully copied!")); +} + +void MainWindow::updateDownloadProgress(uint64_t cur, uint64_t total, bool success) { + if (success && cur < total) { + progress_bar->setValue((cur / (double)total) * 100); + progress_bar->setFormat(tr("Downloading %p% (%1)").arg(formattedDataSize(total).c_str())); + progress_bar->show(); + } else { + progress_bar->hide(); + } +} + +void MainWindow::dockCharts(bool dock) { + if (dock && floating_window) { + floating_window->removeEventFilter(charts_widget); + r_layout->insertWidget(2, charts_widget, 1); + floating_window->deleteLater(); + floating_window = nullptr; + } else if (!dock && !floating_window) { + floating_window = new QWidget(this); + floating_window->setWindowFlags(Qt::Window); + floating_window->setWindowTitle("Charts - Cabana"); + floating_window->setLayout(new QVBoxLayout()); + floating_window->layout()->addWidget(charts_widget); + floating_window->installEventFilter(charts_widget); + floating_window->setMinimumSize(QGuiApplication::primaryScreen()->size() / 2); + floating_window->showMaximized(); + } +} + +void MainWindow::closeEvent(QCloseEvent *event) { + if (detail_widget->undo_stack->index() > 0) { + auto ret = QMessageBox::question(this, tr("Unsaved Changes"), + tr("Are you sure you want to exit without saving?\nAny unsaved changes will be lost."), + QMessageBox::Yes | QMessageBox::No); + if (ret == QMessageBox::No) { + event->ignore(); + return; + } + } + + main_win = nullptr; + if (floating_window) + floating_window->deleteLater(); + + settings.splitter_state = splitter->saveState(); + settings.save(); + QWidget::closeEvent(event); +} + +void MainWindow::setOption() { + SettingsDlg dlg(this); + dlg.exec(); +} diff --git a/tools/cabana/mainwin.h b/tools/cabana/mainwin.h new file mode 100644 index 0000000000..5d377c44ca --- /dev/null +++ b/tools/cabana/mainwin.h @@ -0,0 +1,54 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "tools/cabana/chartswidget.h" +#include "tools/cabana/detailwidget.h" +#include "tools/cabana/messageswidget.h" +#include "tools/cabana/videowidget.h" + +class MainWindow : public QMainWindow { + Q_OBJECT + +public: + MainWindow(); + void dockCharts(bool dock); + void showStatusMessage(const QString &msg, int timeout = 0) { statusBar()->showMessage(msg, timeout); } + +public slots: + void loadDBCFromName(const QString &name); + void loadDBCFromFingerprint(); + void loadDBCFromFile(); + void loadDBCFromClipboard(); + void saveDBCToFile(); + void saveDBCToClipboard(); + +signals: + void showMessage(const QString &msg, int timeout); + void updateProgressBar(uint64_t cur, uint64_t total, bool success); + +protected: + void createActions(); + void createStatusBar(); + void createShortcuts(); + void closeEvent(QCloseEvent *event) override; + void updateDownloadProgress(uint64_t cur, uint64_t total, bool success); + void setOption(); + + VideoWidget *video_widget; + MessagesWidget *messages_widget; + DetailWidget *detail_widget; + ChartsWidget *charts_widget; + QSplitter *splitter; + QWidget *floating_window = nullptr; + QVBoxLayout *r_layout; + QProgressBar *progress_bar; + QLabel *fingerprint_label; + QJsonDocument fingerprint_to_dbc; + QComboBox *dbc_combo; +}; diff --git a/tools/cabana/messageswidget.cc b/tools/cabana/messageswidget.cc new file mode 100644 index 0000000000..dbf87a3da2 --- /dev/null +++ b/tools/cabana/messageswidget.cc @@ -0,0 +1,140 @@ +#include "tools/cabana/messageswidget.h" + +#include +#include +#include +#include + +#include "tools/cabana/dbcmanager.h" + +MessagesWidget::MessagesWidget(QWidget *parent) : QWidget(parent) { + QVBoxLayout *main_layout = new QVBoxLayout(this); + main_layout->setContentsMargins(0, 0, 0, 0); + + // message filter + QLineEdit *filter = new QLineEdit(this); + filter->setClearButtonEnabled(true); + filter->setPlaceholderText(tr("filter messages")); + main_layout->addWidget(filter); + + // message table + table_widget = new QTableView(this); + model = new MessageListModel(this); + table_widget->setModel(model); + table_widget->setSelectionBehavior(QAbstractItemView::SelectRows); + table_widget->setSelectionMode(QAbstractItemView::SingleSelection); + table_widget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); + table_widget->setSortingEnabled(true); + table_widget->sortByColumn(0, Qt::AscendingOrder); + table_widget->setColumnWidth(0, 250); + table_widget->setColumnWidth(1, 80); + table_widget->setColumnWidth(2, 80); + table_widget->horizontalHeader()->setStretchLastSection(true); + table_widget->verticalHeader()->hide(); + main_layout->addWidget(table_widget); + + // signals/slots + QObject::connect(filter, &QLineEdit::textChanged, model, &MessageListModel::setFilterString); + QObject::connect(can, &CANMessages::msgsReceived, model, &MessageListModel::msgsReceived); + QObject::connect(dbc(), &DBCManager::DBCFileChanged, model, &MessageListModel::sortMessages); + QObject::connect(dbc(), &DBCManager::msgUpdated, model, &MessageListModel::sortMessages); + QObject::connect(dbc(), &DBCManager::msgRemoved, model, &MessageListModel::sortMessages); + QObject::connect(table_widget->selectionModel(), &QItemSelectionModel::currentChanged, [=](const QModelIndex ¤t, const QModelIndex &previous) { + if (current.isValid() && current.row() < model->msgs.size()) { + if (model->msgs[current.row()] != current_msg_id) { + current_msg_id = model->msgs[current.row()]; + emit msgSelectionChanged(current_msg_id); + } + } + }); + QObject::connect(model, &MessageListModel::modelReset, [this]() { + if (int row = model->msgs.indexOf(current_msg_id); row != -1) + table_widget->selectionModel()->setCurrentIndex(model->index(row, 0), QItemSelectionModel::Rows | QItemSelectionModel::ClearAndSelect); + }); +} + +// MessageListModel + +QVariant MessageListModel::headerData(int section, Qt::Orientation orientation, int role) const { + if (orientation == Qt::Horizontal && role == Qt::DisplayRole) + return (QString[]){"Name", "ID", "Freq", "Count", "Bytes"}[section]; + return {}; +} + +QVariant MessageListModel::data(const QModelIndex &index, int role) const { + if (role == Qt::DisplayRole) { + const auto &id = msgs[index.row()]; + auto &can_data = can->lastMessage(id); + switch (index.column()) { + case 0: return msgName(id); + case 1: return id; + case 2: return can_data.freq; + case 3: return can_data.count; + case 4: return toHex(can_data.dat); + } + } else if (role == Qt::FontRole && index.column() == columnCount() - 1) { + return QFontDatabase::systemFont(QFontDatabase::FixedFont); + } + return {}; +} + +void MessageListModel::setFilterString(const QString &string) { + filter_str = string; + bool search_id = filter_str.contains(':'); + msgs.clear(); + for (auto it = can->can_msgs.begin(); it != can->can_msgs.end(); ++it) { + if ((search_id ? it.key() : msgName(it.key())).contains(filter_str, Qt::CaseInsensitive)) + msgs.push_back(it.key()); + } + sortMessages(); +} + +void MessageListModel::sortMessages() { + beginResetModel(); + if (sort_column == 0) { + std::sort(msgs.begin(), msgs.end(), [this](auto &l, auto &r) { + bool ret = std::pair{msgName(l), l} < std::pair{msgName(r), r}; + return sort_order == Qt::AscendingOrder ? ret : !ret; + }); + } else if (sort_column == 1) { + std::sort(msgs.begin(), msgs.end(), [this](auto &l, auto &r) { + return sort_order == Qt::AscendingOrder ? l < r : l > r; + }); + } else if (sort_column == 2) { + std::sort(msgs.begin(), msgs.end(), [this](auto &l, auto &r) { + bool ret = std::pair{can->lastMessage(l).freq, l} < std::pair{can->lastMessage(r).freq, r}; + return sort_order == Qt::AscendingOrder ? ret : !ret; + }); + } else if (sort_column == 3) { + std::sort(msgs.begin(), msgs.end(), [this](auto &l, auto &r) { + bool ret = std::pair{can->lastMessage(l).count, l} < std::pair{can->lastMessage(r).count, r}; + return sort_order == Qt::AscendingOrder ? ret : !ret; + }); + } + endResetModel(); +} + +void MessageListModel::msgsReceived(const QHash *new_msgs) { + int prev_row_count = msgs.size(); + if (filter_str.isEmpty() && msgs.size() != can->can_msgs.size()) { + msgs = can->can_msgs.keys(); + } + if (msgs.size() != prev_row_count) { + sortMessages(); + return; + } + for (int i = 0; i < msgs.size(); ++i) { + if (new_msgs->contains(msgs[i])) { + for (int col = 2; col < columnCount(); ++col) + emit dataChanged(index(i, col), index(i, col), {Qt::DisplayRole}); + } + } +} + +void MessageListModel::sort(int column, Qt::SortOrder order) { + if (column != columnCount() - 1) { + sort_column = column; + sort_order = order; + sortMessages(); + } +} diff --git a/tools/cabana/messageswidget.h b/tools/cabana/messageswidget.h new file mode 100644 index 0000000000..3a42bed4be --- /dev/null +++ b/tools/cabana/messageswidget.h @@ -0,0 +1,41 @@ +#pragma once + +#include +#include + +#include "tools/cabana/canmessages.h" + +class MessageListModel : public QAbstractTableModel { +Q_OBJECT + +public: + MessageListModel(QObject *parent) : QAbstractTableModel(parent) {} + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + int columnCount(const QModelIndex &parent = QModelIndex()) const override { return 5; } + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; + int rowCount(const QModelIndex &parent = QModelIndex()) const override { return msgs.size(); } + void sort(int column, Qt::SortOrder order = Qt::AscendingOrder) override; + void setFilterString(const QString &string); + void msgsReceived(const QHash *new_msgs = nullptr); + void sortMessages(); + QStringList msgs; + +private: + QString filter_str; + int sort_column = 0; + Qt::SortOrder sort_order = Qt::AscendingOrder; +}; + +class MessagesWidget : public QWidget { + Q_OBJECT + +public: + MessagesWidget(QWidget *parent); +signals: + void msgSelectionChanged(const QString &message_id); + +protected: + QTableView *table_widget; + QString current_msg_id; + MessageListModel *model; +}; diff --git a/tools/cabana/settings.cc b/tools/cabana/settings.cc new file mode 100644 index 0000000000..c90830973b --- /dev/null +++ b/tools/cabana/settings.cc @@ -0,0 +1,90 @@ +#include "tools/cabana/settings.h" + +#include +#include +#include +#include + +// Settings +Settings settings; + +Settings::Settings() { + load(); +} + +void Settings::save() { + QSettings s("settings", QSettings::IniFormat); + s.setValue("fps", fps); + s.setValue("log_size", can_msg_log_size); + s.setValue("cached_segment", cached_segment_limit); + s.setValue("chart_height", chart_height); + s.setValue("max_chart_x_range", max_chart_x_range); + s.setValue("last_dir", last_dir); + s.setValue("splitter_state", splitter_state); +} + +void Settings::load() { + QSettings s("settings", QSettings::IniFormat); + fps = s.value("fps", 10).toInt(); + can_msg_log_size = s.value("log_size", 50).toInt(); + cached_segment_limit = s.value("cached_segment", 3).toInt(); + chart_height = s.value("chart_height", 200).toInt(); + max_chart_x_range = s.value("max_chart_x_range", 3 * 60).toInt(); + last_dir = s.value("last_dir", QDir::homePath()).toString(); + splitter_state = s.value("splitter_state").toByteArray(); +} + +// SettingsDlg + +SettingsDlg::SettingsDlg(QWidget *parent) : QDialog(parent) { + setWindowTitle(tr("Settings")); + QFormLayout *form_layout = new QFormLayout(this); + + fps = new QSpinBox(this); + fps->setRange(10, 100); + fps->setSingleStep(10); + fps->setValue(settings.fps); + form_layout->addRow("FPS", fps); + + log_size = new QSpinBox(this); + log_size->setRange(50, 500); + log_size->setSingleStep(10); + log_size->setValue(settings.can_msg_log_size); + form_layout->addRow(tr("Signal history log size"), log_size); + + cached_segment = new QSpinBox(this); + cached_segment->setRange(3, 60); + cached_segment->setSingleStep(1); + cached_segment->setValue(settings.cached_segment_limit); + form_layout->addRow(tr("Cached segments limit"), cached_segment); + + max_chart_x_range = new QSpinBox(this); + max_chart_x_range->setRange(1, 60); + max_chart_x_range->setSingleStep(1); + max_chart_x_range->setValue(settings.max_chart_x_range / 60); + form_layout->addRow(tr("Chart range (minutes)"), max_chart_x_range); + + chart_height = new QSpinBox(this); + chart_height->setRange(100, 500); + chart_height->setSingleStep(10); + chart_height->setValue(settings.chart_height); + form_layout->addRow(tr("Chart height"), chart_height); + + auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + form_layout->addRow(buttonBox); + + setFixedWidth(360); + connect(buttonBox, &QDialogButtonBox::accepted, this, &SettingsDlg::save); + connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); +} + +void SettingsDlg::save() { + settings.fps = fps->value(); + settings.can_msg_log_size = log_size->value(); + settings.cached_segment_limit = cached_segment->value(); + settings.chart_height = chart_height->value(); + settings.max_chart_x_range = max_chart_x_range->value() * 60; + settings.save(); + accept(); + emit settings.changed(); +} diff --git a/tools/cabana/settings.h b/tools/cabana/settings.h new file mode 100644 index 0000000000..ee6541798d --- /dev/null +++ b/tools/cabana/settings.h @@ -0,0 +1,41 @@ +#pragma once + +#include +#include +#include +#include + +class Settings : public QObject { + Q_OBJECT + +public: + Settings(); + void save(); + void load(); + + int fps = 10; + int can_msg_log_size = 50; + int cached_segment_limit = 3; + int chart_height = 200; + int max_chart_x_range = 3 * 60; // 3 minutes + QString last_dir; + QByteArray splitter_state; + +signals: + void changed(); +}; + +class SettingsDlg : public QDialog { + Q_OBJECT + +public: + SettingsDlg(QWidget *parent); + void save(); + QSpinBox *fps; + QSpinBox *log_size ; + QSpinBox *cached_segment; + QSpinBox *chart_height; + QSpinBox *max_chart_x_range; +}; + +extern Settings settings; diff --git a/tools/cabana/signaledit.cc b/tools/cabana/signaledit.cc new file mode 100644 index 0000000000..85476c2302 --- /dev/null +++ b/tools/cabana/signaledit.cc @@ -0,0 +1,279 @@ +#include "tools/cabana/signaledit.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "selfdrive/ui/qt/util.h" + +// SignalForm + +SignalForm::SignalForm(QWidget *parent) : QWidget(parent) { + QFormLayout *form_layout = new QFormLayout(this); + + name = new QLineEdit(); + name->setValidator(new QRegExpValidator(QRegExp("^(\\w+)"), name)); + form_layout->addRow(tr("Name"), name); + + size = new QSpinBox(); + size->setMinimum(1); + form_layout->addRow(tr("Size"), size); + + endianness = new QComboBox(); + endianness->addItems({"Little", "Big"}); + form_layout->addRow(tr("Endianness"), endianness); + + form_layout->addRow(tr("lsb"), lsb = new QLabel()); + form_layout->addRow(tr("msb"), msb = new QLabel()); + + sign = new QComboBox(); + sign->addItems({"Signed", "Unsigned"}); + form_layout->addRow(tr("sign"), sign); + + auto double_validator = new QDoubleValidator(this); + + factor = new QLineEdit(); + factor->setValidator(double_validator); + form_layout->addRow(tr("Factor"), factor); + + offset = new QLineEdit(); + offset->setValidator(double_validator); + form_layout->addRow(tr("Offset"), offset); + + // TODO: parse the following parameters in opendbc + unit = new QLineEdit(); + form_layout->addRow(tr("Unit"), unit); + comment = new QLineEdit(); + form_layout->addRow(tr("Comment"), comment); + min_val = new QLineEdit(); + min_val->setValidator(double_validator); + form_layout->addRow(tr("Minimum value"), min_val); + max_val = new QLineEdit(); + max_val->setValidator(double_validator); + form_layout->addRow(tr("Maximum value"), max_val); + val_desc = new QLineEdit(); + form_layout->addRow(tr("Value descriptions"), val_desc); + + QObject::connect(name, &QLineEdit::textEdited, this, &SignalForm::changed); + QObject::connect(factor, &QLineEdit::textEdited, this, &SignalForm::changed); + QObject::connect(offset, &QLineEdit::textEdited, this, &SignalForm::changed); + QObject::connect(sign, SIGNAL(activated(int)), SIGNAL(changed())); + QObject::connect(endianness, SIGNAL(activated(int)), SIGNAL(changed())); + QObject::connect(size, SIGNAL(valueChanged(int)), SIGNAL(changed())); +} + +// SignalEdit + +SignalEdit::SignalEdit(int index, QWidget *parent) : form_idx(index), QWidget(parent) { + QVBoxLayout *main_layout = new QVBoxLayout(this); + main_layout->setContentsMargins(0, 0, 0, 0); + main_layout->setSpacing(0); + + // title bar + auto title_bar = new QWidget(this); + title_bar->setFixedHeight(32); + QHBoxLayout *title_layout = new QHBoxLayout(title_bar); + title_layout->setContentsMargins(0, 0, 0, 0); + title_bar->setStyleSheet("QToolButton {width:15px;height:15px;font-size:15px}"); + color_label = new QLabel(this); + color_label->setFixedWidth(25); + color_label->setContentsMargins(5, 0, 0, 0); + title_layout->addWidget(color_label); + icon = new QLabel(this); + title_layout->addWidget(icon); + title = new ElidedLabel(this); + title->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); + title_layout->addWidget(title); + + plot_btn = new QToolButton(this); + plot_btn->setText("📈"); + plot_btn->setCheckable(true); + plot_btn->setAutoRaise(true); + title_layout->addWidget(plot_btn); + auto seek_btn = new QToolButton(this); + seek_btn->setText("🔍"); + seek_btn->setAutoRaise(true); + seek_btn->setToolTip(tr("Find signal values")); + title_layout->addWidget(seek_btn); + auto remove_btn = new QToolButton(this); + remove_btn->setAutoRaise(true); + remove_btn->setText("x"); + remove_btn->setToolTip(tr("Remove signal")); + title_layout->addWidget(remove_btn); + main_layout->addWidget(title_bar); + + // signal form + form = new SignalForm(this); + form->setVisible(false); + main_layout->addWidget(form); + + // bottom line + QFrame *hline = new QFrame(); + hline->setFrameShape(QFrame::HLine); + hline->setFrameShadow(QFrame::Sunken); + main_layout->addWidget(hline); + + save_timer = new QTimer(this); + save_timer->setInterval(300); + save_timer->setSingleShot(true); + save_timer->callOnTimeout(this, &SignalEdit::saveSignal); + + QObject::connect(title, &ElidedLabel::clicked, [this]() { emit showFormClicked(sig); }); + QObject::connect(plot_btn, &QToolButton::clicked, [this](bool checked) { + emit showChart(msg_id, sig, checked, QGuiApplication::keyboardModifiers() & Qt::ShiftModifier); + }); + QObject::connect(seek_btn, &QToolButton::clicked, [this]() { SignalFindDlg(msg_id, sig, this).exec(); }); + QObject::connect(remove_btn, &QToolButton::clicked, [this]() { emit remove(sig); }); + QObject::connect(form, &SignalForm::changed, [this]() { save_timer->start(); }); + setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); +} + +void SignalEdit::setSignal(const QString &message_id, const Signal *signal) { + sig = signal; + updateForm(msg_id == message_id && form->isVisible()); + msg_id = message_id; + color_label->setText(QString::number(form_idx + 1)); + color_label->setStyleSheet(QString("color:black; background-color:%2").arg(getColor(form_idx))); + title->setText(sig->name.c_str()); + show(); +} + +void SignalEdit::saveSignal() { + if (!sig || !form->changed_by_user) return; + + Signal s = *sig; + s.name = form->name->text().toStdString(); + s.size = form->size->text().toInt(); + s.offset = form->offset->text().toDouble(); + s.factor = form->factor->text().toDouble(); + s.is_signed = form->sign->currentIndex() == 0; + bool little_endian = form->endianness->currentIndex() == 0; + if (little_endian != s.is_little_endian) { + int start = std::floor(s.start_bit / 8); + if (little_endian) { + int end = std::floor((s.start_bit - s.size + 1) / 8); + s.start_bit = start == end ? s.start_bit - s.size + 1 : bigEndianStartBitsIndex(s.start_bit); + } else { + int end = std::floor((s.start_bit + s.size - 1) / 8); + s.start_bit = start == end ? s.start_bit + s.size - 1 : bigEndianBitIndex(s.start_bit); + } + s.is_little_endian = little_endian; + } + if (s.is_little_endian) { + s.lsb = s.start_bit; + s.msb = s.start_bit + s.size - 1; + } else { + s.lsb = bigEndianStartBitsIndex(bigEndianBitIndex(s.start_bit) + s.size - 1); + s.msb = s.start_bit; + } + if (s != *sig) + emit save(this->sig, s); +} + +void SignalEdit::setChartOpened(bool opened) { + plot_btn->setToolTip(opened ? tr("Close Plot") : tr("Show Plot\nSHIFT click to add to previous opened chart")); + plot_btn->setChecked(opened); +} + +void SignalEdit::updateForm(bool visible) { + if (visible && sig) { + form->changed_by_user = false; + if (form->name->text() != sig->name.c_str()) { + form->name->setText(sig->name.c_str()); + } + form->endianness->setCurrentIndex(sig->is_little_endian ? 0 : 1); + form->sign->setCurrentIndex(sig->is_signed ? 0 : 1); + form->factor->setText(QString::number(sig->factor)); + form->offset->setText(QString::number(sig->offset)); + form->msb->setText(QString::number(sig->msb)); + form->lsb->setText(QString::number(sig->lsb)); + form->size->setValue(sig->size); + form->changed_by_user = true; + } + form->setVisible(visible); + icon->setText(visible ? "▼ " : "> "); +} + +void SignalEdit::signalHovered(const Signal *s) { + auto color = sig == s ? "white" : "black"; + color_label->setStyleSheet(QString("color:%1; background-color:%2").arg(color).arg(getColor(form_idx))); +} + +void SignalEdit::enterEvent(QEvent *event) { + emit highlight(sig); + QWidget::enterEvent(event); +} + +void SignalEdit::leaveEvent(QEvent *event) { + emit highlight(nullptr); + QWidget::leaveEvent(event); +} + +// SignalFindDlg + +SignalFindDlg::SignalFindDlg(const QString &id, const Signal *signal, QWidget *parent) : QDialog(parent) { + setWindowTitle(tr("Find signal values")); + QVBoxLayout *main_layout = new QVBoxLayout(this); + + QHBoxLayout *h = new QHBoxLayout(); + h->addWidget(new QLabel(signal->name.c_str())); + QComboBox *comp_box = new QComboBox(); + comp_box->addItems({">", "=", "<"}); + h->addWidget(comp_box); + QLineEdit *value_edit = new QLineEdit("0", this); + value_edit->setValidator(new QDoubleValidator(-500000, 500000, 6, this)); + h->addWidget(value_edit, 1); + QPushButton *search_btn = new QPushButton(tr("Find"), this); + h->addWidget(search_btn); + main_layout->addLayout(h); + + QWidget *container = new QWidget(this); + QVBoxLayout *signals_layout = new QVBoxLayout(container); + QScrollArea *scroll = new QScrollArea(this); + scroll->setWidget(container); + scroll->setWidgetResizable(true); + scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + main_layout->addWidget(scroll); + + QObject::connect(search_btn, &QPushButton::clicked, [=]() { + clearLayout(signals_layout); + + CANMessages::FindFlags comp = CANMessages::EQ; + if (comp_box->currentIndex() == 0) { + comp = CANMessages::GT; + } else if (comp_box->currentIndex() == 2) { + comp = CANMessages::LT; + } + double value = value_edit->text().toDouble(); + + const int limit_results = 50; + auto values = can->findSignalValues(id, signal, value, comp, limit_results); + for (auto &v : values) { + QHBoxLayout *item_layout = new QHBoxLayout(); + item_layout->addWidget(new QLabel(QString::number(v.x(), 'f', 2))); + item_layout->addWidget(new QLabel(QString::number(v.y()))); + item_layout->addStretch(1); + + QPushButton *goto_btn = new QPushButton(tr("Goto"), this); + QObject::connect(goto_btn, &QPushButton::clicked, [sec = v.x()]() { can->seekTo(sec); }); + item_layout->addWidget(goto_btn); + signals_layout->addLayout(item_layout); + } + if (values.size() == limit_results) { + QFrame *hline = new QFrame(); + hline->setFrameShape(QFrame::HLine); + hline->setFrameShadow(QFrame::Sunken); + signals_layout->addWidget(hline); + QLabel *info = new QLabel(tr("Only display the first %1 results").arg(limit_results)); + info->setAlignment(Qt::AlignCenter); + signals_layout->addWidget(info); + } + if (values.size() * 30 > container->height()) { + scroll->setFixedHeight(std::min(values.size() * 30, 300)); + } + }); +} diff --git a/tools/cabana/signaledit.h b/tools/cabana/signaledit.h new file mode 100644 index 0000000000..205be4bb78 --- /dev/null +++ b/tools/cabana/signaledit.h @@ -0,0 +1,66 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include "selfdrive/ui/qt/widgets/controls.h" + +#include "tools/cabana/canmessages.h" +#include "tools/cabana/dbcmanager.h" + +class SignalForm : public QWidget { + Q_OBJECT +public: + SignalForm(QWidget *parent); + QLineEdit *name, *unit, *comment, *val_desc, *offset, *factor, *min_val, *max_val; + QLabel *lsb, *msb; + QSpinBox *size; + QComboBox *sign, *endianness; + bool changed_by_user = false; + + signals: + void changed(); +}; + +class SignalEdit : public QWidget { + Q_OBJECT + +public: + SignalEdit(int index, QWidget *parent = nullptr); + void setSignal(const QString &msg_id, const Signal *sig); + void setChartOpened(bool opened); + void signalHovered(const Signal *sig); + void updateForm(bool show); + const Signal *sig = nullptr; + SignalForm *form = nullptr; + QString msg_id; + +signals: + void highlight(const Signal *sig); + void showChart(const QString &name, const Signal *sig, bool show, bool merge); + void remove(const Signal *sig); + void save(const Signal *sig, const Signal &new_sig); + void showFormClicked(const Signal *sig); + +protected: + void enterEvent(QEvent *event) override; + void leaveEvent(QEvent *event) override; + void saveSignal(); + + ElidedLabel *title; + QLabel *color_label; + QLabel *icon; + int form_idx = 0; + QToolButton *plot_btn; + QTimer *save_timer; +}; + +class SignalFindDlg : public QDialog { +public: + SignalFindDlg(const QString &id, const Signal *signal, QWidget *parent); +}; diff --git a/tools/cabana/tests/test_cabana b/tools/cabana/tests/test_cabana new file mode 100755 index 0000000000..bac242fbdd --- /dev/null +++ b/tools/cabana/tests/test_cabana @@ -0,0 +1,4 @@ +#!/bin/sh +cd "$(dirname "$0")" +export LD_LIBRARY_PATH="../../../opendbc/can:$LD_LIBRARY_PATH" +exec ./_test_cabana "$1" diff --git a/tools/cabana/tests/test_cabana.cc b/tools/cabana/tests/test_cabana.cc new file mode 100644 index 0000000000..586422ffc8 --- /dev/null +++ b/tools/cabana/tests/test_cabana.cc @@ -0,0 +1,67 @@ + +#include "opendbc/can/common.h" +#undef INFO +#include "catch2/catch.hpp" +#include "tools/cabana/dbcmanager.h" +#include "tools/replay/logreader.h" + +// demo route, first segment +const std::string TEST_RLOG_URL = "https://commadata2.blob.core.windows.net/commadata2/4cf7a6ad03080c90/2021-09-29--13-46-36/0/rlog.bz2"; + +TEST_CASE("DBCManager::generateDBC") { + DBCManager dbc_origin(nullptr); + dbc_origin.open("toyota_new_mc_pt_generated"); + DBCManager dbc_from_generated(nullptr); + dbc_from_generated.open("", dbc_origin.generateDBC()); + + auto &msgs = dbc_origin.messages(); + auto &new_msgs = dbc_from_generated.messages(); + REQUIRE(msgs.size() == new_msgs.size()); + for (auto &[address, m] : msgs) { + auto new_m = new_msgs.at(address); + REQUIRE(m.name == new_m.name); + REQUIRE(m.size == new_m.size); + REQUIRE(m.sigs.size() == new_m.sigs.size()); + for (auto &[name, sig] : m.sigs) + REQUIRE(sig == new_m.sigs[name]); + } +} + +TEST_CASE("Parse can messages") { + DBCManager dbc(nullptr); + dbc.open("toyota_new_mc_pt_generated"); + CANParser can_parser(0, "toyota_new_mc_pt_generated", {}, {}); + + LogReader log; + REQUIRE(log.load(TEST_RLOG_URL, nullptr, {}, true)); + REQUIRE(log.events.size() > 0); + for (auto e : log.events) { + if (e->which == cereal::Event::Which::CAN) { + std::map, std::vector> values_1; + for (const auto &c : e->event.getCan()) { + const auto msg = dbc.msg(c.getAddress()); + if (c.getSrc() == 0 && msg) { + for (auto &[name, sig] : msg->sigs) { + double val = get_raw_value((uint8_t *)c.getDat().begin(), c.getDat().size(), sig); + values_1[{c.getAddress(), name.toStdString()}].push_back(val); + } + } + } + + can_parser.UpdateCans(e->mono_time, e->event.getCan()); + auto values_2 = can_parser.query_latest(); + for (auto &[key, v1] : values_1) { + bool found = false; + for (auto &v2 : values_2) { + if (v2.address == key.first && v2.name == key.second) { + REQUIRE(v2.all_values.size() == v1.size()); + REQUIRE(v2.all_values == v1); + found = true; + break; + } + } + REQUIRE(found); + } + } + } +} diff --git a/selfdrive/ui/replay/tests/test_runner.cc b/tools/cabana/tests/test_runner.cc similarity index 100% rename from selfdrive/ui/replay/tests/test_runner.cc rename to tools/cabana/tests/test_runner.cc diff --git a/tools/cabana/videowidget.cc b/tools/cabana/videowidget.cc new file mode 100644 index 0000000000..3e64d907ec --- /dev/null +++ b/tools/cabana/videowidget.cc @@ -0,0 +1,210 @@ +#include "tools/cabana/videowidget.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +inline QString formatTime(int seconds) { + return QDateTime::fromTime_t(seconds).toString(seconds > 60 * 60 ? "hh:mm:ss" : "mm:ss"); +} + +VideoWidget::VideoWidget(QWidget *parent) : QWidget(parent) { + QVBoxLayout *main_layout = new QVBoxLayout(this); + main_layout->setContentsMargins(0, 0, 0, 0); + + cam_widget = new CameraWidget("camerad", VISION_STREAM_ROAD, false, this); + cam_widget->setFixedSize(parent->width(), parent->width() / 1.596); + main_layout->addWidget(cam_widget); + + // slider controls + QHBoxLayout *slider_layout = new QHBoxLayout(); + QLabel *time_label = new QLabel("00:00"); + slider_layout->addWidget(time_label); + + slider = new Slider(this); + slider->setSingleStep(0); + slider_layout->addWidget(slider); + + end_time_label = new QLabel(this); + slider_layout->addWidget(end_time_label); + main_layout->addLayout(slider_layout); + + // btn controls + QHBoxLayout *control_layout = new QHBoxLayout(); + play_btn = new QPushButton("⏸"); + play_btn->setStyleSheet("font-weight:bold; height:16px"); + control_layout->addWidget(play_btn); + + QButtonGroup *group = new QButtonGroup(this); + group->setExclusive(true); + for (float speed : {0.1, 0.5, 1., 2.}) { + QPushButton *btn = new QPushButton(QString("%1x").arg(speed), this); + btn->setCheckable(true); + QObject::connect(btn, &QPushButton::clicked, [=]() { can->setSpeed(speed); }); + control_layout->addWidget(btn); + group->addButton(btn); + if (speed == 1.0) btn->setChecked(true); + } + main_layout->addLayout(control_layout); + + setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + + QObject::connect(can, &CANMessages::updated, this, &VideoWidget::updateState); + QObject::connect(slider, &QSlider::sliderReleased, [this]() { can->seekTo(slider->value() / 1000.0); }); + QObject::connect(slider, &QSlider::valueChanged, [=](int value) { time_label->setText(formatTime(value / 1000)); }); + QObject::connect(cam_widget, &CameraWidget::clicked, [this]() { pause(!can->isPaused()); }); + QObject::connect(play_btn, &QPushButton::clicked, [=]() { pause(!can->isPaused()); }); + QObject::connect(can, &CANMessages::streamStarted, [this]() { + end_time_label->setText(formatTime(can->totalSeconds())); + slider->setRange(0, can->totalSeconds() * 1000); + }); +} + +void VideoWidget::pause(bool pause) { + play_btn->setText(!pause ? "⏸" : "▶"); + can->pause(pause); +} + +void VideoWidget::rangeChanged(double min, double max, bool is_zoomed) { + if (!is_zoomed) { + min = 0; + max = can->totalSeconds(); + } + end_time_label->setText(formatTime(max)); + slider->setRange(min * 1000, max * 1000); +} + +void VideoWidget::updateState() { + if (!slider->isSliderDown()) + slider->setValue(can->currentSec() * 1000); +} + +// Slider +Slider::Slider(QWidget *parent) : QSlider(Qt::Horizontal, parent) { + QTimer *timer = new QTimer(this); + timer->setInterval(2000); + timer->callOnTimeout([this]() { + timeline = can->getTimeline(); + update(); + }); + setMouseTracking(true); + + QObject::connect(can, SIGNAL(streamStarted()), timer, SLOT(start())); + QObject::connect(can, &CANMessages::streamStarted, this, &Slider::streamStarted); +} + +void Slider::streamStarted() { + abort_load_thumbnail = true; + thumnail_future.waitForFinished(); + abort_load_thumbnail = false; + thumbnails.clear(); + thumnail_future = QtConcurrent::run(this, &Slider::loadThumbnails); +} + +void Slider::loadThumbnails() { + const auto segments = can->route()->segments(); + for (auto it = segments.rbegin(); it != segments.rend() && !abort_load_thumbnail; ++it) { + std::string qlog = it->second.qlog.toStdString(); + if (!qlog.empty()) { + LogReader log; + if (log.load(qlog, &abort_load_thumbnail, {cereal::Event::Which::THUMBNAIL}, true, 0, 3)) { + for (auto ev = log.events.cbegin(); ev != log.events.cend() && !abort_load_thumbnail; ++ev) { + auto thumb = (*ev)->event.getThumbnail(); + QString str = getThumbnailString(thumb.getThumbnail()); + std::lock_guard lk(thumbnail_lock); + thumbnails[thumb.getTimestampEof()] = str; + } + } + } + } +} + +QString Slider::getThumbnailString(const capnp::Data::Reader &data) { + QPixmap thumb; + if (thumb.loadFromData(data.begin(), data.size(), "jpeg")) { + thumb = thumb.scaled({thumb.width()/3, thumb.height()/3}, Qt::KeepAspectRatio); + thumbnail_size = thumb.size(); + QByteArray bytes; + QBuffer buffer(&bytes); + buffer.open(QIODevice::WriteOnly); + thumb.save(&buffer, "png"); + return QString("").arg(QString(bytes.toBase64())); + } + return {}; +} + +void Slider::sliderChange(QAbstractSlider::SliderChange change) { + if (change == QAbstractSlider::SliderValueChange) { + int x = width() * ((value() - minimum()) / double(maximum() - minimum())); + if (x != slider_x) { + slider_x = x; + update(); + } + } else { + QAbstractSlider::sliderChange(change); + } +} + +void Slider::paintEvent(QPaintEvent *ev) { + static const QColor colors[] = { + [(int)TimelineType::None] = QColor(111, 143, 175), + [(int)TimelineType::Engaged] = QColor(0, 163, 108), + [(int)TimelineType::UserFlag] = Qt::white, + [(int)TimelineType::AlertInfo] = Qt::green, + [(int)TimelineType::AlertWarning] = QColor(255, 195, 0), + [(int)TimelineType::AlertCritical] = QColor(199, 0, 57)}; + + QPainter p(this); + QRect r = rect().adjusted(0, 4, 0, -4); + p.fillRect(r, colors[(int)TimelineType::None]); + double min = minimum() / 1000.0; + double max = maximum() / 1000.0; + for (auto [begin, end, type] : timeline) { + if (begin > max || end < min) + continue; + r.setLeft(((std::max(min, (double)begin) - min) / (max - min)) * width()); + r.setRight(((std::min(max, (double)end) - min) / (max - min)) * width()); + p.fillRect(r, colors[(int)type]); + } + + QStyleOptionSlider opt; + opt.initFrom(this); + opt.minimum = minimum(); + opt.maximum = maximum(); + opt.subControls = QStyle::SC_SliderHandle; + opt.sliderPosition = value(); + style()->drawComplexControl(QStyle::CC_Slider, &opt, &p); +} + +void Slider::mousePressEvent(QMouseEvent *e) { + QSlider::mousePressEvent(e); + if (e->button() == Qt::LeftButton && !isSliderDown()) { + int value = minimum() + ((maximum() - minimum()) * e->x()) / width(); + setValue(value); + emit sliderReleased(); + } +} + +void Slider::mouseMoveEvent(QMouseEvent *e) { + QString thumb; + { + double seconds = (minimum() + e->pos().x() * ((maximum() - minimum()) / (double)width())) / 1000.0; + std::lock_guard lk(thumbnail_lock); + auto it = thumbnails.lowerBound((seconds + can->routeStartTime()) * 1e9); + if (it != thumbnails.end()) { + thumb = it.value(); + } + } + QPoint pt = mapToGlobal({e->pos().x() - thumbnail_size.width() / 2, -thumbnail_size.height() - 30}); + QToolTip::showText(pt, thumb, this, rect()); + QSlider::mouseMoveEvent(e); +} diff --git a/tools/cabana/videowidget.h b/tools/cabana/videowidget.h new file mode 100644 index 0000000000..ea62081a91 --- /dev/null +++ b/tools/cabana/videowidget.h @@ -0,0 +1,53 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include + +#include "selfdrive/ui/qt/widgets/cameraview.h" +#include "tools/cabana/canmessages.h" + +class Slider : public QSlider { + Q_OBJECT + +public: + Slider(QWidget *parent); + +private: + void mousePressEvent(QMouseEvent *e) override; + void mouseMoveEvent(QMouseEvent *e) override; + void sliderChange(QAbstractSlider::SliderChange change) override; + void paintEvent(QPaintEvent *ev) override; + void streamStarted(); + void loadThumbnails(); + QString getThumbnailString(const capnp::Data::Reader &data); + + int slider_x = -1; + std::vector> timeline; + std::mutex thumbnail_lock; + std::atomic abort_load_thumbnail = false; + QMap thumbnails; + QFuture thumnail_future; + QSize thumbnail_size = {}; +}; + +class VideoWidget : public QWidget { + Q_OBJECT + +public: + VideoWidget(QWidget *parnet = nullptr); + void rangeChanged(double min, double max, bool is_zommed); + +protected: + void updateState(); + void pause(bool pause); + + CameraWidget *cam_widget; + QLabel *end_time_label; + QPushButton *play_btn; + Slider *slider; +}; diff --git a/tools/camerastream/compressed_vipc.py b/tools/camerastream/compressed_vipc.py new file mode 100755 index 0000000000..cab11493f2 --- /dev/null +++ b/tools/camerastream/compressed_vipc.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +import av +import os +import sys +import argparse +import numpy as np +import multiprocessing +import time + +import cereal.messaging as messaging +from cereal.visionipc import VisionIpcServer, VisionStreamType + +W, H = 1928, 1208 +V4L2_BUF_FLAG_KEYFRAME = 8 + +def decoder(addr, sock_name, vipc_server, vst, nvidia): + print("start decoder for %s" % sock_name) + if nvidia: + os.environ["NV_LOW_LATENCY"] = "3" # both bLowLatency and CUVID_PKT_ENDOFPICTURE + sys.path += os.environ["LD_LIBRARY_PATH"].split(":") + import PyNvCodec as nvc # pylint: disable=import-error + + nvDec = nvc.PyNvDecoder(W, H, nvc.PixelFormat.NV12, nvc.CudaVideoCodec.HEVC, 0) + cc1 = nvc.ColorspaceConversionContext(nvc.ColorSpace.BT_709, nvc.ColorRange.JPEG) + conv_yuv = nvc.PySurfaceConverter(W, H, nvc.PixelFormat.NV12, nvc.PixelFormat.YUV420, 0) + nvDwn_yuv = nvc.PySurfaceDownloader(W, H, nvc.PixelFormat.YUV420, 0) + img_yuv = np.ndarray((H*W//2*3), dtype=np.uint8) + else: + codec = av.CodecContext.create("hevc", "r") + + os.environ["ZMQ"] = "1" + messaging.context = messaging.Context() + sock = messaging.sub_sock(sock_name, None, addr=addr, conflate=False) + cnt = 0 + last_idx = -1 + seen_iframe = False + + time_q = [] + while 1: + msgs = messaging.drain_sock(sock, wait_for_one=True) + for evt in msgs: + evta = getattr(evt, evt.which()) + if evta.idx.encodeId != 0 and evta.idx.encodeId != (last_idx+1): + print("DROP PACKET!") + last_idx = evta.idx.encodeId + if not seen_iframe and not (evta.idx.flags & V4L2_BUF_FLAG_KEYFRAME): + print("waiting for iframe") + continue + time_q.append(time.monotonic()) + network_latency = (int(time.time()*1e9) - evta.unixTimestampNanos)/1e6 + frame_latency = ((evta.idx.timestampEof/1e9) - (evta.idx.timestampSof/1e9))*1000 + process_latency = ((evt.logMonoTime/1e9) - (evta.idx.timestampEof/1e9))*1000 + + # put in header (first) + if not seen_iframe: + if nvidia: + nvDec.DecodeSurfaceFromPacket(np.frombuffer(evta.header, dtype=np.uint8)) + else: + codec.decode(av.packet.Packet(evta.header)) + seen_iframe = True + + if nvidia: + rawSurface = nvDec.DecodeSurfaceFromPacket(np.frombuffer(evta.data, dtype=np.uint8)) + if rawSurface.Empty(): + print("DROP SURFACE") + continue + convSurface = conv_yuv.Execute(rawSurface, cc1) + nvDwn_yuv.DownloadSingleSurface(convSurface, img_yuv) + else: + frames = codec.decode(av.packet.Packet(evta.data)) + if len(frames) == 0: + print("DROP SURFACE") + continue + assert len(frames) == 1 + img_yuv = frames[0].to_ndarray(format=av.video.format.VideoFormat('yuv420p')).flatten() + uv_offset = H*W + y = img_yuv[:uv_offset] + uv = img_yuv[uv_offset:].reshape(2, -1).ravel('F') + img_yuv = np.hstack((y, uv)) + + vipc_server.send(vst, img_yuv.data, cnt, int(time_q[0]*1e9), int(time.monotonic()*1e9)) + cnt += 1 + + pc_latency = (time.monotonic()-time_q[0])*1000 + time_q = time_q[1:] + print("%2d %4d %.3f %.3f roll %6.2f ms latency %6.2f ms + %6.2f ms + %6.2f ms = %6.2f ms" % (len(msgs), evta.idx.encodeId, evt.logMonoTime/1e9, evta.idx.timestampEof/1e6, frame_latency, process_latency, network_latency, pc_latency, process_latency+network_latency+pc_latency ), len(evta.data), sock_name) + +def main(addr, cams, nvidia=False): + vipc_server = VisionIpcServer("camerad") + for vst in cams.values(): + vipc_server.create_buffers(vst, 4, False, W, H) + vipc_server.start_listener() + + procs = [] + for k, v in cams.items(): + p = multiprocessing.Process(target=decoder, args=(addr, k, vipc_server, v, nvidia)) + p.start() + procs.append(p) + + for p in procs: + p.join() + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Decode video streams and broadcast on VisionIPC") + parser.add_argument("addr", help="Address of comma three") + parser.add_argument("--nvidia", action="store_true", help="Use nvidia instead of ffmpeg") + parser.add_argument("--cams", default="0,1,2", help="Cameras to decode") + args = parser.parse_args() + + all_cams = [ + ("roadEncodeData", VisionStreamType.VISION_STREAM_ROAD), + ("wideRoadEncodeData", VisionStreamType.VISION_STREAM_WIDE_ROAD), + ("driverEncodeData", VisionStreamType.VISION_STREAM_DRIVER), + ] + cams = dict([all_cams[int(x)] for x in args.cams.split(",")]) + main(args.addr, cams, args.nvidia) diff --git a/tools/camerastream/receive.py b/tools/camerastream/receive.py new file mode 100755 index 0000000000..6f8d67c78f --- /dev/null +++ b/tools/camerastream/receive.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python +import os +import sys +import numpy as np +os.environ['ZMQ'] = '1' + +from common.window import Window +import cereal.messaging as messaging + +# start camerad with 'SEND_ROAD=1 SEND_DRIVER=1 SEND_WIDE_ROAD=1 XMIN=771 XMAX=1156 YMIN=483 YMAX=724 ./camerad' +# also start bridge +# then run this "./receive.py " + +if "FULL" in os.environ: + SCALE = 2 + XMIN, XMAX = 0, 1927 + YMIN, YMAX = 0, 1207 +else: + SCALE = 1 + XMIN = 771 + XMAX = 1156 + YMIN = 483 + YMAX = 724 +H, W = ((YMAX-YMIN+1)//SCALE, (XMAX-XMIN+1)//SCALE) + +if __name__ == '__main__': + cameras = ['roadCameraState', 'wideRoadCameraState', 'driverCameraState'] + if "CAM" in os.environ: + cam = int(os.environ['CAM']) + cameras = cameras[cam:cam+1] + sm = messaging.SubMaster(cameras, addr=sys.argv[1]) + win = Window(W*len(cameras), H) + bdat = np.zeros((H, W*len(cameras), 3), dtype=np.uint8) + + while 1: + sm.update() + for i,k in enumerate(cameras): + if sm.updated[k]: + #print("update", k) + bgr_raw = sm[k].image + dat = np.frombuffer(bgr_raw, dtype=np.uint8).reshape(H, W, 3)[:, :, [2,1,0]] + bdat[:, W*i:W*(i+1)] = dat + win.draw(bdat) + diff --git a/tools/gpstest/.gitignore b/tools/gpstest/.gitignore new file mode 100644 index 0000000000..992088ef34 --- /dev/null +++ b/tools/gpstest/.gitignore @@ -0,0 +1,4 @@ +LimeGPS/ +LimeSuite/ +hackrf/ +gps-sdr-sim/ diff --git a/tools/gpstest/README.md b/tools/gpstest/README.md new file mode 100644 index 0000000000..5aff0ee3d7 --- /dev/null +++ b/tools/gpstest/README.md @@ -0,0 +1,36 @@ +# GPS test setup +Testing the GPS receiver using GPS spoofing. At the moment only +static location relpay is supported. + +# Usage +``` +# on host, start gps signal simulation +./run_static_lime.py +``` + +`run_static_lime.py` downloads the latest ephemeris file from +https://cddis.nasa.gov/archive/gnss/data/daily/20xx/brdc/. + + +# Hardware Setup +* [LimeSDR USB](https://wiki.myriadrf.org/LimeSDR-USB) +* Asus AX58BT antenna + +# Software Setup +* https://github.com/myriadrf/LimeSuite +To communicate with LimeSDR the LimeSuite is needed it abstracts the direct +communication. It also contains examples for a quick start. + +The latest stable version (22.09) does not have the corresponding firmware +download available at https://downloads.myriadrf.org/project/limesuite. Therefore +version 20.10 was chosen. + +* https://github.com/osqzss/LimeGPS +Built on top of LimeSuite (libLimeSuite.so.20.10-1), generates the GPS signal. + +``` +./LimeGPS -e -l + +# Example +./LimeGPS -e /pathTo/brdc2660.22n -l 47.202028,15.740394,100 +``` diff --git a/tools/gpstest/fuzzy_testing.py b/tools/gpstest/fuzzy_testing.py new file mode 100755 index 0000000000..df6691c558 --- /dev/null +++ b/tools/gpstest/fuzzy_testing.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python3 +import sys +import time +import random +import datetime as dt +import subprocess as sp +import multiprocessing +import threading +from typing import Tuple, Any + +from laika.downloader import download_nav +from laika.gps_time import GPSTime +from laika.helpers import ConstellationId + +cache_dir = '/tmp/gpstest/' + + +def download_rinex(): + # TODO: check if there is a better way to get the full brdc file for LimeGPS + gps_time = GPSTime.from_datetime(dt.datetime.utcnow()) + utc_time = dt.datetime.utcnow() - dt.timedelta(1) + gps_time = GPSTime.from_datetime(dt.datetime(utc_time.year, utc_time.month, utc_time.day)) + return download_nav(gps_time, cache_dir, ConstellationId.GPS) + + +def exec_LimeGPS_bin(rinex_file: str, location: str, duration: int): + # this functions should never return, cause return means, timeout is + # reached or it crashed + try: + cmd = ["LimeGPS/LimeGPS", "-e", rinex_file, "-l", location] + sp.check_output(cmd, timeout=duration) + except sp.TimeoutExpired: + print("LimeGPS timeout reached!") + except Exception as e: + print(f"LimeGPS crashed: {str(e)}") + + +def run_lime_gps(rinex_file: str, location: str, duration: int): + print(f"LimeGPS {location} {duration}") + + p = multiprocessing.Process(target=exec_LimeGPS_bin, + args=(rinex_file, location, duration)) + p.start() + return p + + +def get_random_coords(lat, lon) -> Tuple[int, int]: + # jump around the world + # max values, lat: -90 to 90, lon: -180 to 180 + + lat_add = random.random()*20 + 10 + lon_add = random.random()*20 + 20 + + lat = ((lat + lat_add + 90) % 180) - 90 + lon = ((lon + lon_add + 180) % 360) - 180 + return round(lat, 5), round(lon, 5) + +def get_continuous_coords(lat, lon) -> Tuple[int, int]: + # continuously move around the world + + lat_add = random.random()*0.01 + lon_add = random.random()*0.01 + + lat = ((lat + lat_add + 90) % 180) - 90 + lon = ((lon + lon_add + 180) % 360) - 180 + return round(lat, 5), round(lon, 5) + +rc_p: Any = None +def exec_remote_checker(lat, lon, duration, ip_addr): + global rc_p + # TODO: good enough for testing + remote_cmd = "export PYTHONPATH=/data/pythonpath:/data/pythonpath/pyextra && " + remote_cmd += "cd /data/openpilot && " + remote_cmd += f"timeout {duration} /usr/local/pyenv/shims/python tools/gpstest/remote_checker.py " + remote_cmd += f"{lat} {lon}" + + ssh_cmd = ["ssh", "-i", "/home/batman/openpilot/xx/phone/key/id_rsa", + f"comma@{ip_addr}"] + ssh_cmd += [remote_cmd] + + rc_p = sp.Popen(ssh_cmd, stdout=sp.PIPE) + rc_p.wait() + rc_output = rc_p.stdout.read() + print(f"Checker Result: {rc_output.strip().decode('utf-8')}") + + +def run_remote_checker(spoof_proc, lat, lon, duration, ip_addr) -> bool: + checker_thread = threading.Thread(target=exec_remote_checker, + args=(lat, lon, duration, ip_addr)) + checker_thread.start() + + tcnt = 0 + while True: + if not checker_thread.is_alive(): + # assume this only happens when the signal got matched + return True + + # the spoofing process has a timeout, kill checker if reached + if not spoof_proc.is_alive(): + rc_p.kill() + # spoofing process died, assume timeout + print("Spoofing process timeout") + return False + + print(f"Time elapsed: {tcnt}[s]", end = "\r") + time.sleep(1) + tcnt += 1 + + +def main(): + if len(sys.argv) < 2: + print(f"usage: {sys.argv[0]} [-c]") + ip_addr = sys.argv[1] + + continuous_mode = False + if len(sys.argv) == 3 and sys.argv[2] == '-c': + print("Continuous Mode!") + continuous_mode = True + + rinex_file = download_rinex() + + duration = 60*3 # max runtime in seconds + lat, lon = get_random_coords(47.2020, 15.7403) + + while True: + # spoof random location + spoof_proc = run_lime_gps(rinex_file, f"{lat},{lon},100", duration) + start_time = time.monotonic() + + # remote checker runs blocking + if not run_remote_checker(spoof_proc, lat, lon, duration, ip_addr): + # location could not be matched by ublox module + pass + + end_time = time.monotonic() + spoof_proc.terminate() + + # -1 to count process startup + print(f"Time to get Signal: {round(end_time - start_time - 1, 4)}") + + if continuous_mode: + lat, lon = get_continuous_coords(lat, lon) + else: + lat, lon = get_random_coords(lat, lon) + +if __name__ == "__main__": + main() diff --git a/tools/gpstest/patches/hackrf.patch b/tools/gpstest/patches/hackrf.patch new file mode 100644 index 0000000000..afc9ac437b --- /dev/null +++ b/tools/gpstest/patches/hackrf.patch @@ -0,0 +1,44 @@ +diff --git a/host/hackrf-tools/src/CMakeLists.txt b/host/hackrf-tools/src/CMakeLists.txt +index 7115151c..a51388ba 100644 +--- a/host/hackrf-tools/src/CMakeLists.txt ++++ b/host/hackrf-tools/src/CMakeLists.txt +@@ -23,20 +23,20 @@ + + set(INSTALL_DEFAULT_BINDIR "bin" CACHE STRING "Appended to CMAKE_INSTALL_PREFIX") + +-find_package(FFTW REQUIRED) +-include_directories(${FFTW_INCLUDES}) +-get_filename_component(FFTW_LIBRARY_DIRS ${FFTW_LIBRARIES} DIRECTORY) +-link_directories(${FFTW_LIBRARY_DIRS}) ++#find_package(FFTW REQUIRED) ++#include_directories(${FFTW_INCLUDES}) ++#get_filename_component(FFTW_LIBRARY_DIRS ${FFTW_LIBRARIES} DIRECTORY) ++#link_directories(${FFTW_LIBRARY_DIRS}) + + SET(TOOLS + hackrf_transfer +- hackrf_spiflash +- hackrf_cpldjtag ++ #hackrf_spiflash ++ #hackrf_cpldjtag + hackrf_info +- hackrf_debug +- hackrf_clock +- hackrf_sweep +- hackrf_operacake ++ #hackrf_debug ++ #hackrf_clock ++ #hackrf_sweep ++ #hackrf_operacake + ) + + if(MSVC) +@@ -45,7 +45,7 @@ if(MSVC) + ) + LIST(APPEND TOOLS_LINK_LIBS ${FFTW_LIBRARIES}) + else() +- LIST(APPEND TOOLS_LINK_LIBS m fftw3f) ++ LIST(APPEND TOOLS_LINK_LIBS m)# fftw3f) + endif() + + if(NOT libhackrf_SOURCE_DIR) diff --git a/tools/gpstest/patches/limeGPS/inc_ephem_array_size.patch b/tools/gpstest/patches/limeGPS/inc_ephem_array_size.patch new file mode 100644 index 0000000000..9a3525d346 --- /dev/null +++ b/tools/gpstest/patches/limeGPS/inc_ephem_array_size.patch @@ -0,0 +1,13 @@ +diff --git a/gpssim.h b/gpssim.h +index c30b227..2ae0802 100644 +--- a/gpssim.h ++++ b/gpssim.h +@@ -75,7 +75,7 @@ + #define SC08 (8) + #define SC16 (16) + +-#define EPHEM_ARRAY_SIZE (13) // for daily GPS broadcast ephemers file (brdc) ++#define EPHEM_ARRAY_SIZE (20) // for daily GPS broadcast ephemers file (brdc) + + /*! \brief Structure representing GPS time */ + typedef struct diff --git a/tools/gpstest/patches/limeGPS/makefile.patch b/tools/gpstest/patches/limeGPS/makefile.patch new file mode 100644 index 0000000000..f99ce551db --- /dev/null +++ b/tools/gpstest/patches/limeGPS/makefile.patch @@ -0,0 +1,11 @@ +diff --git a/makefile b/makefile +index 51bfabf..d0ea1eb 100644 +--- a/makefile ++++ b/makefile +@@ -1,5 +1,4 @@ + CC=gcc -O2 -Wall + + all: limegps.c gpssim.c +- $(CC) -o LimeGPS limegps.c gpssim.c -lm -lpthread -lLimeSuite +- ++ $(CC) -o LimeGPS limegps.c gpssim.c -lm -lpthread -lLimeSuite -I../LimeSuite/src -L../LimeSuite/builddir/src -Wl,-rpath="$(PWD)/../LimeSuite/builddir/src" diff --git a/tools/gpstest/patches/limeSuite/mcu_error.patch b/tools/gpstest/patches/limeSuite/mcu_error.patch new file mode 100644 index 0000000000..91790a4a2b --- /dev/null +++ b/tools/gpstest/patches/limeSuite/mcu_error.patch @@ -0,0 +1,13 @@ +diff --git a/src/lms7002m/LMS7002M_RxTxCalibrations.cpp b/src/lms7002m/LMS7002M_RxTxCalibrations.cpp +index 41a37044..ac29c6b6 100644 +--- a/src/lms7002m/LMS7002M_RxTxCalibrations.cpp ++++ b/src/lms7002m/LMS7002M_RxTxCalibrations.cpp +@@ -254,7 +254,7 @@ int LMS7002M::CalibrateTx(float_type bandwidth_Hz, bool useExtLoopback) + mcuControl->RunProcedure(useExtLoopback ? MCU_FUNCTION_CALIBRATE_TX_EXTLOOPB : MCU_FUNCTION_CALIBRATE_TX); + status = mcuControl->WaitForMCU(1000); + if(status != MCU_BD::MCU_NO_ERROR) +- return ReportError(EINVAL, "Tx Calibration: MCU error %i (%s)", status, MCU_BD::MCUStatusMessage(status)); ++ return -1; //ReportError(EINVAL, "Tx Calibration: MCU error %i (%s)", status, MCU_BD::MCUStatusMessage(status)); + } + + //sync registers to cache diff --git a/tools/gpstest/patches/limeSuite/reference_print.patch b/tools/gpstest/patches/limeSuite/reference_print.patch new file mode 100644 index 0000000000..5bd7cdf1ed --- /dev/null +++ b/tools/gpstest/patches/limeSuite/reference_print.patch @@ -0,0 +1,13 @@ +diff --git a/src/FPGA_common/FPGA_common.cpp b/src/FPGA_common/FPGA_common.cpp +index 4e81f33e..7381c475 100644 +--- a/src/FPGA_common/FPGA_common.cpp ++++ b/src/FPGA_common/FPGA_common.cpp +@@ -946,7 +946,7 @@ double FPGA::DetectRefClk(double fx3Clk) + + if (i == 0) + return -1; +- lime::info("Reference clock %1.2f MHz", clkTbl[i - 1] / 1e6); ++ //lime::info("Reference clock %1.2f MHz", clkTbl[i - 1] / 1e6); + return clkTbl[i - 1]; + } + diff --git a/tools/gpstest/remote_checker.py b/tools/gpstest/remote_checker.py new file mode 100644 index 0000000000..a649a105c3 --- /dev/null +++ b/tools/gpstest/remote_checker.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +import sys +import time +from typing import List + +from common.params import Params +import cereal.messaging as messaging +from selfdrive.manager.process_config import managed_processes + +DELTA = 0.001 +# assume running openpilot for now +procs: List[str] = []#"ubloxd", "pigeond"] + + +def main(): + if len(sys.argv) != 4: + print("args: ") + return + + quectel_mod = Params().get_bool("UbloxAvailable") + sol_lat = float(sys.argv[2]) + sol_lon = float(sys.argv[3]) + + for p in procs: + managed_processes[p].start() + time.sleep(0.5) # give time to startup + + socket = 'gpsLocation' if quectel_mod else 'gpsLocationExternal' + gps_sock = messaging.sub_sock(socket, timeout=0.1) + + # analyze until the location changed + while True: + events = messaging.drain_sock(gps_sock) + for e in events: + loc = e.gpsLocation if quectel_mod else e.gpsLocationExternal + lat = loc.latitude + lon = loc.longitude + + if abs(lat - sol_lat) < DELTA and abs(lon - sol_lon) < DELTA: + print("MATCH") + return + + time.sleep(0.1) + + for p in procs: + if not managed_processes[p].proc.is_alive(): + print(f"ERROR: '{p}' died") + return + + +if __name__ == "__main__": + main() + for p in procs: + managed_processes[p].stop() diff --git a/tools/gpstest/run_unittest.sh b/tools/gpstest/run_unittest.sh new file mode 100755 index 0000000000..e0ca017a6d --- /dev/null +++ b/tools/gpstest/run_unittest.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +# NOTE: can only run inside limeGPS test box! + +# run limeGPS with random static location +timeout 300 ./simulate_gps_signal.py 32.7518 -117.1962 & +gps_PID=$(ps -aux | grep -m 1 "timeout 300" | awk '{print $2}') + +echo "starting limeGPS..." +sleep 10 + +# run unit tests (skipped when module not present) +python -m unittest test_gps.py +python -m unittest test_gps_qcom.py + +kill $gps_PID diff --git a/tools/gpstest/setup.sh b/tools/gpstest/setup.sh new file mode 100755 index 0000000000..ddf41dd260 --- /dev/null +++ b/tools/gpstest/setup.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -e + +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" +cd $DIR + +if [ ! -d LimeSuite ]; then + git clone https://github.com/myriadrf/LimeSuite.git + cd LimeSuite + # checkout latest version which has firmware updates available + git checkout v20.10.0 + git apply ../patches/limeSuite/* + mkdir builddir && cd builddir + cmake -DCMAKE_BUILD_TYPE=Release .. + make -j4 + cd ../.. +fi + +if [ ! -d LimeGPS ]; then + git clone https://github.com/osqzss/LimeGPS.git + cd LimeGPS + git apply ../patches/limeGPS/* + make + cd .. +fi diff --git a/tools/gpstest/setup_hackrf.sh b/tools/gpstest/setup_hackrf.sh new file mode 100755 index 0000000000..e504ec9447 --- /dev/null +++ b/tools/gpstest/setup_hackrf.sh @@ -0,0 +1,21 @@ +#!/bin/bash +set -e + +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" +cd $DIR + +if [ ! -d gps-sdr-sim ]; then + git clone https://github.com/osqzss/gps-sdr-sim.git + cd gps-sdr-sim + make + cd .. +fi + +if [ ! -d hackrf ]; then + git clone https://github.com/greatscottgadgets/hackrf.git + cd hackrf/host + git apply ../../patches/hackrf.patch + cmake . + make +fi + diff --git a/tools/gpstest/simulate_gps_signal.py b/tools/gpstest/simulate_gps_signal.py new file mode 100755 index 0000000000..a6aca1c404 --- /dev/null +++ b/tools/gpstest/simulate_gps_signal.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +import os +import random +import argparse +import datetime as dt +import subprocess as sp +from typing import Tuple + +from laika.downloader import download_nav +from laika.gps_time import GPSTime +from laika.helpers import ConstellationId + +cache_dir = '/tmp/gpstest/' + + +def download_rinex(): + # TODO: check if there is a better way to get the full brdc file for LimeGPS + gps_time = GPSTime.from_datetime(dt.datetime.utcnow()) + utc_time = dt.datetime.utcnow() - dt.timedelta(1) + gps_time = GPSTime.from_datetime(dt.datetime(utc_time.year, utc_time.month, utc_time.day)) + return download_nav(gps_time, cache_dir, ConstellationId.GPS) + +def get_coords(lat, lon, s1, s2, o1=0, o2=0) -> Tuple[int, int]: + lat_add = random.random()*s1 + o1 + lon_add = random.random()*s2 + o2 + + lat = ((lat + lat_add + 90) % 180) - 90 + lon = ((lon + lon_add + 180) % 360) - 180 + return round(lat, 5), round(lon, 5) + +def get_continuous_coords(lat, lon) -> Tuple[int, int]: + # continuously move around the world + return get_coords(lat, lon, 0.01, 0.01) + +def get_random_coords(lat, lon) -> Tuple[int, int]: + # jump around the world + return get_coords(lat, lon, 20, 20, 10, 20) + +def run_limeSDR_loop(lat, lon, contin_sim, rinex_file, timeout): + while True: + try: + print(f"starting LimeGPS, Location: {lat},{lon}") + cmd = ["LimeGPS/LimeGPS", "-e", rinex_file, "-l", f"{lat},{lon},100"] + sp.check_output(cmd, stderr=sp.PIPE, timeout=timeout) + except KeyboardInterrupt: + print("stopping LimeGPS") + return + except sp.TimeoutExpired: + print("LimeGPS timeout reached!") + except Exception as e: + out_stderr = e.stderr.decode('utf-8')# pylint:disable=no-member + if "Device is busy." in out_stderr: + print("GPS simulation is already running, Device is busy!") + return + + print(f"LimeGPS crashed: {str(e)}") + print(f"stderr:\n{e.stderr.decode('utf-8')}")# pylint:disable=no-member + return + + if contin_sim: + lat, lon = get_continuous_coords(lat, lon) + else: + lat, lon = get_random_coords(lat, lon) + +def run_hackRF_loop(lat, lon, rinex_file, timeout): + + if timeout is not None: + print("no jump mode for hackrf!") + return + + try: + print(f"starting gps-sdr-sim, Location: {lat},{lon}") + # create 30second file and replay with hackrf endless + cmd = ["gps-sdr-sim/gps-sdr-sim", "-e", rinex_file, "-l", f"{lat},{lon},100", "-d", "30"] + sp.check_output(cmd, stderr=sp.PIPE, timeout=timeout) + # created in current working directory + except Exception: + print("Failed to generate gpssim.bin") + + try: + print("starting hackrf_transfer") + # create 30second file and replay with hackrf endless + cmd = ["hackrf/host/hackrf-tools/src/hackrf_transfer", "-t", "gpssim.bin", + "-f", "1575420000", "-s", "2600000", "-a", "1", "-R"] + sp.check_output(cmd, stderr=sp.PIPE, timeout=timeout) + except KeyboardInterrupt: + print("stopping hackrf_transfer") + return + except Exception as e: + print(f"hackrf_transfer crashed:{str(e)}") + + +def main(lat, lon, jump_sim, contin_sim, hackrf_mode): + + if hackrf_mode: + if not os.path.exists('hackrf'): + print("hackrf not found run 'setup_hackrf.sh' first") + return + + if not os.path.exists('gps-sdr-sim'): + print("gps-sdr-sim not found run 'setup_hackrf.sh' first") + return + + output = sp.check_output(["hackrf/host/hackrf-tools/src/hackrf_info"]) + if output.strip() == b"" or b"No HackRF boards found." in output: + print("No HackRF boards found!") + return + + else: + if not os.path.exists('LimeGPS'): + print("LimeGPS not found run 'setup.sh' first") + return + + if not os.path.exists('LimeSuite'): + print("LimeSuite not found run 'setup.sh' first") + return + + output = sp.check_output(["LimeSuite/builddir/LimeUtil/LimeUtil", "--find"]) + if output.strip() == b"": + print("No LimeSDR device found!") + return + print(f"Device: {output.strip().decode('utf-8')}") + + if lat == 0 and lon == 0: + lat, lon = get_random_coords(47.2020, 15.7403) + + rinex_file = download_rinex() + + timeout = None + if jump_sim: + timeout = 30 + + if not hackrf_mode: + run_limeSDR_loop(lat, lon, contin_sim, rinex_file, timeout) + else: + run_hackRF_loop(lat, lon, rinex_file, timeout) + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Simulate static [or random jumping] GPS signal.") + parser.add_argument("lat", type=float, nargs='?', default=0) + parser.add_argument("lon", type=float, nargs='?', default=0) + parser.add_argument("--jump", action="store_true", help="signal that jumps around the world") + parser.add_argument("--contin", action="store_true", help="continuously/slowly moving around the world") + parser.add_argument("--hackrf", action="store_true", help="hackrf mode (DEFAULT: LimeSDR)") + args = parser.parse_args() + main(args.lat, args.lon, args.jump, args.contin, args.hackrf) diff --git a/tools/gpstest/test_gps.py b/tools/gpstest/test_gps.py new file mode 100644 index 0000000000..8bc5dc89a8 --- /dev/null +++ b/tools/gpstest/test_gps.py @@ -0,0 +1,191 @@ +#!/usr/bin/env python3 +import time +import unittest +import struct + +from common.params import Params +import cereal.messaging as messaging +import selfdrive.sensord.pigeond as pd +from system.hardware import TICI +from selfdrive.test.helpers import with_processes + + +def read_events(service, duration_sec): + service_sock = messaging.sub_sock(service, timeout=0.1) + start_time_sec = time.monotonic() + events = [] + while time.monotonic() - start_time_sec < duration_sec: + events += messaging.drain_sock(service_sock) + time.sleep(0.1) + + assert len(events) != 0, f"No '{service}'events collected!" + return events + + +def create_backup(pigeon): + # controlled GNSS stop + pigeon.send(b"\xB5\x62\x06\x04\x04\x00\x00\x00\x08\x00\x16\x74") + + # store almanac in flash + pigeon.send(b"\xB5\x62\x09\x14\x04\x00\x00\x00\x00\x00\x21\xEC") + try: + if not pigeon.wait_for_ack(ack=pd.UBLOX_SOS_ACK, nack=pd.UBLOX_SOS_NACK): + assert False, "Could not store almanac" + except TimeoutError: + pass + + +def verify_ubloxgnss_data(socket: messaging.SubSocket, max_time: int): + start_time = 0 + end_time = 0 + events = messaging.drain_sock(socket) + assert len(events) != 0, "no ublxGnss measurements" + + for event in events: + if event.ubloxGnss.which() != "measurementReport": + continue + + if start_time == 0: + start_time = event.logMonoTime + + if event.ubloxGnss.measurementReport.numMeas != 0: + end_time = event.logMonoTime + break + + assert end_time != 0, "no ublox measurements received!" + + ttfm = (end_time - start_time)/1e9 + assert ttfm < max_time, f"Time to first measurement > {max_time}s, {ttfm}" + + # check for satellite count in measurements + sat_count = [] + end_id = events.index(event)# pylint:disable=undefined-loop-variable + for event in events[end_id:]: + if event.ubloxGnss.which() == "measurementReport": + sat_count.append(event.ubloxGnss.measurementReport.numMeas) + + num_sat = int(sum(sat_count)/len(sat_count)) + assert num_sat >= 5, f"Not enough satellites {num_sat} (TestBox setup!)" + + +def verify_gps_location(socket: messaging.SubSocket, max_time: int): + events = messaging.drain_sock(socket) + assert len(events) != 0, "no gpsLocationExternal measurements" + + start_time = events[0].logMonoTime + end_time = 0 + for event in events: + gps_valid = event.gpsLocationExternal.flags % 2 + + if gps_valid: + end_time = event.logMonoTime + break + + assert end_time != 0, "GPS location never converged!" + + ttfl = (end_time - start_time)/1e9 + assert ttfl < max_time, f"Time to first location > {max_time}s, {ttfl}" + + hacc = events[-1].gpsLocationExternal.accuracy + vacc = events[-1].gpsLocationExternal.verticalAccuracy + assert hacc < 20, f"Horizontal accuracy too high, {hacc}" + assert vacc < 45, f"Vertical accuracy too high, {vacc}" + + +def verify_time_to_first_fix(pigeon): + # get time to first fix from nav status message + nav_status = b"" + while True: + pigeon.send(b"\xb5\x62\x01\x03\x00\x00\x04\x0d") + nav_status = pigeon.receive() + if nav_status[:4] == b"\xb5\x62\x01\x03": + break + + values = struct.unpack(" 40s, {ttff}" + + +class TestGPS(unittest.TestCase): + @classmethod + def setUpClass(cls): + if not TICI: + raise unittest.SkipTest + + ublox_available = Params().get_bool("UbloxAvailable") + if not ublox_available: + raise unittest.SkipTest + + + def tearDown(self): + pd.set_power(False) + + @with_processes(['ubloxd']) + def test_a_ublox_reset(self): + + pigeon, pm = pd.create_pigeon() + pd.init_baudrate(pigeon) + assert pigeon.reset_device(), "Could not reset device!" + + pd.initialize_pigeon(pigeon) + + ugs = messaging.sub_sock("ubloxGnss", timeout=0.1) + gle = messaging.sub_sock("gpsLocationExternal", timeout=0.1) + + # receive some messages (restart after cold start takes up to 30seconds) + pd.run_receiving(pigeon, pm, 60) + + # store almanac for next test + create_backup(pigeon) + + verify_ubloxgnss_data(ugs, 60) + verify_gps_location(gle, 60) + + # skip for now, this might hang for a while + #verify_time_to_first_fix(pigeon) + + + @with_processes(['ubloxd']) + def test_b_ublox_almanac(self): + pigeon, pm = pd.create_pigeon() + pd.init_baudrate(pigeon) + + # device cold start + pigeon.send(b"\xb5\x62\x06\x04\x04\x00\xff\xff\x00\x00\x0c\x5d") + time.sleep(1) # wait for cold start + pd.init_baudrate(pigeon) + + # clear configuration + pigeon.send_with_ack(b"\xb5\x62\x06\x09\x0d\x00\x00\x00\x1f\x1f\x00\x00\x00\x00\x00\x00\x00\x00\x17\x71\x5b") + + # restoring almanac backup + pigeon.send(b"\xB5\x62\x09\x14\x00\x00\x1D\x60") + status = pigeon.wait_for_backup_restore_status() + assert status == 2, "Could not restore almanac backup" + + pd.initialize_pigeon(pigeon) + + ugs = messaging.sub_sock("ubloxGnss", timeout=0.1) + gle = messaging.sub_sock("gpsLocationExternal", timeout=0.1) + + pd.run_receiving(pigeon, pm, 15) + verify_ubloxgnss_data(ugs, 15) + verify_gps_location(gle, 20) + + + @with_processes(['ubloxd']) + def test_c_ublox_startup(self): + pigeon, pm = pd.create_pigeon() + pd.init_baudrate(pigeon) + pd.initialize_pigeon(pigeon) + + ugs = messaging.sub_sock("ubloxGnss", timeout=0.1) + gle = messaging.sub_sock("gpsLocationExternal", timeout=0.1) + pd.run_receiving(pigeon, pm, 10) + verify_ubloxgnss_data(ugs, 10) + verify_gps_location(gle, 10) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/gpstest/test_gps_qcom.py b/tools/gpstest/test_gps_qcom.py new file mode 100644 index 0000000000..b3ce93fc81 --- /dev/null +++ b/tools/gpstest/test_gps_qcom.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +import time +import unittest +import subprocess as sp + +from common.params import Params +from system.hardware import TICI +import cereal.messaging as messaging +from selfdrive.manager.process_config import managed_processes + + +def exec_mmcli(cmd): + cmd = "mmcli -m 0 " + cmd + p = sp.Popen(cmd, shell=True, stdout=sp.PIPE, stderr=sp.PIPE) + return p.communicate() + + +def wait_for_location(socket, timeout): + while True: + events = messaging.drain_sock(socket) + for event in events: + if event.gpsLocation.flags % 2: + return False + + timeout -= 1 + if timeout <= 0: + return True + + time.sleep(0.1) + continue + + +class TestGPS(unittest.TestCase): + @classmethod + def setUpClass(cls): + if not TICI: + raise unittest.SkipTest + + ublox_available = Params().get_bool("UbloxAvailable") + if ublox_available: + raise unittest.SkipTest + + def test_a_quectel_cold_start(self): + # delete assistance data to enforce cold start for GNSS + # testing shows that this takes up to 20min + + _, err = exec_mmcli("--command='AT+QGPSDEL=0'") + assert len(err) == 0, f"GPSDEL failed: {err}" + + managed_processes['rawgpsd'].start() + start_time = time.monotonic() + glo = messaging.sub_sock("gpsLocation", timeout=0.1) + + timeout = 10*60*3 # 3 minute + timedout = wait_for_location(glo, timeout) + managed_processes['rawgpsd'].stop() + + assert timedout is False, "Waiting for location timed out (3min)!" + + duration = time.monotonic() - start_time + assert duration < 60, f"Received GPS location {duration}!" + + + def test_b_quectel_startup(self): + managed_processes['rawgpsd'].start() + start_time = time.monotonic() + glo = messaging.sub_sock("gpsLocation", timeout=0.1) + + timeout = 10*60 # 1 minute + timedout = wait_for_location(glo, timeout) + managed_processes['rawgpsd'].stop() + + assert timedout is False, "Waiting for location timed out (3min)!" + + duration = time.monotonic() - start_time + assert duration < 60, f"Received GPS location {duration}!" + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/joystick/README.md b/tools/joystick/README.md index 5a45785db6..c74e51146c 100644 --- a/tools/joystick/README.md +++ b/tools/joystick/README.md @@ -45,6 +45,17 @@ In order to use a joystick over the network, we need to run joystickd locally fr tools/joystick/joystickd.py ``` +### Web joystick on your mobile device + +A browser-based virtual joystick designed for touch screens. Starts automatically when installed on comma body (non-car robotics platform). +For cars, start the web joystick service manually via SSH before starting the car. + +```shell +tools/joystick/web.py +``` + +After starting the car/body, open the web joystick app at this URL: `http://[comma three IP address]:5000` + --- Now start your car and openpilot should go into joystick mode with an alert on startup! The status of the axes will display on the alert, while button statuses print in the shell. diff --git a/tools/joystick/joystickd.py b/tools/joystick/joystickd.py index 5a86293441..b31dab83fe 100755 --- a/tools/joystick/joystickd.py +++ b/tools/joystick/joystickd.py @@ -1,9 +1,11 @@ #!/usr/bin/env python import os import argparse +import threading from inputs import get_gamepad import cereal.messaging as messaging +from common.realtime import Ratekeeper from common.numpy_fast import interp, clip from common.params import Params from tools.lib.kbhit import KBHit @@ -16,6 +18,8 @@ class Keyboard: self.axes_map = {'w': 'gb', 's': 'gb', 'a': 'steer', 'd': 'steer'} self.axes_values = {'gb': 0., 'steer': 0.} + self.axes_order = ['gb', 'steer'] + self.cancel = False def update(self): key = self.kb.getch().lower() @@ -34,52 +38,70 @@ class Keyboard: class Joystick: - def __init__(self): - self.min_axis_value = 0 - self.max_axis_value = 255 - self.cancel_button = 'BTN_TRIGGER' - self.axes_values = {'ABS_Y': 0., 'ABS_RZ': 0.} # gb, steer + def __init__(self, gamepad=False): + # TODO: find a way to get this from API, perhaps "inputs" doesn't support it + if gamepad: + self.cancel_button = 'BTN_NORTH' # (BTN_NORTH=X, ABS_RZ=Right Trigger) + accel_axis = 'ABS_Y' + steer_axis = 'ABS_RX' + else: + self.cancel_button = 'BTN_TRIGGER' + accel_axis = 'ABS_Y' + steer_axis = 'ABS_RZ' + self.min_axis_value = {accel_axis: 0., steer_axis: 0.} + self.max_axis_value = {accel_axis: 255., steer_axis: 255.} + self.axes_values = {accel_axis: 0., steer_axis: 0.} + self.axes_order = [accel_axis, steer_axis] + self.cancel = False def update(self): joystick_event = get_gamepad()[0] event = (joystick_event.code, joystick_event.state) - self.cancel = False - if event[0] == self.cancel_button and event[1] == 0: # state 0 is falling edge - self.cancel = True + if event[0] == self.cancel_button: + if event[1] == 1: + self.cancel = True + elif event[1] == 0: # state 0 is falling edge + self.cancel = False elif event[0] in self.axes_values: - self.max_axis_value = max(event[1], self.max_axis_value) - self.min_axis_value = min(event[1], self.min_axis_value) + self.max_axis_value[event[0]] = max(event[1], self.max_axis_value[event[0]]) + self.min_axis_value[event[0]] = min(event[1], self.min_axis_value[event[0]]) - norm = -interp(event[1], [self.min_axis_value, self.max_axis_value], [-1., 1.]) + norm = -interp(event[1], [self.min_axis_value[event[0]], self.max_axis_value[event[0]]], [-1., 1.]) self.axes_values[event[0]] = norm if abs(norm) > 0.05 else 0. # center can be noisy, deadzone of 5% else: return False return True -def joystick_thread(use_keyboard): - Params().put_bool('JoystickDebugMode', True) +def send_thread(joystick): joystick_sock = messaging.pub_sock('testJoystick') - joystick = Keyboard() if use_keyboard else Joystick() - + rk = Ratekeeper(100, print_delay_threshold=None) + while 1: + dat = messaging.new_message('testJoystick') + dat.testJoystick.axes = [joystick.axes_values[a] for a in joystick.axes_order] + dat.testJoystick.buttons = [joystick.cancel] + joystick_sock.send(dat.to_bytes()) + print('\n' + ', '.join(f'{name}: {round(v, 3)}' for name, v in joystick.axes_values.items())) + if "WEB" in os.environ: + import requests + requests.get("http://"+os.environ["WEB"]+":5000/control/%f/%f" % tuple([joystick.axes_values[a] for a in joystick.axes_order][::-1]), timeout=None) + rk.keep_time() + +def joystick_thread(joystick): + Params().put_bool('JoystickDebugMode', True) + threading.Thread(target=send_thread, args=(joystick,), daemon=True).start() while True: - ret = joystick.update() - if ret: - dat = messaging.new_message('testJoystick') - dat.testJoystick.axes = [joystick.axes_values[a] for a in joystick.axes_values] - dat.testJoystick.buttons = [joystick.cancel] - joystick_sock.send(dat.to_bytes()) - print('\n' + ', '.join(f'{name}: {round(v, 3)}' for name, v in joystick.axes_values.items())) - + joystick.update() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Publishes events from your joystick to control your car.\n' + 'openpilot must be offroad before starting joysticked.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--keyboard', action='store_true', help='Use your keyboard instead of a joystick') + parser.add_argument('--gamepad', action='store_true', help='Use gamepad configuration instead of joystick') args = parser.parse_args() - if not Params().get_bool("IsOffroad") and "ZMQ" not in os.environ: + if not Params().get_bool("IsOffroad") and "ZMQ" not in os.environ and "WEB" not in os.environ: print("The car must be off before running joystickd.") exit() @@ -93,4 +115,5 @@ if __name__ == '__main__': else: print('Using joystick, make sure to run cereal/messaging/bridge on your device if running over the network!') - joystick_thread(args.keyboard) + joystick = Keyboard() if args.keyboard else Joystick(args.gamepad) + joystick_thread(joystick) diff --git a/tools/joystick/web.py b/tools/joystick/web.py new file mode 100755 index 0000000000..5cba4e938d --- /dev/null +++ b/tools/joystick/web.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +import time +import threading +from flask import Flask + +import cereal.messaging as messaging + +app = Flask(__name__) +pm = messaging.PubMaster(['testJoystick']) + +index = """ + + + + + +
+ +""" + +@app.route("/") +def hello_world(): + return index + +last_send_time = time.monotonic() +@app.route("/control//") +def control(x, y): + global last_send_time + x,y = float(x), float(y) + x = max(-1, min(1, x)) + y = max(-1, min(1, y)) + dat = messaging.new_message('testJoystick') + dat.testJoystick.axes = [y,x] + dat.testJoystick.buttons = [False] + pm.send('testJoystick', dat) + last_send_time = time.monotonic() + return "" + +def handle_timeout(): + while 1: + this_time = time.monotonic() + if (last_send_time+0.5) < this_time: + #print("timeout, no web in %.2f s" % (this_time-last_send_time)) + dat = messaging.new_message('testJoystick') + dat.testJoystick.axes = [0,0] + dat.testJoystick.buttons = [False] + pm.send('testJoystick', dat) + time.sleep(0.1) + +def main(): + threading.Thread(target=handle_timeout, daemon=True).start() + app.run(host="0.0.0.0") + +if __name__ == '__main__': + main() diff --git a/tools/latencylogger/README.md b/tools/latencylogger/README.md new file mode 100644 index 0000000000..c40ec1b9ed --- /dev/null +++ b/tools/latencylogger/README.md @@ -0,0 +1,92 @@ +# LatencyLogger + +LatencyLogger is a tool to track the time from first pixel to actuation. Timestamps are printed in a table as well as plotted in a graph. Start openpilot with `LOG_TIMESTAMPS=1` set to enable the necessary logging. + +## Usage + +``` +$ python latency_logger.py -h +usage: latency_logger.py [-h] [--relative] [--demo] [--plot] [route_or_segment_name] + +A tool for analyzing openpilot's end-to-end latency + +positional arguments: + route_or_segment_name + The route to print (default: None) + +optional arguments: + -h, --help show this help message and exit + --relative Make timestamps relative to the start of each frame (default: False) + --demo Use the demo route instead of providing one (default: False) + --plot If a plot should be generated (default: False) + --offset Offset service to better visualize overlap (default: False) +``` +To timestamp an event, use `LOGT("msg")` in c++ code or `cloudlog.timestamp("msg")` in python code. If the print is warning for frameId assignment ambiguity, use `LOGT(frameId ,"msg")`. + +## Examples + +Timestamps are visualized as diamonds + +| | Relative | Absolute | +| ------------- | ------------- | ------------- | +| Inline | ![inrel](https://user-images.githubusercontent.com/42323981/170559939-465df3b1-bf87-46d5-b5ee-5cc87dc49470.png) | ![inabs](https://user-images.githubusercontent.com/42323981/170559985-a82f87e7-82c4-4e48-a348-4221568dd589.png) | +| Offset | ![offrel](https://user-images.githubusercontent.com/42323981/170559854-93fba90f-acc4-4d08-b317-d3f8fc649ea8.png) | ![offabs](https://user-images.githubusercontent.com/42323981/170559782-06ed5599-d4e3-4701-ad78-5c1eec6cb61e.png) | + +Printed timestamps of a frame with internal durations. +``` +Frame ID: 1202 + camerad + wideRoadCameraState start of frame 0.0 + roadCameraState start of frame 0.049583 + wideRoadCameraState published 35.01206 + WideRoadCamera: Image set 35.020028 + roadCameraState published 38.508261 + RoadCamera: Image set 38.520344 + RoadCamera: Transformed 38.616176 + wideRoadCameraState.processingTime 3.152403049170971 + roadCameraState.processingTime 6.453451234847307 + modeld + Image added 40.909841 + Extra image added 42.515027 + Execution finished 63.002552 + modelV2 published 63.148747 + modelV2.modelExecutionTime 23.62649142742157 + modelV2.gpuExecutionTime 0.0 + plannerd + lateralPlan published 66.915049 + longitudinalPlan published 69.715999 + lateralPlan.solverExecutionTime 0.8170719956979156 + longitudinalPlan.solverExecutionTime 0.5619999719783664 + controlsd + Data sampled 70.217763 + Events updated 71.037178 + sendcan published 72.278775 + controlsState published 72.825226 + Data sampled 80.008354 + Events updated 80.787666 + sendcan published 81.849682 + controlsState published 82.238323 + Data sampled 90.521123 + Events updated 91.626003 + sendcan published 93.413218 + controlsState published 94.143989 + Data sampled 100.991497 + Events updated 101.973774 + sendcan published 103.565575 + controlsState published 104.146088 + Data sampled 110.284387 + Events updated 111.183541 + sendcan published 112.981692 + controlsState published 113.731994 + boardd + sending sendcan to panda: 250027001751393037323631 81.928119 + sendcan sent to panda: 250027001751393037323631 82.164834 + sending sendcan to panda: 250027001751393037323631 93.569986 + sendcan sent to panda: 250027001751393037323631 93.92795 + sending sendcan to panda: 250027001751393037323631 103.689167 + sendcan sent to panda: 250027001751393037323631 104.012235 + sending sendcan to panda: 250027001751393037323631 113.109555 + sendcan sent to panda: 250027001751393037323631 113.525487 + sending sendcan to panda: 250027001751393037323631 122.508434 + sendcan sent to panda: 250027001751393037323631 122.834314 +``` diff --git a/tools/latencylogger/latency_logger.py b/tools/latencylogger/latency_logger.py new file mode 100755 index 0000000000..81a4790dea --- /dev/null +++ b/tools/latencylogger/latency_logger.py @@ -0,0 +1,244 @@ +#!/usr/bin/env python3 +import argparse +import json +import matplotlib.patches as mpatches +import matplotlib.pyplot as plt +import mpld3 +import sys +from bisect import bisect_left, bisect_right +from collections import defaultdict + +from tools.lib.logreader import logreader_from_route_or_segment + +DEMO_ROUTE = "9f583b1d93915c31|2022-05-18--10-49-51--0" + +SERVICES = ['camerad', 'modeld', 'plannerd', 'controlsd', 'boardd'] +# Retrieve controlsd frameId from lateralPlan, mismatch with longitudinalPlan will be ignored +MONOTIME_KEYS = ['modelMonoTime', 'lateralPlanMonoTime'] +MSGQ_TO_SERVICE = { + 'roadCameraState': 'camerad', + 'wideRoadCameraState': 'camerad', + 'modelV2': 'modeld', + 'lateralPlan': 'plannerd', + 'longitudinalPlan': 'plannerd', + 'sendcan': 'controlsd', + 'controlsState': 'controlsd' +} +SERVICE_TO_DURATIONS = { + 'camerad': ['processingTime'], + 'modeld': ['modelExecutionTime', 'gpuExecutionTime'], + 'plannerd': ['solverExecutionTime'], +} + +def read_logs(lr): + data = defaultdict(lambda: defaultdict(lambda: defaultdict(list))) + mono_to_frame = {} + frame_mismatches = [] + frame_id_fails = 0 + latest_sendcan_monotime = 0 + for msg in lr: + if msg.which() == 'sendcan': + latest_sendcan_monotime = msg.logMonoTime + continue + + if msg.which() in MSGQ_TO_SERVICE: + service = MSGQ_TO_SERVICE[msg.which()] + msg_obj = getattr(msg, msg.which()) + + frame_id = -1 + if hasattr(msg_obj, "frameId"): + frame_id = msg_obj.frameId + else: + continue_outer = False + for key in MONOTIME_KEYS: + if hasattr(msg_obj, key): + if getattr(msg_obj, key) == 0: + # Filter out controlsd messages which arrive before the camera loop + continue_outer = True + elif getattr(msg_obj, key) in mono_to_frame: + frame_id = mono_to_frame[getattr(msg_obj, key)] + if continue_outer: + continue + if frame_id == -1: + frame_id_fails += 1 + continue + mono_to_frame[msg.logMonoTime] = frame_id + data['timestamp'][frame_id][service].append((msg.which()+" published", msg.logMonoTime)) + + next_service = SERVICES[SERVICES.index(service)+1] + if not data['start'][frame_id][next_service]: + data['start'][frame_id][next_service] = msg.logMonoTime + data['end'][frame_id][service] = msg.logMonoTime + + if service in SERVICE_TO_DURATIONS: + for duration in SERVICE_TO_DURATIONS[service]: + data['duration'][frame_id][service].append((msg.which()+"."+duration, getattr(msg_obj, duration))) + + if service == SERVICES[0]: + data['timestamp'][frame_id][service].append((msg.which()+" start of frame", msg_obj.timestampSof)) + if not data['start'][frame_id][service]: + data['start'][frame_id][service] = msg_obj.timestampSof + elif msg.which() == 'controlsState': + # Sendcan is published before controlsState, but the frameId is retrieved in CS + data['timestamp'][frame_id][service].append(("sendcan published", latest_sendcan_monotime)) + elif msg.which() == 'modelV2': + if msg_obj.frameIdExtra != frame_id: + frame_mismatches.append(frame_id) + + if frame_id_fails > 20: + print("Warning, many frameId fetch fails", frame_id_fails) + if len(frame_mismatches) > 20: + print("Warning, many frame mismatches", len(frame_mismatches)) + return (data, frame_mismatches) + +# This is not needed in 3.10 as a "key" parameter is added to bisect +class KeyifyList(object): + def __init__(self, inner, key): + self.inner = inner + self.key = key + def __len__(self): + return len(self.inner) + def __getitem__(self, k): + return self.key(self.inner[k]) + +def find_frame_id(time, service, start_times, end_times): + left = bisect_left(KeyifyList(list(start_times.items()), + lambda x: x[1][service] if x[1][service] else -1), time) - 1 + right = bisect_right(KeyifyList(list(end_times.items()), + lambda x: x[1][service] if x[1][service] else float("inf")), time) + return left, right + +def find_t0(start_times, frame_id=-1): + frame_id = frame_id if frame_id > -1 else min(start_times.keys()) + m = max(start_times.keys()) + while frame_id <= m: + for service in SERVICES: + if start_times[frame_id][service]: + return start_times[frame_id][service] + frame_id += 1 + raise Exception('No start time has been set') + +def insert_cloudlogs(lr, timestamps, start_times, end_times): + # at least one cloudlog must be made in controlsd + + t0 = find_t0(start_times) + failed_inserts = 0 + latest_controls_frameid = 0 + for msg in lr: + if msg.which() == "logMessage": + jmsg = json.loads(msg.logMessage) + if "timestamp" in jmsg['msg']: + time = int(jmsg['msg']['timestamp']['time']) + service = jmsg['ctx']['daemon'] + event = jmsg['msg']['timestamp']['event'] + if time < t0: + # Filter out controlsd messages which arrive before the camera loop + continue + + if "frame_id" in jmsg['msg']['timestamp']: + timestamps[int(jmsg['msg']['timestamp']['frame_id'])][service].append((event, time)) + continue + + if service == "boardd": + timestamps[latest_controls_frameid][service].append((event, time)) + end_times[latest_controls_frameid][service] = time + else: + frame_id = find_frame_id(time, service, start_times, end_times) + if frame_id: + if frame_id[0] != frame_id[1]: + event += " (warning: ambiguity)" + frame_id = frame_id[0] + if service == 'controlsd': + latest_controls_frameid = frame_id + timestamps[frame_id][service].append((event, time)) + else: + failed_inserts += 1 + + if latest_controls_frameid == 0: + print("Warning: failed to bind boardd logs to a frame ID. Add a timestamp cloudlog in controlsd.") + elif failed_inserts > len(timestamps): + print(f"Warning: failed to bind {failed_inserts} cloudlog timestamps to a frame ID") + +def print_timestamps(timestamps, durations, start_times, relative): + t0 = find_t0(start_times) + for frame_id in timestamps.keys(): + print('='*80) + print("Frame ID:", frame_id) + if relative: + t0 = find_t0(start_times, frame_id) + + for service in SERVICES: + print(" "+service) + events = timestamps[frame_id][service] + for event, time in sorted(events, key = lambda x: x[1]): + print(" "+'%-53s%-53s' %(event, str((time-t0)/1e6))) + for event, time in durations[frame_id][service]: + print(" "+'%-53s%-53s' %(event, str(time*1000))) + +def graph_timestamps(timestamps, start_times, end_times, relative, offset_services=False, title=""): + # mpld3 doesn't convert properly to D3 font sizes + plt.rcParams.update({'font.size': 18}) + + t0 = find_t0(start_times) + fig, ax = plt.subplots() + ax.set_xlim(0, 130 if relative else 750) + ax.set_ylim(0, 17) + ax.set_xlabel('Time (milliseconds)') + colors = ['blue', 'green', 'red', 'yellow', 'purple'] + offsets = [[0, -5*j] for j in range(len(SERVICES))] if offset_services else None + height = 0.3 if offset_services else 0.9 + assert len(colors) == len(SERVICES), 'Each service needs a color' + + points = {"x": [], "y": [], "labels": []} + for i, (frame_id, services) in enumerate(timestamps.items()): + if relative: + t0 = find_t0(start_times, frame_id) + service_bars = [] + for service, events in services.items(): + if start_times[frame_id][service] and end_times[frame_id][service]: + start = start_times[frame_id][service] + end = end_times[frame_id][service] + service_bars.append(((start-t0)/1e6,(end-start)/1e6)) + for event in events: + points['x'].append((event[1]-t0)/1e6) + points['y'].append(i) + points['labels'].append(event[0]) + ax.broken_barh(service_bars, (i-height/2, height), facecolors=(colors), alpha=0.5, offsets=offsets) + + scatter = ax.scatter(points['x'], points['y'], marker='d', edgecolor='black') + tooltip = mpld3.plugins.PointLabelTooltip(scatter, labels=points['labels']) + mpld3.plugins.connect(fig, tooltip) + + plt.title(title) + # Set size relative window size is not trivial: https://github.com/mpld3/mpld3/issues/65 + fig.set_size_inches(18, 9) + plt.legend(handles=[mpatches.Patch(color=colors[i], label=SERVICES[i]) for i in range(len(SERVICES))]) + return fig + +def get_timestamps(lr): + lr = list(lr) + data, frame_mismatches = read_logs(lr) + insert_cloudlogs(lr, data['timestamp'], data['start'], data['end']) + return data, frame_mismatches + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="A tool for analyzing openpilot's end-to-end latency", + formatter_class = argparse.ArgumentDefaultsHelpFormatter) + parser.add_argument("--relative", action="store_true", help="Make timestamps relative to the start of each frame") + parser.add_argument("--demo", action="store_true", help="Use the demo route instead of providing one") + parser.add_argument("--plot", action="store_true", help="If a plot should be generated") + parser.add_argument("--offset", action="store_true", help="Vertically offset service to better visualize overlap") + parser.add_argument("route_or_segment_name", nargs='?', help="The route to print") + + if len(sys.argv) == 1: + parser.print_help() + sys.exit() + args = parser.parse_args() + + r = DEMO_ROUTE if args.demo else args.route_or_segment_name.strip() + lr = logreader_from_route_or_segment(r, sort_by_time=True) + + data, _ = get_timestamps(lr) + print_timestamps(data['timestamp'], data['duration'], data['start'], args.relative) + if args.plot: + mpld3.show(graph_timestamps(data['timestamp'], data['start'], data['end'], args.relative, offset_services=args.offset, title=r)) diff --git a/tools/lib/README.md b/tools/lib/README.md index c681809eae..3cf239d2df 100644 --- a/tools/lib/README.md +++ b/tools/lib/README.md @@ -1,6 +1,6 @@ ## LogReader -Route is a class for conviently accessing all the [logs](/selfdrive/loggerd/) from your routes. The LogReader class reads the non-video logs, i.e. rlog.bz2 and qlog.bz2. There's also a matching FrameReader class for reading the videos. +Route is a class for conveniently accessing all the [logs](/selfdrive/loggerd/) from your routes. The LogReader class reads the non-video logs, i.e. rlog.bz2 and qlog.bz2. There's also a matching FrameReader class for reading the videos. ```python from tools.lib.route import Route @@ -31,3 +31,21 @@ for msg in lr: if msg.which() == "carState": print(msg.carState.steeringAngleDeg) ``` + +### MultiLogIterator + +`MultiLogIterator` is similar to `LogReader`, but reads multiple logs. + +```python +from tools.lib.route import Route +from tools.lib.logreader import MultiLogIterator + +# setup a MultiLogIterator to read all the logs in the route +r = Route("4cf7a6ad03080c90|2021-09-29--13-46-36") +lr = MultiLogIterator(r.log_paths()) + +# print all the steering angles values from all the logs in the route +for msg in lr: + if msg.which() == "carState": + print(msg.carState.steeringAngleDeg) +``` diff --git a/tools/lib/auth.py b/tools/lib/auth.py index 0e9e7705b5..086027968f 100755 --- a/tools/lib/auth.py +++ b/tools/lib/auth.py @@ -46,8 +46,8 @@ class ClientRedirectHandler(BaseHTTPRequestHandler): return query = self.path.split('?', 1)[-1] - query = parse_qs(query, keep_blank_values=True) - self.server.query_params = query + query_parsed = parse_qs(query, keep_blank_values=True) + self.server.query_params = query_parsed self.send_response(200) self.send_header('Content-type', 'text/plain') @@ -86,13 +86,13 @@ def auth_redirect_link(method): }) return 'https://github.com/login/oauth/authorize?' + urlencode(params) elif method == 'apple': - params.update({ - 'client_id': 'ai.comma.login', - 'response_type': 'code', - 'response_mode': 'form_post', - 'scope': 'name email', - }) - return 'https://appleid.apple.com/auth/authorize?' + urlencode(params) + params.update({ + 'client_id': 'ai.comma.login', + 'response_type': 'code', + 'response_mode': 'form_post', + 'scope': 'name email', + }) + return 'https://appleid.apple.com/auth/authorize?' + urlencode(params) else: raise NotImplementedError(f"no redirect implemented for method {method}") diff --git a/tools/lib/auth_config.py b/tools/lib/auth_config.py index 1699d94e53..7952fee495 100644 --- a/tools/lib/auth_config.py +++ b/tools/lib/auth_config.py @@ -1,7 +1,7 @@ import json import os from common.file_helpers import mkdirs_exists_ok -from selfdrive.hardware import PC +from system.hardware import PC class MissingAuthConfigError(Exception): diff --git a/tools/lib/bootlog.py b/tools/lib/bootlog.py index dc1cf35c52..1e474e5dde 100644 --- a/tools/lib/bootlog.py +++ b/tools/lib/bootlog.py @@ -1,6 +1,7 @@ import datetime import functools import re +from typing import List, Optional from tools.lib.auth_config import get_token from tools.lib.api import CommaApi @@ -35,14 +36,28 @@ class Bootlog: def datetime(self) -> datetime.datetime: return timestamp_to_datetime(self._timestamp) + def __str__(self): + return f"{self._dongle_id}|{self._timestamp}" + def __eq__(self, b) -> bool: + if not isinstance(b, Bootlog): + return False return self.datetime == b.datetime def __lt__(self, b) -> bool: + if not isinstance(b, Bootlog): + return False return self.datetime < b.datetime +def get_bootlog_from_id(bootlog_id: str) -> Optional[Bootlog]: + # TODO: implement an API endpoint for this + bl = Bootlog(bootlog_id) + for b in get_bootlogs(bl.dongle_id): + if b == bl: + return b + return None -def get_bootlogs(dongle_id: str): +def get_bootlogs(dongle_id: str) -> List[Bootlog]: api = CommaApi(get_token()) r = api.get(f'v1/devices/{dongle_id}/bootlogs') return [Bootlog(b) for b in r] diff --git a/tools/lib/filereader.py b/tools/lib/filereader.py index 4ea9ad4290..215f7b2185 100644 --- a/tools/lib/filereader.py +++ b/tools/lib/filereader.py @@ -1,7 +1,7 @@ import os from tools.lib.url_file import URLFile -DATA_ENDPOINT = os.getenv("DATA_ENDPOINT", "http://data-raw.internal/") +DATA_ENDPOINT = os.getenv("DATA_ENDPOINT", "http://data-raw.comma.internal/") def FileReader(fn, debug=False): if fn.startswith("cd:/"): diff --git a/tools/lib/framereader.py b/tools/lib/framereader.py index bdf48bb438..d9920ab128 100644 --- a/tools/lib/framereader.py +++ b/tools/lib/framereader.py @@ -185,20 +185,28 @@ def read_file_check_size(f, sz, cookie): return buff -def rgb24toyuv420(rgb): +def rgb24toyuv(rgb): yuv_from_rgb = np.array([[ 0.299 , 0.587 , 0.114 ], [-0.14714119, -0.28886916, 0.43601035 ], [ 0.61497538, -0.51496512, -0.10001026 ]]) img = np.dot(rgb.reshape(-1, 3), yuv_from_rgb.T).reshape(rgb.shape) - y_len = img.shape[0] * img.shape[1] - uv_len = y_len // 4 + ys = img[:, :, 0] us = (img[::2, ::2, 1] + img[1::2, ::2, 1] + img[::2, 1::2, 1] + img[1::2, 1::2, 1]) / 4 + 128 vs = (img[::2, ::2, 2] + img[1::2, ::2, 2] + img[::2, 1::2, 2] + img[1::2, 1::2, 2]) / 4 + 128 - yuv420 = np.empty(y_len + 2 * uv_len, dtype=img.dtype) + return ys, us, vs + + +def rgb24toyuv420(rgb): + ys, us, vs = rgb24toyuv(rgb) + + y_len = rgb.shape[0] * rgb.shape[1] + uv_len = y_len // 4 + + yuv420 = np.empty(y_len + 2 * uv_len, dtype=rgb.dtype) yuv420[:y_len] = ys.reshape(-1) yuv420[y_len:y_len + uv_len] = us.reshape(-1) yuv420[y_len + uv_len:y_len + 2 * uv_len] = vs.reshape(-1) @@ -206,6 +214,20 @@ def rgb24toyuv420(rgb): return yuv420.clip(0, 255).astype('uint8') +def rgb24tonv12(rgb): + ys, us, vs = rgb24toyuv(rgb) + + y_len = rgb.shape[0] * rgb.shape[1] + uv_len = y_len // 4 + + nv12 = np.empty(y_len + 2 * uv_len, dtype=rgb.dtype) + nv12[:y_len] = ys.reshape(-1) + nv12[y_len::2] = us.reshape(-1) + nv12[y_len+1::2] = vs.reshape(-1) + + return nv12.clip(0, 255).astype('uint8') + + def decompress_video_data(rawdat, vid_fmt, w, h, pix_fmt): # using a tempfile is much faster than proc.communicate for some reason @@ -237,6 +259,8 @@ def decompress_video_data(rawdat, vid_fmt, w, h, pix_fmt): if pix_fmt == "rgb24": ret = np.frombuffer(dat, dtype=np.uint8).reshape(-1, h, w, 3) + elif pix_fmt == "nv12": + ret = np.frombuffer(dat, dtype=np.uint8).reshape(-1, (h*w*3//2)) elif pix_fmt == "yuv420p": ret = np.frombuffer(dat, dtype=np.uint8).reshape(-1, (h*w*3//2)) elif pix_fmt == "yuv444p": @@ -304,7 +328,7 @@ class RawFrameReader(BaseFrameReader): assert self.frame_count is not None assert num+count <= self.frame_count - if pix_fmt not in ("yuv420p", "rgb24"): + if pix_fmt not in ("nv12", "yuv420p", "rgb24"): raise ValueError(f"Unsupported pixel format {pix_fmt!r}") app = [] @@ -313,6 +337,8 @@ class RawFrameReader(BaseFrameReader): rgb_dat = self.load_and_debayer(dat) if pix_fmt == "rgb24": app.append(rgb_dat) + elif pix_fmt == "nv12": + app.append(rgb24tonv12(rgb_dat)) elif pix_fmt == "yuv420p": app.append(rgb24toyuv420(rgb_dat)) else: @@ -329,7 +355,7 @@ class VideoStreamDecompressor: self.h = h self.pix_fmt = pix_fmt - if pix_fmt == "yuv420p": + if pix_fmt in ("nv12", "yuv420p"): self.out_size = w*h*3//2 # yuv420p elif pix_fmt in ("rgb24", "yuv444p"): self.out_size = w*h*3 @@ -348,6 +374,8 @@ class VideoStreamDecompressor: if len(r) == 0: break self.proc.stdin.write(r) + except BrokenPipeError: + pass finally: self.proc.stdin.close() @@ -385,6 +413,8 @@ class VideoStreamDecompressor: ret = np.frombuffer(dat, dtype=np.uint8).reshape((self.h, self.w, 3)) elif self.pix_fmt == "yuv420p": ret = np.frombuffer(dat, dtype=np.uint8) + elif self.pix_fmt == "nv12": + ret = np.frombuffer(dat, dtype=np.uint8) elif self.pix_fmt == "yuv444p": ret = np.frombuffer(dat, dtype=np.uint8).reshape((3, self.h, self.w)) else: @@ -547,7 +577,7 @@ class GOPFrameReader(BaseFrameReader): if num + count > self.frame_count: raise ValueError(f"{num + count} > {self.frame_count}") - if pix_fmt not in ("yuv420p", "rgb24", "yuv444p"): + if pix_fmt not in ("nv12", "yuv420p", "rgb24", "yuv444p"): raise ValueError(f"Unsupported pixel format {pix_fmt!r}") ret = [self._get_one(num + i, pix_fmt) for i in range(count)] diff --git a/tools/lib/kbhit.py b/tools/lib/kbhit.py index ac048fda94..4451d02aea 100644 --- a/tools/lib/kbhit.py +++ b/tools/lib/kbhit.py @@ -22,7 +22,7 @@ class KBHit: self.new_term = self.old_term.copy() # New terminal setting unbuffered - self.new_term[3] &= ~(termios.ICANON | termios.ECHO) # type: ignore + self.new_term[3] &= ~(termios.ICANON | termios.ECHO) termios.tcsetattr(STDIN_FD, termios.TCSAFLUSH, self.new_term) # Support normal-terminal reset at exit diff --git a/tools/lib/logreader.py b/tools/lib/logreader.py index c8d506b4b3..46c648ef12 100755 --- a/tools/lib/logreader.py +++ b/tools/lib/logreader.py @@ -4,9 +4,12 @@ import sys import bz2 import urllib.parse import capnp +import warnings + -from tools.lib.filereader import FileReader from cereal import log as capnp_log +from tools.lib.filereader import FileReader +from tools.lib.route import Route, SegmentName # this is an iterator itself, and uses private variables from LogReader class MultiLogIterator: @@ -66,27 +69,43 @@ class MultiLogIterator: self._inc() return True + def reset(self): + self.__init__(self._log_paths, sort_by_time=self.sort_by_time) + class LogReader: - def __init__(self, fn, canonicalize=True, only_union_types=False, sort_by_time=False): - data_version = None - _, ext = os.path.splitext(urllib.parse.urlparse(fn).path) - with FileReader(fn) as f: - dat = f.read() - - if ext == "": - # old rlogs weren't bz2 compressed - ents = capnp_log.Event.read_multiple_bytes(dat) - elif ext == ".bz2": + def __init__(self, fn, canonicalize=True, only_union_types=False, sort_by_time=False, dat=None): + self.data_version = None + self._only_union_types = only_union_types + + ext = None + if not dat: + _, ext = os.path.splitext(urllib.parse.urlparse(fn).path) + if ext not in ('', '.bz2'): + # old rlogs weren't bz2 compressed + raise Exception(f"unknown extension {ext}") + + with FileReader(fn) as f: + dat = f.read() + + if ext == ".bz2" or dat.startswith(b'BZh9'): dat = bz2.decompress(dat) - ents = capnp_log.Event.read_multiple_bytes(dat) - else: - raise Exception(f"unknown extension {ext}") - self._ents = list(sorted(ents, key=lambda x: x.logMonoTime) if sort_by_time else ents) + ents = capnp_log.Event.read_multiple_bytes(dat) + + _ents = [] + try: + for e in ents: + _ents.append(e) + except capnp.KjException: + warnings.warn("Corrupted events detected", RuntimeWarning) + + self._ents = list(sorted(_ents, key=lambda x: x.logMonoTime) if sort_by_time else _ents) self._ts = [x.logMonoTime for x in self._ents] - self.data_version = data_version - self._only_union_types = only_union_types + + @classmethod + def from_bytes(cls, dat): + return cls("", dat=dat) def __iter__(self): for ent in self._ents: @@ -99,6 +118,15 @@ class LogReader: else: yield ent +def logreader_from_route_or_segment(r, sort_by_time=False): + sn = SegmentName(r, allow_route_name=True) + route = Route(sn.route_name.canonical_name) + if sn.segment_num < 0: + return MultiLogIterator(route.log_paths(), sort_by_time=sort_by_time) + else: + return LogReader(route.log_paths()[sn.segment_num], sort_by_time=sort_by_time) + + if __name__ == "__main__": import codecs # capnproto <= 0.8.0 throws errors converting byte data to string diff --git a/tools/lib/robust_logreader.py b/tools/lib/robust_logreader.py deleted file mode 100755 index c7feb6c3ed..0000000000 --- a/tools/lib/robust_logreader.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python3 -import os -import bz2 -import urllib.parse -import subprocess -import tqdm -import glob -from tempfile import TemporaryDirectory -import capnp - -from tools.lib.logreader import FileReader, LogReader -from cereal import log as capnp_log - - -class RobustLogReader(LogReader): - def __init__(self, fn, canonicalize=True, only_union_types=False, sort_by_time=False): # pylint: disable=super-init-not-called - data_version = None - _, ext = os.path.splitext(urllib.parse.urlparse(fn).path) - with FileReader(fn) as f: - dat = f.read() - - if ext == "": - pass - elif ext == ".bz2": - try: - dat = bz2.decompress(dat) - except ValueError: - print("Failed to decompress, falling back to bzip2recover") - with TemporaryDirectory() as directory: - # Run bzip2recovery on log - with open(os.path.join(directory, 'out.bz2'), 'wb') as f: - f.write(dat) - subprocess.check_call(["bzip2recover", "out.bz2"], cwd=directory) - - # Decompress and concatenate parts - dat = b"" - for n in sorted(glob.glob(f"{directory}/rec*.bz2")): - print(f"Decompressing {n}") - with open(n, 'rb') as f: - dat += bz2.decompress(f.read()) - else: - raise Exception(f"unknown extension {ext}") - - progress = None - while True: - try: - ents = capnp_log.Event.read_multiple_bytes(dat) - self._ents = list(sorted(ents, key=lambda x: x.logMonoTime) if sort_by_time else ents) - break - except capnp.lib.capnp.KjException: - if progress is None: - progress = tqdm.tqdm(total=len(dat)) - - # Cut off bytes at the end until capnp is able to read - dat = dat[:-1] - progress.update(1) - - self._ts = [x.logMonoTime for x in self._ents] - self.data_version = data_version - self._only_union_types = only_union_types diff --git a/tools/lib/route.py b/tools/lib/route.py index 8092096a0b..388cb003e6 100644 --- a/tools/lib/route.py +++ b/tools/lib/route.py @@ -3,14 +3,15 @@ import re from urllib.parse import urlparse from collections import defaultdict from itertools import chain +from typing import Optional from tools.lib.auth_config import get_token from tools.lib.api import CommaApi from tools.lib.helpers import RE -QLOG_FILENAMES = ['qlog.bz2'] +QLOG_FILENAMES = ['qlog', 'qlog.bz2'] QCAMERA_FILENAMES = ['qcamera.ts'] -LOG_FILENAMES = ['rlog.bz2', 'raw_log.bz2'] +LOG_FILENAMES = ['rlog', 'rlog.bz2', 'raw_log.bz2'] CAMERA_FILENAMES = ['fcamera.hevc', 'video.hevc'] DCAMERA_FILENAMES = ['dcamera.hevc'] ECAMERA_FILENAMES = ['ecamera.hevc'] @@ -196,7 +197,11 @@ class SegmentName: # TODO: add constructor that takes dongle_id, time_str, segment_num and then create instances # of this class instead of manually constructing a segment name (use canonical_name prop instead) def __init__(self, name_str: str, allow_route_name=False): - self._name_str = name_str + data_dir_path_separator_index = name_str.rsplit("|", 1)[0].rfind("/") + use_data_dir = (data_dir_path_separator_index != -1) and ("|" in name_str) + self._name_str = name_str[data_dir_path_separator_index + 1:] if use_data_dir else name_str + self._data_dir = name_str[:data_dir_path_separator_index] if use_data_dir else None + seg_num_delim = "--" if self._name_str.count("--") == 2 else "/" name_parts = self._name_str.rsplit(seg_num_delim, 1) if allow_route_name and len(name_parts) == 1: @@ -220,4 +225,7 @@ class SegmentName: @property def route_name(self) -> RouteName: return self._route_name + @property + def data_dir(self) -> Optional[str]: return self._data_dir + def __str__(self) -> str: return self._canonical_name diff --git a/tools/lib/tests/test_caching.py b/tools/lib/tests/test_caching.py index 953b47e95a..d2a2a6872f 100644 --- a/tools/lib/tests/test_caching.py +++ b/tools/lib/tests/test_caching.py @@ -66,4 +66,4 @@ class TestFileDownload(unittest.TestCase): if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/tools/lib/tests/test_readers.py b/tools/lib/tests/test_readers.py index 1d8918ba54..6efa0dc351 100755 --- a/tools/lib/tests/test_readers.py +++ b/tools/lib/tests/test_readers.py @@ -10,7 +10,7 @@ from tools.lib.logreader import LogReader class TestReaders(unittest.TestCase): - @unittest.skip("skip for bandwith reasons") + @unittest.skip("skip for bandwidth reasons") def test_logreader(self): def _check_data(lr): hist = defaultdict(int) @@ -21,7 +21,7 @@ class TestReaders(unittest.TestCase): self.assertEqual(hist['logMessage'], 6857) with tempfile.NamedTemporaryFile(suffix=".bz2") as fp: - r = requests.get("https://github.com/commaai/comma2k19/blob/master/Example_1/b0c9d2329ad1606b%7C2018-08-02--08-34-47/40/raw_log.bz2?raw=true") + r = requests.get("https://github.com/commaai/comma2k19/blob/master/Example_1/b0c9d2329ad1606b%7C2018-08-02--08-34-47/40/raw_log.bz2?raw=true", timeout=10) fp.write(r.content) fp.flush() @@ -31,7 +31,7 @@ class TestReaders(unittest.TestCase): lr_url = LogReader("https://github.com/commaai/comma2k19/blob/master/Example_1/b0c9d2329ad1606b%7C2018-08-02--08-34-47/40/raw_log.bz2?raw=true") _check_data(lr_url) - @unittest.skip("skip for bandwith reasons") + @unittest.skip("skip for bandwidth reasons") def test_framereader(self): def _check_data(f): self.assertEqual(f.frame_count, 1200) @@ -53,7 +53,7 @@ class TestReaders(unittest.TestCase): assert np.all(frame_first_30[15] == frame_15[0]) with tempfile.NamedTemporaryFile(suffix=".hevc") as fp: - r = requests.get("https://github.com/commaai/comma2k19/blob/master/Example_1/b0c9d2329ad1606b%7C2018-08-02--08-34-47/40/video.hevc?raw=true") + r = requests.get("https://github.com/commaai/comma2k19/blob/master/Example_1/b0c9d2329ad1606b%7C2018-08-02--08-34-47/40/video.hevc?raw=true", timeout=10) fp.write(r.content) fp.flush() diff --git a/tools/lib/tests/test_route_library.py b/tools/lib/tests/test_route_library.py new file mode 100755 index 0000000000..fbe7f3e776 --- /dev/null +++ b/tools/lib/tests/test_route_library.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python +import unittest +from collections import namedtuple + +from tools.lib.route import SegmentName + +class TestRouteLibrary(unittest.TestCase): + def test_segment_name_formats(self): + Case = namedtuple('Case', ['input', 'expected_route', 'expected_segment_num', 'expected_data_dir']) + + cases = [ Case("4cf7a6ad03080c90|2021-09-29--13-46-36", "4cf7a6ad03080c90|2021-09-29--13-46-36", -1, None), + Case("4cf7a6ad03080c90/2021-09-29--13-46-36--1", "4cf7a6ad03080c90|2021-09-29--13-46-36", 1, None), + Case("4cf7a6ad03080c90|2021-09-29--13-46-36/2", "4cf7a6ad03080c90|2021-09-29--13-46-36", 2, None), + Case("4cf7a6ad03080c90/2021-09-29--13-46-36/3", "4cf7a6ad03080c90|2021-09-29--13-46-36", 3, None), + Case("/data/media/0/realdata/4cf7a6ad03080c90|2021-09-29--13-46-36", "4cf7a6ad03080c90|2021-09-29--13-46-36", -1, "/data/media/0/realdata"), + Case("/data/media/0/realdata/4cf7a6ad03080c90|2021-09-29--13-46-36--1", "4cf7a6ad03080c90|2021-09-29--13-46-36", 1, "/data/media/0/realdata"), + Case("/data/media/0/realdata/4cf7a6ad03080c90|2021-09-29--13-46-36/2", "4cf7a6ad03080c90|2021-09-29--13-46-36", 2, "/data/media/0/realdata") ] + + def _validate(case): + route_or_segment_name = case.input + + s = SegmentName(route_or_segment_name, allow_route_name=True) + + self.assertEqual(str(s.route_name), case.expected_route) + self.assertEqual(s.segment_num, case.expected_segment_num) + self.assertEqual(s.data_dir, case.expected_data_dir) + + for case in cases: + _validate(case) + +if __name__ == "__main__": + unittest.main() diff --git a/tools/lib/url_file.py b/tools/lib/url_file.py index 8ad2f96b3a..1e94a588f1 100644 --- a/tools/lib/url_file.py +++ b/tools/lib/url_file.py @@ -87,6 +87,7 @@ class URLFile: file_begin = self._pos file_end = self._pos + ll if ll is not None else self.get_length() + assert file_end != -1, f"Remote file is empty or doesn't exist: {self._url}" # We have to align with chunks we store. Position is the begginiing of the latest chunk that starts before or at our file position = (file_begin // CHUNK_SIZE) * CHUNK_SIZE response = b"" diff --git a/tools/mac_setup.sh b/tools/mac_setup.sh index fa1a23dd47..e85292da03 100755 --- a/tools/mac_setup.sh +++ b/tools/mac_setup.sh @@ -4,16 +4,33 @@ set -e DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" ROOT="$(cd $DIR/../ && pwd)" +ARCH=$(uname -m) + +if [[ $SHELL == "/bin/zsh" ]]; then + RC_FILE="$HOME/.zshrc" +elif [[ $SHELL == "/bin/bash" ]]; then + RC_FILE="$HOME/.bashrc" +fi # Install brew if required if [[ $(command -v brew) == "" ]]; then echo "Installing Hombrew" /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" echo "[ ] installed brew t=$SECONDS" + + # make brew available now + if [[ $ARCH == "x86_64" ]]; then + echo 'eval "$(/usr/local/homebrew/bin/brew shellenv)"' >> $RC_FILE + eval "$(/usr/local/homebrew/bin/brew shellenv)" + else + echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> $RC_FILE + eval "$(/opt/homebrew/bin/brew shellenv)" + fi fi # TODO: remove protobuf,protobuf-c,swig when casadi can be pip installed brew bundle --file=- <<-EOS +brew "catch2" brew "cmake" brew "cppcheck" brew "git-lfs" @@ -35,25 +52,28 @@ brew "zeromq" brew "protobuf" brew "protobuf-c" brew "swig" -cask "gcc-arm-embedded" EOS +# Install gcc-arm-embedded 10.3-2021.10. 11.x is broken on M1 Macs with Xcode 13.3~ +brew uninstall gcc-arm-embedded || true +curl -L https://github.com/Homebrew/homebrew-cask/raw/d407663b8017a0a062c7fc0b929faf2e16abd1ff/Casks/gcc-arm-embedded.rb > /tmp/gcc-arm-embedded.rb +brew install --cask /tmp/gcc-arm-embedded.rb +rm /tmp/gcc-arm-embedded.rb + echo "[ ] finished brew install t=$SECONDS" -if [[ $SHELL == "/bin/zsh" ]]; then - RC_FILE="$HOME/.zshrc" -elif [[ $SHELL == "/bin/bash" ]]; then - RC_FILE="$HOME/.bash_profile" -fi +BREW_PREFIX=$(brew --prefix) + +# archive backend tools for pip dependencies +export LDFLAGS="$LDFLAGS -L${BREW_PREFIX}/opt/zlib/lib" +export LDFLAGS="$LDFLAGS -L${BREW_PREFIX}/opt/bzip2/lib" +export CPPFLAGS="$CPPFLAGS -I${BREW_PREFIX}/opt/zlib/include" +export CPPFLAGS="$CPPFLAGS -I${BREW_PREFIX}/opt/bzip2/include" -export LDFLAGS="$LDFLAGS -L/usr/local/opt/zlib/lib" -export LDFLAGS="$LDFLAGS -L/usr/local/opt/bzip2/lib" -export LDFLAGS="$LDFLAGS -L/usr/local/opt/openssl@1.1/lib" -export CPPFLAGS="$CPPFLAGS -I/usr/local/opt/zlib/include" -export CPPFLAGS="$CPPFLAGS -I/usr/local/opt/bzip2/include" -export CPPFLAGS="$CPPFLAGS -I/usr/local/opt/openssl@1.1/include" -export PATH="$PATH:/usr/local/opt/openssl@1.1/bin" -export PATH="$PATH:/usr/local/bin" +# pycurl curl/openssl backend dependencies +export LDFLAGS="$LDFLAGS -L${BREW_PREFIX}/opt/openssl@3/lib" +export CPPFLAGS="$CPPFLAGS -I${BREW_PREFIX}/opt/openssl@3/include" +export PYCURL_SSL_LIBRARY=openssl # openpilot environment if [ -z "$OPENPILOT_ENV" ] && [ -n "$RC_FILE" ] && [ -z "$CI" ]; then @@ -68,7 +88,7 @@ eval "$(pyenv init --path)" echo "[ ] installed python dependencies t=$SECONDS" # install casadi -VENV=`pipenv --venv` +VENV=`poetry env info --path` PYTHON_VER=3.8 PYTHON_VERSION=$(cat $ROOT/.python-version) if [ ! -f "$VENV/include/casadi/casadi.hpp" ]; then diff --git a/tools/openpilot_build.sh b/tools/openpilot_build.sh deleted file mode 100644 index f0f89d936e..0000000000 --- a/tools/openpilot_build.sh +++ /dev/null @@ -1 +0,0 @@ -docker run --rm -v $(pwd):/tmp/openpilot -it commaai/openpilot bash -c 'cd /tmp/openpilot && scons -j$(nproc)' diff --git a/tools/plotjuggler/README.md b/tools/plotjuggler/README.md index 2e79aecbca..b4190384db 100644 --- a/tools/plotjuggler/README.md +++ b/tools/plotjuggler/README.md @@ -4,7 +4,7 @@ ## Installation -Once you've cloned and are in openpilot, this command will download PlotJuggler and install our plugins: +Once you've [set up the openpilot environment](../README.md), this command will download PlotJuggler and install our plugins: `cd tools/plotjuggler && ./juggle.py --install` @@ -12,7 +12,7 @@ Once you've cloned and are in openpilot, this command will download PlotJuggler ``` $ ./juggle.py -h -usage: juggle.py [-h] [--demo] [--qlog] [--can] [--stream] [--layout [LAYOUT]] [--install] +usage: juggle.py [-h] [--demo] [--qlog] [--ci] [--can] [--stream] [--layout [LAYOUT]] [--install] [--dbc DBC] [route_or_segment_name] [segment_count] A helper to run PlotJuggler on openpilot routes @@ -23,13 +23,17 @@ positional arguments: segment_count The number of segments to plot (default: None) optional arguments: - -h, --help show this help message and exit - --demo Use the demo route instead of providing one (default: False) - --qlog Use qlogs (default: False) - --can Parse CAN data (default: False) - --stream Start PlotJuggler in streaming mode (default: False) - --layout [LAYOUT] Run PlotJuggler with a pre-defined layout (default: None) - --install Install or update PlotJuggler + plugins (default: False) + -h, --help show this help message and exit + --demo Use the demo route instead of providing one (default: False) + --qlog Use qlogs (default: False) + --ci Download data from openpilot CI bucket (default: False) + --can Parse CAN data (default: False) + --stream Start PlotJuggler in streaming mode (default: False) + --layout [LAYOUT] Run PlotJuggler with a pre-defined layout (default: None) + --install Install or update PlotJuggler + plugins (default: False) + --dbc DBC Set the DBC name to load for parsing CAN data. If not set, the DBC will be automatically + inferred from the logs. (default: None) + ``` Examples using route name: @@ -62,7 +66,7 @@ If you create a layout that's useful for others, consider upstreaming it. ### Tuning -Use this layout to improve your car's tuning and generate plots for tuning PRs. Also see the tuning wiki and tuning PR template. +Use this layout to improve your car's tuning and generate plots for tuning PRs. Also see the [tuning wiki](https://github.com/commaai/openpilot/wiki/Tuning) and tuning PR template. `--layout layouts/tuning.xml` diff --git a/tools/plotjuggler/juggle.py b/tools/plotjuggler/juggle.py index af69bd7c8b..1e592da3b1 100755 --- a/tools/plotjuggler/juggle.py +++ b/tools/plotjuggler/juggle.py @@ -12,9 +12,8 @@ import argparse from common.basedir import BASEDIR from selfdrive.test.process_replay.compare_logs import save_log -from tools.lib.api import CommaApi -from tools.lib.auth_config import get_token -from tools.lib.robust_logreader import RobustLogReader +from selfdrive.test.openpilotci import get_url +from tools.lib.logreader import LogReader from tools.lib.route import Route, SegmentName from urllib.parse import urlparse, parse_qs @@ -24,7 +23,8 @@ DEMO_ROUTE = "4cf7a6ad03080c90|2021-09-29--13-46-36" RELEASES_URL="https://github.com/commaai/PlotJuggler/releases/download/latest" INSTALL_DIR = os.path.join(juggle_dir, "bin") PLOTJUGGLER_BIN = os.path.join(juggle_dir, "bin/plotjuggler") - +MINIMUM_PLOTJUGGLER_VERSION = (3, 5, 2) +MAX_STREAMING_BUFFER_SIZE = 1000 def install(): m = f"{platform.system()}-{platform.machine()}" @@ -37,7 +37,7 @@ def install(): os.mkdir(INSTALL_DIR) url = os.path.join(RELEASES_URL, m + ".tar.gz") - with requests.get(url, stream=True) as r, tempfile.NamedTemporaryFile() as tmp: + with requests.get(url, stream=True, timeout=10) as r, tempfile.NamedTemporaryFile() as tmp: r.raise_for_status() with open(tmp.name, 'wb') as tmpf: for chunk in r.iter_content(chunk_size=1024*1024): @@ -47,18 +47,24 @@ def install(): tar.extractall(path=INSTALL_DIR) +def get_plotjuggler_version(): + out = subprocess.check_output([PLOTJUGGLER_BIN, "-v"], encoding="utf-8").strip() + version = out.split(" ")[1] + return tuple(map(int, version.split("."))) + + def load_segment(segment_name): if segment_name is None: return [] try: - return list(RobustLogReader(segment_name)) - except ValueError as e: + return list(LogReader(segment_name)) + except (AssertionError, ValueError) as e: print(f"Error parsing {segment_name}: {e}") return [] -def start_juggler(fn=None, dbc=None, layout=None): +def start_juggler(fn=None, dbc=None, layout=None, route_or_segment_name=None): env = os.environ.copy() env["BASEDIR"] = BASEDIR env["PATH"] = f"{INSTALL_DIR}:{os.getenv('PATH', '')}" @@ -70,19 +76,26 @@ def start_juggler(fn=None, dbc=None, layout=None): extra_args += f" -d {fn}" if layout is not None: extra_args += f" -l {layout}" + if route_or_segment_name is not None: + extra_args += f" --window_title \"{route_or_segment_name}\"" - cmd = f'{PLOTJUGGLER_BIN} --plugin_folders {INSTALL_DIR}{extra_args}' + cmd = f'{PLOTJUGGLER_BIN} --buffer_size {MAX_STREAMING_BUFFER_SIZE} --plugin_folders {INSTALL_DIR}{extra_args}' subprocess.call(cmd, shell=True, env=env, cwd=juggle_dir) -def juggle_route(route_or_segment_name, segment_count, qlog, can, layout): +def juggle_route(route_or_segment_name, segment_count, qlog, can, layout, dbc=None, ci=False): segment_start = 0 if 'cabana' in route_or_segment_name: query = parse_qs(urlparse(route_or_segment_name).query) - api = CommaApi(get_token()) - logs = api.get(f'v1/route/{query["route"][0]}/log_urls?sig={query["sig"][0]}&exp={query["exp"][0]}') - elif route_or_segment_name.startswith("http://") or route_or_segment_name.startswith("https://") or os.path.isfile(route_or_segment_name): + route_or_segment_name = query["route"][0] + + if route_or_segment_name.startswith(("http://", "https://", "cd:/")) or os.path.isfile(route_or_segment_name): logs = [route_or_segment_name] + elif ci: + route_or_segment_name = SegmentName(route_or_segment_name, allow_route_name=True) + route = route_or_segment_name.route_name.canonical_name + segment_start = max(route_or_segment_name.segment_num, 0) + logs = [get_url(route, i) for i in range(100)] # Assume there not more than 100 segments else: route_or_segment_name = SegmentName(route_or_segment_name, allow_route_name=True) segment_start = max(route_or_segment_name.segment_num, 0) @@ -90,15 +103,15 @@ def juggle_route(route_or_segment_name, segment_count, qlog, can, layout): if route_or_segment_name.segment_num != -1 and segment_count is None: segment_count = 1 - r = Route(route_or_segment_name.route_name.canonical_name) + r = Route(route_or_segment_name.route_name.canonical_name, route_or_segment_name.data_dir) logs = r.qlog_paths() if qlog else r.log_paths() segment_end = segment_start + segment_count if segment_count else None logs = logs[segment_start:segment_end] if None in logs: - ans = input(f"{logs.count(None)}/{len(logs)} of the rlogs in this segment are missing, would you like to fall back to the qlogs? (y/n) ") - if ans == 'y': + resp = input(f"{logs.count(None)}/{len(logs)} of the rlogs in this segment are missing, would you like to fall back to the qlogs? (y/n) ") + if resp == 'y': logs = r.qlog_paths()[segment_start:segment_end] else: print("Please try a different route or segment") @@ -113,19 +126,19 @@ def juggle_route(route_or_segment_name, segment_count, qlog, can, layout): all_data = [d for d in all_data if d.which() not in ['can', 'sendcan']] # Infer DBC name from logs - dbc = None - for cp in [m for m in all_data if m.which() == 'carParams']: - try: - DBC = __import__(f"selfdrive.car.{cp.carParams.carName}.values", fromlist=['DBC']).DBC - dbc = DBC[cp.carParams.carFingerprint]['pt'] - except Exception: - pass - break + if dbc is None: + for cp in [m for m in all_data if m.which() == 'carParams']: + try: + DBC = __import__(f"selfdrive.car.{cp.carParams.carName}.values", fromlist=['DBC']).DBC + dbc = DBC[cp.carParams.carFingerprint]['pt'] + except Exception: + pass + break with tempfile.NamedTemporaryFile(suffix='.rlog', dir=juggle_dir) as tmp: save_log(tmp.name, all_data, compress=False) del all_data - start_juggler(tmp.name, dbc, layout) + start_juggler(tmp.name, dbc, layout, route_or_segment_name) if __name__ == "__main__": @@ -134,10 +147,12 @@ if __name__ == "__main__": parser.add_argument("--demo", action="store_true", help="Use the demo route instead of providing one") parser.add_argument("--qlog", action="store_true", help="Use qlogs") + parser.add_argument("--ci", action="store_true", help="Download data from openpilot CI bucket") parser.add_argument("--can", action="store_true", help="Parse CAN data") parser.add_argument("--stream", action="store_true", help="Start PlotJuggler in streaming mode") parser.add_argument("--layout", nargs='?', help="Run PlotJuggler with a pre-defined layout") parser.add_argument("--install", action="store_true", help="Install or update PlotJuggler + plugins") + parser.add_argument("--dbc", help="Set the DBC name to load for parsing CAN data. If not set, the DBC will be automatically inferred from the logs.") parser.add_argument("route_or_segment_name", nargs='?', help="The route or segment name to plot (cabana share URL accepted)") parser.add_argument("segment_count", type=int, nargs='?', help="The number of segments to plot") @@ -153,9 +168,13 @@ if __name__ == "__main__": if not os.path.exists(PLOTJUGGLER_BIN): print("PlotJuggler is missing. Downloading...") install() + + if get_plotjuggler_version() < MINIMUM_PLOTJUGGLER_VERSION: + print("PlotJuggler is out of date. Installing update...") + install() if args.stream: start_juggler(layout=args.layout) else: route_or_segment_name = DEMO_ROUTE if args.demo else args.route_or_segment_name.strip() - juggle_route(route_or_segment_name, args.segment_count, args.qlog, args.can, args.layout) + juggle_route(route_or_segment_name, args.segment_count, args.qlog, args.can, args.layout, args.dbc, args.ci) diff --git a/tools/plotjuggler/layouts/controls_mismatch_debug.xml b/tools/plotjuggler/layouts/controls_mismatch_debug.xml index e50b5ffb34..adca3eed29 100644 --- a/tools/plotjuggler/layouts/controls_mismatch_debug.xml +++ b/tools/plotjuggler/layouts/controls_mismatch_debug.xml @@ -1,27 +1,34 @@ - + - + - - + + - - + + - - + + + + + + + + + diff --git a/tools/plotjuggler/layouts/longitudinal.xml b/tools/plotjuggler/layouts/longitudinal.xml new file mode 100644 index 0000000000..ff8f3ad193 --- /dev/null +++ b/tools/plotjuggler/layouts/longitudinal.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tools/plotjuggler/layouts/max-torque-debug.xml b/tools/plotjuggler/layouts/max-torque-debug.xml new file mode 100644 index 0000000000..20a49c2181 --- /dev/null +++ b/tools/plotjuggler/layouts/max-torque-debug.xml @@ -0,0 +1,92 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + if (v3 == 0 and v4 == 1) then + return (value * v1 ^ 2) - (v2 * 9.81) +end +return 0 + /controlsState/curvature + + /carState/vEgo + /liveParameters/roll + /carState/steeringPressed + /carControl/latActive + + + + + return (value * v1 ^ 2) - (v2 * 9.81) + /controlsState/desiredCurvature + + /carState/vEgo + /liveParameters/roll + + + + + return (value * v1 ^ 2) - (v2 * 9.81) + /controlsState/curvature + + /carState/vEgo + /liveParameters/roll + + + + + + + diff --git a/tools/plotjuggler/layouts/system_lag_debug.xml b/tools/plotjuggler/layouts/system_lag_debug.xml new file mode 100644 index 0000000000..b1699348cc --- /dev/null +++ b/tools/plotjuggler/layouts/system_lag_debug.xml @@ -0,0 +1,68 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tools/plotjuggler/layouts/thermal_debug.xml b/tools/plotjuggler/layouts/thermal_debug.xml new file mode 100644 index 0000000000..c10b78f1c5 --- /dev/null +++ b/tools/plotjuggler/layouts/thermal_debug.xml @@ -0,0 +1,100 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tools/plotjuggler/layouts/torque-controller.xml b/tools/plotjuggler/layouts/torque-controller.xml new file mode 100644 index 0000000000..443255968a --- /dev/null +++ b/tools/plotjuggler/layouts/torque-controller.xml @@ -0,0 +1,92 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + return value * 3.6 + /carState/vEgo + + + + return value * 2.23694 + /carState/vEgo + + + + return (value * v1 ^ 2) - (v2 * 9.81) + /controlsState/desiredCurvature + + /carState/vEgo + /liveParameters/roll + + + + + return (value * v1 ^ 2) - (v2 * 9.81) + /controlsState/curvature + + /carState/vEgo + /liveParameters/roll + + + + + + + diff --git a/tools/plotjuggler/layouts/tuning.xml b/tools/plotjuggler/layouts/tuning.xml index 877fb82a5d..503e726caf 100644 --- a/tools/plotjuggler/layouts/tuning.xml +++ b/tools/plotjuggler/layouts/tuning.xml @@ -161,12 +161,12 @@ if (time > last_bad_time + engage_delay) then else return 0 end - /liveLocationKalman/angularVelocityCalibrated/value/2 - + /liveLocationKalman/angularVelocityCalibrated/value/2 + /carState/steeringPressed /carControl/enabled /liveLocationKalman/velocityCalibrated/value/0 - + engage_delay = 5 @@ -184,11 +184,11 @@ if (time > last_bad_time + engage_delay) then else return 0 end - /controlsState/curvature - + /controlsState/curvature + /carState/steeringPressed /carControl/enabled - + engage_delay = 5 @@ -206,11 +206,11 @@ if (time > last_bad_time + engage_delay) then else return 0 end - /lateralPlan/curvatures/0 - + /lateralPlan/curvatures/0 + /carState/steeringPressed /carControl/enabled - + engage_delay = 5 @@ -229,12 +229,12 @@ if (time > last_bad_time + engage_delay) then else return 0 end - /carState/aEgo - + /carState/aEgo + /carState/brakePressed /carState/gasPressed /carControl/enabled - + engage_delay = 5 @@ -253,12 +253,12 @@ if (time > last_bad_time + engage_delay) then else return 0 end - /longitudinalPlan/accels/0 - + /longitudinalPlan/accels/0 + /carState/brakePressed /carState/gasPressed /carControl/enabled - + engage_delay = 5 @@ -277,12 +277,12 @@ if (time > last_bad_time + engage_delay) then else return 0 end - /carControl/actuators/accel - + /carControl/actuators/accel + /carState/brakePressed /carState/gasPressed /carControl/enabled - + diff --git a/tools/plotjuggler/test_plotjuggler.py b/tools/plotjuggler/test_plotjuggler.py index edaec9c80a..8fc032042a 100755 --- a/tools/plotjuggler/test_plotjuggler.py +++ b/tools/plotjuggler/test_plotjuggler.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 import os +import glob import signal import subprocess import time @@ -9,12 +10,14 @@ from common.basedir import BASEDIR from common.timeout import Timeout from tools.plotjuggler.juggle import install +PJ_DIR = os.path.join(BASEDIR, "tools/plotjuggler") + class TestPlotJuggler(unittest.TestCase): def test_demo(self): install() - pj = os.path.join(BASEDIR, "tools/plotjuggler/juggle.py") + pj = os.path.join(PJ_DIR, "juggle.py") p = subprocess.Popen(f'QT_QPA_PLATFORM=offscreen {pj} --demo None 1 --qlog', stderr=subprocess.PIPE, shell=True, start_new_session=True) @@ -29,5 +32,22 @@ class TestPlotJuggler(unittest.TestCase): self.assertEqual(p.poll(), None) os.killpg(os.getpgid(p.pid), signal.SIGTERM) + # TODO: also test that layouts successfully load + def test_layouts(self): + bad_strings = ( + # if a previously loaded file is defined, + # PJ will throw a warning when loading the layout + "fileInfo", + "previouslyLoaded_Datafiles", + ) + for fn in glob.glob(os.path.join(PJ_DIR, "layouts/*")): + name = os.path.basename(fn) + with self.subTest(layout=name): + with open(fn) as f: + layout = f.read() + violations = [s for s in bad_strings if s in layout] + assert len(violations) == 0, f"These should be stripped out of the layout: {str(violations)}" + + if __name__ == "__main__": unittest.main() diff --git a/tools/replay/.gitignore b/tools/replay/.gitignore new file mode 100644 index 0000000000..83f0e99a8b --- /dev/null +++ b/tools/replay/.gitignore @@ -0,0 +1,5 @@ +moc_* +*.moc + +replay +tests/test_replay diff --git a/tools/replay/README.md b/tools/replay/README.md index a0706d8df2..2d0b702bd0 100644 --- a/tools/replay/README.md +++ b/tools/replay/README.md @@ -6,15 +6,15 @@ ```bash # Log in via browser to have access to non-public routes -python lib/auth.py +python tools/lib/auth.py # Start a replay -selfdrive/ui/replay/replay +tools/replay/replay # Example: -# selfdrive/ui/replay/replay '4cf7a6ad03080c90|2021-09-29--13-46-36' +# tools/replay/replay '4cf7a6ad03080c90|2021-09-29--13-46-36' # or use --demo to replay the default demo route: -# selfdrive/ui/replay/replay --demo +# tools/replay/replay --demo # watch the replay with the normal openpilot UI cd selfdrive/ui && ./ui @@ -24,9 +24,10 @@ python replay/ui.py ``` ## usage + ``` bash -$ selfdrive/ui/replay/replay -h -Usage: selfdrive/ui/replay/replay [options] route +$ tools/replay/replay -h +Usage: tools/replay/replay [options] route Mock openpilot components by publishing logged messages. Options: @@ -51,7 +52,7 @@ simply replay a route using the `--dcam` and `--ecam` flags: ```bash # start a replay -cd selfdrive/ui/replay && ./replay --demo --dcam --ecam +cd tools/replay && ./replay --demo --dcam --ecam # then start watch3 cd selfdrive/ui && ./watch3 @@ -61,7 +62,7 @@ cd selfdrive/ui && ./watch3 ## Stream CAN messages to your device -Replay CAN messages as they were recorded using a [panda jungle](https://comma.ai/shop/products/panda-jungle). The jungle has 6x OBD-C ports for connecting all your comma devices. +Replay CAN messages as they were recorded using a [panda jungle](https://comma.ai/shop/products/panda-jungle). The jungle has 6x OBD-C ports for connecting all your comma devices. Check out the [jungle repo](https://github.com/commaai/panda_jungle) for more info. `can_replay.py` is a convenient script for when any CAN data will do. @@ -70,5 +71,5 @@ In order to replay specific route: MOCK=1 selfdrive/boardd/tests/boardd_old.py # In another terminal: -selfdrive/ui/replay/replay +tools/replay/replay ``` diff --git a/tools/replay/SConscript b/tools/replay/SConscript new file mode 100644 index 0000000000..4ddeb662e0 --- /dev/null +++ b/tools/replay/SConscript @@ -0,0 +1,25 @@ +import os +Import('env', 'qt_env', 'arch', 'common', 'messaging', 'visionipc', + 'cereal', 'transformations') + +base_frameworks = qt_env['FRAMEWORKS'] +base_libs = [common, messaging, cereal, visionipc, transformations, 'zmq', + 'capnp', 'kj', 'm', 'ssl', 'crypto', 'pthread'] + qt_env["LIBS"] + +if arch == "Darwin": + base_frameworks.append('OpenCL') +else: + base_libs.append('OpenCL') + +qt_libs = ['qt_util'] + base_libs +qt_env['CXXFLAGS'] += ["-Wno-deprecated-declarations"] + +replay_lib_src = ["replay.cc", "consoleui.cc", "camera.cc", "filereader.cc", "logreader.cc", "framereader.cc", "route.cc", "util.cc"] + +replay_lib = qt_env.Library("qt_replay", replay_lib_src, LIBS=qt_libs, FRAMEWORKS=base_frameworks) +Export('replay_lib') +replay_libs = [replay_lib, 'avutil', 'avcodec', 'avformat', 'bz2', 'curl', 'yuv', 'ncurses'] + qt_libs +qt_env.Program("replay", ["main.cc"], LIBS=replay_libs, FRAMEWORKS=base_frameworks) + +if GetOption('test'): + qt_env.Program('tests/test_replay', ['tests/test_runner.cc', 'tests/test_replay.cc'], LIBS=[replay_libs]) diff --git a/selfdrive/ui/replay/camera.cc b/tools/replay/camera.cc similarity index 65% rename from selfdrive/ui/replay/camera.cc rename to tools/replay/camera.cc index 9bcc00583e..72b385dca8 100644 --- a/selfdrive/ui/replay/camera.cc +++ b/tools/replay/camera.cc @@ -1,9 +1,9 @@ -#include "selfdrive/ui/replay/camera.h" -#include "selfdrive/ui/replay/util.h" +#include "tools/replay/camera.h" +#include "tools/replay/util.h" #include -CameraServer::CameraServer(std::pair camera_size[MAX_CAMERAS], bool send_yuv) : send_yuv(send_yuv) { +CameraServer::CameraServer(std::pair camera_size[MAX_CAMERAS]) { for (int i = 0; i < MAX_CAMERAS; ++i) { std::tie(cameras_[i].width, cameras_[i].height) = camera_size[i]; } @@ -25,10 +25,7 @@ void CameraServer::startVipcServer() { for (auto &cam : cameras_) { if (cam.width > 0 && cam.height > 0) { rInfo("camera[%d] frame size %dx%d", cam.type, cam.width, cam.height); - vipc_server_->create_buffers(cam.rgb_type, UI_BUF_COUNT, true, cam.width, cam.height); - if (send_yuv) { - vipc_server_->create_buffers(cam.yuv_type, YUV_BUFFER_COUNT, false, cam.width, cam.height); - } + vipc_server_->create_buffers(cam.stream_type, YUV_BUFFER_COUNT, false, cam.width, cam.height); if (!cam.thread.joinable()) { cam.thread = std::thread(&CameraServer::cameraThread, this, std::ref(cam)); } @@ -39,10 +36,10 @@ void CameraServer::startVipcServer() { void CameraServer::cameraThread(Camera &cam) { auto read_frame = [&](FrameReader *fr, int frame_id) { - VisionBuf *rgb_buf = vipc_server_->get_buffer(cam.rgb_type); - VisionBuf *yuv_buf = send_yuv ? vipc_server_->get_buffer(cam.yuv_type) : nullptr; - bool ret = fr->get(frame_id, (uint8_t *)rgb_buf->addr, yuv_buf ? (uint8_t *)yuv_buf->addr : nullptr); - return ret ? std::pair{rgb_buf, yuv_buf} : std::pair{nullptr, nullptr}; + VisionBuf *yuv_buf = vipc_server_->get_buffer(cam.stream_type); + assert(yuv_buf); + bool ret = fr->get(frame_id, (uint8_t *)yuv_buf->addr); + return ret ? yuv_buf : nullptr; }; while (true) { @@ -51,17 +48,17 @@ void CameraServer::cameraThread(Camera &cam) { const int id = eidx.getSegmentId(); bool prefetched = (id == cam.cached_id && eidx.getSegmentNum() == cam.cached_seg); - auto [rgb, yuv] = prefetched ? cam.cached_buf : read_frame(fr, id); - if (rgb || yuv) { + auto yuv = prefetched ? cam.cached_buf : read_frame(fr, id); + if (yuv) { VisionIpcBufExtra extra = { .frame_id = eidx.getFrameId(), .timestamp_sof = eidx.getTimestampSof(), .timestamp_eof = eidx.getTimestampEof(), }; - if (rgb) vipc_server_->send(rgb, &extra, false); - if (yuv) vipc_server_->send(yuv, &extra, false); + yuv->set_frame_id(eidx.getFrameId()); + vipc_server_->send(yuv, &extra, false); } else { - rError("camera[%d] failed to get frame:", cam.type, eidx.getSegmentId()); + rError("camera[%d] failed to get frame: %lu", cam.type, eidx.getSegmentId()); } cam.cached_id = id + 1; @@ -77,10 +74,16 @@ void CameraServer::pushFrame(CameraType type, FrameReader *fr, const cereal::Enc if (cam.width != fr->width || cam.height != fr->height) { cam.width = fr->width; cam.height = fr->height; - waitFinish(); + waitForSent(); startVipcServer(); } ++publishing_; cam.queue.push({fr, eidx}); } + +void CameraServer::waitForSent() { + while (publishing_ > 0) { + std::this_thread::yield(); + } +} diff --git a/selfdrive/ui/replay/camera.h b/tools/replay/camera.h similarity index 52% rename from selfdrive/ui/replay/camera.h rename to tools/replay/camera.h index 340a120e8c..66d33142fb 100644 --- a/selfdrive/ui/replay/camera.h +++ b/tools/replay/camera.h @@ -2,41 +2,37 @@ #include #include "cereal/visionipc/visionipc_server.h" -#include "selfdrive/common/queue.h" -#include "selfdrive/ui/replay/framereader.h" -#include "selfdrive/ui/replay/logreader.h" +#include "common/queue.h" +#include "tools/replay/framereader.h" +#include "tools/replay/logreader.h" class CameraServer { public: - CameraServer(std::pair camera_size[MAX_CAMERAS] = nullptr, bool send_yuv = false); + CameraServer(std::pair camera_size[MAX_CAMERAS] = nullptr); ~CameraServer(); void pushFrame(CameraType type, FrameReader* fr, const cereal::EncodeIndex::Reader& eidx); - inline void waitFinish() { - while (publishing_ > 0) usleep(0); - } + void waitForSent(); protected: struct Camera { CameraType type; - VisionStreamType rgb_type; - VisionStreamType yuv_type; + VisionStreamType stream_type; int width; int height; std::thread thread; SafeQueue> queue; int cached_id = -1; int cached_seg = -1; - std::pair cached_buf; + VisionBuf * cached_buf; }; void startVipcServer(); void cameraThread(Camera &cam); Camera cameras_[MAX_CAMERAS] = { - {.type = RoadCam, .rgb_type = VISION_STREAM_RGB_BACK, .yuv_type = VISION_STREAM_ROAD}, - {.type = DriverCam, .rgb_type = VISION_STREAM_RGB_FRONT, .yuv_type = VISION_STREAM_DRIVER}, - {.type = WideRoadCam, .rgb_type = VISION_STREAM_RGB_WIDE, .yuv_type = VISION_STREAM_WIDE_ROAD}, + {.type = RoadCam, .stream_type = VISION_STREAM_ROAD}, + {.type = DriverCam, .stream_type = VISION_STREAM_DRIVER}, + {.type = WideRoadCam, .stream_type = VISION_STREAM_WIDE_ROAD}, }; std::atomic publishing_ = 0; std::unique_ptr vipc_server_; - bool send_yuv; }; diff --git a/tools/replay/can_replay.py b/tools/replay/can_replay.py index 6d68e75fe7..0b8b4fe0a1 100755 --- a/tools/replay/can_replay.py +++ b/tools/replay/can_replay.py @@ -2,6 +2,7 @@ import os import time import threading +import multiprocessing from tqdm import tqdm os.environ['FILEREADER_CACHE'] = '1' @@ -9,12 +10,16 @@ os.environ['FILEREADER_CACHE'] = '1' from common.basedir import BASEDIR from common.realtime import config_realtime_process, Ratekeeper, DT_CTRL from selfdrive.boardd.boardd import can_capnp_to_can_list -from tools.lib.logreader import LogReader +from tools.plotjuggler.juggle import load_segment from panda import Panda + try: - from panda_jungle import PandaJungle # pylint: disable=import-error -except Exception: - PandaJungle = None # type: ignore + # this bool can be replaced when mypy understands this pattern + panda_jungle_imported = True + from panda_jungle import PandaJungle # pylint: disable=import-error # type: ignore +except ImportError: + PandaJungle = None + panda_jungle_imported = False def send_thread(s, flock): @@ -82,7 +87,7 @@ def connect(): if __name__ == "__main__": - if PandaJungle is None: + if not panda_jungle_imported: print("\33[31m", "WARNING: cannot connect to jungles. Clone the jungle library to enable support:", "\033[0m") print("\033[34m", f"cd {BASEDIR} && git clone https://github.com/commaai/panda_jungle", "\033[0m") @@ -90,11 +95,10 @@ if __name__ == "__main__": ROUTE = "77611a1fac303767/2020-03-24--09-50-38" REPLAY_SEGS = list(range(10, 16)) # route has 82 segments available CAN_MSGS = [] - for i in tqdm(REPLAY_SEGS): - log_url = f"https://commadataci.blob.core.windows.net/openpilotci/{ROUTE}/{i}/rlog.bz2" - lr = LogReader(log_url) - CAN_MSGS += [can_capnp_to_can_list(m.can) for m in lr if m.which() == 'can'] - + logs = [f"https://commadataci.blob.core.windows.net/openpilotci/{ROUTE}/{i}/rlog.bz2" for i in REPLAY_SEGS] + with multiprocessing.Pool(24) as pool: + for lr in tqdm(pool.map(load_segment, logs)): + CAN_MSGS += [can_capnp_to_can_list(m.can) for m in lr if m.which() == 'can'] # set both to cycle ignition IGN_ON = int(os.getenv("ON", "0")) diff --git a/selfdrive/ui/replay/consoleui.cc b/tools/replay/consoleui.cc similarity index 91% rename from selfdrive/ui/replay/consoleui.cc rename to tools/replay/consoleui.cc index 72e2fcf802..77357a2873 100644 --- a/selfdrive/ui/replay/consoleui.cc +++ b/tools/replay/consoleui.cc @@ -1,9 +1,9 @@ -#include "selfdrive/ui/replay/consoleui.h" +#include "tools/replay/consoleui.h" #include #include -#include "selfdrive/common/version.h" +#include "common/version.h" namespace { @@ -18,6 +18,10 @@ const std::initializer_list> keyboard_shortc {"space", "Pause/Resume"}, {"e", "Next Engagement"}, {"d", "Next Disengagement"}, + {"t", "Next User Tag"}, + {"i", "Next Info"}, + {"w", "Next Warning"}, + {"c", "Next Critical"}, }, { {"enter", "Enter seek request"}, @@ -32,6 +36,7 @@ enum Color { Yellow, Green, Red, + Cyan, BrightWhite, Engaged, Disengaged, @@ -70,6 +75,7 @@ ConsoleUI::ConsoleUI(Replay *replay, QObject *parent) : replay(replay), sm({"car init_pair(Color::Debug, 246, COLOR_BLACK); // #949494 init_pair(Color::Yellow, 184, COLOR_BLACK); init_pair(Color::Red, COLOR_RED, COLOR_BLACK); + init_pair(Color::Cyan, COLOR_CYAN, COLOR_BLACK); init_pair(Color::BrightWhite, 15, COLOR_BLACK); init_pair(Color::Disengaged, COLOR_BLUE, COLOR_BLUE); init_pair(Color::Engaged, 28, 28); @@ -150,13 +156,13 @@ void ConsoleUI::timerEvent(QTimerEvent *ev) { } void ConsoleUI::updateStatus() { - auto write_item = [this](int y, int x, const char *key, const std::string &value, const char *unit, + auto write_item = [this](int y, int x, const char *key, const std::string &value, const std::string &unit, bool bold = false, Color color = Color::BrightWhite) { auto win = w[Win::CarState]; wmove(win, y, x); add_str(win, key); add_str(win, value.c_str(), color, bold); - add_str(win, unit); + add_str(win, unit.c_str()); }; static const std::pair status_text[] = { {"loading...", Color::Red}, @@ -171,9 +177,8 @@ void ConsoleUI::updateStatus() { } auto [status_str, status_color] = status_text[status]; write_item(0, 0, "STATUS: ", status_str, " ", false, status_color); - std::string suffix = util::string_format(" / %s [%d/%d] ", format_seconds(replay->totalSeconds()).c_str(), - replay->currentSeconds() / 60, replay->route()->segments().size()); - write_item(0, 25, "TIME: ", format_seconds(replay->currentSeconds()), suffix.c_str(), true); + std::string suffix = " / " + format_seconds(replay->totalSeconds()); + write_item(0, 25, "TIME: ", format_seconds(replay->currentSeconds()), suffix, true); auto p = sm["liveParameters"].getLiveParameters(); write_item(1, 0, "STIFFNESS: ", util::string_format("%.2f %%", p.getStiffnessFactor() * 100), " "); @@ -205,6 +210,7 @@ void ConsoleUI::displayTimelineDesc() { {Color::Green, " Info ", true}, {Color::Yellow, " Warning ", true}, {Color::Red, " Critical ", true}, + {Color::Cyan, " User Tag ", true}, }; for (auto [color, name, bold] : indicators) { add_str(w[Win::TimelineDesc], "__", color, bold); @@ -241,7 +247,7 @@ void ConsoleUI::updateProgressBar(uint64_t cur, uint64_t total, bool success) { void ConsoleUI::updateSummary() { const auto &route = replay->route(); - mvwprintw(w[Win::Stats], 0, 0, "Route: %s, %d segments", qPrintable(route->name()), route->segments().size()); + mvwprintw(w[Win::Stats], 0, 0, "Route: %s, %lu segments", qPrintable(route->name()), route->segments().size()); mvwprintw(w[Win::Stats], 1, 0, "Car Fingerprint: %s", replay->carFingerprint().c_str()); wrefresh(w[Win::Stats]); } @@ -263,6 +269,8 @@ void ConsoleUI::updateTimeline() { if (type == TimelineType::Engaged) { mvwchgat(win, 1, start_pos, end_pos - start_pos + 1, A_COLOR, Color::Engaged, NULL); mvwchgat(win, 2, start_pos, end_pos - start_pos + 1, A_COLOR, Color::Engaged, NULL); + } else if (type == TimelineType::UserFlag) { + mvwchgat(win, 3, start_pos, end_pos - start_pos + 1, ACS_S3, Color::Cyan, NULL); } else { auto color_id = Color::Green; if (type != TimelineType::AlertInfo) { @@ -336,6 +344,14 @@ void ConsoleUI::handleKey(char c) { replay->seekToFlag(FindFlag::nextEngagement); } else if (c == 'd') { replay->seekToFlag(FindFlag::nextDisEngagement); + } else if (c == 't') { + replay->seekToFlag(FindFlag::nextUserFlag); + } else if (c == 'i') { + replay->seekToFlag(FindFlag::nextInfo); + } else if (c == 'w') { + replay->seekToFlag(FindFlag::nextWarning); + } else if (c == 'c') { + replay->seekToFlag(FindFlag::nextCritical); } else if (c == 'm') { replay->seekTo(+60, true); } else if (c == 'M') { diff --git a/selfdrive/ui/replay/consoleui.h b/tools/replay/consoleui.h similarity index 96% rename from selfdrive/ui/replay/consoleui.h rename to tools/replay/consoleui.h index bce1146d46..20e07524dd 100644 --- a/selfdrive/ui/replay/consoleui.h +++ b/tools/replay/consoleui.h @@ -7,7 +7,7 @@ #include #include -#include "selfdrive/ui/replay/replay.h" +#include "tools/replay/replay.h" #include class ConsoleUI : public QObject { diff --git a/selfdrive/ui/replay/filereader.cc b/tools/replay/filereader.cc similarity index 91% rename from selfdrive/ui/replay/filereader.cc rename to tools/replay/filereader.cc index b57a62d501..88879067c9 100644 --- a/selfdrive/ui/replay/filereader.cc +++ b/tools/replay/filereader.cc @@ -1,9 +1,9 @@ -#include "selfdrive/ui/replay/filereader.h" +#include "tools/replay/filereader.h" #include -#include "selfdrive/common/util.h" -#include "selfdrive/ui/replay/util.h" +#include "common/util.h" +#include "tools/replay/util.h" std::string cacheFilePath(const std::string &url) { static std::string cache_path = [] { diff --git a/selfdrive/ui/replay/filereader.h b/tools/replay/filereader.h similarity index 100% rename from selfdrive/ui/replay/filereader.h rename to tools/replay/filereader.h diff --git a/selfdrive/ui/replay/framereader.cc b/tools/replay/framereader.cc similarity index 75% rename from selfdrive/ui/replay/framereader.cc rename to tools/replay/framereader.cc index a0aa35e6ae..a1ff7b9f8e 100644 --- a/selfdrive/ui/replay/framereader.cc +++ b/tools/replay/framereader.cc @@ -1,11 +1,19 @@ -#include "selfdrive/ui/replay/framereader.h" -#include "selfdrive/ui/replay/util.h" +#include "tools/replay/framereader.h" +#include "tools/replay/util.h" #include #include "libyuv.h" #include "cereal/visionipc/visionbuf.h" +#ifdef __APPLE__ +#define HW_DEVICE_TYPE AV_HWDEVICE_TYPE_VIDEOTOOLBOX +#define HW_PIX_FMT AV_PIX_FMT_VIDEOTOOLBOX +#else +#define HW_DEVICE_TYPE AV_HWDEVICE_TYPE_CUDA +#define HW_PIX_FMT AV_PIX_FMT_CUDA +#endif + namespace { struct buffer_data { @@ -30,7 +38,7 @@ enum AVPixelFormat get_hw_format(AVCodecContext *ctx, const enum AVPixelFormat * for (const enum AVPixelFormat *p = pix_fmts; *p != -1; p++) { if (*p == *hw_pix_fmt) return *p; } - rWarning("Please run replay with the --no-cuda flag!"); + rWarning("Please run replay with the --no-hw-decoder flag!"); // fallback to YUV420p *hw_pix_fmt = AV_PIX_FMT_NONE; return AV_PIX_FMT_YUV420P; @@ -57,15 +65,15 @@ FrameReader::~FrameReader() { } } -bool FrameReader::load(const std::string &url, bool no_cuda, std::atomic *abort, bool local_cache, int chunk_size, int retries) { +bool FrameReader::load(const std::string &url, bool no_hw_decoder, std::atomic *abort, bool local_cache, int chunk_size, int retries) { FileReader f(local_cache, chunk_size, retries); std::string data = f.read(url, abort); if (data.empty()) return false; - return load((std::byte *)data.data(), data.size(), no_cuda, abort); + return load((std::byte *)data.data(), data.size(), no_hw_decoder, abort); } -bool FrameReader::load(const std::byte *data, size_t size, bool no_cuda, std::atomic *abort) { +bool FrameReader::load(const std::byte *data, size_t size, bool no_hw_decoder, std::atomic *abort) { input_ctx = avformat_alloc_context(); if (!input_ctx) return false; @@ -106,11 +114,9 @@ bool FrameReader::load(const std::byte *data, size_t size, bool no_cuda, std::at height = decoder_ctx->height; visionbuf_compute_aligned_width_and_height(width, height, &aligned_width, &aligned_height); - if (has_cuda_device && !no_cuda) { - if (!initHardwareDecoder(AV_HWDEVICE_TYPE_CUDA)) { - rWarning("No CUDA capable device was found. fallback to CPU decoding."); - } else { - nv12toyuv_buffer.resize(getYUVSize()); + if (has_hw_decoder && !no_hw_decoder) { + if (!initHardwareDecoder(HW_DEVICE_TYPE)) { + rWarning("No device with hardware decoder found. fallback to CPU decoding."); } } @@ -127,7 +133,7 @@ bool FrameReader::load(const std::byte *data, size_t size, bool no_cuda, std::at break; } packets.push_back(pkt); - // some stream seems to contian no keyframes + // some stream seems to contain no keyframes key_frames_count_ += pkt->flags & AV_PKT_FLAG_KEY; } valid_ = valid_ && !packets.empty(); @@ -151,7 +157,7 @@ bool FrameReader::initHardwareDecoder(AVHWDeviceType hw_device_type) { int ret = av_hwdevice_ctx_create(&hw_device_ctx, hw_device_type, nullptr, nullptr, 0); if (ret < 0) { hw_pix_fmt = AV_PIX_FMT_NONE; - has_cuda_device = false; + has_hw_decoder = false; rWarning("Failed to create specified HW device %d.", ret); return false; } @@ -162,15 +168,15 @@ bool FrameReader::initHardwareDecoder(AVHWDeviceType hw_device_type) { return true; } -bool FrameReader::get(int idx, uint8_t *rgb, uint8_t *yuv) { - assert(rgb || yuv); +bool FrameReader::get(int idx, uint8_t *yuv) { + assert(yuv != nullptr); if (!valid_ || idx < 0 || idx >= packets.size()) { return false; } - return decode(idx, rgb, yuv); + return decode(idx, yuv); } -bool FrameReader::decode(int idx, uint8_t *rgb, uint8_t *yuv) { +bool FrameReader::decode(int idx, uint8_t *yuv) { int from_idx = idx; if (idx != prev_idx + 1 && key_frames_count_ > 1) { // seeking to the nearest key frame @@ -186,7 +192,7 @@ bool FrameReader::decode(int idx, uint8_t *rgb, uint8_t *yuv) { for (int i = from_idx; i <= idx; ++i) { AVFrame *f = decodeFrame(packets[i]); if (f && i == idx) { - return copyBuffers(f, rgb, yuv); + return copyBuffers(f, yuv); } } return false; @@ -218,29 +224,23 @@ AVFrame *FrameReader::decodeFrame(AVPacket *pkt) { } } -bool FrameReader::copyBuffers(AVFrame *f, uint8_t *rgb, uint8_t *yuv) { - if (hw_pix_fmt == AV_PIX_FMT_CUDA) { - uint8_t *y = yuv ? yuv : nv12toyuv_buffer.data(); - uint8_t *u = y + width * height; - uint8_t *v = u + (width / 2) * (height / 2); - libyuv::NV12ToI420(f->data[0], f->linesize[0], f->data[1], f->linesize[1], - y, width, u, width / 2, v, width / 2, width, height); - libyuv::I420ToRGB24(y, width, u, width / 2, v, width / 2, - rgb, aligned_width * 3, width, height); +bool FrameReader::copyBuffers(AVFrame *f, uint8_t *yuv) { + assert(f != nullptr && yuv != nullptr); + uint8_t *y = yuv; + uint8_t *uv = y + width * height; + if (hw_pix_fmt == HW_PIX_FMT) { + for (int i = 0; i < height/2; i++) { + memcpy(y + (i*2 + 0)*width, f->data[0] + (i*2 + 0)*f->linesize[0], width); + memcpy(y + (i*2 + 1)*width, f->data[0] + (i*2 + 1)*f->linesize[0], width); + memcpy(uv + i*width, f->data[1] + i*f->linesize[1], width); + } } else { - if (yuv) { - uint8_t *u = yuv + width * height; - uint8_t *v = u + (width / 2) * (height / 2); - libyuv::I420Copy(f->data[0], f->linesize[0], + libyuv::I420ToNV12(f->data[0], f->linesize[0], f->data[1], f->linesize[1], f->data[2], f->linesize[2], - yuv, width, u, width / 2, v, width / 2, + y, width, + uv, width, width, height); - } - libyuv::I420ToRGB24(f->data[0], f->linesize[0], - f->data[1], f->linesize[1], - f->data[2], f->linesize[2], - rgb, aligned_width * 3, width, height); } return true; } diff --git a/selfdrive/ui/replay/framereader.h b/tools/replay/framereader.h similarity index 61% rename from selfdrive/ui/replay/framereader.h rename to tools/replay/framereader.h index 8de5c1f93e..e50b61d7f4 100644 --- a/selfdrive/ui/replay/framereader.h +++ b/tools/replay/framereader.h @@ -4,7 +4,7 @@ #include #include -#include "selfdrive/ui/replay/filereader.h" +#include "tools/replay/filereader.h" extern "C" { #include @@ -19,10 +19,10 @@ class FrameReader { public: FrameReader(); ~FrameReader(); - bool load(const std::string &url, bool no_cuda = false, std::atomic *abort = nullptr, bool local_cache = false, int chunk_size = -1, int retries = 0); - bool load(const std::byte *data, size_t size, bool no_cuda = false, std::atomic *abort = nullptr); - bool get(int idx, uint8_t *rgb, uint8_t *yuv); - int getRGBSize() const { return aligned_width * aligned_height * 3; } + bool load(const std::string &url, bool no_hw_decoder = false, std::atomic *abort = nullptr, bool local_cache = false, + int chunk_size = -1, int retries = 0); + bool load(const std::byte *data, size_t size, bool no_hw_decoder = false, std::atomic *abort = nullptr); + bool get(int idx, uint8_t *yuv); int getYUVSize() const { return width * height * 3 / 2; } size_t getFrameCount() const { return packets.size(); } bool valid() const { return valid_; } @@ -32,9 +32,9 @@ public: private: bool initHardwareDecoder(AVHWDeviceType hw_device_type); - bool decode(int idx, uint8_t *rgb, uint8_t *yuv); + bool decode(int idx, uint8_t *yuv); AVFrame * decodeFrame(AVPacket *pkt); - bool copyBuffers(AVFrame *f, uint8_t *rgb, uint8_t *yuv); + bool copyBuffers(AVFrame *f, uint8_t *yuv); std::vector packets; std::unique_ptrav_frame_, hw_frame; @@ -46,7 +46,6 @@ private: AVPixelFormat hw_pix_fmt = AV_PIX_FMT_NONE; AVBufferRef *hw_device_ctx = nullptr; - std::vector nv12toyuv_buffer; int prev_idx = -1; - inline static std::atomic has_cuda_device = true; + inline static std::atomic has_hw_decoder = true; }; diff --git a/tools/replay/lib/ui_helpers.py b/tools/replay/lib/ui_helpers.py index 33a1e77e05..d66fe79306 100644 --- a/tools/replay/lib/ui_helpers.py +++ b/tools/replay/lib/ui_helpers.py @@ -10,8 +10,7 @@ from matplotlib.backends.backend_agg import FigureCanvasAgg from common.transformations.camera import (eon_f_frame_size, eon_f_focal_length, tici_f_frame_size, tici_f_focal_length, get_view_frame_from_calib_frame) -from selfdrive.config import UIParams as UP -from selfdrive.config import RADAR_TO_CAMERA +from selfdrive.controls.lib.radar_helpers import RADAR_TO_CAMERA RED = (255, 0, 0) @@ -24,6 +23,15 @@ WHITE = (255, 255, 255) _FULL_FRAME_SIZE = { } +class UIParams: + lidar_x, lidar_y, lidar_zoom = 384, 960, 6 + lidar_car_x, lidar_car_y = lidar_x / 2., lidar_y / 1.1 + car_hwidth = 1.7272 / 2 * lidar_zoom + car_front = 2.6924 * lidar_zoom + car_back = 1.8796 * lidar_zoom + car_color = 110 +UP = UIParams + _BB_TO_FULL_FRAME = {} _CALIB_BB_TO_FULL = {} _FULL_FRAME_TO_BB = {} diff --git a/selfdrive/ui/replay/logreader.cc b/tools/replay/logreader.cc similarity index 74% rename from selfdrive/ui/replay/logreader.cc rename to tools/replay/logreader.cc index 579fe50644..e3d5071412 100644 --- a/selfdrive/ui/replay/logreader.cc +++ b/tools/replay/logreader.cc @@ -1,7 +1,7 @@ -#include "selfdrive/ui/replay/logreader.h" +#include "tools/replay/logreader.h" #include -#include "selfdrive/ui/replay/util.h" +#include "tools/replay/util.h" Event::Event(const kj::ArrayPtr &amsg, bool frame) : reader(amsg), frame(frame) { words = kj::ArrayPtr(amsg.begin(), reader.getEnd()); @@ -46,26 +46,36 @@ LogReader::~LogReader() { #endif } -bool LogReader::load(const std::string &url, std::atomic *abort, bool local_cache, int chunk_size, int retries) { - FileReader f(local_cache, chunk_size, retries); - std::string data = f.read(url, abort); - if (data.empty()) return false; +bool LogReader::load(const std::string &url, std::atomic *abort, + const std::set &allow, + bool local_cache, int chunk_size, int retries) { + raw_ = FileReader(local_cache, chunk_size, retries).read(url, abort); + if (raw_.empty()) return false; - return load((std::byte*)data.data(), data.size(), abort); + if (url.find(".bz2") != std::string::npos) { + raw_ = decompressBZ2(raw_, abort); + if (raw_.empty()) return false; + } + return parse(allow, abort); } bool LogReader::load(const std::byte *data, size_t size, std::atomic *abort) { - raw_ = decompressBZ2(data, size, abort); - if (raw_.empty()) { - if (!(abort && *abort)) { - rWarning("failed to decompress log"); - } - return false; - } + raw_.assign((const char *)data, size); + return parse({}, abort); +} +bool LogReader::parse(const std::set &allow, std::atomic *abort) { try { kj::ArrayPtr words((const capnp::word *)raw_.data(), raw_.size() / sizeof(capnp::word)); while (words.size() > 0 && !(abort && *abort)) { + if (!allow.empty()) { + capnp::FlatArrayMessageReader reader(words); + auto which = reader.getRoot().which(); + if (allow.find(which) == allow.end()) { + words = kj::arrayPtr(reader.getEnd(), words.end()); + continue; + } + } #ifdef HAS_MEMORY_RESOURCE Event *evt = new (mbr_) Event(words); diff --git a/selfdrive/ui/replay/logreader.h b/tools/replay/logreader.h similarity index 85% rename from selfdrive/ui/replay/logreader.h rename to tools/replay/logreader.h index 7ada20605e..010839af22 100644 --- a/selfdrive/ui/replay/logreader.h +++ b/tools/replay/logreader.h @@ -5,9 +5,11 @@ #include #endif +#include + #include "cereal/gen/cpp/log.capnp.h" -#include "selfdrive/camerad/cameras/camera_common.h" -#include "selfdrive/ui/replay/filereader.h" +#include "system/camerad/cameras/camera_common.h" +#include "tools/replay/filereader.h" const CameraType ALL_CAMERAS[] = {RoadCam, DriverCam, WideRoadCam}; const int MAX_CAMERAS = std::size(ALL_CAMERAS); @@ -50,12 +52,13 @@ class LogReader { public: LogReader(size_t memory_pool_block_size = DEFAULT_EVENT_MEMORY_POOL_BLOCK_SIZE); ~LogReader(); - bool load(const std::string &url, std::atomic *abort = nullptr, bool local_cache = false, int chunk_size = -1, int retries = 0); + bool load(const std::string &url, std::atomic *abort = nullptr, const std::set &allow = {}, + bool local_cache = false, int chunk_size = -1, int retries = 0); bool load(const std::byte *data, size_t size, std::atomic *abort = nullptr); - std::vector events; private: + bool parse(const std::set &allow, std::atomic *abort); std::string raw_; #ifdef HAS_MEMORY_RESOURCE std::pmr::monotonic_buffer_resource *mbr_ = nullptr; diff --git a/selfdrive/ui/replay/main.cc b/tools/replay/main.cc similarity index 87% rename from selfdrive/ui/replay/main.cc rename to tools/replay/main.cc index a7d2f54042..40dace0c91 100644 --- a/selfdrive/ui/replay/main.cc +++ b/tools/replay/main.cc @@ -1,13 +1,11 @@ #include #include -#include "selfdrive/ui/replay/consoleui.h" -#include "selfdrive/ui/replay/replay.h" - -const QString DEMO_ROUTE = "4cf7a6ad03080c90|2021-09-29--13-46-36"; +#include "tools/replay/consoleui.h" +#include "tools/replay/replay.h" int main(int argc, char *argv[]) { - QApplication app(argc, argv); + QCoreApplication app(argc, argv); const std::tuple flags[] = { {"dcam", REPLAY_FLAG_DCAM, "load driver camera"}, @@ -15,8 +13,7 @@ int main(int argc, char *argv[]) { {"no-loop", REPLAY_FLAG_NO_LOOP, "stop at the end of the route"}, {"no-cache", REPLAY_FLAG_NO_FILE_CACHE, "turn off local cache"}, {"qcam", REPLAY_FLAG_QCAMERA, "load qcamera"}, - {"yuv", REPLAY_FLAG_SEND_YUV, "send yuv frame"}, - {"no-cuda", REPLAY_FLAG_NO_CUDA, "disable CUDA"}, + {"no-hw-decoder", REPLAY_FLAG_NO_HW_DECODER, "disable HW video decoding"}, {"no-vipc", REPLAY_FLAG_NO_VIPC, "do not output video"}, }; diff --git a/selfdrive/ui/replay/replay.cc b/tools/replay/replay.cc similarity index 83% rename from selfdrive/ui/replay/replay.cc rename to tools/replay/replay.cc index fd1a4b1990..339e688be1 100644 --- a/selfdrive/ui/replay/replay.cc +++ b/tools/replay/replay.cc @@ -1,14 +1,14 @@ -#include "selfdrive/ui/replay/replay.h" +#include "tools/replay/replay.h" #include #include #include #include "cereal/services.h" -#include "selfdrive/common/params.h" -#include "selfdrive/common/timing.h" -#include "selfdrive/hardware/hw.h" -#include "selfdrive/ui/replay/util.h" +#include "common/params.h" +#include "common/timing.h" +#include "system/hardware/hw.h" +#include "tools/replay/util.h" Replay::Replay(QString route, QStringList allow, QStringList block, SubMaster *sm_, uint32_t flags, QString data_dir, QObject *parent) : sm(sm_), flags_(flags), QObject(parent) { @@ -19,6 +19,9 @@ Replay::Replay(QString route, QStringList allow, QStringList block, SubMaster *s if ((allow.empty() || allow.contains(it.name)) && !block.contains(it.name)) { uint16_t which = event_struct.getFieldByName(it.name).getProto().getDiscriminantValue(); sockets_[which] = it.name; + if (!allow.empty() || !block.empty()) { + allow_list.insert((cereal::Event::Which)which); + } s.push_back(it.name); } } @@ -81,7 +84,7 @@ void Replay::start(int seconds) { } void Replay::updateEvents(const std::function &lambda) { - // set updating_events to true to force stream thread relase the lock and wait for evnets_udpated. + // set updating_events to true to force stream thread release the lock and wait for evnets_udpated. updating_events_ = true; { std::unique_lock lk(stream_lock_); @@ -91,17 +94,17 @@ void Replay::updateEvents(const std::function &lambda) { stream_cv_.notify_one(); } -void Replay::seekTo(int seconds, bool relative) { +void Replay::seekTo(double seconds, bool relative) { seconds = relative ? seconds + currentSeconds() : seconds; updateEvents([&]() { - seconds = std::max(0, seconds); - int seg = seconds / 60; + seconds = std::max(double(0.0), seconds); + int seg = (int)seconds / 60; if (segments_.find(seg) == segments_.end()) { rWarning("can't seek to %d s segment %d is invalid", seconds, seg); return true; } - rInfo("seeking to %d s, segment %d", seconds, seg); + rInfo("seeking to %d s, segment %d", (int)seconds, seg); current_segment_ = seg; cur_mono_time_ = route_start_ts_ + seconds * 1e9; return isSegmentMerged(seg); @@ -120,9 +123,11 @@ void Replay::buildTimeline() { uint64_t alert_begin = 0; TimelineType alert_type = TimelineType::None; - for (int i = 0; i < segments_.size() && !exit_; ++i) { + for (auto it = segments_.cbegin(); it != segments_.cend() && !exit_; ++it) { LogReader log; - if (!log.load(route_->at(i).qlog.toStdString(), &exit_, !hasFlag(REPLAY_FLAG_NO_FILE_CACHE), 0, 3)) continue; + if (!log.load(route_->at(it->first).qlog.toStdString(), &exit_, + {cereal::Event::Which::CONTROLS_STATE, cereal::Event::Which::USER_FLAG}, + !hasFlag(REPLAY_FLAG_NO_FILE_CACHE), 0, 3)) continue; for (const Event *e : log.events) { if (e->which == cereal::Event::Which::CONTROLS_STATE) { @@ -149,6 +154,9 @@ void Replay::buildTimeline() { timeline.push_back({toSeconds(alert_begin), toSeconds(e->mono_time), alert_type}); alert_begin = 0; } + } else if (e->which == cereal::Event::Which::USER_FLAG) { + std::lock_guard lk(timeline_lock); + timeline.push_back({toSeconds(e->mono_time), toSeconds(e->mono_time), TimelineType::UserFlag}); } } } @@ -163,6 +171,13 @@ std::optional Replay::find(FindFlag flag) { } else if (flag == FindFlag::nextDisEngagement && end_ts > cur_ts) { return end_ts; } + } else if (start_ts > cur_ts) { + if ((flag == FindFlag::nextUserFlag && type == TimelineType::UserFlag) || + (flag == FindFlag::nextInfo && type == TimelineType::AlertInfo) || + (flag == FindFlag::nextWarning && type == TimelineType::AlertWarning) || + (flag == FindFlag::nextCritical && type == TimelineType::AlertCritical)) { + return start_ts; + } } } return std::nullopt; @@ -196,7 +211,7 @@ void Replay::queueSegment() { SegmentMap::iterator cur, end; cur = end = segments_.lower_bound(std::min(current_segment_.load(), segments_.rbegin()->first)); - for (int i = 0; end != segments_.end() && i <= FORWARD_SEGS; ++i) { + for (int i = 0; end != segments_.end() && i <= segment_cache_limit + FORWARD_FETCH_SEGS; ++i) { ++end; } // load one segment at a time @@ -205,7 +220,7 @@ void Replay::queueSegment() { if ((seg && !seg->isLoaded()) || !seg) { if (!seg) { rDebug("loading segment %d...", n); - seg = std::make_unique(n, route_->at(n), flags_); + seg = std::make_unique(n, route_->at(n), flags_, allow_list); QObject::connect(seg.get(), &Segment::loadFinished, this, &Replay::segmentLoadFinished); } break; @@ -235,7 +250,7 @@ void Replay::mergeSegments(const SegmentMap::iterator &begin, const SegmentMap:: // merge 3 segments in sequence. std::vector segments_need_merge; size_t new_events_size = 0; - for (auto it = begin; it != end && it->second && it->second->isLoaded() && segments_need_merge.size() < 3; ++it) { + for (auto it = begin; it != end && it->second && it->second->isLoaded() && segments_need_merge.size() < segment_cache_limit; ++it) { segments_need_merge.push_back(it->first); new_events_size += it->second->log->events.size(); } @@ -260,6 +275,9 @@ void Replay::mergeSegments(const SegmentMap::iterator &begin, const SegmentMap:: segments_merged_ = segments_need_merge; return true; }); + if (stream_thread_) { + emit segmentsMerged(); + } } } @@ -275,8 +293,12 @@ void Replay::startStream(const Segment *cur_segment) { it = std::find_if(events.begin(), events.end(), [](auto e) { return e->which == cereal::Event::Which::CAR_PARAMS; }); if (it != events.end()) { car_fingerprint_ = (*it)->event.getCarParams().getCarFingerprint(); - auto bytes = (*it)->bytes(); + capnp::MallocMessageBuilder builder; + builder.setRoot((*it)->event.getCarParams()); + auto words = capnp::messageToFlatArray(builder); + auto bytes = words.asBytes(); Params().put("CarParams", (const char *)bytes.begin(), bytes.size()); + Params().put("CarParamsPersistent", (const char *)bytes.begin(), bytes.size()); } else { rWarning("failed to read CarParams from current segment"); } @@ -289,9 +311,10 @@ void Replay::startStream(const Segment *cur_segment) { camera_size[type] = {fr->width, fr->height}; } } - camera_server_ = std::make_unique(camera_size, hasFlag(REPLAY_FLAG_SEND_YUV)); + camera_server_ = std::make_unique(camera_size); } + emit segmentsMerged(); // start stream thread stream_thread_ = new QThread(); QObject::connect(stream_thread_, &QThread::started, [=]() { stream(); }); @@ -302,6 +325,8 @@ void Replay::startStream(const Segment *cur_segment) { } void Replay::publishMessage(const Event *e) { + if (event_filter && event_filter(e, filter_opaque)) return; + if (sm == nullptr) { auto bytes = e->bytes(); int ret = pm->send(sockets_[e->which], (capnp::byte *)bytes.begin(), bytes.size()); @@ -333,6 +358,7 @@ void Replay::publishFrame(const Event *e) { void Replay::stream() { cereal::Event::Which cur_which = cereal::Event::Which::INIT_DATA; + double prev_replay_speed = 1.0; std::unique_lock lk(stream_lock_); while (true) { @@ -357,7 +383,8 @@ void Replay::stream() { setCurrentSegment(toSeconds(cur_mono_time_) / 60); // migration for pandaState -> pandaStates to keep UI working for old segments - if (cur_which == cereal::Event::Which::PANDA_STATE_D_E_P_R_E_C_A_T_E_D) { + if (cur_which == cereal::Event::Which::PANDA_STATE_D_E_P_R_E_C_A_T_E_D && + sockets_[cereal::Event::Which::PANDA_STATES] != nullptr) { MessageBuilder msg; auto ps = msg.initEvent().initPandaStates(1); ps[0].setIgnitionLine(true); @@ -367,14 +394,15 @@ void Replay::stream() { if (cur_which < sockets_.size() && sockets_[cur_which] != nullptr) { // keep time - long etime = cur_mono_time_ - evt_start_ts; + long etime = (cur_mono_time_ - evt_start_ts) / speed_; long rtime = nanos_since_boot() - loop_start_ts; long behind_ns = etime - rtime; // if behind_ns is greater than 1 second, it means that an invalid segemnt is skipped by seeking/replaying - if (behind_ns >= 1 * 1e9) { - // reset start times + if (behind_ns >= 1 * 1e9 || speed_ != prev_replay_speed) { + // reset event start times evt_start_ts = cur_mono_time_; loop_start_ts = nanos_since_boot(); + prev_replay_speed = speed_; } else if (behind_ns > 0 && !hasFlag(REPLAY_FLAG_FULL_SPEED)) { precise_nano_sleep(behind_ns); } @@ -383,7 +411,7 @@ void Replay::stream() { publishMessage(evt); } else if (camera_server_) { if (hasFlag(REPLAY_FLAG_FULL_SPEED)) { - camera_server_->waitFinish(); + camera_server_->waitForSent(); } publishFrame(evt); } @@ -391,7 +419,7 @@ void Replay::stream() { } // wait for frame to be sent before unlock.(frameReader may be deleted after unlock) if (camera_server_) { - camera_server_->waitFinish(); + camera_server_->waitForSent(); } if (eit == events_->end() && !hasFlag(REPLAY_FLAG_NO_LOOP)) { diff --git a/selfdrive/ui/replay/replay.h b/tools/replay/replay.h similarity index 67% rename from selfdrive/ui/replay/replay.h rename to tools/replay/replay.h index d20d5bb920..88c285125a 100644 --- a/selfdrive/ui/replay/replay.h +++ b/tools/replay/replay.h @@ -4,11 +4,13 @@ #include -#include "selfdrive/ui/replay/camera.h" -#include "selfdrive/ui/replay/route.h" +#include "tools/replay/camera.h" +#include "tools/replay/route.h" + +const QString DEMO_ROUTE = "4cf7a6ad03080c90|2021-09-29--13-46-36"; // one segment uses about 100M of memory -constexpr int FORWARD_SEGS = 5; +constexpr int FORWARD_FETCH_SEGS = 3; enum REPLAY_FLAGS { REPLAY_FLAG_NONE = 0x0000, @@ -17,18 +19,22 @@ enum REPLAY_FLAGS { REPLAY_FLAG_NO_LOOP = 0x0010, REPLAY_FLAG_NO_FILE_CACHE = 0x0020, REPLAY_FLAG_QCAMERA = 0x0040, - REPLAY_FLAG_SEND_YUV = 0x0080, - REPLAY_FLAG_NO_CUDA = 0x0100, + REPLAY_FLAG_NO_HW_DECODER = 0x0100, REPLAY_FLAG_FULL_SPEED = 0x0200, REPLAY_FLAG_NO_VIPC = 0x0400, }; enum class FindFlag { nextEngagement, - nextDisEngagement + nextDisEngagement, + nextUserFlag, + nextInfo, + nextWarning, + nextCritical }; -enum class TimelineType { None, Engaged, AlertInfo, AlertWarning, AlertCritical }; +enum class TimelineType { None, Engaged, AlertInfo, AlertWarning, AlertCritical, UserFlag }; +typedef bool (*replayEventFilter)(const Event *, void *); class Replay : public QObject { Q_OBJECT @@ -42,15 +48,28 @@ public: void stop(); void pause(bool pause); void seekToFlag(FindFlag flag); - void seekTo(int seconds, bool relative); + void seekTo(double seconds, bool relative); inline bool isPaused() const { return paused_; } + // the filter is called in streaming thread.try to return quickly from it to avoid blocking streaming. + // the filter function must return true if the event should be filtered. + // otherwise it must return false. + inline void installEventFilter(replayEventFilter filter, void *opaque) { + filter_opaque = opaque; + event_filter = filter; + } + inline int segmentCacheLimit() const { return segment_cache_limit; } + inline void setSegmentCacheLimit(int n) { segment_cache_limit = std::max(3, n); } inline bool hasFlag(REPLAY_FLAGS flag) const { return flags_ & flag; } inline void addFlag(REPLAY_FLAGS flag) { flags_ |= flag; } inline void removeFlag(REPLAY_FLAGS flag) { flags_ &= ~flag; } inline const Route* route() const { return route_.get(); } - inline int currentSeconds() const { return (cur_mono_time_ - route_start_ts_) / 1e9; } + inline double currentSeconds() const { return double(cur_mono_time_ - route_start_ts_) / 1e9; } + inline uint64_t routeStartTime() const { return route_start_ts_; } inline int toSeconds(uint64_t mono_time) const { return (mono_time - route_start_ts_) / 1e9; } inline int totalSeconds() const { return segments_.size() * 60; } + inline void setSpeed(float speed) { speed_ = speed; } + inline float getSpeed() const { return speed_; } + inline const std::vector *events() const { return events_.get(); } inline const std::string &carFingerprint() const { return car_fingerprint_; } inline const std::vector> getTimeline() { std::lock_guard lk(timeline_lock); @@ -59,9 +78,10 @@ public: signals: void streamStarted(); + void segmentsMerged(); protected slots: - void segmentLoadFinished(bool sucess); + void segmentLoadFinished(bool success); protected: typedef std::map> SegmentMap; @@ -92,7 +112,7 @@ protected: bool paused_ = false; bool events_updated_ = false; uint64_t route_start_ts_ = 0; - uint64_t cur_mono_time_ = 0; + std::atomic cur_mono_time_ = 0; std::unique_ptr> events_; std::unique_ptr> new_events_; std::vector segments_merged_; @@ -108,5 +128,10 @@ protected: std::mutex timeline_lock; QFuture timeline_future; std::vector> timeline; + std::set allow_list; std::string car_fingerprint_; + float speed_ = 1.0; + replayEventFilter event_filter = nullptr; + void *filter_opaque = nullptr; + int segment_cache_limit = 3; }; diff --git a/selfdrive/ui/replay/route.cc b/tools/replay/route.cc similarity index 80% rename from selfdrive/ui/replay/route.cc rename to tools/replay/route.cc index e6a6177149..f0d6ec5a12 100644 --- a/selfdrive/ui/replay/route.cc +++ b/tools/replay/route.cc @@ -1,4 +1,4 @@ -#include "selfdrive/ui/replay/route.h" +#include "tools/replay/route.h" #include #include @@ -7,10 +7,12 @@ #include #include -#include "selfdrive/hardware/hw.h" +#include + +#include "system/hardware/hw.h" #include "selfdrive/ui/qt/api.h" -#include "selfdrive/ui/replay/replay.h" -#include "selfdrive/ui/replay/util.h" +#include "tools/replay/replay.h" +#include "tools/replay/util.h" Route::Route(const QString &route, const QString &data_dir) : data_dir_(data_dir) { route_ = parseRoute(route); @@ -35,7 +37,11 @@ bool Route::load() { bool Route::loadFromServer() { QEventLoop loop; HttpRequest http(nullptr, !Hardware::PC()); - QObject::connect(&http, &HttpRequest::requestDone, [&](const QString &json, bool success) { + QObject::connect(&http, &HttpRequest::requestDone, [&](const QString &json, bool success, QNetworkReply::NetworkError error) { + if (error == QNetworkReply::ContentAccessDenied || error == QNetworkReply::AuthenticationRequiredError) { + qWarning() << ">> Unauthorized. Authenticate with tools/lib/auth.py <<"; + } + loop.exit(success ? loadFromJson(json) : 0); }); http.sendRequest("https://api.commadotai.com/v1/route/" + route_.str + "/files"); @@ -71,10 +77,14 @@ bool Route::loadFromLocal() { } void Route::addFileToSegment(int n, const QString &file) { - const QString name = QUrl(file).fileName(); - if (name == "rlog.bz2") { + QString name = QUrl(file).fileName(); + + const int pos = name.lastIndexOf("--"); + name = pos != -1 ? name.mid(pos + 2) : name; + + if (name == "rlog.bz2" || name == "rlog") { segments_[n].rlog = file; - } else if (name == "qlog.bz2") { + } else if (name == "qlog.bz2" || name == "qlog") { segments_[n].qlog = file; } else if (name == "fcamera.hevc") { segments_[n].road_cam = file; @@ -89,7 +99,9 @@ void Route::addFileToSegment(int n, const QString &file) { // class Segment -Segment::Segment(int n, const SegmentFile &files, uint32_t flags) : seg_num(n), flags(flags) { +Segment::Segment(int n, const SegmentFile &files, uint32_t flags, + const std::set &allow) + : seg_num(n), flags(flags), allow(allow) { // [RoadCam, DriverCam, WideRoadCam, log]. fallback to qcamera/qlog const std::array file_list = { (flags & REPLAY_FLAG_QCAMERA) || files.road_cam.isEmpty() ? files.qcamera : files.road_cam, @@ -117,10 +129,10 @@ void Segment::loadFile(int id, const std::string file) { bool success = false; if (id < MAX_CAMERAS) { frames[id] = std::make_unique(); - success = frames[id]->load(file, flags & REPLAY_FLAG_NO_CUDA, &abort_, local_cache, 20 * 1024 * 1024, 3); + success = frames[id]->load(file, flags & REPLAY_FLAG_NO_HW_DECODER, &abort_, local_cache, 20 * 1024 * 1024, 3); } else { log = std::make_unique(); - success = log->load(file, &abort_, local_cache, 0, 3); + success = log->load(file, &abort_, allow, local_cache, 0, 3); } if (!success) { diff --git a/selfdrive/ui/replay/route.h b/tools/replay/route.h similarity index 85% rename from selfdrive/ui/replay/route.h rename to tools/replay/route.h index ac8fba75ca..6b78ebad87 100644 --- a/selfdrive/ui/replay/route.h +++ b/tools/replay/route.h @@ -2,9 +2,9 @@ #include -#include "selfdrive/ui/replay/framereader.h" -#include "selfdrive/ui/replay/logreader.h" -#include "selfdrive/ui/replay/util.h" +#include "tools/replay/framereader.h" +#include "tools/replay/logreader.h" +#include "tools/replay/util.h" struct RouteIdentifier { QString dongle_id; @@ -47,7 +47,7 @@ class Segment : public QObject { Q_OBJECT public: - Segment(int n, const SegmentFile &files, uint32_t flags); + Segment(int n, const SegmentFile &files, uint32_t flags, const std::set &allow = {}); ~Segment(); inline bool isLoaded() const { return !loading_ && !abort_; } @@ -65,4 +65,5 @@ protected: std::atomic loading_ = 0; QFutureSynchronizer synchronizer_; uint32_t flags; + std::set allow; }; diff --git a/selfdrive/ui/replay/tests/test_replay.cc b/tools/replay/tests/test_replay.cc similarity index 93% rename from selfdrive/ui/replay/tests/test_replay.cc rename to tools/replay/tests/test_replay.cc index 3cafa9b534..30e3c811ee 100644 --- a/selfdrive/ui/replay/tests/test_replay.cc +++ b/tools/replay/tests/test_replay.cc @@ -5,11 +5,10 @@ #include #include "catch2/catch.hpp" -#include "selfdrive/common/util.h" -#include "selfdrive/ui/replay/replay.h" -#include "selfdrive/ui/replay/util.h" +#include "common/util.h" +#include "tools/replay/replay.h" +#include "tools/replay/util.h" -const QString DEMO_ROUTE = "4cf7a6ad03080c90|2021-09-29--13-46-36"; const std::string TEST_RLOG_URL = "https://commadataci.blob.core.windows.net/openpilotci/0c94aa1e1296d7c6/2021-05-05--19-48-37/0/rlog.bz2"; const std::string TEST_RLOG_CHECKSUM = "5b966d4bb21a100a8c4e59195faeb741b975ccbe268211765efd1763d892bfb3"; @@ -71,6 +70,7 @@ TEST_CASE("LogReader") { FileReader reader(true); std::string corrupt_content = reader.read(TEST_RLOG_URL); corrupt_content.resize(corrupt_content.length() / 2); + corrupt_content = decompressBZ2(corrupt_content); LogReader log; REQUIRE(log.load((std::byte *)corrupt_content.data(), corrupt_content.size())); REQUIRE(log.events.size() > 0); @@ -102,11 +102,10 @@ void read_segment(int n, const SegmentFile &segment_file, uint32_t flags) { if (cam == RoadCam || cam == WideRoadCam) { REQUIRE(fr->getFrameCount() == 1200); } - std::unique_ptr rgb_buf = std::make_unique(fr->getRGBSize()); std::unique_ptr yuv_buf = std::make_unique(fr->getYUVSize()); // sequence get 100 frames for (int i = 0; i < 100; ++i) { - REQUIRE(fr->get(i, rgb_buf.get(), yuv_buf.get())); + REQUIRE(fr->get(i, yuv_buf.get())); } } @@ -198,8 +197,8 @@ void TestReplay::test_seek() { stream_thread_ = new QThread(this); QEventLoop loop; std::thread thread = std::thread([&]() { - for (int i = 0; i < 50; ++i) { - testSeekTo(random_int(0, 3 * 60)); + for (int i = 0; i < 10; ++i) { + testSeekTo(random_int(0, 1 * 60)); } loop.quit(); }); @@ -208,8 +207,7 @@ void TestReplay::test_seek() { } TEST_CASE("Replay") { - auto flag = GENERATE(REPLAY_FLAG_NO_FILE_CACHE, REPLAY_FLAG_NONE); - TestReplay replay(DEMO_ROUTE, flag); + TestReplay replay(DEMO_ROUTE); REQUIRE(replay.load()); replay.test_seek(); } diff --git a/tools/replay/tests/test_runner.cc b/tools/replay/tests/test_runner.cc new file mode 100644 index 0000000000..b20ac86c64 --- /dev/null +++ b/tools/replay/tests/test_runner.cc @@ -0,0 +1,10 @@ +#define CATCH_CONFIG_RUNNER +#include "catch2/catch.hpp" +#include + +int main(int argc, char **argv) { + // unit tests for Qt + QCoreApplication app(argc, argv); + const int res = Catch::Session().run(argc, argv); + return (res < 0xff ? res : 0xff); +} diff --git a/tools/replay/ui.py b/tools/replay/ui.py index b39377ffdc..bbcd49061e 100755 --- a/tools/replay/ui.py +++ b/tools/replay/ui.py @@ -10,15 +10,14 @@ import pygame # pylint: disable=import-error import cereal.messaging as messaging from common.numpy_fast import clip from common.basedir import BASEDIR -from selfdrive.config import UIParams as UP -from tools.replay.lib.ui_helpers import (_BB_TO_FULL_FRAME, +from tools.replay.lib.ui_helpers import (_BB_TO_FULL_FRAME, UP, _INTRINSICS, BLACK, GREEN, YELLOW, Calibration, get_blank_lid_overlay, init_plots, maybe_update_radar_points, plot_lead, plot_model, pygame_modules_have_loaded) -from cereal.visionipc.visionipc_pyx import VisionIpcClient, VisionStreamType # pylint: disable=no-name-in-module, import-error +from cereal.visionipc import VisionIpcClient, VisionStreamType os.environ['BASEDIR'] = BASEDIR @@ -100,7 +99,7 @@ def ui_thread(addr): draw_plots = init_plots(plot_arr, name_to_arr_idx, plot_xlims, plot_ylims, plot_names, plot_colors, plot_styles) - vipc_client = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_RGB_BACK, True) + vipc_client = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_ROAD, True) while 1: list(pygame.event.get()) @@ -112,21 +111,17 @@ def ui_thread(addr): if not vipc_client.is_connected(): vipc_client.connect(True) - rgb_img_raw = vipc_client.recv() + yuv_img_raw = vipc_client.recv() - if rgb_img_raw is None or not rgb_img_raw.any(): + if yuv_img_raw is None or not yuv_img_raw.any(): continue - num_px = len(rgb_img_raw) // 3 - imgff_shape = (vipc_client.height, vipc_client.width, 3) + imgff = np.frombuffer(yuv_img_raw, dtype=np.uint8).reshape((vipc_client.height * 3 // 2, vipc_client.width)) + num_px = vipc_client.width * vipc_client.height + bgr = cv2.cvtColor(imgff, cv2.COLOR_YUV2RGB_NV12) - if imgff is None or imgff.shape != imgff_shape: - imgff = np.zeros(imgff_shape, dtype=np.uint8) - - imgff = np.frombuffer(rgb_img_raw, dtype=np.uint8).reshape((vipc_client.height, vipc_client.width, 3)) - imgff = imgff[:, :, ::-1] # Convert BGR to RGB zoom_matrix = _BB_TO_FULL_FRAME[num_px] - cv2.warpAffine(imgff, zoom_matrix[:2], (img.shape[1], img.shape[0]), dst=img, flags=cv2.WARP_INVERSE_MAP) + cv2.warpAffine(bgr, zoom_matrix[:2], (img.shape[1], img.shape[0]), dst=img, flags=cv2.WARP_INVERSE_MAP) intrinsic_matrix = _INTRINSICS[num_px] diff --git a/tools/replay/unlog_ci_segment.py b/tools/replay/unlog_ci_segment.py index 5bceef875e..c008a7aeff 100755 --- a/tools/replay/unlog_ci_segment.py +++ b/tools/replay/unlog_ci_segment.py @@ -35,7 +35,7 @@ def replay(route, segment, loop): frame_idx = {m.roadEncodeIdx.frameId: m.roadEncodeIdx.segmentId for m in msgs if m.which() == 'roadEncodeIdx' and m.roadEncodeIdx.type == 'fullHEVC'} socks = {} - lag = 0 + lag = 0.0 i = 0 max_i = len(msgs) - 2 @@ -66,7 +66,7 @@ def replay(route, segment, loop): lag += (next_msg.logMonoTime - msg.logMonoTime) / 1e9 lag -= time.time() - start_time - dt = max(lag, 0) + dt = max(lag, 0.0) lag -= dt time.sleep(dt) diff --git a/selfdrive/ui/replay/util.cc b/tools/replay/util.cc similarity index 98% rename from selfdrive/ui/replay/util.cc rename to tools/replay/util.cc index 5f06a6c834..a6ebbec615 100644 --- a/selfdrive/ui/replay/util.cc +++ b/tools/replay/util.cc @@ -1,4 +1,4 @@ -#include "selfdrive/ui/replay/util.h" +#include "tools/replay/util.h" #include #include @@ -12,8 +12,8 @@ #include #include -#include "selfdrive/common/timing.h" -#include "selfdrive/common/util.h" +#include "common/timing.h" +#include "common/util.h" ReplayMessageHandler message_handler = nullptr; DownloadProgressHandler download_progress_handler = nullptr; @@ -305,7 +305,7 @@ void precise_nano_sleep(long sleep_ns) { // spin wait if (sleep_ns > 0) { while ((nanos_since_boot() - start_sleep) <= sleep_ns) { - usleep(0); + std::this_thread::yield(); } } } diff --git a/selfdrive/ui/replay/util.h b/tools/replay/util.h similarity index 100% rename from selfdrive/ui/replay/util.h rename to tools/replay/util.h diff --git a/tools/scripts/fetch_image_from_route.py b/tools/scripts/fetch_image_from_route.py index 39751ba551..139373f665 100755 --- a/tools/scripts/fetch_image_from_route.py +++ b/tools/scripts/fetch_image_from_route.py @@ -18,7 +18,7 @@ segment = int(sys.argv[2]) frame = int(sys.argv[3]) url = 'https://api.commadotai.com/v1/route/'+sys.argv[1]+"/files" -r = requests.get(url, headers={"Authorization": "JWT "+jwt}) +r = requests.get(url, headers={"Authorization": "JWT "+jwt}, timeout=10) assert r.status_code == 200 print("got api response") diff --git a/tools/scripts/setup_ssh_keys.py b/tools/scripts/setup_ssh_keys.py index 5b5ebfbac5..b6d4486733 100755 --- a/tools/scripts/setup_ssh_keys.py +++ b/tools/scripts/setup_ssh_keys.py @@ -11,7 +11,7 @@ if __name__ == "__main__": exit(1) username = sys.argv[1] - keys = requests.get(f"https://github.com/{username}.keys") + keys = requests.get(f"https://github.com/{username}.keys", timeout=10) if keys.status_code == 200: Params().put("GithubSshKeys", keys.text) diff --git a/tools/serial/connect.sh b/tools/serial/connect.sh index 037152019f..a073310b0a 100755 --- a/tools/serial/connect.sh +++ b/tools/serial/connect.sh @@ -1,8 +1,8 @@ #!/bin/bash while true; do - if ls /dev/ttyUSB* 2> /dev/null; then - sudo screen /dev/ttyUSB* 115200 + if ls /dev/serial/by-id/usb-FTDI_FT230X* 2> /dev/null; then + sudo screen /dev/serial/by-id/usb-FTDI_FT230X* 115200 fi sleep 0.005 done diff --git a/tools/sim/Dockerfile.sim b/tools/sim/Dockerfile.sim index 4ffd5bea14..3692d48e0f 100644 --- a/tools/sim/Dockerfile.sim +++ b/tools/sim/Dockerfile.sim @@ -1,44 +1,9 @@ -FROM ghcr.io/commaai/openpilot-base:latest +FROM ghcr.io/commaai/openpilot-base-cl:latest -RUN apt-get update && apt-get install -y --no-install-recommends\ - apt-utils \ - unzip \ - tar \ - curl \ - xz-utils \ - alien \ - dbus \ - gcc-arm-none-eabi \ - tmux \ - vim \ - lsb-core \ - libx11-6 \ - && rm -rf /var/lib/apt/lists/* - -# Intel OpenCL driver -ARG INTEL_DRIVER=l_opencl_p_18.1.0.015.tgz -ARG INTEL_DRIVER_URL=http://registrationcenter-download.intel.com/akdlm/irc_nas/vcp/15532 -RUN mkdir -p /tmp/opencl-driver-intel -WORKDIR /tmp/opencl-driver-intel -RUN echo INTEL_DRIVER is $INTEL_DRIVER && \ - curl -O $INTEL_DRIVER_URL/$INTEL_DRIVER && \ - tar -xzf $INTEL_DRIVER && \ - for i in $(basename $INTEL_DRIVER .tgz)/rpm/*.rpm; do alien --to-deb $i; done && \ - dpkg -i *.deb && \ - rm -rf $INTEL_DRIVER $(basename $INTEL_DRIVER .tgz) *.deb && \ - mkdir -p /etc/OpenCL/vendors && \ - echo /opt/intel/opencl_compilers_and_libraries_18.1.0.015/linux/compiler/lib/intel64_lin/libintelocl.so > /etc/OpenCL/vendors/intel.icd && \ - rm -rf /tmp/opencl-driver-intel - -ENV NVIDIA_VISIBLE_DEVICES all -ENV NVIDIA_DRIVER_CAPABILITIES graphics,utility,compute -ENV QTWEBENGINE_DISABLE_SANDBOX 1 - -RUN dbus-uuidgen > /etc/machine-id - -# Install CARLA python api -RUN pip install --upgrade pip && \ - pip install --no-cache-dir carla==0.9.12 +RUN apt-get update && apt-get install -y --no-install-recommends \ + tmux \ + vim \ + && rm -rf /var/lib/apt/lists/* # get same tmux config used on NEOS for debugging RUN cd $HOME && \ @@ -53,13 +18,16 @@ COPY ./third_party $HOME/openpilot/third_party COPY ./pyextra $HOME/openpilot/pyextra COPY ./site_scons $HOME/openpilot/site_scons COPY ./rednose $HOME/openpilot/rednose +COPY ./laika $HOME/openpilot/laika COPY ./common $HOME/openpilot/common -COPY ./models $HOME/openpilot/models COPY ./opendbc $HOME/openpilot/opendbc COPY ./cereal $HOME/openpilot/cereal COPY ./panda $HOME/openpilot/panda COPY ./selfdrive $HOME/openpilot/selfdrive +COPY ./system $HOME/openpilot/system COPY ./tools $HOME/openpilot/tools WORKDIR $HOME/openpilot -RUN scons -j$(nproc) +RUN scons --cache-readonly -j12 + +RUN python -c "from selfdrive.test.helpers import set_params_enabled; set_params_enabled()" diff --git a/tools/sim/Dockerfile.sim_nvidia b/tools/sim/Dockerfile.sim_nvidia new file mode 100644 index 0000000000..5e5dd263da --- /dev/null +++ b/tools/sim/Dockerfile.sim_nvidia @@ -0,0 +1,21 @@ +FROM ubuntu:20.04 + +ENV DEBIAN_FRONTEND=noninteractive +RUN apt-get update && \ + apt-get install -y --no-install-recommends \ + apt-utils \ + sudo \ + ssh \ + curl \ + ca-certificates \ + git \ + git-lfs && \ + rm -rf /var/lib/apt/lists/* + +RUN curl -fsSL https://get.docker.com -o get-docker.sh && \ + sudo sh get-docker.sh && \ + distribution=$(. /etc/os-release;echo $ID$VERSION_ID) && \ + curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | sudo apt-key add - && \ + curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | sudo tee /etc/apt/sources.list.d/nvidia-docker.list && \ + sudo apt-get update && \ + sudo apt-get install -y nvidia-docker2 diff --git a/tools/sim/README.md b/tools/sim/README.md index 3cc124cdbb..69a89aefab 100644 --- a/tools/sim/README.md +++ b/tools/sim/README.md @@ -1,44 +1,58 @@ openpilot in simulator ===================== -openpilot implements a [bridge](bridge.py) that allows it to run in the [CARLA simulator](https://carla.org/). +openpilot implements a [bridge](bridge.py) that allows it to run in the [CARLA simulator](https://carla.org/). ## System Requirements -openpilot doesn't have any extreme hardware requirements, however CARLA requires an NVIDIA graphics card and is very resource-intensive and may not run smoothly on your system. For this case, we have a low quality mode you can activate by running: -``` -./start_openpilot_docker.sh --low_quality -``` +openpilot doesn't have any extreme hardware requirements, however CARLA requires an NVIDIA graphics card and is very resource-intensive and may not run smoothly on your system. +For this case, we have the simulator in low quality by default. You can also check out the [CARLA python documentation](https://carla.readthedocs.io/en/latest/python_api/) to find more parameters to tune that might increase performance on your system. ## Running the simulator - -First, start the CARLA server in one terminal. -``` +Start Carla simulator, openpilot and bridge processes located in tools/sim: +``` bash +# Terminal 1 ./start_carla.sh + +# Terminal 2 - Run openpilot and bridge in one Docker: +./start_openpilot_docker.sh + +# Running the latest local code execute + # Terminal 2: + ./launch_openpilot.sh + # Terminal 3 + ./bridge.py ``` -Then, start the bridge and openpilot in another terminal. +### Bridge usage +_Same commands hold for start_openpilot_docker_ ``` -./start_openpilot_docker.sh +$ ./bridge.py -h +Usage: bridge.py [options] +Bridge between CARLA and openpilot. + +Options: + -h, --help show this help message and exit + --joystick Use joystick input to control the car + --high_quality Set simulator to higher quality (requires good GPU) + --town TOWN Select map to drive in + --spawn_point NUM Number of the spawn point to start in + --host HOST Host address of Carla client (127.0.0.1 as default) + --port PORT Port of Carla client (2000 as default) ``` To engage openpilot press 1 a few times while focused on bridge.py to increase the cruise speed. - -## Controls - -You can control openpilot driving in the simulation with the following keys - -| key | functionality | -| :---: | :---------------: | -| 1 | Cruise up 5 mph | -| 2 | Cruise down 5 mph | -| 3 | Cruise cancel | -| q | Exit all | - -To see the options for changing the environment, such as the town, spawn point or precipitation, you can run `./start_openpilot_docker.sh --help`. -This will print the help output inside the docker container. You need to exit the docker container before running `./start_openpilot_docker.sh` again. +All inputs: + +| key | functionality | +|:----:|:-----------------:| +| 1 | Cruise up 1 mph | +| 2 | Cruise down 1 mph | +| 3 | Cruise cancel | +| q | Exit all | +| wasd | Control manually | ## Further Reading diff --git a/tools/sim/__init__.py b/tools/sim/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tools/sim/bridge.py b/tools/sim/bridge.py index 2e19faefcd..f72927ba9a 100755 --- a/tools/sim/bridge.py +++ b/tools/sim/bridge.py @@ -1,9 +1,10 @@ #!/usr/bin/env python3 import argparse import math +import os +import signal import threading import time -import os from multiprocessing import Process, Queue from typing import Any @@ -11,43 +12,48 @@ import carla # pylint: disable=import-error import numpy as np import pyopencl as cl import pyopencl.array as cl_array -from lib.can import can_function import cereal.messaging as messaging from cereal import log -from cereal.visionipc.visionipc_pyx import VisionIpcServer, VisionStreamType # pylint: disable=no-name-in-module, import-error +from cereal.visionipc import VisionIpcServer, VisionStreamType from common.basedir import BASEDIR from common.numpy_fast import clip from common.params import Params from common.realtime import DT_DMON, Ratekeeper from selfdrive.car.honda.values import CruiseButtons from selfdrive.test.helpers import set_params_enabled - -parser = argparse.ArgumentParser(description='Bridge between CARLA and openpilot.') -parser.add_argument('--joystick', action='store_true') -parser.add_argument('--low_quality', action='store_true') -parser.add_argument('--town', type=str, default='Town04_Opt') -parser.add_argument('--spawn_point', dest='num_selected_spawn_point', type=int, default=16) - -args = parser.parse_args() +from tools.sim.lib.can import can_function W, H = 1928, 1208 REPEAT_COUNTER = 5 PRINT_DECIMATION = 100 STEER_RATIO = 15. -pm = messaging.PubMaster(['roadCameraState', 'sensorEvents', 'can', "gpsLocationExternal"]) +pm = messaging.PubMaster(['roadCameraState', 'wideRoadCameraState', 'accelerometer', 'gyroscope', 'can', "gpsLocationExternal"]) sm = messaging.SubMaster(['carControl', 'controlsState']) +def parse_args(add_args=None): + parser = argparse.ArgumentParser(description='Bridge between CARLA and openpilot.') + parser.add_argument('--joystick', action='store_true') + parser.add_argument('--high_quality', action='store_true') + parser.add_argument('--dual_camera', action='store_true') + parser.add_argument('--town', type=str, default='Town04_Opt') + parser.add_argument('--spawn_point', dest='num_selected_spawn_point', type=int, default=16) + parser.add_argument('--host', dest='host', type=str, default='127.0.0.1') + parser.add_argument('--port', dest='port', type=int, default=2000) + + return parser.parse_args(add_args) + class VehicleState: def __init__(self): - self.speed = 0 - self.angle = 0 + self.speed = 0.0 + self.angle = 0.0 self.bearing_deg = 0.0 self.vel = carla.Vector3D() self.cruise_button = 0 self.is_engaged = False + self.ignition = True def steer_rate_limit(old, new): @@ -63,27 +69,35 @@ def steer_rate_limit(old, new): class Camerad: def __init__(self): - self.frame_id = 0 + self.frame_road_id = 0 + self.frame_wide_id = 0 self.vipc_server = VisionIpcServer("camerad") - # TODO: remove RGB buffers once the last RGB vipc subscriber is removed - self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_RGB_BACK, 4, True, W, H) - self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_ROAD, 40, False, W, H) + self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_ROAD, 5, False, W, H) + self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_WIDE_ROAD, 5, False, W, H) self.vipc_server.start_listener() # set up for pyopencl rgb to yuv conversion self.ctx = cl.create_some_context() self.queue = cl.CommandQueue(self.ctx) - cl_arg = f" -DHEIGHT={H} -DWIDTH={W} -DRGB_STRIDE={W*3} -DUV_WIDTH={W // 2} -DUV_HEIGHT={H // 2} -DRGB_SIZE={W * H} -DCL_DEBUG " + cl_arg = f" -DHEIGHT={H} -DWIDTH={W} -DRGB_STRIDE={W * 3} -DUV_WIDTH={W // 2} -DUV_HEIGHT={H // 2} -DRGB_SIZE={W * H} -DCL_DEBUG " - # TODO: move rgb_to_yuv.cl to local dir once the frame stream camera is removed - kernel_fn = os.path.join(BASEDIR, "selfdrive", "camerad", "transforms", "rgb_to_yuv.cl") - prg = cl.Program(self.ctx, open(kernel_fn).read()).build(cl_arg) - self.krnl = prg.rgb_to_yuv + kernel_fn = os.path.join(BASEDIR, "tools/sim/rgb_to_nv12.cl") + with open(kernel_fn) as f: + prg = cl.Program(self.ctx, f.read()).build(cl_arg) + self.krnl = prg.rgb_to_nv12 self.Wdiv4 = W // 4 if (W % 4 == 0) else (W + (4 - W % 4)) // 4 self.Hdiv4 = H // 4 if (H % 4 == 0) else (H + (4 - H % 4)) // 4 - def cam_callback(self, image): + def cam_callback_road(self, image): + self._cam_callback(image, self.frame_road_id, 'roadCameraState', VisionStreamType.VISION_STREAM_ROAD) + self.frame_road_id += 1 + + def cam_callback_wide_road(self, image): + self._cam_callback(image, self.frame_wide_id, 'wideRoadCameraState', VisionStreamType.VISION_STREAM_WIDE_ROAD) + self.frame_wide_id += 1 + + def _cam_callback(self, image, frame_id, pub_type, yuv_type): img = np.frombuffer(image.raw_data, dtype=np.dtype("uint8")) img = np.reshape(img, (H, W, 4)) img = img[:, :, [0, 1, 2]].copy() @@ -93,46 +107,51 @@ class Camerad: rgb_cl = cl_array.to_device(self.queue, rgb) yuv_cl = cl_array.empty_like(rgb_cl) self.krnl(self.queue, (np.int32(self.Wdiv4), np.int32(self.Hdiv4)), None, rgb_cl.data, yuv_cl.data).wait() - yuv = np.resize(yuv_cl.get(), np.int32(rgb.size / 2)) - eof = self.frame_id * 0.05 + yuv = np.resize(yuv_cl.get(), rgb.size // 2) + eof = int(frame_id * 0.05 * 1e9) - # TODO: remove RGB send once the last RGB vipc subscriber is removed - self.vipc_server.send(VisionStreamType.VISION_STREAM_RGB_BACK, img.tobytes(), self.frame_id, eof, eof) - self.vipc_server.send(VisionStreamType.VISION_STREAM_ROAD, yuv.data.tobytes(), self.frame_id, eof, eof) + self.vipc_server.send(yuv_type, yuv.data.tobytes(), frame_id, eof, eof) - dat = messaging.new_message('roadCameraState') - dat.roadCameraState = { - "frameId": image.frame, + dat = messaging.new_message(pub_type) + msg = { + "frameId": frame_id, "transform": [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0] } - pm.send('roadCameraState', dat) - self.frame_id += 1 - + setattr(dat, pub_type, msg) + pm.send(pub_type, dat) def imu_callback(imu, vehicle_state): - vehicle_state.bearing_deg = math.degrees(imu.compass) - dat = messaging.new_message('sensorEvents', 2) - dat.sensorEvents[0].sensor = 4 - dat.sensorEvents[0].type = 0x10 - dat.sensorEvents[0].init('acceleration') - dat.sensorEvents[0].acceleration.v = [imu.accelerometer.x, imu.accelerometer.y, imu.accelerometer.z] - # copied these numbers from locationd - dat.sensorEvents[1].sensor = 5 - dat.sensorEvents[1].type = 0x10 - dat.sensorEvents[1].init('gyroUncalibrated') - dat.sensorEvents[1].gyroUncalibrated.v = [imu.gyroscope.x, imu.gyroscope.y, imu.gyroscope.z] - pm.send('sensorEvents', dat) - - -def panda_state_function(exit_event: threading.Event): + # send 5x since 'sensor_tick' doesn't seem to work. limited by the world tick? + for _ in range(5): + vehicle_state.bearing_deg = math.degrees(imu.compass) + dat = messaging.new_message('accelerometer') + dat.accelerometer.sensor = 4 + dat.accelerometer.type = 0x1 + dat.accelerometer.timestamp = dat.logMonoTime # TODO: use the IMU timestamp + dat.accelerometer.init('acceleration') + dat.accelerometer.acceleration.v = [imu.accelerometer.x, imu.accelerometer.y, imu.accelerometer.z] + pm.send('accelerometer', dat) + + # copied these numbers from locationd + dat = messaging.new_message('gyroscope') + dat.gyroscope.sensor = 5 + dat.gyroscope.type = 0x10 + dat.gyroscope.timestamp = dat.logMonoTime # TODO: use the IMU timestamp + dat.gyroscope.init('gyroUncalibrated') + dat.gyroscope.gyroUncalibrated.v = [imu.gyroscope.x, imu.gyroscope.y, imu.gyroscope.z] + pm.send('gyroscope', dat) + time.sleep(0.01) + + +def panda_state_function(vs: VehicleState, exit_event: threading.Event): pm = messaging.PubMaster(['pandaStates']) while not exit_event.is_set(): dat = messaging.new_message('pandaStates', 1) dat.valid = True dat.pandaStates[0] = { - 'ignitionLine': True, + 'ignitionLine': vs.ignition, 'pandaType': "blackPanda", 'controlsAllowed': True, 'safetyModel': 'hondaNidec' @@ -169,7 +188,7 @@ def gps_callback(gps, vehicle_state): ] dat.gpsLocationExternal = { - "timestamp": int(time.time() * 1000), + "unixTimestampMillis": int(time.time() * 1000), "flags": 1, # valid fix "accuracy": 1.0, "verticalAccuracy": 1.0, @@ -188,12 +207,12 @@ def gps_callback(gps, vehicle_state): def fake_driver_monitoring(exit_event: threading.Event): - pm = messaging.PubMaster(['driverState', 'driverMonitoringState']) + pm = messaging.PubMaster(['driverStateV2', 'driverMonitoringState']) while not exit_event.is_set(): # dmonitoringmodeld output - dat = messaging.new_message('driverState') - dat.driverState.faceProb = 1.0 - pm.send('driverState', dat) + dat = messaging.new_message('driverStateV2') + dat.driverStateV2.leftDriverData.faceProb = 1.0 + pm.send('driverStateV2', dat) # dmonitoringd output dat = messaging.new_message('driverMonitoringState') @@ -215,255 +234,331 @@ def can_function_runner(vs: VehicleState, exit_event: threading.Event): i += 1 -def bridge(q): - # setup CARLA - client = carla.Client("127.0.0.1", 2000) - client.set_timeout(10.0) - world = client.load_world(args.town) - - settings = world.get_settings() - settings.synchronous_mode = True # Enables synchronous mode - settings.fixed_delta_seconds = 0.05 - world.apply_settings(settings) - - world.set_weather(carla.WeatherParameters.ClearSunset) - - if args.low_quality: - world.unload_map_layer(carla.MapLayer.Foliage) - world.unload_map_layer(carla.MapLayer.Buildings) - world.unload_map_layer(carla.MapLayer.ParkedVehicles) - world.unload_map_layer(carla.MapLayer.Props) - world.unload_map_layer(carla.MapLayer.StreetLights) - world.unload_map_layer(carla.MapLayer.Particles) - - blueprint_library = world.get_blueprint_library() - - world_map = world.get_map() - - vehicle_bp = blueprint_library.filter('vehicle.tesla.*')[1] - spawn_points = world_map.get_spawn_points() - assert len(spawn_points) > args.num_selected_spawn_point, \ - f'''No spawn point {args.num_selected_spawn_point}, try a value between 0 and - {len(spawn_points)} for this town.''' - spawn_point = spawn_points[args.num_selected_spawn_point] - vehicle = world.spawn_actor(vehicle_bp, spawn_point) - - max_steer_angle = vehicle.get_physics_control().wheels[0].max_steer_angle - - # make tires less slippery - # wheel_control = carla.WheelPhysicsControl(tire_friction=5) - physics_control = vehicle.get_physics_control() - physics_control.mass = 2326 - # physics_control.wheels = [wheel_control]*4 - physics_control.torque_curve = [[20.0, 500.0], [5000.0, 500.0]] - physics_control.gear_switch_time = 0.0 - vehicle.apply_physics_control(physics_control) - - blueprint = blueprint_library.find('sensor.camera.rgb') - blueprint.set_attribute('image_size_x', str(W)) - blueprint.set_attribute('image_size_y', str(H)) - blueprint.set_attribute('fov', '40') - blueprint.set_attribute('sensor_tick', '0.05') - transform = carla.Transform(carla.Location(x=0.8, z=1.13)) - camera = world.spawn_actor(blueprint, transform, attach_to=vehicle) - camerad = Camerad() - camera.listen(camerad.cam_callback) - - vehicle_state = VehicleState() - - # reenable IMU - imu_bp = blueprint_library.find('sensor.other.imu') - imu = world.spawn_actor(imu_bp, transform, attach_to=vehicle) - imu.listen(lambda imu: imu_callback(imu, vehicle_state)) - - gps_bp = blueprint_library.find('sensor.other.gnss') - gps = world.spawn_actor(gps_bp, transform, attach_to=vehicle) - gps.listen(lambda gps: gps_callback(gps, vehicle_state)) - - # launch fake car threads - threads = [] - exit_event = threading.Event() - threads.append(threading.Thread(target=panda_state_function, args=(exit_event,))) - threads.append(threading.Thread(target=peripheral_state_function, args=(exit_event,))) - threads.append(threading.Thread(target=fake_driver_monitoring, args=(exit_event,))) - threads.append(threading.Thread(target=can_function_runner, args=(vehicle_state, exit_event,))) - for t in threads: - t.start() - - # can loop - rk = Ratekeeper(100, print_delay_threshold=0.05) - - # init - throttle_ease_out_counter = REPEAT_COUNTER - brake_ease_out_counter = REPEAT_COUNTER - steer_ease_out_counter = REPEAT_COUNTER - - vc = carla.VehicleControl(throttle=0, steer=0, brake=0, reverse=False) - - is_openpilot_engaged = False - throttle_out = steer_out = brake_out = 0 - throttle_op = steer_op = brake_op = 0 - throttle_manual = steer_manual = brake_manual = 0 - - old_steer = old_brake = old_throttle = 0 - throttle_manual_multiplier = 0.7 # keyboard signal is always 1 - brake_manual_multiplier = 0.7 # keyboard signal is always 1 - steer_manual_multiplier = 45 * STEER_RATIO # keyboard signal is always 1 - - while True: - # 1. Read the throttle, steer and brake from op or manual controls - # 2. Set instructions in Carla - # 3. Send current carstate to op via can - - cruise_button = 0 - throttle_out = steer_out = brake_out = 0.0 - throttle_op = steer_op = brake_op = 0 - throttle_manual = steer_manual = brake_manual = 0.0 - - # --------------Step 1------------------------------- - if not q.empty(): - message = q.get() - m = message.split('_') - if m[0] == "steer": - steer_manual = float(m[1]) - is_openpilot_engaged = False - elif m[0] == "throttle": - throttle_manual = float(m[1]) - is_openpilot_engaged = False - elif m[0] == "brake": - brake_manual = float(m[1]) - is_openpilot_engaged = False - elif m[0] == "reverse": - cruise_button = CruiseButtons.CANCEL - is_openpilot_engaged = False - elif m[0] == "cruise": - if m[1] == "down": - cruise_button = CruiseButtons.DECEL_SET - is_openpilot_engaged = True - elif m[1] == "up": - cruise_button = CruiseButtons.RES_ACCEL - is_openpilot_engaged = True - elif m[1] == "cancel": - cruise_button = CruiseButtons.CANCEL - is_openpilot_engaged = False - elif m[0] == "quit": - break - - throttle_out = throttle_manual * throttle_manual_multiplier - steer_out = steer_manual * steer_manual_multiplier - brake_out = brake_manual * brake_manual_multiplier - - old_steer = steer_out - old_throttle = throttle_out - old_brake = brake_out +def connect_carla_client(host: str, port: int): + client = carla.Client(host, port) + client.set_timeout(5) + return client - if is_openpilot_engaged: - sm.update(0) - # TODO gas and brake is deprecated - throttle_op = clip(sm['carControl'].actuators.accel / 1.6, 0.0, 1.0) - brake_op = clip(-sm['carControl'].actuators.accel / 4.0, 0.0, 1.0) - steer_op = sm['carControl'].actuators.steeringAngleDeg +class CarlaBridge: - throttle_out = throttle_op - steer_out = steer_op - brake_out = brake_op + def __init__(self, arguments): + set_params_enabled() - steer_out = steer_rate_limit(old_steer, steer_out) - old_steer = steer_out + self.params = Params() - else: - if throttle_out == 0 and old_throttle > 0: - if throttle_ease_out_counter > 0: - throttle_out = old_throttle - throttle_ease_out_counter += -1 - else: - throttle_ease_out_counter = REPEAT_COUNTER - old_throttle = 0 - - if brake_out == 0 and old_brake > 0: - if brake_ease_out_counter > 0: - brake_out = old_brake - brake_ease_out_counter += -1 - else: - brake_ease_out_counter = REPEAT_COUNTER - old_brake = 0 - - if steer_out == 0 and old_steer != 0: - if steer_ease_out_counter > 0: - steer_out = old_steer - steer_ease_out_counter += -1 - else: - steer_ease_out_counter = REPEAT_COUNTER - old_steer = 0 - - # --------------Step 2------------------------------- - steer_carla = steer_out / (max_steer_angle * STEER_RATIO * -1) - - steer_carla = np.clip(steer_carla, -1, 1) - steer_out = steer_carla * (max_steer_angle * STEER_RATIO * -1) - old_steer = steer_carla * (max_steer_angle * STEER_RATIO * -1) - - vc.throttle = throttle_out / 0.6 - vc.steer = steer_carla - vc.brake = brake_out - vehicle.apply_control(vc) - - # --------------Step 3------------------------------- - vel = vehicle.get_velocity() - speed = math.sqrt(vel.x**2 + vel.y**2 + vel.z**2) # in m/s - vehicle_state.speed = speed - vehicle_state.vel = vel - vehicle_state.angle = steer_out - vehicle_state.cruise_button = cruise_button - vehicle_state.is_engaged = is_openpilot_engaged - - if rk.frame % PRINT_DECIMATION == 0: - print("frame: ", "engaged:", is_openpilot_engaged, "; throttle: ", round(vc.throttle, 3), "; steer(c/deg): ", round(vc.steer, 3), round(steer_out, 3), "; brake: ", round(vc.brake, 3)) - - if rk.frame % 5 == 0: - world.tick() + msg = messaging.new_message('liveCalibration') + msg.liveCalibration.validBlocks = 20 + msg.liveCalibration.rpyCalib = [0.0, 0.0, 0.0] + self.params.put("CalibrationParams", msg.to_bytes()) + self.params.put_bool("WideCameraOnly", not arguments.dual_camera) - rk.keep_time() + self._args = arguments + self._carla_objects = [] + self._camerad = None + self._exit_event = threading.Event() + self._threads = [] + self._keep_alive = True + self.started = False + signal.signal(signal.SIGTERM, self._on_shutdown) + self._exit = threading.Event() - # Clean up resources in the opposite order they were created. - exit_event.set() - for t in reversed(threads): - t.join() - gps.destroy() - imu.destroy() - camera.destroy() - vehicle.destroy() + def _on_shutdown(self, signal, frame): + self._keep_alive = False - -def bridge_keep_alive(q: Any): - while 1: + def bridge_keep_alive(self, q: Queue, retries: int): try: - bridge(q) - break - except RuntimeError: - print("Restarting bridge...") + while self._keep_alive: + try: + self._run(q) + break + except RuntimeError as e: + self.close() + if retries == 0: + raise + + # Reset for another try + self._carla_objects = [] + self._threads = [] + self._exit_event = threading.Event() + + retries -= 1 + if retries <= -1: + print(f"Restarting bridge. Error: {e} ") + else: + print(f"Restarting bridge. Retries left {retries}. Error: {e} ") + finally: + # Clean up resources in the opposite order they were created. + self.close() + + def _run(self, q: Queue): + client = connect_carla_client(self._args.host, self._args.port) + world = client.load_world(self._args.town) + + settings = world.get_settings() + settings.synchronous_mode = True # Enables synchronous mode + settings.fixed_delta_seconds = 0.05 + world.apply_settings(settings) + + world.set_weather(carla.WeatherParameters.ClearSunset) + + if not self._args.high_quality: + world.unload_map_layer(carla.MapLayer.Foliage) + world.unload_map_layer(carla.MapLayer.Buildings) + world.unload_map_layer(carla.MapLayer.ParkedVehicles) + world.unload_map_layer(carla.MapLayer.Props) + world.unload_map_layer(carla.MapLayer.StreetLights) + world.unload_map_layer(carla.MapLayer.Particles) + + blueprint_library = world.get_blueprint_library() + + world_map = world.get_map() + + vehicle_bp = blueprint_library.filter('vehicle.tesla.*')[1] + vehicle_bp.set_attribute('role_name', 'hero') + spawn_points = world_map.get_spawn_points() + assert len(spawn_points) > self._args.num_selected_spawn_point, f'''No spawn point {self._args.num_selected_spawn_point}, try a value between 0 and + {len(spawn_points)} for this town.''' + spawn_point = spawn_points[self._args.num_selected_spawn_point] + vehicle = world.spawn_actor(vehicle_bp, spawn_point) + self._carla_objects.append(vehicle) + max_steer_angle = vehicle.get_physics_control().wheels[0].max_steer_angle + + # make tires less slippery + # wheel_control = carla.WheelPhysicsControl(tire_friction=5) + physics_control = vehicle.get_physics_control() + physics_control.mass = 2326 + # physics_control.wheels = [wheel_control]*4 + physics_control.torque_curve = [[20.0, 500.0], [5000.0, 500.0]] + physics_control.gear_switch_time = 0.0 + vehicle.apply_physics_control(physics_control) + + transform = carla.Transform(carla.Location(x=0.8, z=1.13)) + + def create_camera(fov, callback): + blueprint = blueprint_library.find('sensor.camera.rgb') + blueprint.set_attribute('image_size_x', str(W)) + blueprint.set_attribute('image_size_y', str(H)) + blueprint.set_attribute('fov', str(fov)) + if not self._args.high_quality: + blueprint.set_attribute('enable_postprocess_effects', 'False') + camera = world.spawn_actor(blueprint, transform, attach_to=vehicle) + camera.listen(callback) + return camera + + self._camerad = Camerad() + + if self._args.dual_camera: + road_camera = create_camera(fov=40, callback=self._camerad.cam_callback_road) + self._carla_objects.append(road_camera) + + road_wide_camera = create_camera(fov=120, callback=self._camerad.cam_callback_wide_road) # fov bigger than 120 shows unwanted artifacts + self._carla_objects.append(road_wide_camera) + + vehicle_state = VehicleState() + + # re-enable IMU + imu_bp = blueprint_library.find('sensor.other.imu') + imu_bp.set_attribute('sensor_tick', '0.01') + imu = world.spawn_actor(imu_bp, transform, attach_to=vehicle) + imu.listen(lambda imu: imu_callback(imu, vehicle_state)) + + gps_bp = blueprint_library.find('sensor.other.gnss') + gps = world.spawn_actor(gps_bp, transform, attach_to=vehicle) + gps.listen(lambda gps: gps_callback(gps, vehicle_state)) + self.params.put_bool("UbloxAvailable", True) + + self._carla_objects.extend([imu, gps]) + # launch fake car threads + self._threads.append(threading.Thread(target=panda_state_function, args=(vehicle_state, self._exit_event,))) + self._threads.append(threading.Thread(target=peripheral_state_function, args=(self._exit_event,))) + self._threads.append(threading.Thread(target=fake_driver_monitoring, args=(self._exit_event,))) + self._threads.append(threading.Thread(target=can_function_runner, args=(vehicle_state, self._exit_event,))) + for t in self._threads: + t.start() + + # init + throttle_ease_out_counter = REPEAT_COUNTER + brake_ease_out_counter = REPEAT_COUNTER + steer_ease_out_counter = REPEAT_COUNTER + + vc = carla.VehicleControl(throttle=0, steer=0, brake=0, reverse=False) + + is_openpilot_engaged = False + throttle_out = steer_out = brake_out = 0. + throttle_op = steer_op = brake_op = 0. + throttle_manual = steer_manual = brake_manual = 0. + + old_steer = old_brake = old_throttle = 0. + throttle_manual_multiplier = 0.7 # keyboard signal is always 1 + brake_manual_multiplier = 0.7 # keyboard signal is always 1 + steer_manual_multiplier = 45 * STEER_RATIO # keyboard signal is always 1 + + # Simulation tends to be slow in the initial steps. This prevents lagging later + for _ in range(20): + world.tick() + + # loop + rk = Ratekeeper(100, print_delay_threshold=0.05) + + while self._keep_alive: + # 1. Read the throttle, steer and brake from op or manual controls + # 2. Set instructions in Carla + # 3. Send current carstate to op via can + + cruise_button = 0 + throttle_out = steer_out = brake_out = 0.0 + throttle_op = steer_op = brake_op = 0.0 + throttle_manual = steer_manual = brake_manual = 0.0 + + # --------------Step 1------------------------------- + if not q.empty(): + message = q.get() + m = message.split('_') + if m[0] == "steer": + steer_manual = float(m[1]) + is_openpilot_engaged = False + elif m[0] == "throttle": + throttle_manual = float(m[1]) + is_openpilot_engaged = False + elif m[0] == "brake": + brake_manual = float(m[1]) + is_openpilot_engaged = False + elif m[0] == "reverse": + cruise_button = CruiseButtons.CANCEL + is_openpilot_engaged = False + elif m[0] == "cruise": + if m[1] == "down": + cruise_button = CruiseButtons.DECEL_SET + is_openpilot_engaged = True + elif m[1] == "up": + cruise_button = CruiseButtons.RES_ACCEL + is_openpilot_engaged = True + elif m[1] == "cancel": + cruise_button = CruiseButtons.CANCEL + is_openpilot_engaged = False + elif m[0] == "ignition": + vehicle_state.ignition = not vehicle_state.ignition + elif m[0] == "quit": + break + + throttle_out = throttle_manual * throttle_manual_multiplier + steer_out = steer_manual * steer_manual_multiplier + brake_out = brake_manual * brake_manual_multiplier + + old_steer = steer_out + old_throttle = throttle_out + old_brake = brake_out + + if is_openpilot_engaged: + sm.update(0) + + # TODO gas and brake is deprecated + throttle_op = clip(sm['carControl'].actuators.accel / 1.6, 0.0, 1.0) + brake_op = clip(-sm['carControl'].actuators.accel / 4.0, 0.0, 1.0) + steer_op = sm['carControl'].actuators.steeringAngleDeg + + throttle_out = throttle_op + steer_out = steer_op + brake_out = brake_op + + steer_out = steer_rate_limit(old_steer, steer_out) + old_steer = steer_out + + else: + if throttle_out == 0 and old_throttle > 0: + if throttle_ease_out_counter > 0: + throttle_out = old_throttle + throttle_ease_out_counter += -1 + else: + throttle_ease_out_counter = REPEAT_COUNTER + old_throttle = 0 + + if brake_out == 0 and old_brake > 0: + if brake_ease_out_counter > 0: + brake_out = old_brake + brake_ease_out_counter += -1 + else: + brake_ease_out_counter = REPEAT_COUNTER + old_brake = 0 + + if steer_out == 0 and old_steer != 0: + if steer_ease_out_counter > 0: + steer_out = old_steer + steer_ease_out_counter += -1 + else: + steer_ease_out_counter = REPEAT_COUNTER + old_steer = 0 + + # --------------Step 2------------------------------- + steer_carla = steer_out / (max_steer_angle * STEER_RATIO * -1) + + steer_carla = np.clip(steer_carla, -1, 1) + steer_out = steer_carla * (max_steer_angle * STEER_RATIO * -1) + old_steer = steer_carla * (max_steer_angle * STEER_RATIO * -1) + + vc.throttle = throttle_out / 0.6 + vc.steer = steer_carla + vc.brake = brake_out + vehicle.apply_control(vc) + + # --------------Step 3------------------------------- + vel = vehicle.get_velocity() + speed = math.sqrt(vel.x ** 2 + vel.y ** 2 + vel.z ** 2) # in m/s + vehicle_state.speed = speed + vehicle_state.vel = vel + vehicle_state.angle = steer_out + vehicle_state.cruise_button = cruise_button + vehicle_state.is_engaged = is_openpilot_engaged + + if rk.frame % PRINT_DECIMATION == 0: + print("frame: ", "engaged:", is_openpilot_engaged, "; throttle: ", round(vc.throttle, 3), "; steer(c/deg): ", + round(vc.steer, 3), round(steer_out, 3), "; brake: ", round(vc.brake, 3)) + + if rk.frame % 5 == 0: + world.tick() + rk.keep_time() + self.started = True + + def close(self): + self.started = False + self._exit_event.set() + + for s in self._carla_objects: + try: + s.destroy() + except Exception as e: + print("Failed to destroy carla object", e) + for t in reversed(self._threads): + t.join() + + def run(self, queue, retries=-1): + bridge_p = Process(target=self.bridge_keep_alive, args=(queue, retries), daemon=True) + bridge_p.start() + return bridge_p if __name__ == "__main__": - # make sure params are in a good state - set_params_enabled() + q: Any = Queue() + args = parse_args() - msg = messaging.new_message('liveCalibration') - msg.liveCalibration.validBlocks = 20 - msg.liveCalibration.rpyCalib = [0.0, 0.0, 0.0] - Params().put("CalibrationParams", msg.to_bytes()) + try: + carla_bridge = CarlaBridge(args) + p = carla_bridge.run(q) - q: Any = Queue() - p = Process(target=bridge_keep_alive, args=(q,), daemon=True) - p.start() + if args.joystick: + # start input poll for joystick + from tools.sim.lib.manual_ctrl import wheel_poll_thread - if args.joystick: - # start input poll for joystick - from lib.manual_ctrl import wheel_poll_thread - wheel_poll_thread(q) + wheel_poll_thread(q) + else: + # start input poll for keyboard + from tools.sim.lib.keyboard_ctrl import keyboard_poll_thread + + keyboard_poll_thread(q) p.join() - else: - # start input poll for keyboard - from lib.keyboard_ctrl import keyboard_poll_thread - keyboard_poll_thread(q) + + finally: + # Try cleaning up the wide camera param + # in case users want to use replay after + Params().remove("WideCameraOnly") diff --git a/tools/sim/build_container.sh b/tools/sim/build_container.sh index 451277d590..81afb82d83 100755 --- a/tools/sim/build_container.sh +++ b/tools/sim/build_container.sh @@ -3,7 +3,7 @@ DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" cd $DIR/../../ -docker pull ghcr.io/commaai/openpilot-base:latest +docker pull ghcr.io/commaai/openpilot-base-cl:latest docker build \ --cache-from ghcr.io/commaai/openpilot-sim:latest \ -t ghcr.io/commaai/openpilot-sim:latest \ diff --git a/tools/sim/launch_openpilot.sh b/tools/sim/launch_openpilot.sh index b94a453b7b..2100f05b67 100755 --- a/tools/sim/launch_openpilot.sh +++ b/tools/sim/launch_openpilot.sh @@ -3,9 +3,14 @@ export PASSIVE="0" export NOBOARD="1" export SIMULATION="1" +export SKIP_FW_QUERY="1" export FINGERPRINT="HONDA CIVIC 2016" -export BLOCK="camerad,loggerd" +export BLOCK="camerad,loggerd,encoderd,micd" +if [[ "$CI" ]]; then + # TODO: offscreen UI should work + export BLOCK="${BLOCK},ui" +fi DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" -cd ../../selfdrive/manager && ./manager.py +cd ../../selfdrive/manager && exec ./manager.py diff --git a/tools/sim/lib/can.py b/tools/sim/lib/can.py index af0f415bbc..af4339b2e4 100755 --- a/tools/sim/lib/can.py +++ b/tools/sim/lib/can.py @@ -33,47 +33,48 @@ def can_function(pm, speed, angle, idx, cruise_button, is_engaged): # *** powertrain bus *** speed = speed * 3.6 # convert m/s to kph - msg.append(packer.make_can_msg("ENGINE_DATA", 0, {"XMISSION_SPEED": speed}, idx)) + msg.append(packer.make_can_msg("ENGINE_DATA", 0, {"XMISSION_SPEED": speed})) msg.append(packer.make_can_msg("WHEEL_SPEEDS", 0, { "WHEEL_SPEED_FL": speed, "WHEEL_SPEED_FR": speed, "WHEEL_SPEED_RL": speed, "WHEEL_SPEED_RR": speed - }, -1)) + })) - msg.append(packer.make_can_msg("SCM_BUTTONS", 0, {"CRUISE_BUTTONS": cruise_button}, idx)) + msg.append(packer.make_can_msg("SCM_BUTTONS", 0, {"CRUISE_BUTTONS": cruise_button})) values = {"COUNTER_PEDAL": idx & 0xF} - checksum = crc8_pedal(packer.make_can_msg("GAS_SENSOR", 0, {"COUNTER_PEDAL": idx & 0xF}, -1)[2][:-1]) + checksum = crc8_pedal(packer.make_can_msg("GAS_SENSOR", 0, {"COUNTER_PEDAL": idx & 0xF})[2][:-1]) values["CHECKSUM_PEDAL"] = checksum - msg.append(packer.make_can_msg("GAS_SENSOR", 0, values, -1)) - - msg.append(packer.make_can_msg("GEARBOX", 0, {"GEAR": 4, "GEAR_SHIFTER": 8}, idx)) - msg.append(packer.make_can_msg("GAS_PEDAL_2", 0, {}, idx)) - msg.append(packer.make_can_msg("SEATBELT_STATUS", 0, {"SEATBELT_DRIVER_LATCHED": 1}, idx)) - msg.append(packer.make_can_msg("STEER_STATUS", 0, {}, idx)) - msg.append(packer.make_can_msg("STEERING_SENSORS", 0, {"STEER_ANGLE": angle}, idx)) - msg.append(packer.make_can_msg("VSA_STATUS", 0, {}, idx)) - msg.append(packer.make_can_msg("STANDSTILL", 0, {"WHEELS_MOVING": 1 if speed >= 1.0 else 0}, idx)) - msg.append(packer.make_can_msg("STEER_MOTOR_TORQUE", 0, {}, idx)) - msg.append(packer.make_can_msg("EPB_STATUS", 0, {}, idx)) - msg.append(packer.make_can_msg("DOORS_STATUS", 0, {}, idx)) - msg.append(packer.make_can_msg("CRUISE_PARAMS", 0, {}, idx)) - msg.append(packer.make_can_msg("CRUISE", 0, {}, idx)) - msg.append(packer.make_can_msg("SCM_FEEDBACK", 0, {"MAIN_ON": 1}, idx)) - msg.append(packer.make_can_msg("POWERTRAIN_DATA", 0, {"ACC_STATUS": int(is_engaged)}, idx)) + msg.append(packer.make_can_msg("GAS_SENSOR", 0, values)) + + msg.append(packer.make_can_msg("GEARBOX", 0, {"GEAR": 4, "GEAR_SHIFTER": 8})) + msg.append(packer.make_can_msg("GAS_PEDAL_2", 0, {})) + msg.append(packer.make_can_msg("SEATBELT_STATUS", 0, {"SEATBELT_DRIVER_LATCHED": 1})) + msg.append(packer.make_can_msg("STEER_STATUS", 0, {})) + msg.append(packer.make_can_msg("STEERING_SENSORS", 0, {"STEER_ANGLE": angle})) + msg.append(packer.make_can_msg("VSA_STATUS", 0, {})) + msg.append(packer.make_can_msg("STANDSTILL", 0, {"WHEELS_MOVING": 1 if speed >= 1.0 else 0})) + msg.append(packer.make_can_msg("STEER_MOTOR_TORQUE", 0, {})) + msg.append(packer.make_can_msg("EPB_STATUS", 0, {})) + msg.append(packer.make_can_msg("DOORS_STATUS", 0, {})) + msg.append(packer.make_can_msg("CRUISE_PARAMS", 0, {})) + msg.append(packer.make_can_msg("CRUISE", 0, {})) + msg.append(packer.make_can_msg("SCM_FEEDBACK", 0, {"MAIN_ON": 1})) + msg.append(packer.make_can_msg("POWERTRAIN_DATA", 0, {"ACC_STATUS": int(is_engaged)})) msg.append(packer.make_can_msg("HUD_SETTING", 0, {})) + msg.append(packer.make_can_msg("CAR_SPEED", 0, {})) # *** cam bus *** - msg.append(packer.make_can_msg("STEERING_CONTROL", 2, {}, idx)) - msg.append(packer.make_can_msg("ACC_HUD", 2, {}, idx)) - msg.append(packer.make_can_msg("BRAKE_COMMAND", 2, {}, idx)) + msg.append(packer.make_can_msg("STEERING_CONTROL", 2, {})) + msg.append(packer.make_can_msg("ACC_HUD", 2, {})) + msg.append(packer.make_can_msg("BRAKE_COMMAND", 2, {})) # *** radar bus *** if idx % 5 == 0: - msg.append(rpacker.make_can_msg("RADAR_DIAGNOSTIC", 1, {"RADAR_STATE": 0x79}, -1)) + msg.append(rpacker.make_can_msg("RADAR_DIAGNOSTIC", 1, {"RADAR_STATE": 0x79})) for i in range(16): - msg.append(rpacker.make_can_msg("TRACK_%d" % i, 1, {"LONG_DIST": 255.5}, -1)) + msg.append(rpacker.make_can_msg("TRACK_%d" % i, 1, {"LONG_DIST": 255.5})) pm.send('can', can_list_to_can_capnp(msg)) diff --git a/tools/sim/lib/keyboard_ctrl.py b/tools/sim/lib/keyboard_ctrl.py index 08d120d61b..803aa091a3 100644 --- a/tools/sim/lib/keyboard_ctrl.py +++ b/tools/sim/lib/keyboard_ctrl.py @@ -38,7 +38,7 @@ def getch() -> str: def keyboard_poll_thread(q: 'Queue[str]'): while True: c = getch() - # print("got %s" % c) + print("got %s" % c) if c == '1': q.put("cruise_up") elif c == '2': @@ -53,6 +53,8 @@ def keyboard_poll_thread(q: 'Queue[str]'): q.put("brake_%f" % 1.0) elif c == 'd': q.put("steer_%f" % -0.15) + elif c == 'i': + q.put("ignition") elif c == 'q': q.put("quit") break diff --git a/tools/sim/lib/manual_ctrl.py b/tools/sim/lib/manual_ctrl.py index 7c47e2ba4a..8f1bcc2b57 100755 --- a/tools/sim/lib/manual_ctrl.py +++ b/tools/sim/lib/manual_ctrl.py @@ -9,8 +9,8 @@ from typing import NoReturn # Iterate over the joystick devices. print('Available devices:') for fn in os.listdir('/dev/input'): - if fn.startswith('js'): - print(f' /dev/input/{fn}') + if fn.startswith('js'): + print(f' /dev/input/{fn}') # We'll store the states here. axis_states = {} @@ -18,74 +18,74 @@ button_states = {} # These constants were borrowed from linux/input.h axis_names = { - 0x00 : 'x', - 0x01 : 'y', - 0x02 : 'z', - 0x03 : 'rx', - 0x04 : 'ry', - 0x05 : 'rz', - 0x06 : 'trottle', - 0x07 : 'rudder', - 0x08 : 'wheel', - 0x09 : 'gas', - 0x0a : 'brake', - 0x10 : 'hat0x', - 0x11 : 'hat0y', - 0x12 : 'hat1x', - 0x13 : 'hat1y', - 0x14 : 'hat2x', - 0x15 : 'hat2y', - 0x16 : 'hat3x', - 0x17 : 'hat3y', - 0x18 : 'pressure', - 0x19 : 'distance', - 0x1a : 'tilt_x', - 0x1b : 'tilt_y', - 0x1c : 'tool_width', - 0x20 : 'volume', - 0x28 : 'misc', + 0x00 : 'x', + 0x01 : 'y', + 0x02 : 'z', + 0x03 : 'rx', + 0x04 : 'ry', + 0x05 : 'rz', + 0x06 : 'trottle', + 0x07 : 'rudder', + 0x08 : 'wheel', + 0x09 : 'gas', + 0x0a : 'brake', + 0x10 : 'hat0x', + 0x11 : 'hat0y', + 0x12 : 'hat1x', + 0x13 : 'hat1y', + 0x14 : 'hat2x', + 0x15 : 'hat2y', + 0x16 : 'hat3x', + 0x17 : 'hat3y', + 0x18 : 'pressure', + 0x19 : 'distance', + 0x1a : 'tilt_x', + 0x1b : 'tilt_y', + 0x1c : 'tool_width', + 0x20 : 'volume', + 0x28 : 'misc', } button_names = { - 0x120 : 'trigger', - 0x121 : 'thumb', - 0x122 : 'thumb2', - 0x123 : 'top', - 0x124 : 'top2', - 0x125 : 'pinkie', - 0x126 : 'base', - 0x127 : 'base2', - 0x128 : 'base3', - 0x129 : 'base4', - 0x12a : 'base5', - 0x12b : 'base6', - 0x12f : 'dead', - 0x130 : 'a', - 0x131 : 'b', - 0x132 : 'c', - 0x133 : 'x', - 0x134 : 'y', - 0x135 : 'z', - 0x136 : 'tl', - 0x137 : 'tr', - 0x138 : 'tl2', - 0x139 : 'tr2', - 0x13a : 'select', - 0x13b : 'start', - 0x13c : 'mode', - 0x13d : 'thumbl', - 0x13e : 'thumbr', - - 0x220 : 'dpad_up', - 0x221 : 'dpad_down', - 0x222 : 'dpad_left', - 0x223 : 'dpad_right', - - # XBox 360 controller uses these codes. - 0x2c0 : 'dpad_left', - 0x2c1 : 'dpad_right', - 0x2c2 : 'dpad_up', - 0x2c3 : 'dpad_down', + 0x120 : 'trigger', + 0x121 : 'thumb', + 0x122 : 'thumb2', + 0x123 : 'top', + 0x124 : 'top2', + 0x125 : 'pinkie', + 0x126 : 'base', + 0x127 : 'base2', + 0x128 : 'base3', + 0x129 : 'base4', + 0x12a : 'base5', + 0x12b : 'base6', + 0x12f : 'dead', + 0x130 : 'a', + 0x131 : 'b', + 0x132 : 'c', + 0x133 : 'x', + 0x134 : 'y', + 0x135 : 'z', + 0x136 : 'tl', + 0x137 : 'tr', + 0x138 : 'tl2', + 0x139 : 'tr2', + 0x13a : 'select', + 0x13b : 'start', + 0x13c : 'mode', + 0x13d : 'thumbl', + 0x13e : 'thumbr', + + 0x220 : 'dpad_up', + 0x221 : 'dpad_down', + 0x222 : 'dpad_left', + 0x223 : 'dpad_right', + + # XBox 360 controller uses these codes. + 0x2c0 : 'dpad_left', + 0x2c1 : 'dpad_right', + 0x2c2 : 'dpad_up', + 0x2c3 : 'dpad_down', } axis_map = [] @@ -118,18 +118,18 @@ def wheel_poll_thread(q: 'Queue[str]') -> NoReturn: ioctl(jsdev, 0x80406a32, buf) # JSIOCGAXMAP for _axis in buf[:num_axes]: - axis_name = axis_names.get(_axis, f'unknown(0x{_axis:02x})') - axis_map.append(axis_name) - axis_states[axis_name] = 0.0 + axis_name = axis_names.get(_axis, f'unknown(0x{_axis:02x})') + axis_map.append(axis_name) + axis_states[axis_name] = 0.0 # Get the button map. buf = array.array('H', [0] * 200) ioctl(jsdev, 0x80406a34, buf) # JSIOCGBTNMAP for btn in buf[:num_buttons]: - btn_name = button_names.get(btn, f'unknown(0x{btn:03x})') - button_map.append(btn_name) - button_states[btn_name] = 0 + btn_name = button_names.get(btn, f'unknown(0x{btn:03x})') + button_map.append(btn_name) + button_states[btn_name] = 0 print('%d axes found: %s' % (num_axes, ', '.join(axis_map))) print('%d buttons found: %s' % (num_buttons, ', '.join(button_map))) diff --git a/tools/sim/lib/replay.sh b/tools/sim/lib/replay.sh deleted file mode 100755 index e65a4b69a7..0000000000 --- a/tools/sim/lib/replay.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash - -cd ~/openpilot/tools/nui - -# vision, boardd, sensorsd -ALLOW=frame,can,ubloxRaw,health,sensorEvents,gpsNMEA,gpsLocationExternal ./nui "02ec6bea180a4d36/2019-10-25--10-18-09" diff --git a/selfdrive/camerad/transforms/rgb_to_yuv.cl b/tools/sim/rgb_to_nv12.cl similarity index 75% rename from selfdrive/camerad/transforms/rgb_to_yuv.cl rename to tools/sim/rgb_to_nv12.cl index 60dbdb4d5e..54816d5d7d 100644 --- a/selfdrive/camerad/transforms/rgb_to_yuv.cl +++ b/tools/sim/rgb_to_nv12.cl @@ -29,23 +29,21 @@ inline void convert_4_ys(__global uchar * out_yuv, int yi, const uchar8 rgbs1, c vstore4(yy, 0, out_yuv + yi); } -inline void convert_uv(__global uchar * out_yuv, int ui, int vi, +inline void convert_uv(__global uchar * out_yuv, int uvi, const uchar8 rgbs1, const uchar8 rgbs2) { // U & V: average of 2x2 pixels square const short ab = AVERAGE(rgbs1.s0, rgbs1.s3, rgbs2.s0, rgbs2.s3); const short ag = AVERAGE(rgbs1.s1, rgbs1.s4, rgbs2.s1, rgbs2.s4); const short ar = AVERAGE(rgbs1.s2, rgbs1.s5, rgbs2.s2, rgbs2.s5); #ifdef CL_DEBUG - if(ui >= RGB_SIZE + RGB_SIZE / 4) - printf("U overflow, %d >= %d\n", ui, RGB_SIZE + RGB_SIZE / 4); - if(vi >= RGB_SIZE + RGB_SIZE / 2) - printf("V overflow, %d >= %d\n", vi, RGB_SIZE + RGB_SIZE / 2); + if(uvi >= RGB_SIZE + RGB_SIZE / 2) + printf("UV overflow, %d >= %d\n", uvi, RGB_SIZE + RGB_SIZE / 2); #endif - out_yuv[ui] = RGB_TO_U(ar, ag, ab); - out_yuv[vi] = RGB_TO_V(ar, ag, ab); + out_yuv[uvi] = RGB_TO_U(ar, ag, ab); + out_yuv[uvi+1] = RGB_TO_V(ar, ag, ab); } -inline void convert_2_uvs(__global uchar * out_yuv, int ui, int vi, +inline void convert_2_uvs(__global uchar * out_yuv, int uvi, const uchar8 rgbs1, const uchar8 rgbs2, const uchar8 rgbs3, const uchar8 rgbs4) { // U & V: average of 2x2 pixels square const short ab1 = AVERAGE(rgbs1.s0, rgbs1.s3, rgbs2.s0, rgbs2.s3); @@ -54,25 +52,20 @@ inline void convert_2_uvs(__global uchar * out_yuv, int ui, int vi, const short ab2 = AVERAGE(rgbs1.s6, rgbs3.s1, rgbs2.s6, rgbs4.s1); const short ag2 = AVERAGE(rgbs1.s7, rgbs3.s2, rgbs2.s7, rgbs4.s2); const short ar2 = AVERAGE(rgbs3.s0, rgbs3.s3, rgbs4.s0, rgbs4.s3); - uchar2 u2 = (uchar2)( + uchar4 uv = (uchar4)( RGB_TO_U(ar1, ag1, ab1), - RGB_TO_U(ar2, ag2, ab2) - ); - uchar2 v2 = (uchar2)( RGB_TO_V(ar1, ag1, ab1), + RGB_TO_U(ar2, ag2, ab2), RGB_TO_V(ar2, ag2, ab2) ); #ifdef CL_DEBUG1 - if(ui > RGB_SIZE + RGB_SIZE / 4 - 2) - printf("U 2 overflow, %d >= %d\n", ui, RGB_SIZE + RGB_SIZE / 4 - 2); - if(vi > RGB_SIZE + RGB_SIZE / 2 - 2) - printf("V 2 overflow, %d >= %d\n", vi, RGB_SIZE + RGB_SIZE / 2 - 2); + if(uvi > RGB_SIZE + RGB_SIZE / 2 - 4) + printf("UV2 overflow, %d >= %d\n", uvi, RGB_SIZE + RGB_SIZE / 2 - 2); #endif - vstore2(u2, 0, out_yuv + ui); - vstore2(v2, 0, out_yuv + vi); + vstore4(uv, 0, out_yuv + uvi); } -__kernel void rgb_to_yuv(__global uchar const * const rgb, +__kernel void rgb_to_nv12(__global uchar const * const rgb, __global uchar * out_yuv) { const int dx = get_global_id(0); @@ -81,8 +74,7 @@ __kernel void rgb_to_yuv(__global uchar const * const rgb, const int row = mul24(dy, 4); // Current row in rgb image const int bgri_start = mad24(row, RGB_STRIDE, mul24(col, 3)); // Start offset of rgb data being converted const int yi_start = mad24(row, WIDTH, col); // Start offset in the target yuv buffer - int ui = mad24(row / 2, UV_WIDTH, RGB_SIZE + col / 2); - int vi = mad24(row / 2 , UV_WIDTH, RGB_SIZE + UV_WIDTH * UV_HEIGHT + col / 2); + int uvi = mad24(row / 2, WIDTH, RGB_SIZE + col); int num_col = min(WIDTH - col, 4); int num_row = min(HEIGHT - row, 4); if(num_row == 4) { @@ -99,15 +91,15 @@ __kernel void rgb_to_yuv(__global uchar const * const rgb, convert_4_ys(out_yuv, yi_start + WIDTH, rgbs1_0, rgbs1_1); convert_4_ys(out_yuv, yi_start + WIDTH * 2, rgbs2_0, rgbs2_1); convert_4_ys(out_yuv, yi_start + WIDTH * 3, rgbs3_0, rgbs3_1); - convert_2_uvs(out_yuv, ui, vi, rgbs0_0, rgbs1_0, rgbs0_1, rgbs1_1); - convert_2_uvs(out_yuv, ui + UV_WIDTH, vi + UV_WIDTH, rgbs2_0, rgbs3_0, rgbs2_1, rgbs3_1); + convert_2_uvs(out_yuv, uvi, rgbs0_0, rgbs1_0, rgbs0_1, rgbs1_1); + convert_2_uvs(out_yuv, uvi + WIDTH, rgbs2_0, rgbs3_0, rgbs2_1, rgbs3_1); } else if(num_col == 2) { convert_2_ys(out_yuv, yi_start, rgbs0_0); convert_2_ys(out_yuv, yi_start + WIDTH, rgbs1_0); convert_2_ys(out_yuv, yi_start + WIDTH * 2, rgbs2_0); convert_2_ys(out_yuv, yi_start + WIDTH * 3, rgbs3_0); - convert_uv(out_yuv, ui, vi, rgbs0_0, rgbs1_0); - convert_uv(out_yuv, ui + UV_WIDTH, vi + UV_WIDTH, rgbs2_0, rgbs3_0); + convert_uv(out_yuv, uvi, rgbs0_0, rgbs1_0); + convert_uv(out_yuv, uvi + WIDTH, rgbs2_0, rgbs3_0); } } else { const uchar8 rgbs0_0 = vload8(0, rgb + bgri_start); @@ -117,11 +109,11 @@ __kernel void rgb_to_yuv(__global uchar const * const rgb, if(num_col == 4) { convert_4_ys(out_yuv, yi_start, rgbs0_0, rgbs0_1); convert_4_ys(out_yuv, yi_start + WIDTH, rgbs1_0, rgbs1_1); - convert_2_uvs(out_yuv, ui, vi, rgbs0_0, rgbs1_0, rgbs0_1, rgbs1_1); + convert_2_uvs(out_yuv, uvi, rgbs0_0, rgbs1_0, rgbs0_1, rgbs1_1); } else if(num_col == 2) { convert_2_ys(out_yuv, yi_start, rgbs0_0); convert_2_ys(out_yuv, yi_start + WIDTH, rgbs1_0); - convert_uv(out_yuv, ui, vi, rgbs0_0, rgbs1_0); + convert_uv(out_yuv, uvi, rgbs0_0, rgbs1_0); } } } diff --git a/tools/sim/start_carla.sh b/tools/sim/start_carla.sh index 6418dacaee..7ead6699f0 100755 --- a/tools/sim/start_carla.sh +++ b/tools/sim/start_carla.sh @@ -2,26 +2,33 @@ # Requires nvidia docker - https://github.com/NVIDIA/nvidia-docker if ! $(apt list --installed | grep -q nvidia-container-toolkit); then - if [ -z "$INSTALL" ]; then - echo "Nvidia docker is required. Re-run with INSTALL=1 to automatically install." - exit 0 - else + read -p "Nvidia docker is required. Do you want to install it now? (y/n)"; + if [ "${REPLY}" == "y" ]; then distribution=$(. /etc/os-release;echo $ID$VERSION_ID) echo $distribution curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | sudo apt-key add - curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | sudo tee /etc/apt/sources.list.d/nvidia-docker.list - sudo apt-get update && sudo apt-get install -y nvidia-container-toolkit + sudo apt-get update && sudo apt-get install -y nvidia-docker2 # Also installs docker-ce and nvidia-container-toolkit sudo systemctl restart docker + else + exit 0 fi fi -docker pull carlasim/carla:0.9.12 +docker pull carlasim/carla:0.9.13 + +EXTRA_ARGS="-it" +if [[ "$DETACH" ]]; then + EXTRA_ARGS="-d" +fi +docker kill carla_sim || true docker run \ + --name carla_sim \ --rm \ --gpus all \ --net=host \ -v /tmp/.X11-unix:/tmp/.X11-unix:rw \ - -it \ - carlasim/carla:0.9.12 \ - /bin/bash ./CarlaUE4.sh -opengl -nosound -RenderOffScreen -benchmark -fps=20 -quality-level=High + $EXTRA_ARGS \ + carlasim/carla:0.9.13 \ + /bin/bash ./CarlaUE4.sh -opengl -nosound -RenderOffScreen -benchmark -fps=20 -quality-level=Low diff --git a/tools/sim/start_openpilot_docker.sh b/tools/sim/start_openpilot_docker.sh index 106dbdeccb..dba89b8b70 100755 --- a/tools/sim/start_openpilot_docker.sh +++ b/tools/sim/start_openpilot_docker.sh @@ -3,22 +3,27 @@ DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" cd $DIR -# expose X to the container -xhost +local:root - -docker pull ghcr.io/commaai/openpilot-sim:latest - OPENPILOT_DIR="/openpilot" -if ! [[ -z "$MOUNT_OPENPILOT" ]] -then +if ! [[ -z "$MOUNT_OPENPILOT" ]]; then OPENPILOT_DIR="$(dirname $(dirname $DIR))" EXTRA_ARGS="-v $OPENPILOT_DIR:$OPENPILOT_DIR -e PYTHONPATH=$OPENPILOT_DIR:$PYTHONPATH" fi +if [[ "$CI" ]]; then + CMD="CI=1 ${OPENPILOT_DIR}/tools/sim/tests/test_carla_integration.py" +else + # expose X to the container + xhost +local:root + + docker pull ghcr.io/commaai/openpilot-sim:latest + CMD="./tmux_script.sh $*" + EXTRA_ARGS="${EXTRA_ARGS} -it" +fi + +docker kill openpilot_client || true docker run --net=host\ --name openpilot_client \ --rm \ - -it \ --gpus all \ --device=/dev/dri:/dev/dri \ --device=/dev/input:/dev/input \ @@ -29,4 +34,4 @@ docker run --net=host\ -w "$OPENPILOT_DIR/tools/sim" \ $EXTRA_ARGS \ ghcr.io/commaai/openpilot-sim:latest \ - /bin/bash -c "./tmux_script.sh $*" + /bin/bash -c "$CMD" diff --git a/tools/sim/tests/__init__.py b/tools/sim/tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tools/sim/tests/test_carla_integration.py b/tools/sim/tests/test_carla_integration.py new file mode 100755 index 0000000000..f467391967 --- /dev/null +++ b/tools/sim/tests/test_carla_integration.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +import subprocess +import time +import unittest +import os +from multiprocessing import Queue + +from cereal import messaging +from common.basedir import BASEDIR +from selfdrive.manager.helpers import unblock_stdout +from tools.sim import bridge +from tools.sim.bridge import CarlaBridge + +CI = "CI" in os.environ + +SIM_DIR = os.path.join(BASEDIR, "tools/sim") + +class TestCarlaIntegration(unittest.TestCase): + """ + Tests need Carla simulator to run + """ + processes = None + carla_process = None + + def setUp(self): + self.processes = [] + + if not CI: + # We want to make sure that carla_sim docker isn't still running. + subprocess.run("docker rm -f carla_sim", shell=True, stderr=subprocess.PIPE, check=False) + self.carla_process = subprocess.Popen("./start_carla.sh", cwd=SIM_DIR) + + # Too many lagging messages in bridge.py can cause a crash. This prevents it. + unblock_stdout() + # Wait 10 seconds to startup carla + time.sleep(10) + + def test_engage(self): + # Startup manager and bridge.py. Check processes are running, then engage and verify. + p_manager = subprocess.Popen("./launch_openpilot.sh", cwd=SIM_DIR) + self.processes.append(p_manager) + + sm = messaging.SubMaster(['controlsState', 'carEvents', 'managerState']) + q = Queue() + carla_bridge = CarlaBridge(bridge.parse_args([])) + p_bridge = carla_bridge.run(q, retries=10) + self.processes.append(p_bridge) + + max_time_per_step = 60 + + # Wait for bridge to startup + start_waiting = time.monotonic() + while not carla_bridge.started and time.monotonic() < start_waiting + max_time_per_step: + time.sleep(0.1) + self.assertEqual(p_bridge.exitcode, None, f"Bridge process should be running, but exited with code {p_bridge.exitcode}") + + start_time = time.monotonic() + no_car_events_issues_once = False + car_event_issues = [] + not_running = [] + while time.monotonic() < start_time + max_time_per_step: + sm.update() + + not_running = [p.name for p in sm['managerState'].processes if not p.running and p.shouldBeRunning] + car_event_issues = [event.name for event in sm['carEvents'] if any([event.noEntry, event.softDisable, event.immediateDisable])] + + if sm.all_alive() and len(car_event_issues) == 0 and len(not_running) == 0: + no_car_events_issues_once = True + break + + self.assertTrue(no_car_events_issues_once, f"Failed because no messages received, or CarEvents '{car_event_issues}' or processes not running '{not_running}'") + + start_time = time.monotonic() + min_counts_control_active = 100 + control_active = 0 + + while time.monotonic() < start_time + max_time_per_step: + sm.update() + + q.put("cruise_down") # Try engaging + + if sm.all_alive() and sm['controlsState'].active: + control_active += 1 + + if control_active == min_counts_control_active: + break + + self.assertEqual(min_counts_control_active, control_active, f"Simulator did not engage a minimal of {min_counts_control_active} steps was {control_active}") + + def tearDown(self): + print("Test shutting down. CommIssues are acceptable") + for p in reversed(self.processes): + p.terminate() + + for p in reversed(self.processes): + if isinstance(p, subprocess.Popen): + p.wait(15) + else: + p.join(15) + + # Stop carla simulator by removing docker container + subprocess.run("docker rm -f carla_sim", shell=True, stderr=subprocess.PIPE, check=False) + if self.carla_process is not None: + self.carla_process.wait() + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/ssh/README.md b/tools/ssh/README.md index 5c7f3519b2..67b5271a42 100644 --- a/tools/ssh/README.md +++ b/tools/ssh/README.md @@ -7,11 +7,11 @@ In order to SSH into your device, you'll need a GitHub account with SSH keys. Se * Enable SSH in your device's settings * Enter your GitHub username in the device's settings * Connect to your device - * Username: `root` (comma two) or `comma` (comma three) + * Username: `comma` * Port: `22` or `8022` -Here's an example command for connecting to your device using its tethered connection: -`ssh root@192.168.43.1` +Here's an example command for connecting to your device using its tethered connection:
+`ssh comma@192.168.43.1` For doing development work on device, it's recommended to use [SSH agent forwarding](https://docs.github.com/en/developers/overview/using-ssh-agent-forwarding). @@ -22,3 +22,53 @@ The public keys are only fetched from your GitHub account once. In order to upda The `id_rsa` key in this directory only works while your device is in the setup state with no software installed. After installation, that default key will be removed. See the [community wiki](https://github.com/commaai/openpilot/wiki/SSH) for more detailed instructions and information. + +# Connecting to ssh.comma.ai +SSH into your comma device from anywhere with `ssh.comma.ai`. + +## Setup + +With software version 0.6.1 or newer, enter your GitHub username on your device under Developer Settings. Your GitHub authorized public keys will become your authorized SSH keys for `ssh.comma.ai`. You can add any additional keys in `/system/comma/home/.ssh/authorized_keys.persist`. + +Requires [comma SIM with comma prime](https://comma.ai/shop) activated with comma connect, available on iOS and Android. comma two and EON ship with a pre-inserted comma SIM. + +## Recommended .ssh/config + +With the below SSH configuration, you can type `ssh comma-{dongleid}` to connect to your device through `ssh.comma.ai`.
+For example: `ssh comma-ffffffffffffffff` + +``` +Host comma-* + Port 22 + User comma + IdentityFile ~/.ssh/my_github_key + ProxyCommand ssh %h@ssh.comma.ai -W %h:%p +Host ssh.comma.ai + Hostname ssh.comma.ai + Port 22 + IdentityFile ~/.ssh/my_github_key +``` + +## One-off connection + +``` +ssh -i ~/.ssh/my_github_key -o ProxyCommand="ssh -i ~/.ssh/my_github_key -W %h:%p -p %p %h@ssh.comma.ai" comma@ffffffffffffffff +``` +(Replace `ffffffffffffffff` with your dongle_id) + +## ssh.comma.ai host key fingerprint + +``` +Host key fingerprint is SHA256:X22GOmfjGb9J04IA2+egtdaJ7vW9Fbtmpz9/x8/W1X4 ++---[RSA 4096]----+ +| | +| | +| . | +| + o | +| S = + +..| +| + @ = .=| +| . B @ ++=| +| o * B XE| +| .o o OB/| ++----[SHA256]-----+ +``` diff --git a/tools/tuning/measure_steering_accuracy.py b/tools/tuning/measure_steering_accuracy.py new file mode 100755 index 0000000000..4819be770f --- /dev/null +++ b/tools/tuning/measure_steering_accuracy.py @@ -0,0 +1,156 @@ +#!/usr/bin/env python3 +# type: ignore + +import os +import time +import argparse +import signal +from collections import defaultdict + +import cereal.messaging as messaging +from tools.lib.logreader import logreader_from_route_or_segment + +def sigint_handler(signal, frame): + exit(0) +signal.signal(signal.SIGINT, sigint_handler) + +class SteeringAccuracyTool: + all_groups = {"germany": (45, "45 - up m/s // 162 - up km/h // 101 - up mph"), + "veryfast": (35, "35 - 45 m/s // 126 - 162 km/h // 78 - 101 mph"), + "fast": (25, "25 - 35 m/s // 90 - 126 km/h // 56 - 78 mph"), + "medium": (15, "15 - 25 m/s // 54 - 90 km/h // 34 - 56 mph"), + "slow": (5, " 5 - 15 m/s // 18 - 54 km/h // 11 - 34 mph"), + "crawl": (0, " 0 - 5 m/s // 0 - 18 km/h // 0 - 11 mph")} + + def __init__(self, args): + self.msg_cnt = 0 + self.cnt = 0 + self.total_error = 0 + + if args.group == "all": + self.display_groups = self.all_groups.keys() + elif args.group in self.all_groups.keys(): + self.display_groups = [args.group] + else: + raise ValueError("invalid speed group, see help") + + self.speed_group_stats = {} + for group in self.all_groups: + self.speed_group_stats[group] = defaultdict(lambda: {'err': 0, "cnt": 0, "=": 0, "+": 0, "-": 0, "steer": 0, "limited": 0, "saturated": 0, "dpp": 0}) + + def update(self, sm): + self.msg_cnt += 1 + + lateralControlState = sm['controlsState'].lateralControlState + control_type = list(lateralControlState.to_dict().keys())[0] + control_state = lateralControlState.__getattr__(control_type) + + v_ego = sm['carState'].vEgo + active = sm['controlsState'].active + steer = sm['carControl'].actuatorsOutput.steer + standstill = sm['carState'].standstill + steer_limited = abs(sm['carControl'].actuators.steer - sm['carControl'].actuatorsOutput.steer) > 1e-2 + overriding = sm['carState'].steeringPressed + changing_lanes = sm['lateralPlan'].laneChangeState != 0 + d_path_points = sm['lateralPlan'].dPathPoints + # must be engaged, not at standstill, not overriding steering, and not changing lanes + if active and not standstill and not overriding and not changing_lanes: + self.cnt += 1 + + # wait 5 seconds after engage / standstill / override / lane change + if self.cnt >= 500: + actual_angle = control_state.steeringAngleDeg + desired_angle = control_state.steeringAngleDesiredDeg + + # calculate error before rounding, then round for stats grouping + angle_error = abs(desired_angle - actual_angle) + actual_angle = round(actual_angle, 1) + desired_angle = round(desired_angle, 1) + angle_error = round(angle_error, 2) + angle_abs = int(abs(round(desired_angle, 0))) + + for group, group_props in self.all_groups.items(): + if v_ego > group_props[0]: + # collect stats + self.speed_group_stats[group][angle_abs]["cnt"] += 1 + self.speed_group_stats[group][angle_abs]["err"] += angle_error + self.speed_group_stats[group][angle_abs]["steer"] += abs(steer) + if len(d_path_points): + self.speed_group_stats[group][angle_abs]["dpp"] += abs(d_path_points[0]) + if steer_limited: + self.speed_group_stats[group][angle_abs]["limited"] += 1 + if control_state.saturated: + self.speed_group_stats[group][angle_abs]["saturated"] += 1 + if actual_angle == desired_angle: + self.speed_group_stats[group][angle_abs]["="] += 1 + else: + if desired_angle == 0.: + overshoot = True + else: + overshoot = desired_angle < actual_angle if desired_angle > 0. else desired_angle > actual_angle + self.speed_group_stats[group][angle_abs]["+" if overshoot else "-"] += 1 + break + else: + self.cnt = 0 + + if self.msg_cnt % 100 == 0: + print(chr(27) + "[2J") + if self.cnt != 0: + print("COLLECTING ...\n") + else: + print("DISABLED (not active, standstill, steering override, or lane change)\n") + for group in self.display_groups: + if len(self.speed_group_stats[group]) > 0: + print(f"speed group: {group:10s} {self.all_groups[group][1]:>96s}") + print(f" {'-'*118}") + for k in sorted(self.speed_group_stats[group].keys()): + v = self.speed_group_stats[group][k] + print(f' {k:#2}° | actuator:{int(v["steer"] / v["cnt"] * 100):#3}% | error: {round(v["err"] / v["cnt"], 2):2.2f}° | -:{int(v["-"] / v["cnt"] * 100):#3}% | =:{int(v["="] / v["cnt"] * 100):#3}% | +:{int(v["+"] / v["cnt"] * 100):#3}% | lim:{v["limited"]:#5} | sat:{v["saturated"]:#5} | path dev: {round(v["dpp"] / v["cnt"], 2):2.2f}m | total: {v["cnt"]:#5}') + print("") + + +if __name__ == "__main__": + + parser = argparse.ArgumentParser(description='Steering accuracy measurement tool') + parser.add_argument('--route', help="route name") + parser.add_argument('--addr', default='127.0.0.1', help="IP address for optional ZMQ listener, default to msgq") + parser.add_argument('--group', default='all', help="speed group to display, [crawl|slow|medium|fast|veryfast|germany|all], default to all") + parser.add_argument('--cache', default=False, action='store_true', help="use cached data, default to False") + args = parser.parse_args() + + if args.cache: + os.environ['FILEREADER_CACHE'] = '1' + + tool = SteeringAccuracyTool(args) + + if args.route is not None: + print(f"loading {args.route}...") + lr = logreader_from_route_or_segment(args.route, sort_by_time=True) + + sm = {} + for msg in lr: + if msg.which() == 'carState': + sm['carState'] = msg.carState + elif msg.which() == 'carControl': + sm['carControl'] = msg.carControl + elif msg.which() == 'controlsState': + sm['controlsState'] = msg.controlsState + elif msg.which() == 'lateralPlan': + sm['lateralPlan'] = msg.lateralPlan + + if msg.which() == 'carControl' and 'carState' in sm and 'controlsState' in sm and 'lateralPlan' in sm: + tool.update(sm) + + else: + if args.addr != "127.0.0.1": + os.environ["ZMQ"] = "1" + messaging.context = messaging.Context() + + carControl = messaging.sub_sock('carControl', addr=args.addr, conflate=True) + sm = messaging.SubMaster(['carState', 'carControl', 'controlsState', 'lateralPlan'], addr=args.addr) + time.sleep(1) # Make sure all submaster data is available before going further + + print("waiting for messages...") + while messaging.recv_one(carControl): + sm.update() + tool.update(sm) diff --git a/tools/ubuntu_setup.sh b/tools/ubuntu_setup.sh index e688c79c12..89d33a6127 100755 --- a/tools/ubuntu_setup.sh +++ b/tools/ubuntu_setup.sh @@ -4,16 +4,27 @@ set -e DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" ROOT="$(cd $DIR/../ && pwd)" +SUDO="" # NOTE: this is used in a docker build, so do not run any scripts here. +# Use sudo if not root +if [[ ! $(id -u) -eq 0 ]]; then + if [[ -z $(which sudo) ]]; then + echo "Please install sudo or run as root" + exit 1 + fi + SUDO="sudo" +fi + # Install packages present in all supported versions of Ubuntu function install_ubuntu_common_requirements() { - sudo apt-get update - sudo apt-get install -y --no-install-recommends \ + $SUDO apt-get update + $SUDO apt-get install -y --no-install-recommends \ autoconf \ build-essential \ ca-certificates \ + casync \ clang \ cmake \ make \ @@ -45,6 +56,7 @@ function install_ubuntu_common_requirements() { libomp-dev \ libopencv-dev \ libpng16-16 \ + libportaudio2 \ libssl-dev \ libsqlite3-dev \ libusb-1.0-0-dev \ @@ -55,48 +67,51 @@ function install_ubuntu_common_requirements() { ocl-icd-libopencl1 \ ocl-icd-opencl-dev \ clinfo \ - python-dev \ qml-module-qtquick2 \ qtmultimedia5-dev \ qtlocation5-dev \ qtpositioning5-dev \ + qttools5-dev-tools \ libqt5sql5-sqlite \ libqt5svg5-dev \ + libqt5charts5-dev \ libqt5x11extras5-dev \ libreadline-dev \ libdw1 \ valgrind } -# Install Ubuntu 21.10 packages -function install_ubuntu_latest_requirements() { +# Install Ubuntu 22.04 LTS packages +function install_ubuntu_jammy_requirements() { install_ubuntu_common_requirements - sudo apt-get install -y --no-install-recommends \ + $SUDO apt-get install -y --no-install-recommends \ qtbase5-dev \ qtchooser \ qt5-qmake \ - qtbase5-dev-tools + qtbase5-dev-tools \ + python3-dev } # Install Ubuntu 20.04 packages -function install_ubuntu_lts_requirements() { +function install_ubuntu_focal_requirements() { install_ubuntu_common_requirements - sudo apt-get install -y --no-install-recommends \ + $SUDO apt-get install -y --no-install-recommends \ libavresample-dev \ - qt5-default + qt5-default \ + python-dev } # Detect OS using /etc/os-release file if [ -f "/etc/os-release" ]; then source /etc/os-release - case "$ID $VERSION_ID" in - "ubuntu 21.10") - install_ubuntu_latest_requirements + case "$VERSION_CODENAME" in + "jammy") + install_ubuntu_jammy_requirements ;; - "ubuntu 20.04") - install_ubuntu_lts_requirements + "focal") + install_ubuntu_focal_requirements ;; *) echo "$ID $VERSION_ID is unsupported. This setup script is written for Ubuntu 20.04." @@ -105,7 +120,11 @@ if [ -f "/etc/os-release" ]; then if [[ ! $REPLY =~ ^[Yy]$ ]]; then exit 1 fi - install_ubuntu_lts_requirements + if [ "$UBUNTU_CODENAME" = "jammy" ]; then + install_ubuntu_jammy_requirements + else + install_ubuntu_focal_requirements + fi esac else echo "No /etc/os-release in the system" diff --git a/tools/webcam/Dockerfile b/tools/webcam/Dockerfile index 70317cd924..78a25e836d 100644 --- a/tools/webcam/Dockerfile +++ b/tools/webcam/Dockerfile @@ -32,7 +32,8 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ mv opencv-${OPENCV_VERSION} OpenCV && \ cd OpenCV && mkdir build && cd build && \ cmake -DWITH_OPENGL=ON -DFORCE_VTK=ON -DWITH_TBB=ON -DWITH_GDAL=ON \ - -DWITH_XINE=ON -DENABLE_PRECOMPILED_HEADERS=OFF .. && \ + -DWITH_XINE=ON -DENABLE_PRECOMPILED_HEADERS=OFF -DBUILD_TESTS=OFF \ + -DBUILD_PERF_TESTS=OFF -DBUILD_EXAMPLES=OFF -DBUILD_opencv_apps=OFF .. && \ make -j8 && \ make install && \ ldconfig && \ diff --git a/tools/webcam/README.md b/tools/webcam/README.md index 48e5accb2a..237e07cdb6 100644 --- a/tools/webcam/README.md +++ b/tools/webcam/README.md @@ -1,3 +1,5 @@ +# NOTE: this README is outdated. #24590 tracks adding back webcam support + # Run openpilot with webcam on PC What's needed: @@ -16,21 +18,21 @@ git clone https://github.com/commaai/openpilot.git - Follow [this readme](https://github.com/commaai/openpilot/tree/master/tools) to install the requirements - Add line "export PYTHONPATH=$HOME/openpilot" to your ~/.bashrc - Install tensorflow 2.2 and nvidia drivers: nvidia-xxx/cuda10.0/cudnn7.6.5 -- Install [OpenCL Driver](http://registrationcenter-download.intel.com/akdlm/irc_nas/vcp/15532/l_opencl_p_18.1.0.015.tgz) +- Install [OpenCL Driver](https://registrationcenter-download.intel.com/akdlm/irc_nas/vcp/15532/l_opencl_p_18.1.0.015.tgz) - Install [OpenCV4](https://www.pyimagesearch.com/2018/08/15/how-to-install-opencv-4-on-ubuntu/) (ignore the Python part) ## Build openpilot for webcam ``` cd ~/openpilot ``` -- check out selfdrive/camerad/cameras/camera_webcam.cc lines 72 and 146 before building if any camera is upside down +- check out system/camerad/cameras/camera_webcam.cc lines 72 and 146 before building if any camera is upside down ``` USE_WEBCAM=1 scons -j$(nproc) ``` ## Connect the hardware - Connect the road facing camera first, then the driver facing camera -- (default indexes are 1 and 2; can be modified in selfdrive/camerad/cameras/camera_webcam.cc) +- (default indexes are 1 and 2; can be modified in system/camerad/cameras/camera_webcam.cc) - Connect your computer to panda ## GO diff --git a/tools/zookeeper/__init__.py b/tools/zookeeper/__init__.py old mode 100755 new mode 100644 index cd64d3a1fb..42438cb209 --- a/tools/zookeeper/__init__.py +++ b/tools/zookeeper/__init__.py @@ -1,9 +1,6 @@ #!/usr/bin/env python3 - -# Python library to control Zookeeper - -import ft4222 # pylint: disable=import-error -import ft4222.I2CMaster # pylint: disable=import-error +import ft4222 +import ft4222.I2CMaster DEBUG = False diff --git a/tools/zookeeper/enable_and_wait.py b/tools/zookeeper/enable_and_wait.py index 398ef412b1..6907e6017c 100755 --- a/tools/zookeeper/enable_and_wait.py +++ b/tools/zookeeper/enable_and_wait.py @@ -1,12 +1,16 @@ #!/usr/bin/env python3 - import os import sys import time +from socket import gethostbyname, gaierror from tools.zookeeper import Zookeeper def is_online(ip): - return (os.system(f"ping -c 1 {ip} > /dev/null") == 0) + try: + addr = gethostbyname(ip) + return (os.system(f"ping -c 1 {addr} > /dev/null") == 0) + except gaierror: + return False if __name__ == "__main__": z = Zookeeper() diff --git a/tools/zookeeper/power_monitor.py b/tools/zookeeper/power_monitor.py index f2796bad31..fa1f442bbc 100755 --- a/tools/zookeeper/power_monitor.py +++ b/tools/zookeeper/power_monitor.py @@ -1,30 +1,40 @@ -#!/usr/bin/env python - +#!/usr/bin/env python3 import sys import time -from tools.zookeeper import Zookeeper +import datetime -# Usage: check_consumption.py -# Exit code: 0 -> passed -# 1 -> failed +from common.realtime import Ratekeeper +from common.filter_simple import FirstOrderFilter +from tools.zookeeper import Zookeeper if __name__ == "__main__": z = Zookeeper() + z.set_device_power(True) + z.set_device_ignition(False) duration = None if len(sys.argv) > 1: duration = int(sys.argv[1]) + rate = 123 + rk = Ratekeeper(rate, print_delay_threshold=None) + fltr = FirstOrderFilter(0, 5, 1. / rate, initialized=False) + + measurements = [] + start_time = time.monotonic() + try: - start_time = time.monotonic() - measurements = [] while duration is None or time.monotonic() - start_time < duration: - p = z.read_power() - print(round(p, 3), "W") - measurements.append(p) - time.sleep(0.25) + fltr.update(z.read_power()) + if rk.frame % rate == 0: + measurements.append(fltr.x) + t = datetime.timedelta(seconds=time.monotonic() - start_time) + avg = sum(measurements) / len(measurements) + print(f"Now: {fltr.x:.2f} W, Avg: {avg:.2f} W over {t}") + rk.keep_time() except KeyboardInterrupt: pass - finally: - average_power = sum(measurements)/len(measurements) - print(f"Average power: {round(average_power, 4)}W") + + t = datetime.timedelta(seconds=time.monotonic() - start_time) + avg = sum(measurements) / len(measurements) + print(f"\nAverage power: {avg:.2f}W over {t}") diff --git a/tools/zookeeper/requirements.txt b/tools/zookeeper/requirements.txt deleted file mode 100644 index 6f70576caf..0000000000 --- a/tools/zookeeper/requirements.txt +++ /dev/null @@ -1 +0,0 @@ -ft4222==1.2.1 \ No newline at end of file diff --git a/update_requirements.sh b/update_requirements.sh index ac9472dca2..9195799ca3 100755 --- a/update_requirements.sh +++ b/update_requirements.sh @@ -1,14 +1,33 @@ -#!/bin/bash - +#!/usr/bin/env bash set -e DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" cd $DIR +RC_FILE="${HOME}/.$(basename ${SHELL})rc" +if [ "$(uname)" == "Darwin" ] && [ $SHELL == "/bin/bash" ]; then + RC_FILE="$HOME/.bash_profile" +fi + if ! command -v "pyenv" > /dev/null 2>&1; then echo "pyenv install ..." curl -L https://github.com/pyenv/pyenv-installer/raw/master/bin/pyenv-installer | bash + + echo -e "\n. ~/.pyenvrc" >> $RC_FILE + cat < "${HOME}/.pyenvrc" +if [ -z "\$PYENV_ROOT" ]; then + export PATH=\$HOME/.pyenv/bin:\$HOME/.pyenv/shims:\$PATH + export PYENV_ROOT="\$HOME/.pyenv" + eval "\$(pyenv init -)" + eval "\$(pyenv virtualenv-init -)" +fi +EOF + + # setup now without restarting shell export PATH=$HOME/.pyenv/bin:$HOME/.pyenv/shims:$PATH + export PYENV_ROOT="$HOME/.pyenv" + eval "$(pyenv init -)" + eval "$(pyenv virtualenv-init -)" fi export MAKEFLAGS="-j$(nproc)" @@ -26,29 +45,35 @@ fi eval "$(pyenv init --path)" echo "update pip" -pip install pip==21.3.1 -pip install pipenv==2021.11.23 +pip install pip==22.3 +pip install poetry==1.2.2 -if [ -d "./xx" ]; then - export PIPENV_SYSTEM=1 - export PIPENV_PIPFILE=./xx/Pipfile -fi +poetry config virtualenvs.prefer-active-python true --local -if [ -z "$PIPENV_SYSTEM" ]; then - echo "PYTHONPATH=${PWD}" > .env - RUN="pipenv run" -else - RUN="" +POETRY_INSTALL_ARGS="" +if [ -d "./xx" ] || [ -n "$XX" ]; then + echo "WARNING: using xx dependency group, installing globally" + poetry config virtualenvs.create false --local + POETRY_INSTALL_ARGS="--with xx --sync" fi echo "pip packages install..." -pipenv install --dev --deploy --clear +poetry install --no-cache --no-root $POETRY_INSTALL_ARGS pyenv rehash -if [ -f "$DIR/.pre-commit-config.yaml" ]; then - echo "precommit install ..." - $RUN pre-commit install - [ -d "./xx" ] && (cd xx && $RUN pre-commit install) - [ -d "./notebooks" ] && (cd notebooks && $RUN pre-commit install) - echo "pre-commit hooks installed" +if [ -d "./xx" ] || [ -n "$POETRY_VIRTUALENVS_CREATE" ]; then + RUN="" +else + echo "PYTHONPATH=${PWD}" > .env + poetry self add poetry-dotenv-plugin@^0.1.0 + RUN="poetry run" fi + +echo "pre-commit hooks install..." +shopt -s nullglob +for f in .pre-commit-config.yaml */.pre-commit-config.yaml; do + cd $DIR/$(dirname $f) + if [ -e ".git" ]; then + $RUN pre-commit install + fi +done