Apple's open-source XNU kernel on Android phones: its own loader and drivers, Metal on the Adreno. Runs from RAM; a reboot gives the phone back to Android.
C
Camera for iOS: groundwork behind cam=5 (no frames reach apps yet)
vcvkk8d2d3d70b708
diff --git a/README.md b/README.mdindex 462bc4c..cf7ea47 100644--- a/README.md+++ b/README.md@@ -287,7 +287,7 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=8" ./xl run #| `sound=N` | с `adsp=1`, шаг 3 звука, путь к динамикам, как его строит Android (числа — из живого дерева устройств телефона, его путей микшера и его ядра): `sound=1` — ножки TDM (GPIO 97–100) отданы интерфейсу, звуковой процессор включает его тактовую частоту (3,072 МГц), группу и порт 0x9000 (PRI_TDM_RX_0) и запускает его; по ножкам видно, что тактовый сигнал и синхронизация кадров идут. `sound=2` — ещё и поток: наша память видна процессору через SMMU (поток 0x1801), путь ADM к порту, поток ASM, и в него 3 с пишется тон 1 кГц −20 дБ полной шкалы; процессор забирает его с частотой 48 кГц. Усилители выключены. `sound=3` — ещё и усилители: настраиваются из профиля «Music» конфигурации Android (`/vendor/etc/aw882xx_acf.bin` телефона в `fw-audio/`, в git не попадает, `userland/build.sh` кладёт её в `/fw` образа системы), каждая запись читается обратно, при любом расхождении или сбое оба сразу выключаются; громкость плавно поднимается до `sound_below` восьмых долей дБ ниже уровня Android (по умолчанию 240, то есть на 30 дБ тише; выше уровня Android — никогда), тон звучит 3 с, потом всё затихает, выключается и возвращается как было. `sound=4` — то, что играет iOS (`/dev/redwood-audio`), до конца сеанса: порт и поток работают всё время (без звука в них идёт тишина), усилители настраиваются один раз и выключены, а когда в записи iOS появляется не тишина, включаются и быстро (как у драйвера Android) выводятся на `sound_below`; после трёх секунд тишины снова выключаются. Звук доходит до усилителей через 160 мс после записи, усилители готовы через 65 мс. У динамика в модуле HAL есть регулятор громкости, его значение уходит в ядро (`ioctl` `REDWOOD_AUDIO_SET_VOLUME`) и задаёт уровень усилителей ниже потолка (0 — усилители не включаются), но iOS ставит его только раз, на максимум, а громкость кнопок и Пункта управления применяет к самим отсчётам (программная громкость для динамика iPhone X в таблицах VirtualAudio); при громкости 0 iOS пишет тишину, и усилители тоже не включаются. Проверка — `RC_JOBS=rc.jobs.volume`. По пути к усилителям — сторож (см. выше): `sound_gain=N` (восьмые доли дБ, 0–96), `sound_guard_as=N` (для проверки: сторож считает усилители на N ниже уровня Android и сдерживает, как сдерживал бы там). `sound_secs=S` (не больше 3 с тоном), `sound_pause=MS`. Подробности в начале `bsd/dev/redwood_sound.c` и `bsd/dev/redwood_speaker.c` || `haptic=N` | моторчик вибрации: Awinic AW86927 на I2C (шина QUP SE9, GPIO 36/37, адрес 0x5a; сброс — GPIO 35), линейный мотор с резонансом 175,5 Гц; всё — из живого дерева устройств Android, его журнала и регистров (`bsd/dev/redwood_haptic.c`). `haptic=1` — только читать: из загрузчика Android сброс держит чип выключенным, он не отвечает. `haptic=2` — сброс отпущен, как это делает драйвер Android, регистры прочитаны и сравнены с Android. `haptic=3` — ещё и настройка Android (каждая запись читается обратно; аналоговые регистры — за разблокировкой 0x5b) и волновые формы Android (`/vendor/firmware/aw8697_haptic.bin` телефона в `fw-haptic/`, в git не попадает; `userland/build.sh` кладёт его в `fw/` малого образа) в ОЗУ чипа, с проверкой чтением. `haptic=4` — ещё и одна короткая форма (`haptic_effect=1…10`) один раз, с усилением Android. `haptic=5` — моторчик для iOS до конца сеанса: всё, что iOS играет на своём устройстве «Actuator» (системные отклики и вибрация звонка, CoreHaptics приложений, отклики UIKit — например, меню иконки по долгому нажатию), звуковой модуль HAL отдаёт в `/dev/redwood-haptic`, и ядро играет по нему формы Android: каждую волну iOS — коротким толчком (форма 1), а длинную — повтором формы 11, пока iOS играет, но не дольше 1 с, после чего мотор столько же отдыхает; усиление — по громкости волны iOS: от трети полной шкалы и выше — усиление Android (0x80), ниже — до пяти восьмых его у самых тихих, и никогда не выше Android (волны iOS для Taptic Engine почти всегда гораздо тише полной шкалы, и в прямой пропорции большинство откликов выходило на десятой доле усиления Android — их было не почувствовать). Проверка обычных касаний: `RC_JOBS=rc.jobs.haptic2` (долгое нажатие на иконку, переключатель в Настройках). Без `haptic=5` iOS играет на «Actuator» как обычно, но в мотор ничего не идёт. Проверка: `RC_JOBS=rc.jobs.haptic`. Любая неисправность, о которой говорит чип, несовпадение при чтении или неотвеченный байт — чип снова в сброс до конца сеанса; не дольше 1 с на эффект; в конце сеанса и при панике — сброс || `torch=N` | фонарик: светодиодный модуль вспышки PM8350C (SPMI, ведомый 2, регистры 0xee00; задний светодиод — канал 0), значения Android: его фонарик горит на 125 мА через канал 0 (прочитано у включённого фонарика Android), шаг тока 12,5 мА, порядок записей — драйвера Xiaomi `leds-qti-flash.c` (`bsd/dev/redwood_torch.c`). `torch=1` — только читать: канал арбитра, тип модуля, регистры, температурная тревога PMIC. `torch=2` — ещё и зажечь один раз на 125 мА на `torch_secs` (по умолчанию 2 с). `torch=3` — фонарик для iOS: `/dev/redwood-torch` принимает уровень 0…1000 (тысячные тока Android, не выше 125 мА); загрузчик с `torch=N` добавляет в дерево `/product/camera` со свойством `flash` айфона (кнопка фонарика в Пункте управления), а `libredwood-media.dylib` отдаёт FigFlashlight в mediaserverd своё «устройство» вместо отсутствующей камеры (`userland/src/inject_media.c`). Пределы: записи — только в шесть регистров этого модуля, каждая читается обратно, канал арбитра перепроверяется; не дольше `torch_max_s` подряд (по умолчанию 30 с, не больше 120), потом темно, пока iOS не попросит снова; 10 раз в секунду — флаги неисправности и перегрева модуля, температурная тревога PMIC и температура батареи (не выше 45 °C; из battmgr при `adsp=1` или из `battery=1`) — что-то не так, и фонарик гаснет до конца сеанса; в конце сеанса и при панике — погашен. Проверка: `RC_JOBS=rc.jobs.torch` (`torch_test` — как программа, через AVFlashlight; потом кнопка в Пункте управления) |-| `cam=N` | камеры: макрокамера — OmniVision OV02B10 (2 Мп, камера 2 Android, «redwood_aac_ov02b10_macro»); всё — из живого дерева устройств (cam-sensor2), файла модуля камеры Android (`/vendor/lib64/camera/com.qti.sensormodule.redwood_aac_ov02b10_macro.bin`: адрес, где и как читается ID чипа, порядок включения) и драйверов ядра Android (`bsd/dev/redwood_camera.c`). Датчик — на CCI 1, ведущий 0 (GPIO 73/74, здесь I2C вручную, как у других драйверов), адрес 0x3c; сброс — GPIO 77; MCLK — mclk2 camcc на 19,2 МГц на GPIO 66 (у Android эти 19,2 МГц — от PLL2 camcc, здесь — от самого кварца, без PLL); питание — LDO6 (1,8 В, DOVDD) и LDO7 (2,8 В, AVDD) PM8008i, который на I2C последовательного движка 1 (GPIO 4/5, адреса 0x08 и 0x09) и выходит из сброса по GPIO 3 PM8350C, как его выводит Android. `cam=1` — только смотреть: тактовые частоты и домен питания камеры, ножки, сброс PM8008i и, если он не в сбросе, сам PM8008i. `cam=2` — ещё и включить датчик в порядке файла модуля (у макрокамеры: сброс низкий, 1 мс; DOVDD; AVDD, 2 мс; верхний домен питания камеры и MCLK, 4 мс; сброс высокий, 9 мс), прочитать ID чипа так, как читает Android (16-битный регистр по 16-битному адресу 0x0203; ждёт 0x002b), и выключить в обратном порядке. Пределы: напряжения — только Android (1,8 и 2,8 В у макрокамеры, 1,0 и 1,8 В у широкой), записи — только в перечисленные регистры (у каждого устройства — список, проверяется при каждой записи), каждая читается обратно; неотвеченный байт, регулятор не готов вовремя или сообщает о перегрузке по току, запись не читается обратно — всё выключается и больше ничего не пишется; в конце сеанса и при панике включённое выключается, найденное включённым остаётся включённым. `cam_after=S` — через сколько секунд после старта (по умолчанию 20). `cam=3` — путь кадра без датчика: генератор тестовой картинки CSID-lite 0 (RAW10 1600×1200, цветные полосы) → его путь RDI 0 → IFE-lite 0, чей мастер записи 0 пишет кадр в память через SMMU (поток 0x800, маска 0x4e0, в свободный контекст с нашими таблицами); для этого — голоса RPMh за CX на SVS и MX на SVS_L1 (через вторую TCS DRV 2, в конце отдаются), PLL0 camcc (1,2 ГГц), RCG и ветви камеры на частотах уровня «svs» из дерева устройств (cphy_rx, CSID, IFE-lite — 400 МГц, таймер PHY — 300, camnoc — 150, slow_ahb — 80), всё — по драйверам Android (`camcc-yupik.c`, `cam_ife_csid_lite17x.h`, `cam_vfe_lite16x.h`, `cam_vfe_bus_ver2.c`). `cam=4` — кадры самого датчика: питание и ID, как при `cam=2`, его таблицы Android — инициализация (108 записей), режим (1600×1200 RAW10, одна линия, 665,6 Мбит/с, 30 кадров/с), «пуск», таблица экспозиции; CSIPHY 2 (v1.2.1, D-PHY, линия данных 0 и линия такта; число отсчётов установления — из файла модуля для этого режима, 20, `cam_settle=N` — своё), приёмник CSID-lite 0 от PHY 2 и тот же путь RDI 0 → IFE-lite 0 → SMMU → память; несколько кадров подряд в два места, последний остаётся; потом «стоп» и всё выключается. Таблицы читаются при запуске из `fw/camera-ov02b10.tab` малого образа: его делает `tools/camsensor.py` из файла модуля датчика Android (`fw-camera/com.qti.sensormodule.redwood_aac_ov02b10_macro.bin` с телефона; ни он, ни таблицы в git не попадают). `cam_pattern=1` — тестовые полосы самого датчика вместо изображения, `cam_frames=N` — сколько кадров (по умолчанию 8), `cam_shutter=СТРОК`, `cam_gain=N` — своя экспозиция и усиление. Память с кадрами загрузчик отдаёт после сеанса: `./xl camera [префикс]` забирает её и через `tools/camraw.py` делает картинки (`префикс-N.png` — по пикселю на ячейку 2×2 Байера, серый мир, гамма 2,2; `префикс-N-raw.png` — сырые значения; порядок Байера изображения датчика — RGGB: в снимке комнаты друг за другом следуют второй и третий отсчёты ячейки, то есть зелёные; его собственные полосы приходят со сдвигом на строку, как GBRG; `--bayer N` — другой порядок; `cam_vblank=СТРОК` — удлинить кадр для выдержки длиннее 1200 строк). `cam_sensor=wide` — то же для основной широкоугольной камеры, Samsung S5KHM2SD (108 Мп, камера 0 Android, «redwood_sunny_s5khm2sd_wide», cam-sensor0): CCI 0, ведущий 1 (GPIO 71/72), адрес 0x20, ID чипа 0xfad2 по адресу 0x0000; сброс — GPIO 21; MCLK — mclk1 camcc (19,2 МГц, GPIO 65); питание — LDO1 (1,0 В, VDIG) и LDO5 (1,8 В, VIO) PM8008i и VANA 2,8 В от постоянного регулятора, который включает GPIO 106 (всё — напряжения дерева устройств); порядок включения и выключения, ID, таблицы и режимы — из её файла модуля (`fw-camera/com.qti.sensormodule.redwood_sunny_s5khm2sd_wide.bin` → `fw/camera-s5khm2sd.tab`, формат RWCTAB02 — все режимы, порядок питания, назначение линий; инициализация — 1441 запись; шесть режимов, от 12000×9000 до 1920×1080 на 240 кадрах/с). Кадры — по трём трио C-PHY в CSIPHY 1 (трёхфазные таблицы v1.2.1 Android и строка таблицы скоростей, покрывающая скорость трио; число отсчётов установления — из файла модуля, 34), CSID-lite 0 — в режиме C-PHY. `cam_mode=N` — режим из таблицы датчика (по умолчанию — с наименьшим числом пикселей: у широкой — 1920×1080 RAW10 на 120 кадрах/с, 3,11 Гбит/с на трио). Порядок Байера широкой — GBRG (в снимке комнаты друг за другом следуют первый и четвёртый отсчёты; красный против синего — по сырым уровням обеих камер при одном тёплом свете), заголовок кадра говорит его сам. Экспозиция широкой — регистры SMIA внутри group hold 0x0104: `cam_vblank` — длина кадра 0x0340, `cam_shutter` — выдержка 0x0202, `cam_gain` — аналоговое усиление 0x0204 (32 — 1×). `cam=5` — широкая камера для iOS: устройство `/dev/redwood-camera` (`bsd/sys/redwood_camera.h`); первое чтение после открытия включает датчик и запускает кадры (режим — `cam_mode`, по умолчанию 1: 4000×3000 RAW10, 30 кадров/с), последнее закрытие, секунда без чтения или любая неисправность всё выключают (после неисправности — до конца сеанса). Кадры идут по кругу в три места памяти ядра (отображённые через SMMU постранично): одно пишет IFE, одно может копировать чтение, одно готово; когда кадр готов, адрес следующего места уходит мастеру записи, который берёт его на следующем начале кадра, а кадр, за которым адрес опоздал, не отдаётся. Строка RAW10 у мастера записи выровнена на 16 байт (4000 пикселей — 5008 байт, а не 5000). `read()` отдаёт заголовок (номер, время, выдержка, усиление, длина кадра и строки) и сам кадр; `write()` принимает выдержку и усиление (пишутся между кадрами в group hold, с пределами: усиление 1×…64×, кадр не длиннее 0xfff0 строк) или картинку для хоста (память под неё — `cam_keep_mb`, по умолчанию 24, берётся при загрузке одним куском; `./xl camera` её забирает, `tools/camraw.py` понимает NV12 и BGRA). Проверка — `RC_JOBS=rc.jobs.camera` (`camera_test raw`: кадры через `src/camera_isp.c` — замер, автоэкспозиция, баланс белого, гамма, NV12) |+| `cam=N` | камеры: макрокамера — OmniVision OV02B10 (2 Мп, камера 2 Android, «redwood_aac_ov02b10_macro»); всё — из живого дерева устройств (cam-sensor2), файла модуля камеры Android (`/vendor/lib64/camera/com.qti.sensormodule.redwood_aac_ov02b10_macro.bin`: адрес, где и как читается ID чипа, порядок включения) и драйверов ядра Android (`bsd/dev/redwood_camera.c`). Датчик — на CCI 1, ведущий 0 (GPIO 73/74, здесь I2C вручную, как у других драйверов), адрес 0x3c; сброс — GPIO 77; MCLK — mclk2 camcc на 19,2 МГц на GPIO 66 (у Android эти 19,2 МГц — от PLL2 camcc, здесь — от самого кварца, без PLL); питание — LDO6 (1,8 В, DOVDD) и LDO7 (2,8 В, AVDD) PM8008i, который на I2C последовательного движка 1 (GPIO 4/5, адреса 0x08 и 0x09) и выходит из сброса по GPIO 3 PM8350C, как его выводит Android. `cam=1` — только смотреть: тактовые частоты и домен питания камеры, ножки, сброс PM8008i и, если он не в сбросе, сам PM8008i. `cam=2` — ещё и включить датчик в порядке файла модуля (у макрокамеры: сброс низкий, 1 мс; DOVDD; AVDD, 2 мс; верхний домен питания камеры и MCLK, 4 мс; сброс высокий, 9 мс), прочитать ID чипа так, как читает Android (16-битный регистр по 16-битному адресу 0x0203; ждёт 0x002b), и выключить в обратном порядке. Пределы: напряжения — только Android (1,8 и 2,8 В у макрокамеры, 1,0 и 1,8 В у широкой), записи — только в перечисленные регистры (у каждого устройства — список, проверяется при каждой записи), каждая читается обратно; неотвеченный байт, регулятор не готов вовремя или сообщает о перегрузке по току, запись не читается обратно — всё выключается и больше ничего не пишется; в конце сеанса и при панике включённое выключается, найденное включённым остаётся включённым. `cam_after=S` — через сколько секунд после старта (по умолчанию 20). `cam=3` — путь кадра без датчика: генератор тестовой картинки CSID-lite 0 (RAW10 1600×1200, цветные полосы) → его путь RDI 0 → IFE-lite 0, чей мастер записи 0 пишет кадр в память через SMMU (поток 0x800, маска 0x4e0, в свободный контекст с нашими таблицами); для этого — голоса RPMh за CX на SVS и MX на SVS_L1 (через вторую TCS DRV 2, в конце отдаются), PLL0 camcc (1,2 ГГц), RCG и ветви камеры на частотах уровня «svs» из дерева устройств (cphy_rx, CSID, IFE-lite — 400 МГц, таймер PHY — 300, camnoc — 150, slow_ahb — 80), всё — по драйверам Android (`camcc-yupik.c`, `cam_ife_csid_lite17x.h`, `cam_vfe_lite16x.h`, `cam_vfe_bus_ver2.c`). `cam=4` — кадры самого датчика: питание и ID, как при `cam=2`, его таблицы Android — инициализация (108 записей), режим (1600×1200 RAW10, одна линия, 665,6 Мбит/с, 30 кадров/с), «пуск», таблица экспозиции; CSIPHY 2 (v1.2.1, D-PHY, линия данных 0 и линия такта; число отсчётов установления — из файла модуля для этого режима, 20, `cam_settle=N` — своё), приёмник CSID-lite 0 от PHY 2 и тот же путь RDI 0 → IFE-lite 0 → SMMU → память; несколько кадров подряд в два места, последний остаётся; потом «стоп» и всё выключается. Таблицы читаются при запуске из `fw/camera-ov02b10.tab` малого образа: его делает `tools/camsensor.py` из файла модуля датчика Android (`fw-camera/com.qti.sensormodule.redwood_aac_ov02b10_macro.bin` с телефона; ни он, ни таблицы в git не попадают). `cam_pattern=1` — тестовые полосы самого датчика вместо изображения, `cam_frames=N` — сколько кадров (по умолчанию 8), `cam_shutter=СТРОК`, `cam_gain=N` — своя экспозиция и усиление. Память с кадрами загрузчик отдаёт после сеанса: `./xl camera [префикс]` забирает её и через `tools/camraw.py` делает картинки (`префикс-N.png` — по пикселю на ячейку 2×2 Байера, серый мир, гамма 2,2; `префикс-N-raw.png` — сырые значения; порядок Байера изображения датчика — RGGB: в снимке комнаты друг за другом следуют второй и третий отсчёты ячейки, то есть зелёные; его собственные полосы приходят со сдвигом на строку, как GBRG; `--bayer N` — другой порядок; `cam_vblank=СТРОК` — удлинить кадр для выдержки длиннее 1200 строк). `cam_sensor=wide` — то же для основной широкоугольной камеры, Samsung S5KHM2SD (108 Мп, камера 0 Android, «redwood_sunny_s5khm2sd_wide», cam-sensor0): CCI 0, ведущий 1 (GPIO 71/72), адрес 0x20, ID чипа 0xfad2 по адресу 0x0000; сброс — GPIO 21; MCLK — mclk1 camcc (19,2 МГц, GPIO 65); питание — LDO1 (1,0 В, VDIG) и LDO5 (1,8 В, VIO) PM8008i и VANA 2,8 В от постоянного регулятора, который включает GPIO 106 (всё — напряжения дерева устройств); порядок включения и выключения, ID, таблицы и режимы — из её файла модуля (`fw-camera/com.qti.sensormodule.redwood_sunny_s5khm2sd_wide.bin` → `fw/camera-s5khm2sd.tab`, формат RWCTAB02 — все режимы, порядок питания, назначение линий; инициализация — 1441 запись; шесть режимов, от 12000×9000 до 1920×1080 на 240 кадрах/с). Кадры — по трём трио C-PHY в CSIPHY 1 (трёхфазные таблицы v1.2.1 Android и строка таблицы скоростей, покрывающая скорость трио; число отсчётов установления — из файла модуля, 34), CSID-lite 0 — в режиме C-PHY. `cam_mode=N` — режим из таблицы датчика (по умолчанию — с наименьшим числом пикселей: у широкой — 1920×1080 RAW10 на 120 кадрах/с, 3,11 Гбит/с на трио). Порядок Байера широкой — GBRG (в снимке комнаты друг за другом следуют первый и четвёртый отсчёты; красный против синего — по сырым уровням обеих камер при одном тёплом свете), заголовок кадра говорит его сам. Экспозиция широкой — регистры SMIA внутри group hold 0x0104: `cam_vblank` — длина кадра 0x0340, `cam_shutter` — выдержка 0x0202, `cam_gain` — аналоговое усиление 0x0204 (32 — 1×). `cam=5` — широкая камера для iOS: устройство `/dev/redwood-camera` (`bsd/sys/redwood_camera.h`); первое чтение после открытия включает датчик и запускает кадры (режим — `cam_mode`, по умолчанию 1: 4000×3000 RAW10, 30 кадров/с), последнее закрытие, секунда без чтения или любая неисправность всё выключают (после неисправности — до конца сеанса). Кадры идут по кругу в три места памяти ядра (отображённые через SMMU постранично): одно пишет IFE, одно может копировать чтение, одно готово; когда кадр готов, адрес следующего места уходит мастеру записи, который берёт его на следующем начале кадра, а кадр, за которым адрес опоздал, не отдаётся. Строка RAW10 у мастера записи выровнена на 16 байт (4000 пикселей — 5008 байт, а не 5000). `read()` отдаёт заголовок (номер, время, выдержка, усиление, длина кадра и строки) и сам кадр; `write()` принимает выдержку и усиление (пишутся между кадрами в group hold, с пределами: усиление 1×…64×, кадр не длиннее 0xfff0 строк) или картинку для хоста (память под неё — `cam_keep_mb`, по умолчанию 24, берётся при загрузке одним куском; `./xl camera` её забирает, `tools/camraw.py` понимает NV12 и BGRA). `camera_test raw` — кадры через `src/camera_isp.c` (замер, автоэкспозиция, баланс белого, гамма, NV12). Устройство появляется сразу при старте ядра (раньше mediaserverd, который ищет камеры один раз, при старте); чтения ждут, пока датчик не включится. `cam_pattern=1` — цветные полосы: собственные полосы датчика, если в файле модуля есть их таблица, иначе — генератора CSID (у широкой камеры таблица пустая, поэтому — CSID, как при `cam=3`, датчик тогда не включается вовсе); `cam_pattern=2` — всегда CSID. Для iOS: `libredwood-media.dylib` в mediaserverd даёт его `BWFigCaptureDeviceVendor` наше устройство захвата (`src/camera_device.c`: FigCaptureDevice и FigCaptureStream, производные объекты CoreMedia, как у H10ISP.mediacapture; форматы названы, как «Photo» и «Video-60» задней камеры в `D22/AVCaptureSession.plist`); AVFoundation перечисляет «Back Camera» с 16 форматами (`camera_avtest`), Camera.app открывается. НЕ ГОТОВО: до приложений кадры пока не доходят — сессия Camera.app берёт поток и тут же отдаёт его (граф захвата не строится), раз за разом; предпросмотр чёрный (`RC_JOBS=rc.jobs.camera`) || `mic=N` | с `adsp=1`, основной микрофон (`bsd/dev/redwood_mic.c`, значения Android). `mic=1` — только посмотреть: звуковой процессор голосует за блоки LPASS и даёт тактовые частоты макроса TX (19,2 МГц), регистры макросов TX и VA, ведущего SoundWire, ножек LPASS и сброса кодека читаются; без всех четырёх ни один регистр не трогается. `mic=2` — ещё и кодек поднят настолько, чтобы ответить по SoundWire: сброс (GPIO83) отпущен, как это делает Android, ножки ведущего (LPASS GPIO 0, 1, 2, 14) — в активное состояние Android, тактовые частоты макроса TX, ведущий запущен, устройство TX кодека перечислено и его номер прочитан. `mic=3` — ещё и запись с микрофона `mic_secs` секунд (по умолчанию 10, не больше 600): настройка кодека, как в `wcd938x_init_reg()`, смещение микрофона 2750 мВ, ADC1 в режиме «low power», «ADC1 Volume» 6, дециматор 1 и порт codec DMA, шина SoundWire как на пути Android «handset-mic» (выше). Каждая запись читается обратно, любое расхождение или отказ звукового процессора — всё останавливается. Для проверки: `mic_input=0` (дециматор слушает ноль — точная тишина), `mic_adc=0`, `mic_test=1` (без смещения), `mic_test=2` (вход ADC1 удержан), `mic_main=1`, `mic_tap=1` с `haptic=5`. `mic=4` — микрофон для iOS: путь до кодека поднимается, только пока iOS записывает (пока открыт `/dev/redwood-mic`, кольцо на 341 мс, чтение никогда не ждёт и держится в 40 мс за звуковым процессором), а в плагине звука `RedwoodAudio.driver` есть устройство «Codec» с одним входом и источником данных `imic` («Bottom»), из которого VirtualAudio, как на iPhone, делает «iPhone Microphone» (Built-In Microphone). Приложения записывают с него: «Диктофон» пишет и рисует волну (`RC_JOBS=rc.jobs.voicememos`), `record_test` (AVAudioRecorder) — 6,00 с из 6,00, на частоте мотора 175,5 Гц с `haptic=5` уровень растёт с −68 до −29 дБFS (`RC_JOBS=rc.jobs.mic`, с `sound=4 sound_below=720` — сначала беззвучная проверка динамиков). Программа без интерфейса, записывающая в фоне, получает оранжевую точку, но не плашку записи в строке состояния, и MediaSafetyNet в mediaserverd, как на iPhone, через девять секунд такой записи останавливает mediaserverd; записи `record_test` поэтому короче и с паузой между ними. В конце и при выключении звукового процессора всё возвращается как было: кодек снова в сбросе, ножки и регистры как были || `battmgr=0` | с `adsp=1` батарея не спрашивается. Без него (по умолчанию) ядро раз в 10 с спрашивает у звукового процессора, который у этого телефона и ведёт батарею с зарядкой (как Android — `qti_battery_charger`, Linux — `qcom_battmgr` поверх `pmic_glink`), по каналу `PMIC_RTR_ADSP_APPS` процент заряда, зарядку, напряжение, ток, температуру, заряд в мА·ч, ёмкость, циклы и что даёт порт USB — только читает, ни пределов, ни токов не задаёт — и показывает это iOS так же, как батарея iPhone: службой `RedwoodBattery` класса `IOPMPowerSource` (`iokit/Kernel/RedwoodBattery.cpp`). Её читает powerd, и дальше всё делает сама iOS: батарея с процентом и молнией в строке состояния, «58% Charged» на экране блокировки, виджет «Батареи», Настройки → Аккумулятор (переключатель «Заряд в процентах» работает; в образе он включён); перехваты батареи в SpringBoard при этой службе уступают iOS. Сверено с Android (`dumpsys battery` и `/sys/class/power_supply/battery` сразу после): 56 % и 58 %, «заряжается», напряжение, температура, заряд, ёмкость 3677 из 5000 мА·ч, 890 циклов совпадают. Номера свойств — этой прошивки: до 9-го как у Linux, дальше на один больше; `battmgr=2` пишет в журнал все. Те же числа — в `kern.redwood.battery_*`. С `battery=1` (путь загрузчика через UEFI) не включается. Историю заряда и расход по приложениям iOS 16 берёт из журнала энергии, который ведёт aggregated (`com.apple.powerlog.plxpclogger.xpc` и другие службы; база `CurrentPowerlog.PLSQL`); раньше он был в списке не запускаемых (`userland/mkjobs.py`), и страница «Аккумулятор» вечно крутила колёсико. Теперь она открывается сразу: в первые минуты — «As you use your iPhone, battery usage will be reported here» (так iOS говорит, пока данных о расходе нет), через час — график уровня заряда за 24 часа и список приложений («Connected to Charger», пока телефон на зарядке); экран всё это время iOS считала выключенным («Screen On 0m»), отчего — ещё не разобрано. Расход в процентах по приложениям iOS считает из энергии частей системы на кристалле, которую на iPhone сообщают счётчики IOReport («Energy Model»); их здесь нет. Не показывается износ в «Состоянии аккумулятора» (powerd ждёт серийный номер батареи, а его прошивка не даёт; вместо цифры колёсико). Проверка — `RC_JOBS=rc.jobs.battery` (`battery_test`), `RC_JOBS=rc.jobs.battery2` (страницы Настроек, в конце `battery_test powerlog`: что журнал энергии собрал — таблицы, строки, время), `RC_JOBS=rc.jobs.battery3` (то же после часа работы приложений) |@@ -462,7 +462,10 @@ iPhone»); перегенерировать: `python3 ios165/fetch-from-ipsw.pyMobileGestalt отвечает `DeviceSupportsClosedLoopHaptics`, и iOS играет вибрацию и отклики волнами на устройстве«Actuator»; без него она ищет в IOKit старый вибромотор («vibrator»), которого у iPhone X нет, и не вибрирует вовсе.Из узла `/product/camera` загрузчик берёт (только с `torch=N`) одно свойство `flash` — MobileGestalt `camera-flash`,-кнопка фонарика в Пункте управления; остального о камере айфона здесь нет, и дерево этого не говорит.+кнопка фонарика в Пункте управления; с `cam=5` сам узел есть и без него (MobileGestalt `video-camera`). С `cam=5` есть+ещё и `/arm-io/isp` — узел ISP айфона, из его свойств только `camera-rear` = 1, без `compatible` и `device_type` (ни+один драйвер его не берёт): по нему MobileGestalt отвечает `still-camera` и `rear-facing-camera`, а SpringBoard+показывает Camera.app (на первой странице, справа вверху). Остального о камере айфона здесь нет, и дерево этого не говорит.### Userland и образыdiff --git a/userland/build.sh b/userland/build.shindex f2cdfbb..8a43f24 100755--- a/userland/build.sh+++ b/userland/build.sh@@ -114,6 +114,7 @@ if [ -d $IOS/rootfs/usr/lib ]; then$DYN -framework CoreFoundation -lMobileGestalt -o obj/mg_test src/mg_test.c$DYN -framework CoreFoundation -framework AVFoundation -lobjc -o obj/torch_test src/torch_test.c$DYN -O2 -o obj/camera_test src/camera_test.c src/camera_isp.c+ $DYN -fobjc-arc -framework Foundation -framework AVFoundation -o obj/camera_avtest src/camera_avtest.m# (the microphone as an application records: allowed to, by an entitlement, if ldid is there)$DYN -framework CoreFoundation -framework AVFoundation -lobjc -o obj/record_test src/record_test.c &&{ ${LDID:-ldid} -Ssrc/record_test.entitlements obj/record_test 2>/dev/null ||@@ -142,8 +143,9 @@ if [ -d $IOS/rootfs/usr/lib ]; then-o obj/libredwood.dylib src/inject.c$DYN -dynamiclib -install_name /redwood/lib/libredwood-sb.dylib -framework CoreFoundation -framework IOKit -lobjc \-o obj/libredwood-sb.dylib src/inject_sb.c- $DYN -dynamiclib -install_name /redwood/lib/libredwood-media.dylib -framework CoreFoundation -lobjc \- -o obj/libredwood-media.dylib src/inject_media.c+ $DYN -O2 -dynamiclib -install_name /redwood/lib/libredwood-media.dylib -framework CoreFoundation -framework CoreMedia \+ -framework CoreVideo -framework IOSurface -lobjc \+ -o obj/libredwood-media.dylib src/inject_media.c src/camera_device.c src/camera_isp.c# the output device of the audio server: a plug-in for CoreAudio's HAL$DYN -bundle -framework CoreFoundation -o obj/RedwoodAudio src/audio_plugin.cif [ -n "$GL" ]; then@@ -174,6 +176,7 @@ if [ -d $IOS/rootfs/usr/lib ]; then[ -f obj/sound_test ] && cp obj/sound_test root/bin/[ -f obj/torch_test ] && cp obj/torch_test root/bin/[ -f obj/camera_test ] && cp obj/camera_test root/bin/+ [ -f obj/camera_avtest ] && cp obj/camera_avtest root/bin/[ -f obj/record_test ] && cp obj/record_test root/bin/for f in $EXTRA; do cp "$f" root/bin/; donemkdir -p root/libdiff --git a/userland/rc.jobs.camera b/userland/rc.jobs.cameraindex 2d46fbd..f64d891 100644--- a/userland/rc.jobs.camera+++ b/userland/rc.jobs.camera@@ -1,7 +1,11 @@# Commands run by the launchd job com.redwood.demo (see com.redwood.demo.plist).-# The wide camera for iOS, its frames (RC_JOBS=rc.jobs.camera, with cam=5): a program reads 150 of them from the-# kernel's /dev/redwood-camera (camera_test raw: src/camera_isp.c's exposure and white balance at work on them), says-# what came and how fast, and leaves the last one as a picture for the host (xl camera). The kernel's "camera:" lines-# say when the sensor streamed and why it stopped.+# The wide camera for iOS (RC_JOBS=rc.jobs.camera, with cam=5; with cam_pattern=1 its frames are colour bars):+# first what AVFoundation lists (camera_avtest: the device is libredwood-media.dylib's in mediaserverd,+# camera_device.c, whose frames come from the kernel's /dev/redwood-camera), then Camera.app opened from the home+# screen as a finger opens it (with cam=5 the loader's /arm-io/isp node puts its icon on the first page, top right),+# its preview left running for 40 seconds (xl screenshot meanwhile). NOT FINISHED: the preview stays black, no+# frames reach it yet (see camera_device.c). The kernel's "camera:" lines say when the frames came and why they+# stopped; mediaserverd's "redwood: camera:" lines what the capture stack asked of the device./redwood/bin/sound_test springboard-/redwood/bin/camera_test raw 150+/redwood/bin/camera_avtest+/redwood/bin/rwtouch wait 10 swipe 0.5 0.985 0.5 0.3 200 wait 6 tap 0.845 0.36 wait 40diff --git a/userland/src/camera_avtest.m b/userland/src/camera_avtest.mnew file mode 100644index 0000000..a768051--- /dev/null+++ b/userland/src/camera_avtest.m@@ -0,0 +1,39 @@+/*+ * camera_avtest: what cameras iOS lists for applications, as AVFoundation gives them: the video+ * devices, and every format of the default one (on this machine the device is libredwood-media.dylib's+ * in mediaserverd: camera_device.c, the kernel's /dev/redwood-camera, cam=5).+ *+ * usage: camera_avtest+ *+ * Frames are for applications in the foreground, as iOS has it: a program like this one is not+ * given any (its session is interrupted at once). Camera.app is the test for those (rc.jobs.camera).+ */+#import <AVFoundation/AVFoundation.h>+#include <stdio.h>++int+main(void)+{+ @autoreleasepool {+ setvbuf(stdout, NULL, _IOLBF, 0);+#pragma clang diagnostic push+#pragma clang diagnostic ignored "-Wdeprecated-declarations"+ NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];+#pragma clang diagnostic pop+ printf("camera_avtest: %lu video device(s)\n", (unsigned long)devices.count);+ for (AVCaptureDevice *d in devices) {+ printf("camera_avtest: %s (%s), position %ld, %lu formats\n", d.localizedName.UTF8String, d.uniqueID.UTF8String,+ (long)d.position, (unsigned long)d.formats.count);+ }+ AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];+ if (device == nil) {+ printf("camera_avtest: no default video device\n");+ return 1;+ }+ for (AVCaptureDeviceFormat *f in device.formats) {+ printf("camera_avtest: format %s\n", f.description.UTF8String);+ }+ printf("camera_avtest: the default device's active format: %s\n", device.activeFormat.description.UTF8String);+ return 0;+ }+}diff --git a/userland/src/camera_device.c b/userland/src/camera_device.cnew file mode 100644index 0000000..61ca690--- /dev/null+++ b/userland/src/camera_device.c@@ -0,0 +1,983 @@+/*+ * The wide camera as iOS's capture stack wants a camera: a FigCaptureDevice with one FigCaptureStream+ * (the back camera), made for mediaserverd's BWFigCaptureDeviceVendor in place of the one Apple's+ * H10ISP.mediacapture makes of the iPhone's ISP (part of libredwood-media.dylib; inject_media.c+ * gives the vendor our device's create function when the kernel has a camera: cam=5).+ *+ * Both are CoreMedia "derived objects" (CMDerivedObjectCreate): a table of functions for the base+ * class (properties) and one for the device or stream class, as H10ISP's are laid out in iOS 16.5:+ * device RequestStreams, RelinquishStreams (and a processing session and Pearl calibration, not here)+ * stream Start, Stop, AddAttachmentsToSampleBuffer+ * The stream's frames go to the capture graph through the blocks it is given in its property+ * "VideoOutputHandlers" ({ output: { PixelBufferHandler: ^(CVPixelBufferRef, CMTime) } }), for the+ * outputs "VideoOutputConfigurations" describes (size, pixel format) and "VideoOutputsEnabled"+ * switches on. A frame: read from the kernel's /dev/redwood-camera (RAW10), made into a picture by+ * camera_isp.c (exposure, white balance, gamma, scaling), one pixel buffer for each output.+ *+ * The formats the stream offers are named as the iPhone X's back camera's are in CMCapture's+ * D22/AVCaptureSession.plist (FigCaptureStreamFormats "Photo" and "Video-60", by the sensor sizes+ * and frame rates the plist matches them by), so that its AVCaptureDevice formats and session presets+ * resolve: the pictures are scaled from the sensor's 4000x3000 to whatever size is asked for.+ *+ * Everything asked of the device and the stream that is not answered here is said in mediaserverd's+ * log ("redwood: camera: ..."), once per property.+ *+ * NOT FINISHED: no frames reach applications yet. AVFoundation lists the back camera with the+ * plist's formats, and Camera.app opens, but its session takes the stream and gives it back at once+ * (the capture graph is not built: captureSession_buildGraphWithConfiguration takes the device+ * back), over and over; the stream is never started.+ */+#include <CoreFoundation/CoreFoundation.h>+#include <CoreMedia/CoreMedia.h>+#include <CoreVideo/CoreVideo.h>+#include <IOSurface/IOSurfaceRef.h>+#include <dispatch/dispatch.h>+#include <dlfcn.h>+#include <errno.h>+#include <fcntl.h>+#include <pthread.h>+#include <stdarg.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <unistd.h>+#include "camera_isp.h"++void redwood_camera_say(const char *format, ...) __attribute__((format(printf, 1, 2)));++void+redwood_camera_say(const char *format, ...)+{+ char line[400];+ va_list ap;+ int n = snprintf(line, sizeof(line), "redwood: camera: ");++ va_start(ap, format);+ n += vsnprintf(line + n, sizeof(line) - (size_t)n, format, ap);+ va_end(ap);+ if (n > (int)sizeof(line) - 2) {+ n = sizeof(line) - 2;+ }+ line[n++] = '\n';+ write(2, line, (size_t)n);+}+#define say redwood_camera_say++/* ---- CoreMedia's derived objects, as iOS 16.5 lays them out ---------------------------------------- */++typedef struct OpaqueCMBaseObject *CMBaseObjectRef;+typedef const void *CMBaseClassID;++struct base_class {+ uint64_t version;+ uint64_t storage_size;+ Boolean (*equal)(CMBaseObjectRef, CMBaseObjectRef);+ OSStatus (*invalidate)(CMBaseObjectRef);+ void (*finalize)(CMBaseObjectRef);+ CFStringRef (*copy_debug_description)(CMBaseObjectRef);+ OSStatus (*copy_property)(CMBaseObjectRef, CFStringRef, CFAllocatorRef, void *);+ OSStatus (*set_property)(CMBaseObjectRef, CFStringRef, CFTypeRef);+ OSStatus (*notification_barrier)(CMBaseObjectRef);+ const void * protocols;+ const void * reserved;+};+struct device_class {+ uint64_t version; /* 3 */+ void * processing_session_create;+ OSStatus (*request_streams)(CMBaseObjectRef, CFArrayRef, CFDictionaryRef);+ OSStatus (*relinquish_streams)(CMBaseObjectRef, CFArrayRef, CFDictionaryRef);+ void * pearl_calibration;+};+struct stream_class {+ uint64_t version; /* 2 */+ OSStatus (*start)(CMBaseObjectRef);+ OSStatus (*stop)(CMBaseObjectRef);+ OSStatus (*add_attachments)(CMBaseObjectRef, CMSampleBufferRef, CFDictionaryRef);+};+struct vtable {+ const void * reserved;+ const struct base_class *base;+ const void * derived;+};++#define ERR_PARAM (-12780)+#define ERR_NOT_AVAILABLE (-12783)+#define ERR_UNSUPPORTED (-12782)++static OSStatus (*derived_create)(CFAllocatorRef, const struct vtable *, CMBaseClassID, CMBaseObjectRef *);+static void *(*derived_storage)(CMBaseObjectRef);+static CMBaseClassID (*device_class_id)(void);+static CMBaseClassID (*stream_class_id)(void);+static CFStringRef port_back; /* kFigCapturePortType_BackFacingCamera */++static bool+find_functions(void)+{+ CFStringRef *port;++ derived_create = dlsym(RTLD_DEFAULT, "CMDerivedObjectCreate");+ derived_storage = dlsym(RTLD_DEFAULT, "CMBaseObjectGetDerivedStorage");+ device_class_id = dlsym(RTLD_DEFAULT, "FigCaptureDeviceGetClassID");+ stream_class_id = dlsym(RTLD_DEFAULT, "FigCaptureStreamGetClassID");+ port = dlsym(RTLD_DEFAULT, "kFigCapturePortType_BackFacingCamera");+ port_back = port != NULL ? *port : NULL;+ if (derived_create == NULL || derived_storage == NULL || device_class_id == NULL || stream_class_id == NULL || port_back == NULL) {+ say("CoreMedia's or CMCapture's functions are not there: no camera");+ return false;+ }+ return true;+}++/* ---- what is asked and not answered: said once per name ------------------------------------------- */++static CFMutableSetRef said_names;+static pthread_mutex_t said_lock = PTHREAD_MUTEX_INITIALIZER;++static void+say_once(const char *what, CFStringRef key, CFTypeRef value)+{+ char name[160] = "?", text[300] = "";+ CFStringRef tag = CFStringCreateWithFormat(NULL, NULL, CFSTR("%s %@"), what, key);++ pthread_mutex_lock(&said_lock);+ if (said_names == NULL) {+ said_names = CFSetCreateMutable(NULL, 0, &kCFTypeSetCallBacks);+ }+ bool first = !CFSetContainsValue(said_names, tag);++ CFSetAddValue(said_names, tag);+ pthread_mutex_unlock(&said_lock);+ CFRelease(tag);+ if (!first) {+ return;+ }+ CFStringGetCString(key, name, sizeof(name), kCFStringEncodingUTF8);+ if (value != NULL) {+ CFStringRef d = CFCopyDescription(value);++ CFStringGetCString(d, text, sizeof(text), kCFStringEncodingUTF8);+ CFRelease(d);+ for (char *c = text; *c; c++) {+ *c = *c == '\n' ? ' ' : *c;+ }+ }+ say("%s %s%s%s", what, name, value ? " = " : "", text);+}++/* ---- numbers and dictionaries ---------------------------------------------------------------------- */++static CFNumberRef+number_i(int64_t v)+{+ return CFNumberCreate(NULL, kCFNumberSInt64Type, &v);+}++static CFNumberRef+number_f(double v)+{+ return CFNumberCreate(NULL, kCFNumberDoubleType, &v);+}++static void+put(CFMutableDictionaryRef d, const char *key, CFTypeRef value)+{+ CFStringRef k = CFStringCreateWithCString(NULL, key, kCFStringEncodingUTF8);++ CFDictionarySetValue(d, k, value);+ CFRelease(k);+ CFRelease(value);+}++static void+put_k(CFMutableDictionaryRef d, CFStringRef key, CFTypeRef value)+{+ CFDictionarySetValue(d, key, value);+ CFRelease(value);+}++static int64_t+get_i(CFDictionaryRef d, const char *key, int64_t otherwise)+{+ CFStringRef k = CFStringCreateWithCString(NULL, key, kCFStringEncodingUTF8);+ CFTypeRef v = d ? CFDictionaryGetValue(d, k) : NULL;+ int64_t out = otherwise;++ CFRelease(k);+ if (v != NULL && CFGetTypeID(v) == CFNumberGetTypeID()) {+ CFNumberGetValue(v, kCFNumberSInt64Type, &out);+ } else if (v != NULL && CFGetTypeID(v) == CFBooleanGetTypeID()) {+ out = CFBooleanGetValue(v);+ }+ return out;+}++static CFDictionaryRef+new_dict(void)+{+ return CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);+}++static bool+key_is(CFStringRef key, const char *name)+{+ char buffer[128];++ return CFStringGetCString(key, buffer, sizeof(buffer), kCFStringEncodingUTF8) && strcmp(buffer, name) == 0;+}++/* ---- what the device and the stream say they have ---------------------------------------------------- */++/*+ * The capture stack asks only for the properties an object lists in its "SupportedPropertiesDictionary"+ * ({ name: { PropertyType, ReadWriteStatus } }). Listed here: what is answered, and what is taken+ * (and, for now, mostly not acted on) without failing the graph that sets it.+ */+struct prop {+ const char *name, *type, *access;+};++static const struct prop stream_props[] = {+ { "PortType", "String", "ReadOnly" }, { "UniqueID", "String", "ReadOnly" }, { "NonLocalizedName", "String", "ReadOnly" },+ { "SupportedFormatsArray", "Collection", "ReadOnly" }, { "FocalLength", "Number", "ReadOnly" },+ { "LensFNumber", "Number", "ReadOnly" }, { "MaxZoomFactor", "Number", "ReadOnly" }, { "SupportedColorSpaces", "Collection", "ReadOnly" },+ { "HasAutoFocusPositionSensor", "Boolean", "ReadOnly" }, { "Clock", "Clock", "ReadOnly" },+ { "FormatIndex", "Number", "ReadWrite" }, { "MinimumFrameRate", "Number", "ReadWrite" }, { "MaximumFrameRate", "Number", "ReadWrite" },+ { "MaximumAllowedFrameRate", "Number", "ReadWrite" }, { "VideoOutputConfigurations", "Collection", "ReadWrite" },+ { "VideoOutputsEnabled", "Collection", "ReadWrite" }, { "VideoOutputHandlers", "Collection", "WriteOnly" },+ { "DeferAdditionOfAttachments", "Boolean", "ReadWrite" }, { "TorchLevel", "Number", "ReadWrite" },+ { "HighCurrentTorchEnabled", "Boolean", "ReadWrite" }, { "ColorSpace", "Number", "ReadWrite" }, { "ZoomFactor", "Number", "ReadWrite" },+ { "ExposureBias", "Number", "ReadWrite" }, { "DeviceOrientation", "Number", "ReadWrite" }, { "FlashMode", "Number", "ReadWrite" },+ { "StillImageCaptureNow", "Collection", "WriteOnly" }, { "LockAENow", "Boolean", "WriteOnly" }, { "UnlockAENow", "Boolean", "WriteOnly" },+ { "LockAWBNow", "Boolean", "WriteOnly" }, { "UnlockAWBNow", "Boolean", "WriteOnly" }, { "MaxIntegrationTime", "Number", "ReadWrite" },+ { "AEMaxGain", "Number", "ReadWrite" }, { "AEMinGain", "Number", "ReadWrite" }, { "FaceDetectionEnabled", "Boolean", "ReadWrite" },+ { "VideoRecordingInProgress", "Boolean", "ReadWrite" }, { "MemoryPoolID", "Number", "ReadWrite" },+ { "ChromaNoiseReductionEnabled", "Boolean", "ReadWrite" }, { "TemporalNoiseReductionEnabled", "Boolean", "ReadWrite" },+ { "MultipleOutputSupportEnabled", "Boolean", "ReadWrite" }, { "VideoOutputsColorInfo", "Collection", "ReadWrite" },+ { "RegionOfInterestForCameraControls", "Collection", "ReadWrite" }, { "AEMeteringMode", "Number", "ReadWrite" },+ { "MaxFrameCoalescingDuration", "Number", "ReadWrite" }, { "LimitAERange", "Boolean", "ReadWrite" },+}, device_props[] = {+ { "StreamArray", "Collection", "ReadOnly" }, { "Clock", "Clock", "ReadOnly" }, { "ClientIsActive", "Boolean", "ReadWrite" },+ { "SupportedSynchronizedStreamsGroups", "Collection", "ReadOnly" }, { "MemoryPoolID", "Number", "ReadWrite" },+};++static CFDictionaryRef+supported(const struct prop *p, size_t n)+{+ CFMutableDictionaryRef all = (CFMutableDictionaryRef)new_dict();++ for (size_t i = 0; i < n; i++) {+ CFMutableDictionaryRef one = (CFMutableDictionaryRef)new_dict();++ put(one, "PropertyType", CFStringCreateWithCString(NULL, p[i].type, kCFStringEncodingUTF8));+ put(one, "ReadWriteStatus", CFStringCreateWithCString(NULL, p[i].access, kCFStringEncodingUTF8));+ put(all, p[i].name, one);+ }+ return all;+}++/* ---- the formats ----------------------------------------------------------------------------------- */++#define PF_420F 0x34323066 /* '420f' */+#define PF_420V 0x34323076 /* '420v' */+#define PF_BGRA 0x42475241 /* 'BGRA' */++static CFDictionaryRef+output_info(int width, int height)+{+ CFMutableDictionaryRef o = (CFMutableDictionaryRef)new_dict();+ CFNumberRef pf[3] = { number_i(PF_420F), number_i(PF_420V), number_i(PF_BGRA) };+ CFArrayRef pfs = CFArrayCreate(NULL, (const void **)pf, 3, &kCFTypeArrayCallBacks);++ for (int i = 0; i < 3; i++) {+ CFRelease(pf[i]);+ }+ put(o, "SupportedPixelFormats", pfs);+ put(o, "NativeWidth", number_i(width));+ put(o, "NativeHeight", number_i(height));+ put(o, "MaxDownscaleFactor", number_f(32));+ put(o, "MaxScaleFactor", number_f(1));+ put(o, "MinScaleFactor", number_f(1.0 / 32));+ put(o, "OutputWidthAlignmentRequirement", number_i(16));+ return o;+}++static CFDictionaryRef+format(int sensor_width, int sensor_height, int max_fps, bool binned)+{+ CFMutableDictionaryRef f = (CFMutableDictionaryRef)new_dict(), outputs = (CFMutableDictionaryRef)new_dict();+ CMVideoFormatDescriptionRef fd = NULL;++ CMVideoFormatDescriptionCreate(NULL, PF_420F, sensor_width, sensor_height, NULL, &fd);+ if (fd != NULL) {+ put(f, "FormatDescription", fd);+ }+ put(f, "VideoMinFrameRate", number_f(2));+ put(f, "VideoMaxFrameRate", number_f(max_fps));+ put(f, "VideoIsBinned", CFRetain(binned ? kCFBooleanTrue : kCFBooleanFalse));+ put(f, "VideoBinningFactorHorizontal", number_i(binned ? 2 : 1));+ put(f, "VideoBinningFactorVertical", number_i(binned ? 2 : 1));+ put(f, "VideoFieldOfView", number_f(65.0));+ put(f, "VideoMinIntegrationTime", number_i(100));+ put(f, "VideoMaxIntegrationTime", number_i(1000000 / 15));+ put(f, "VideoRawBitDepth", number_i(10));+ put(f, "VideoMaxWidth", number_i(sensor_width));+ put(f, "VideoMaxHeight", number_i(sensor_height));+ put(f, "Experimental", CFRetain(kCFBooleanFalse));+ put(f, "SensorWidth", number_i(sensor_width));+ put(f, "SensorHeight", number_i(sensor_height));+ put(f, "ISOBase", number_f(32));+ put(f, "DefaultAEMaxGain", number_f(64));+ put(outputs, "PrimaryScaler", output_info(sensor_width, sensor_height));+ put(outputs, "SecondaryScaler", output_info(sensor_width, sensor_height));+ put(outputs, "StillImage", output_info(sensor_width, sensor_height));+ put(f, "SupportedOutputs", outputs);+ return f;+}++/* ---- the stream ------------------------------------------------------------------------------------- */++struct output {+ const char * name;+ CFDictionaryRef config; /* from VideoOutputConfigurations */+ bool enabled;+ void * handler; /* a block: ^(CVPixelBufferRef, CMTime) */+ CVPixelBufferPoolRef pool;+ int pool_width, pool_height;+ uint32_t pool_format;+ uint64_t delivered;+};++#define OUTPUTS 3+static const char *const output_names[OUTPUTS] = { "PrimaryScaler", "SecondaryScaler", "StillImage" };++struct stream {+ CFArrayRef formats;+ CFDictionaryRef supported;+ int format_index;+ double min_fps, max_fps;+ struct output out[OUTPUTS];+ pthread_mutex_t lock;+ pthread_t worker;+ volatile bool running;+ bool worker_started;+ int torch;+ uint64_t frames;+};++static struct stream *+stream_of(CMBaseObjectRef o)+{+ return derived_storage(o);+}++static int+output_index(CFStringRef name)+{+ for (int i = 0; i < OUTPUTS; i++) {+ if (key_is(name, output_names[i])) {+ return i;+ }+ }+ return -1;+}++static OSStatus+stream_copy_property(CMBaseObjectRef o, CFStringRef key, CFAllocatorRef allocator, void *out)+{+ struct stream *s = stream_of(o);+ CFTypeRef value = NULL;++ (void)allocator;+ if (key_is(key, "PortType")) {+ value = CFRetain(port_back);+ } else if (key_is(key, "UniqueID") || key_is(key, "ModelID")) {+ value = CFRetain(CFSTR("com.apple.avfoundation.avcapturedevice.built-in_video:0"));+ } else if (key_is(key, "NonLocalizedName") || key_is(key, "LocalizedName")) {+ value = CFRetain(CFSTR("Back Camera"));+ } else if (key_is(key, "Manufacturer")) {+ value = CFRetain(CFSTR("Apple Inc."));+ } else if (key_is(key, "SupportedFormatsArray")) {+ value = CFRetain(s->formats);+ } else if (key_is(key, "FormatIndex")) {+ value = number_i(s->format_index);+ } else if (key_is(key, "MinimumFrameRate")) {+ value = number_f(s->min_fps);+ } else if (key_is(key, "MaximumFrameRate")) {+ value = number_f(s->max_fps);+ } else if (key_is(key, "Clock")) {+ value = CFRetain(CMClockGetHostTimeClock());+ } else if (key_is(key, "TorchLevel") || key_is(key, "ExposureBias")) {+ value = number_f(0);+ } else if (key_is(key, "SupportedPropertiesDictionary")) {+ value = CFRetain(s->supported);+ } else if (key_is(key, "FocalLength")) {+ value = number_f(4.0); /* (the iPhone X's wide camera's, in millimetres) */+ } else if (key_is(key, "LensFNumber")) {+ value = number_f(1.8);+ } else if (key_is(key, "MaxZoomFactor")) {+ value = number_f(16);+ } else if (key_is(key, "ZoomFactor")) {+ value = number_f(1);+ } else if (key_is(key, "SupportedColorSpaces")) {+ CFNumberRef srgb = number_i(0);++ value = CFArrayCreate(NULL, (const void **)&srgb, 1, &kCFTypeArrayCallBacks);+ CFRelease(srgb);+ } else if (key_is(key, "ColorSpace") || key_is(key, "DeviceOrientation") || key_is(key, "FlashMode")) {+ value = number_i(0);+ } else if (key_is(key, "HasAutoFocusPositionSensor") || key_is(key, "HighCurrentTorchEnabled") ||+ key_is(key, "DeferAdditionOfAttachments")) {+ value = CFRetain(kCFBooleanFalse);+ } else {+ say_once("stream: no answer for", key, NULL);+ return ERR_NOT_AVAILABLE;+ }+ *(CFTypeRef *)out = value;+ return 0;+}++static void torch_set(struct stream *s, CFTypeRef value);++static OSStatus+stream_set_property(CMBaseObjectRef o, CFStringRef key, CFTypeRef value)+{+ struct stream *s = stream_of(o);++ if (key_is(key, "FormatIndex")) {+ int64_t i = 0;++ if (value != NULL && CFGetTypeID(value) == CFNumberGetTypeID()) {+ CFNumberGetValue(value, kCFNumberSInt64Type, &i);+ }+ if (i < 0 || i >= CFArrayGetCount(s->formats)) {+ return ERR_PARAM;+ }+ s->format_index = (int)i;+ say("stream: format %lld", (long long)i);+ return 0;+ }+ if (key_is(key, "MinimumFrameRate") || key_is(key, "MaximumFrameRate")) {+ double fps = 0;++ if (value != NULL && CFGetTypeID(value) == CFNumberGetTypeID()) {+ CFNumberGetValue(value, kCFNumberDoubleType, &fps);+ }+ *(key_is(key, "MinimumFrameRate") ? &s->min_fps : &s->max_fps) = fps;+ say_once("stream: set", key, value);+ return 0;+ }+ if (key_is(key, "VideoOutputConfigurations") || key_is(key, "VideoOutputsEnabled") || key_is(key, "VideoOutputHandlers")) {+ bool configs = key_is(key, "VideoOutputConfigurations"), enabled = key_is(key, "VideoOutputsEnabled");++ say_once("stream: set", key, value);+ if (value == NULL || CFGetTypeID(value) != CFDictionaryGetTypeID()) {+ return 0;+ }+ pthread_mutex_lock(&s->lock);+ CFIndex n = CFDictionaryGetCount(value);+ const void **keys = calloc((size_t)n + 1, sizeof(void *)), **values = calloc((size_t)n + 1, sizeof(void *));++ CFDictionaryGetKeysAndValues(value, keys, values);+ for (CFIndex i = 0; i < n; i++) {+ int k = CFGetTypeID(keys[i]) == CFStringGetTypeID() ? output_index(keys[i]) : -1;+ struct output *out;++ if (k < 0) {+ say_once("stream: an output not here:", keys[i], NULL);+ continue;+ }+ out = &s->out[k];+ if (configs) {+ if (out->config != NULL) {+ CFRelease(out->config);+ }+ out->config = CFGetTypeID(values[i]) == CFDictionaryGetTypeID() ? CFRetain(values[i]) : NULL;+ } else if (enabled) {+ int64_t on = 1;++ if (CFGetTypeID(values[i]) == CFBooleanGetTypeID()) {+ on = CFBooleanGetValue(values[i]);+ } else if (CFGetTypeID(values[i]) == CFNumberGetTypeID()) {+ CFNumberGetValue(values[i], kCFNumberSInt64Type, &on);+ }+ out->enabled = on != 0;+ } else {+ CFTypeRef h = CFGetTypeID(values[i]) == CFDictionaryGetTypeID() ?+ CFDictionaryGetValue(values[i], CFSTR("PixelBufferHandler")) : NULL;++ if (out->handler != NULL) {+ CFRelease(out->handler);+ }+ out->handler = h != NULL ? (void *)CFRetain(h) : NULL;+ }+ }+ free(keys);+ free(values);+ pthread_mutex_unlock(&s->lock);+ return 0;+ }+ if (key_is(key, "TorchLevel")) {+ torch_set(s, value);+ return 0;+ }+ say_once("stream: set (not used)", key, value);+ return 0;+}++/* the flashlight: TorchLevel (0 to 1) as thousandths to the kernel's /dev/redwood-torch (torch=3) */+static void+torch_set(struct stream *s, CFTypeRef value)+{+ float level = 0;+ uint32_t thousandths;++ if (value != NULL && CFGetTypeID(value) == CFNumberGetTypeID()) {+ CFNumberGetValue(value, kCFNumberFloatType, &level);+ }+ level = level < 0 ? 0 : level > 1 ? 1 : level;+ thousandths = (uint32_t)(level * 1000 + 0.5f);+ if (s->torch < 0) {+ s->torch = open("/dev/redwood-torch", O_WRONLY);+ }+ if (s->torch < 0 || write(s->torch, &thousandths, sizeof(thousandths)) != (ssize_t)sizeof(thousandths)) {+ say("the flashlight at %u of 1000 NOT TAKEN (no /dev/redwood-torch)", thousandths);+ } else {+ say("the flashlight at %u of 1000", thousandths);+ }+}++/* ---- the frames ------------------------------------------------------------------------------------- */++struct render_job {+ const struct isp *isp;+ const struct redwood_camera_frame *f;+ const uint8_t *raw;+ CVPixelBufferRef pb;+ uint32_t format, width, height, pieces;+};++static void+render_piece(void *context, size_t i)+{+ struct render_job *j = context;+ uint32_t rows = (j->height + j->pieces - 1) / j->pieces, first = (uint32_t)i * rows, end = first + rows;++ first &= ~1u;+ end = i + 1 == j->pieces ? j->height : end & ~1u;+ if (j->format == PF_BGRA) {+ isp_render_bgra(j->isp, j->f, j->raw, CVPixelBufferGetBaseAddress(j->pb), CVPixelBufferGetBytesPerRow(j->pb), j->width,+ j->height, first, end);+ } else {+ isp_render_nv12(j->isp, j->f, j->raw, CVPixelBufferGetBaseAddressOfPlane(j->pb, 0), CVPixelBufferGetBytesPerRowOfPlane(j->pb, 0),+ CVPixelBufferGetBaseAddressOfPlane(j->pb, 1), CVPixelBufferGetBytesPerRowOfPlane(j->pb, 1), j->width, j->height, first, end,+ j->format == PF_420V);+ }+}++static CVPixelBufferRef+output_buffer(struct output *out, int width, int height, uint32_t pf)+{+ CVPixelBufferRef pb = NULL;++ if (out->pool == NULL || out->pool_width != width || out->pool_height != height || out->pool_format != pf) {+ CFMutableDictionaryRef a = (CFMutableDictionaryRef)new_dict();++ if (out->pool != NULL) {+ CVPixelBufferPoolRelease(out->pool);+ out->pool = NULL;+ }+ put_k(a, kCVPixelBufferWidthKey, number_i(width));+ put_k(a, kCVPixelBufferHeightKey, number_i(height));+ put_k(a, kCVPixelBufferPixelFormatTypeKey, number_i(pf));+ put_k(a, kCVPixelBufferIOSurfacePropertiesKey, new_dict());+ if (CVPixelBufferPoolCreate(NULL, NULL, a, &out->pool) != kCVReturnSuccess) {+ out->pool = NULL;+ }+ CFRelease(a);+ out->pool_width = width;+ out->pool_height = height;+ out->pool_format = pf;+ say("%s: %dx%d %c%c%c%c buffers%s", out->name, width, height, pf >> 24, pf >> 16 & 255, pf >> 8 & 255, pf & 255,+ out->pool ? "" : " CANNOT BE MADE");+ }+ if (out->pool == NULL || CVPixelBufferPoolCreatePixelBuffer(NULL, out->pool, &pb) != kCVReturnSuccess) {+ return NULL;+ }+ return pb;+}++typedef void (^pixel_buffer_handler)(CVPixelBufferRef, CMTime);++static void+deliver(struct stream *s, struct output *out, const struct isp *isp, const struct redwood_camera_frame *f, const uint8_t *raw)+{+ int width = (int)get_i(out->config, "Width", 0), height = (int)get_i(out->config, "Height", 0);+ uint32_t pf = (uint32_t)get_i(out->config, "PixelFormat", PF_420F);+ CVPixelBufferRef pb;++ (void)s;+ if (width <= 0 || height <= 0 || width > 8192 || height > 8192) {+ return;+ }+ pf = pf == PF_420V || pf == PF_BGRA ? pf : PF_420F;+ if ((pb = output_buffer(out, width, height, pf)) == NULL) {+ return;+ }+ CVPixelBufferLockBaseAddress(pb, 0);++ struct render_job job = { isp, f, raw, pb, pf, (uint32_t)width, (uint32_t)height, 8 };++ dispatch_apply_f(job.pieces, dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0), &job, render_piece);+ CVPixelBufferUnlockBaseAddress(pb, 0);+ CVBufferSetAttachment(pb, kCVImageBufferYCbCrMatrixKey, kCVImageBufferYCbCrMatrix_ITU_R_601_4, kCVAttachmentMode_ShouldPropagate);+ CVBufferSetAttachment(pb, kCVImageBufferColorPrimariesKey, kCVImageBufferColorPrimaries_ITU_R_709_2, kCVAttachmentMode_ShouldPropagate);+ CVBufferSetAttachment(pb, kCVImageBufferTransferFunctionKey, kCVImageBufferTransferFunction_ITU_R_709_2,+ kCVAttachmentMode_ShouldPropagate);++ CMTime pts = CMClockMakeHostTimeFromSystemUnits(f->time);++ ((pixel_buffer_handler)out->handler)(pb, pts);+ CVPixelBufferRelease(pb);+ if (out->delivered++ == 0) {+ say("%s: the first picture given (%dx%d)", out->name, width, height);+ }+}++static void *+worker(void *context)+{+ CMBaseObjectRef o = context;+ struct stream *s = stream_of(o);+ struct redwood_camera_frame head;+ struct isp isp;+ struct isp_stats st;+ uint8_t *buffer = NULL;+ size_t bytes = 0;+ int device = open(REDWOOD_CAMERA_DEVICE, O_RDWR), failures = 0;++ pthread_setname_np("redwood-camera");+ if (device < 0) {+ say("no %s (%s): no frames", REDWOOD_CAMERA_DEVICE, strerror(errno));+ return NULL;+ }+ isp_init(&isp);+ while (s->running && failures < 5) {+ ssize_t n;++ if (buffer == NULL) {+ n = read(device, &head, sizeof(head));+ if (n != (ssize_t)sizeof(head)) {+ failures += n < 0 && errno == EAGAIN ? 0 : 1;+ if (n < 0 && errno == EIO) {+ say("the kernel's camera has had a fault: no frames");+ break;+ }+ continue;+ }+ bytes = sizeof(head) + (size_t)head.stride * head.height;+ buffer = malloc(bytes);+ say("frames of %ux%u from the kernel", head.width, head.height);+ continue;+ }+ n = read(device, buffer, bytes);+ if (n != (ssize_t)bytes) {+ if (n < 0 && errno == EIO) {+ say("the kernel's camera has had a fault: no more frames");+ break;+ }+ failures += n < 0 && errno == EAGAIN ? 0 : 1;+ continue;+ }+ failures = 0;++ const struct redwood_camera_frame *f = (const void *)buffer;+ const uint8_t *raw = buffer + f->header_bytes;+ struct redwood_camera_command c;++ isp_measure(f, raw, &st);+ isp_awb(&isp, &st);+ if (isp_ae(&isp, f, &st, &c)) {+ (void)write(device, &c, sizeof(c));+ }+ s->frames++;+ pthread_mutex_lock(&s->lock);+ for (int i = 0; i < OUTPUTS; i++) {+ struct output *out = &s->out[i];++ if (out->handler != NULL && out->config != NULL && (out->enabled || i == 0)) {+ deliver(s, out, &isp, f, raw);+ }+ }+ pthread_mutex_unlock(&s->lock);+ if (s->frames == 1 || s->frames % 300 == 0) {+ say("frame %llu: exposure %.1f ms, gain %.1fx, digital %.2fx, green %.0f above black", f->sequence,+ f->exposure_lines * (double)f->line_ns / 1e6, (double)f->gain / f->gain_unity, isp.digital, st.mean[1]);+ }+ }+ free(buffer);+ close(device);+ say("the frames stopped (%llu)", s->frames);+ return NULL;+}++static OSStatus+stream_start(CMBaseObjectRef o)+{+ struct stream *s = stream_of(o);++ if (s->running) {+ return 0;+ }+ s->running = true;+ s->frames = 0;+ say("stream: start (format %d)", s->format_index);+ if (pthread_create(&s->worker, NULL, worker, o) != 0) {+ s->running = false;+ return ERR_UNSUPPORTED;+ }+ s->worker_started = true;+ return 0;+}++static OSStatus+stream_stop(CMBaseObjectRef o)+{+ struct stream *s = stream_of(o);++ say("stream: stop");+ s->running = false;+ if (s->worker_started) {+ pthread_join(s->worker, NULL);+ s->worker_started = false;+ }+ return 0;+}++static OSStatus+stream_add_attachments(CMBaseObjectRef o, CMSampleBufferRef sbuf, CFDictionaryRef options)+{+ static bool said;++ (void)o;+ (void)sbuf;+ if (!said) {+ said = true;+ say("stream: AddAttachmentsToSampleBuffer (options %s)", options ? "given" : "none");+ }+ return 0;+}++static OSStatus+stream_invalidate(CMBaseObjectRef o)+{+ (void)stream_stop(o);+ return 0;+}++static void+stream_finalize(CMBaseObjectRef o)+{+ struct stream *s = stream_of(o);++ (void)stream_stop(o);+ for (int i = 0; i < OUTPUTS; i++) {+ if (s->out[i].config) {+ CFRelease(s->out[i].config);+ }+ if (s->out[i].handler) {+ CFRelease(s->out[i].handler);+ }+ if (s->out[i].pool) {+ CVPixelBufferPoolRelease(s->out[i].pool);+ }+ }+ if (s->formats) {+ CFRelease(s->formats);+ }+ if (s->supported) {+ CFRelease(s->supported);+ }+ if (s->torch >= 0) {+ close(s->torch);+ }+}++static CFStringRef+stream_description(CMBaseObjectRef o)+{+ (void)o;+ return CFRetain(CFSTR("<RedwoodCaptureStream: the wide camera>"));+}++static const struct base_class stream_base = {+ 1, sizeof(struct stream), NULL, stream_invalidate, stream_finalize, stream_description, stream_copy_property, stream_set_property,+ NULL, NULL, NULL+};+static const struct stream_class stream_derived = { 2, stream_start, stream_stop, stream_add_attachments };+static const struct vtable stream_vtable = { NULL, &stream_base, &stream_derived };++static CMBaseObjectRef+stream_create(CFAllocatorRef allocator)+{+ CMBaseObjectRef o = NULL;+ struct stream *s;++ if (derived_create(allocator, &stream_vtable, stream_class_id(), &o) != 0 || o == NULL) {+ say("the stream cannot be made");+ return NULL;+ }+ s = stream_of(o);+ memset(s, 0, sizeof(*s));+ pthread_mutex_init(&s->lock, NULL);+ s->torch = -1;+ s->min_fps = 2;+ s->max_fps = 30;+ for (int i = 0; i < OUTPUTS; i++) {+ s->out[i].name = output_names[i];+ }++ /* "Photo" and "Video-60" of D22/AVCaptureSession.plist's back camera */+ CFDictionaryRef f[2] = { format(4032, 3024, 30, false), format(4224, 2376, 60, false) };++ s->formats = CFArrayCreate(NULL, (const void **)f, 2, &kCFTypeArrayCallBacks);+ s->supported = supported(stream_props, sizeof(stream_props) / sizeof(stream_props[0]));+ CFRelease(f[0]);+ CFRelease(f[1]);+ return o;+}++/* ---- the device ------------------------------------------------------------------------------------- */++struct device {+ CFArrayRef streams;+ CFDictionaryRef supported;+};++static OSStatus+device_copy_property(CMBaseObjectRef o, CFStringRef key, CFAllocatorRef allocator, void *out)+{+ struct device *d = derived_storage(o);+ CFTypeRef value = NULL;++ (void)allocator;+ if (key_is(key, "StreamArray")) {+ value = CFRetain(d->streams);+ } else if (key_is(key, "Clock")) {+ value = CFRetain(CMClockGetHostTimeClock());+ } else if (key_is(key, "SupportedPropertiesDictionary")) {+ value = CFRetain(d->supported);+ } else if (key_is(key, "SupportedSynchronizedStreamsGroups")) {+ value = CFArrayCreate(NULL, NULL, 0, &kCFTypeArrayCallBacks);+ } else {+ say_once("device: no answer for", key, NULL);+ return ERR_NOT_AVAILABLE;+ }+ *(CFTypeRef *)out = value;+ return 0;+}++static OSStatus+device_set_property(CMBaseObjectRef o, CFStringRef key, CFTypeRef value)+{+ (void)o;+ say_once("device: set (not used)", key, value);+ return 0;+}++static unsigned requests, relinquishes;++static OSStatus+device_request_streams(CMBaseObjectRef o, CFArrayRef streams, CFDictionaryRef options)+{+ (void)o;+ if (requests++ < 3) {+ say("device: streams asked for (%ld)%s", streams ? (long)CFArrayGetCount(streams) : 0L, options ? ", with options" : "");+ if (options != NULL) {+ say_once("device: the request's options", CFSTR("RequestStreams"), options);+ }+ }+ return 0;+}++static OSStatus+device_relinquish_streams(CMBaseObjectRef o, CFArrayRef streams, CFDictionaryRef options)+{+ (void)o;+ (void)options;+ if (relinquishes++ < 3) {+ say("device: streams given back (%ld)", streams ? (long)CFArrayGetCount(streams) : 0L);+ } else if (relinquishes % 1000 == 0) {+ say("device: streams given back %u times", relinquishes);+ }+ return 0;+}++static OSStatus+device_invalidate(CMBaseObjectRef o)+{+ (void)o;+ return 0;+}++static void+device_finalize(CMBaseObjectRef o)+{+ struct device *d = derived_storage(o);++ if (d->streams) {+ CFRelease(d->streams);+ }+ if (d->supported) {+ CFRelease(d->supported);+ }+}++static CFStringRef+device_description(CMBaseObjectRef o)+{+ (void)o;+ return CFRetain(CFSTR("<RedwoodCaptureDevice: the POCO X5 Pro's wide camera>"));+}++static const struct base_class device_base = {+ 1, sizeof(struct device), NULL, device_invalidate, device_finalize, device_description, device_copy_property, device_set_property,+ NULL, NULL, NULL+};+static const struct device_class device_derived = { 3, NULL, device_request_streams, device_relinquish_streams, NULL };+static const struct vtable device_vtable = { NULL, &device_base, &device_derived };++/* The vendor's device create function (as H10ISPCaptureDeviceCreate is called). */+OSStatus redwood_camera_device_create(CFAllocatorRef allocator, CFDictionaryRef options, CMBaseObjectRef *out);++OSStatus+redwood_camera_device_create(CFAllocatorRef allocator, CFDictionaryRef options, CMBaseObjectRef *out)+{+ static bool found, usable;+ CMBaseObjectRef device = NULL, stream;+ struct device *d;++ (void)options;+ if (!found) {+ found = true;+ usable = find_functions();+ }+ if (!usable || out == NULL) {+ return ERR_UNSUPPORTED;+ }+ if ((stream = stream_create(allocator)) == NULL) {+ return ERR_UNSUPPORTED;+ }+ if (derived_create(allocator, &device_vtable, device_class_id(), &device) != 0 || device == NULL) {+ CFRelease(stream);+ say("the device cannot be made");+ return ERR_UNSUPPORTED;+ }+ d = derived_storage(device);+ memset(d, 0, sizeof(*d));+ d->streams = CFArrayCreate(NULL, (const void **)&stream, 1, &kCFTypeArrayCallBacks);+ d->supported = supported(device_props, sizeof(device_props) / sizeof(device_props[0]));+ CFRelease(stream);+ *out = device;+ say("the device made: one stream, the back camera");+ return 0;+}diff --git a/userland/src/camera_isp.c b/userland/src/camera_isp.cindex 4a816dc..96a100b 100644--- a/userland/src/camera_isp.c+++ b/userland/src/camera_isp.c@@ -215,8 +215,10 @@ render_line(const struct isp *isp, const struct redwood_camera_frame *f, const uvoidisp_render_nv12(const struct isp *isp, const struct redwood_camera_frame *f, const uint8_t *raw, uint8_t *y, size_t y_stride,- uint8_t *uv, size_t uv_stride, uint32_t width, uint32_t height, uint32_t first_row, uint32_t end_row)+ uint8_t *uv, size_t uv_stride, uint32_t width, uint32_t height, uint32_t first_row, uint32_t end_row, bool video_range){+ /* video range: luma 16 to 235, chroma 16 to 240 (219 and 224 steps of the full 255) */+ int ly = video_range ? 219 : 256, lc = video_range ? 224 : 256, oy = video_range ? 16 : 0;uint8_t line[2][3 * 8192];if (width > 8192) {@@ -230,7 +232,7 @@ isp_render_nv12(const struct isp *isp, const struct redwood_camera_frame *f, conconst uint8_t *p = line[l];for (uint32_t x = 0; x < width; x++, p += 3) {- out[x] = (uint8_t)((77 * p[0] + 150 * p[1] + 29 * p[2]) >> 8);+ out[x] = (uint8_t)(oy + (((77 * p[0] + 150 * p[1] + 29 * p[2]) >> 8) * ly >> 8));}}uint8_t *o = uv + (size_t)(row / 2) * uv_stride;@@ -240,7 +242,7 @@ isp_render_nv12(const struct isp *isp, const struct redwood_camera_frame *f, conint R = line[0][3 * x] + line[0][3 * x1] + line[1][3 * x] + line[1][3 * x1];int G = line[0][3 * x + 1] + line[0][3 * x1 + 1] + line[1][3 * x + 1] + line[1][3 * x1 + 1];int B = line[0][3 * x + 2] + line[0][3 * x1 + 2] + line[1][3 * x + 2] + line[1][3 * x1 + 2];- int cb = ((-43 * R - 85 * G + 128 * B) >> 10) + 128, cr = ((128 * R - 107 * G - 21 * B) >> 10) + 128;+ int cb = (((-43 * R - 85 * G + 128 * B) >> 10) * lc >> 8) + 128, cr = (((128 * R - 107 * G - 21 * B) >> 10) * lc >> 8) + 128;o[x] = (uint8_t)(cb < 0 ? 0 : cb > 255 ? 255 : cb);o[x + 1] = (uint8_t)(cr < 0 ? 0 : cr > 255 ? 255 : cr);diff --git a/userland/src/camera_isp.h b/userland/src/camera_isp.hindex 0b22fd4..efefe3f 100644--- a/userland/src/camera_isp.h+++ b/userland/src/camera_isp.h@@ -37,10 +37,11 @@ bool isp_ae(struct isp *isp, const struct redwood_camera_frame *f, const structvoid isp_awb(struct isp *isp, const struct isp_stats *s);/** A picture of the frame, width x height, of the sensor's middle part with the picture's proportions- * (rows from first_row to end_row only, for doing it in pieces). NV12: y and uv planes; BGRA: y only.+ * (rows from first_row to end_row only, for doing it in pieces). NV12: y and uv planes, full range (420f) or video+ * range (420v); BGRA: y only.*/void isp_render_nv12(const struct isp *isp, const struct redwood_camera_frame *f, const uint8_t *raw, uint8_t *y, size_t y_stride,- uint8_t *uv, size_t uv_stride, uint32_t width, uint32_t height, uint32_t first_row, uint32_t end_row);+ uint8_t *uv, size_t uv_stride, uint32_t width, uint32_t height, uint32_t first_row, uint32_t end_row, bool video_range);void isp_render_bgra(const struct isp *isp, const struct redwood_camera_frame *f, const uint8_t *raw, uint8_t *out, size_t stride,uint32_t width, uint32_t height, uint32_t first_row, uint32_t end_row);diff --git a/userland/src/camera_test.c b/userland/src/camera_test.cindex 3cc0adb..2e08e1c 100644--- a/userland/src/camera_test.c+++ b/userland/src/camera_test.c@@ -129,7 +129,7 @@ raw(int frames, bool ae, bool keep_raw)uint8_t *y = (uint8_t *)(keep + 1);uint64_t t0 = mach_absolute_time();- isp_render_nv12(&isp, f, (const uint8_t *)f + f->header_bytes, y, w, y + (size_t)w * h, w, w, h, 0, h);+ isp_render_nv12(&isp, f, (const uint8_t *)f + f->header_bytes, y, w, y + (size_t)w * h, w, w, h, 0, h, false);printf("camera_test: the picture (%ux%u NV12) made in %.1f ms\n", w, h, ms_since(t0));memset(keep, 0, sizeof(*keep));keep->command = REDWOOD_CAMERA_KEEP;diff --git a/userland/src/inject_media.c b/userland/src/inject_media.cindex 7a01bec..e329c3a 100644--- a/userland/src/inject_media.c+++ b/userland/src/inject_media.c@@ -22,6 +22,12 @@* by where it calls from -- is given one of ours, with a device and a stream whose torch level goes* to the kernel (see flashlight_*() below). Everybody else still gets none, as before.*+ * The camera (only where the kernel has one: cam=5, /dev/redwood-camera): the vendor is made for+ * everybody, with the create function of our capture device (camera_device.c) in place of the+ * one H10ISP.mediacapture would give for the iPhone's ISP. NOT FINISHED: no frames reach+ * applications yet (see camera_device.c). Its stream takes the torch level too, so FigFlashlight+ * would need nothing of its own then (not tried yet).+ ** CMCapture is not loaded yet when this library is: the methods are replaced when its image* arrives.*/@@ -30,6 +36,7 @@#include <mach-o/dyld.h>#include <objc/message.h>#include <objc/runtime.h>+#include <pthread.h>#include <stdarg.h>#include <stdbool.h>#include <stdio.h>@@ -67,6 +74,8 @@ prewarm_portrait_filter(__unused id self, __unused SEL selector, __unused int ve/* ---- the flashlight ------------------------------------------------------------------------------- */static int torch = -1; /* /dev/redwood-torch */+static bool camera; /* /dev/redwood-camera is there */+extern int redwood_camera_device_create(const void *allocator, const void *options, void **out);static Class vendor_class, device_class, stream_class;static IMP original_shared_vendor;static unsigned torch_said;@@ -81,16 +90,34 @@ static const struct { uintptr_t from, to; } flashlight_code[] = {/* +[BWFigCaptureDeviceVendor sharedCaptureDeviceVendor] */static id-flashlight_shared_vendor(id self, SEL selector)+shared_vendor(id self, SEL selector){uintptr_t caller = (uintptr_t)__builtin_return_address(0) - slide;id vendor = ((id (*)(id, SEL))original_shared_vendor)(self, selector);- static id ours;+ static id ours, camera_vendor;+ static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;if (vendor != NULL) {return vendor;}- for (size_t i = 0; i < sizeof(flashlight_code) / sizeof(flashlight_code[0]); i++) {+ if (!camera && access("/dev/redwood-camera", F_OK) == 0) {+ camera = true; /* (should the kernel have made it after mediaserverd started) */+ say("redwood: mediaserverd: the kernel has a camera (/dev/redwood-camera)\n");+ }+ if (camera) {+ pthread_mutex_lock(&lock);+ if (camera_vendor == NULL) {+ id made = ((id (*)(Class, SEL))objc_msgSend)(objc_getClass("BWFigCaptureDeviceVendor"), sel_registerName("alloc"));++ camera_vendor = ((id (*)(id, SEL, void *))objc_msgSend)(made, sel_registerName("initWithDeviceCreateFunction:"),+ (void *)redwood_camera_device_create);+ say("redwood: mediaserverd: the camera's device vendor %s\n", camera_vendor ? "made (camera_device.c)" :+ "CANNOT BE MADE");+ }+ pthread_mutex_unlock(&lock);+ return camera_vendor;+ }+ for (size_t i = 0; torch >= 0 && i < sizeof(flashlight_code) / sizeof(flashlight_code[0]); i++) {if (caller >= flashlight_code[i].from && caller < flashlight_code[i].to) {if (ours == NULL) {ours = class_createInstance(vendor_class, 0);@@ -217,19 +244,19 @@ flashlight_classes(void)/** The class methods replaced, each as soon as its class exists. `expected` is the unslid address* of the code in iOS 16.5 (20F66): a method that is not what it was is left alone. `original`, where- * there is one, keeps what was there; the flashlight's is replaced only where the kernel has one.+ * there is one, keeps what was there (the vendor's: given as it is wherever there is one, and where+ * there is none, ours only with the kernel's camera or flashlight).*/static struct replacement {const char *class_name, *selector;- bool flashlight;uintptr_t expected;IMP replacement, *original;bool done;} replacements[] = {- { "BWCoreImageFilterRenderer", "prewarmPortraitFilterVersion:semanticStyleFilters:", false, 0x1a2115c0cUL,+ { "BWCoreImageFilterRenderer", "prewarmPortraitFilterVersion:semanticStyleFilters:", 0x1a2115c0cUL,(IMP)prewarm_portrait_filter, NULL, false },- { "BWFigCaptureDeviceVendor", "sharedCaptureDeviceVendor", true, 0x1a1ef0d04UL,- (IMP)flashlight_shared_vendor, &original_shared_vendor, false },+ { "BWFigCaptureDeviceVendor", "sharedCaptureDeviceVendor", 0x1a1ef0d04UL,+ (IMP)shared_vendor, &original_shared_vendor, false },};static void@@ -241,7 +268,7 @@ image_added(__unused const struct mach_header *header, __unused intptr_t image_sMethod method;IMP original;- if (r->done || (r->flashlight && torch < 0) || (cls = objc_getClass(r->class_name)) == NULL) {+ if (r->done || (cls = objc_getClass(r->class_name)) == NULL) {continue;}r->done = true;@@ -272,9 +299,13 @@ redwood_media_init(void)}slide = (uintptr_t)_dyld_get_shared_cache_range(&length) - CACHE_BASE;torch = open("/dev/redwood-torch", O_WRONLY);+ camera = access("/dev/redwood-camera", F_OK) == 0;if (torch >= 0) {flashlight_classes();say("redwood: mediaserverd: the kernel has a flashlight (/dev/redwood-torch)\n");}+ if (camera) {+ say("redwood: mediaserverd: the kernel has a camera (/dev/redwood-camera)\n");+ }_dyld_register_func_for_add_image(image_added); /* also called for every image already there */}diff --git a/xnu/files/bsd/dev/redwood_camera.c b/xnu/files/bsd/dev/redwood_camera.cindex b5444d7..5692573 100644--- a/xnu/files/bsd/dev/redwood_camera.c+++ b/xnu/files/bsd/dev/redwood_camera.c@@ -2793,6 +2793,14 @@ static struct { uint32_t lines, gain, frame_lines; bool pending; } ios_ask;static struct { uint32_t lines, gain, frame_lines; uint64_t from; } ios_now, ios_next;static vm_offset_t keep;static uint64_t keep_bytes;+/*+ * What the frames are (boot-arg cam_pattern): 0 the sensor's picture; 1 colour bars -- the sensor's own,+ * where its module file has a table for them (Android's "testPatternData"), else the CSID's; 2 the+ * CSID's colour bars (no sensor at all). The wide camera's module file has no colour bars of the+ * sensor's (its one test pattern table is empty), so cam_pattern=1 gives it the CSID's.+ */+enum { SOURCE_SENSOR, SOURCE_SENSOR_PATTERN, SOURCE_CSID_TPG };+static int ios_source = SOURCE_SENSOR;static uint64_tios_ms(void)@@ -2878,7 +2886,7 @@ ios_stop(const char *why)}lck_mtx_unlock(&ios_lock);wakeup(&ios_frames_done);- if (!broken) {+ if (!broken && ios_source != SOURCE_CSID_TPG) {(void)sensor_table("off");}show_paths("at the end");@@ -2903,6 +2911,26 @@ ios_start(void)if (!ring_alloc(RAW10_STRIDE(ios_mode->width) * ios_mode->height)) {return false;}+ if (ios_source == SOURCE_CSID_TPG) {+ /* the CSID's colour bars in the mode's size, as cam=3 makes them: no sensor, no CSIPHY */+ if (!titan_up() || !smmu_up() || !csid_reset() ||+ !csid_config(-1, 4, 0x3210, TPG_VC, ios_mode->width, ios_mode->height, false) ||+ !ife_config(FRAME_ADDRESSES, ring_frame_bytes, 0) || !tpg_start()) {+ return false;+ }+ lck_mtx_lock(&ios_lock);+ for (int i = 0; i < RING; i++) {+ place[i].state = PLACE_FREE;+ }+ place[0].state = PLACE_WRITING;+ lck_mtx_unlock(&ios_lock);+ ios_now.lines = ios_next.lines = ios_mode->frame_length - EXPOSURE_MARGIN;+ ios_now.gain = ios_next.gain = GAIN_UNITY;+ ios_now.frame_lines = ios_next.frame_lines = ios_mode->frame_length;+ ios_next.from = 0;+ say("camera: the frames for iOS: the CSID's colour bars, %ux%u (no sensor)\n", ios_mode->width, ios_mode->height);+ return true;+ }if (!power_up() || !healthy() || !read_chip_id() || !sensor_table("init") || !sensor_table(ios_res()) || !healthy() ||!titan_up() || !smmu_up() || !csid_reset() ||!csid_config((int)hw->csiphy, ios_mode->lanes, ctab->lane_assign & ((1u << (4 * ios_mode->lanes)) - 1), 0, ios_mode->width,@@ -2911,6 +2939,9 @@ ios_start(void)(uint64_t)ios_mode->pixel_clock * 10 / ios_mode->lanes)) {return false;}+ if (ios_source == SOURCE_SENSOR_PATTERN && !sensor_table("tpgon")) {+ return false;+ }lck_mtx_lock(&ios_lock);for (int i = 0; i < RING; i++) {place[i].state = PLACE_FREE;@@ -3027,7 +3058,7 @@ ios_session(void)if (bus & WM0_DONE) {wakeup(&ios_frames_done);}- if (ask) {+ if (ask && ios_source != SOURCE_CSID_TPG) {exposure_limits(&lines, &gain, &frame_lines);if (lines != ios_now.lines || gain != ios_now.gain || frame_lines != ios_now.frame_lines) {if (!exposure_write(lines, gain, frame_lines)) {@@ -3135,7 +3166,7 @@ camdev_read(__unused dev_t dev, struct uio *uio, __unused int ioflag)f.height = ios_mode->height;f.stride = RAW10_STRIDE(ios_mode->width);f.format = 1;- f.bayer = hw->bayer;+ f.bayer = ios_source == SOURCE_CSID_TPG ? 0 : ios_source == SOURCE_SENSOR_PATTERN && hw->omnivision ? 2 : hw->bayer;f.black = 64;f.sequence = place[b].sequence;f.time = place[b].time;@@ -3250,11 +3281,24 @@ static const struct cdevsw camdev_cdevsw = {.d_mmap = eno_mmap, .d_strategy = eno_strat, .d_type = 0};-/* cam=5: the device, and a session whenever a read wants frames, until a fault. */+/*+ * The device node, made as the thread starts (before mediaserverd does: its capture stack looks for+ * cameras once, when it starts); reads wait until serve_ios() is there to answer them.+ */+static bool camdev_made;++static void+camdev_make(void)+{+ int major = cdevsw_add(-1, &camdev_cdevsw);++ camdev_made = major >= 0 && devfs_make_node(makedev(major, 0), DEVFS_CHAR, UID_ROOT, GID_WHEEL, 0666, "redwood-camera") != NULL;+}++/* cam=5: a session whenever a read wants frames, until a fault. */static voidserve_ios(void){- int major;uint32_t mode_n = 1;if (!ctab_load()) {@@ -3272,14 +3316,24 @@ serve_ios(void)return;}ios_line_ns = (uint32_t)(1000000000000ull / ((uint64_t)ios_mode->fps_milli * ios_mode->frame_length));+ uint32_t pattern = 0, count = 0;+ const struct ctab_entry *tpgon;++ (void)PE_parse_boot_argn("cam_pattern", &pattern, sizeof(pattern));+ tpgon = ctab_find("tpgon", &count);+ ios_source = pattern == 0 ? SOURCE_SENSOR : pattern == 1 && tpgon != NULL && count > 0 && tpgon[0].address != 0 ?+ SOURCE_SENSOR_PATTERN : SOURCE_CSID_TPG;+ if (pattern != 0) {+ say("camera: cam_pattern=%u: %s\n", pattern, ios_source == SOURCE_SENSOR_PATTERN ? "the sensor's colour bars (its tpgon table)" :+ "the CSID's colour bars");+ }/* the first exposure, until the program asks for its own: boot-args as cam=4's, else a room's */ios_ask.lines = ios_mode->frame_length - EXPOSURE_MARGIN;ios_ask.gain = 8 * GAIN_UNITY;ios_ask.frame_lines = 0;(void)PE_parse_boot_argn("cam_shutter", &ios_ask.lines, sizeof(ios_ask.lines));(void)PE_parse_boot_argn("cam_gain", &ios_ask.gain, sizeof(ios_ask.gain));- major = cdevsw_add(-1, &camdev_cdevsw);- if (major < 0 || devfs_make_node(makedev(major, 0), DEVFS_CHAR, UID_ROOT, GID_WHEEL, 0666, "redwood-camera") == NULL) {+ if (!camdev_made) {say("camera: /dev/redwood-camera cannot be made\n");return;}@@ -3353,6 +3407,9 @@ camera_thread(__unused void *parameter, __unused wait_result_t result)char which[16] = "";(void)PE_parse_boot_argn("cam_after", &secs, sizeof(secs));+ if (level == 5) {+ camdev_make();+ }wait_ms(secs * 1000); /* (the system up first: nothing else is on these buses then) */tlmm = ml_io_map(TLMM_PHYS, TLMM_SIZE);gcc = ml_io_map(GCC_PHYS, 0x30000);diff --git a/xnuloader/loader.c b/xnuloader/loader.cindex 5542565..741de39 100644--- a/xnuloader/loader.c+++ b/xnuloader/loader.c@@ -1737,6 +1737,8 @@ run_kernel(int have_checkpoint, uint64_t checkpoint)int more_cores = 0, battery_requested = 0;/* "torch=N" (not 0) there too: the phone's flashlight is the kernel's (bsd/dev/redwood_torch.c) */int torch_requested = 0;+ /* "cam=5" there too: the phone's wide camera is iOS's (bsd/dev/redwood_camera.c) */+ int camera_requested = 0;/* (the loader stays for run after run: what the last run's arguments said must not hold for this one) */gamut_p3 = 0;for (const char *c = pi.cmdline; *c; c++) {@@ -1747,6 +1749,7 @@ run_kernel(int have_checkpoint, uint64_t checkpoint)battery_requested |= starts_with(c, "battery=1") && (c == pi.cmdline || c[-1] == ' ') &&(c[9] == 0 || c[9] == ' ');torch_requested |= starts_with(c, "torch=") && (c == pi.cmdline || c[-1] == ' ') && c[6] >= '1' && c[6] <= '9';+ camera_requested |= starts_with(c, "cam=5") && (c == pi.cmdline || c[-1] == ' ') && (c[5] == 0 || c[5] == ' ');gamut_p3 |= starts_with(c, "gamut=p3") && (c == pi.cmdline || c[-1] == ' ');}if (battery_requested) {@@ -1994,11 +1997,14 @@ run_kernel(int have_checkpoint, uint64_t checkpoint)dt_end(&w);/** and of its camera what is here: with torch=N the flash (MobileGestalt's camera-flash; without- * it Control Center has no flashlight). The rest of the iPhone's camera is not here, nor said to be.+ * it Control Center has no flashlight); with cam=5 the node itself, for a camera there is (with it+ * MobileGestalt's video-camera). The rest of the iPhone's camera is not here, nor said to be.*/- if (torch_requested) {+ if (torch_requested || camera_requested) {dt_begin(&w, "camera");- dt_identity_one(&w, identity_camera, sizeof(identity_camera) / sizeof(identity_camera[0]), identity_camera_data, "flash");+ if (torch_requested) {+ dt_identity_one(&w, identity_camera, sizeof(identity_camera) / sizeof(identity_camera[0]), identity_camera_data, "flash");+ }dt_end(&w);}dt_end(&w);@@ -2078,6 +2084,16 @@ run_kernel(int have_checkpoint, uint64_t checkpoint)dt_prop(&w, "ranges", ranges, sizeof(ranges));dt_prop_u32(&w, "#address-cells", 2);dt_prop_u32(&w, "#size-cells", 2);+ /*+ * With cam=5, where MobileGestalt looks for the cameras (IODeviceTree:/arm-io/isp, its still-camera and+ * rear-facing-camera, by which SpringBoard shows Camera.app): the iPhone's ISP node, of its+ * properties only the camera at the back. Neither a compatible nor a device_type: no driver matches it.+ */+ if (camera_requested) {+ dt_begin(&w, "isp");+ dt_prop_u32(&w, "camera-rear", 1);+ dt_end(&w);+ }dt_begin(&w, "gic");dt_prop_str(&w, "device_type", "interrupt-controller");dt_prop_str(&w, "compatible", "arm,gic-v3");