diff --git a/.github/workflows/topology.yml b/.github/workflows/topology.yml index 13d3882..5a078b0 100644 --- a/.github/workflows/topology.yml +++ b/.github/workflows/topology.yml @@ -25,7 +25,7 @@ jobs: sudo apt-get update sudo apt-get -y install ninja-build cmake m4 \ automake autoconf libtool gettext libasound2-dev \ - pkg-config python3-construct rpm cpio fakeroot + pkg-config python3-construct python3-pytest rpm cpio fakeroot - name: Install autoconf 2.72 run: | diff --git a/.github/workflows/validator.yml b/.github/workflows/validator.yml new file mode 100644 index 0000000..d56357f --- /dev/null +++ b/.github/workflows/validator.yml @@ -0,0 +1,86 @@ +--- +name: SOF Topology Validator + +# yamllint disable-line rule:truthy +on: [pull_request, push, workflow_dispatch, workflow_call] + +permissions: + contents: read + +concurrency: + group: "${{ github.workflow }}-${{ github.event_name }}-\ + ${{ github.event_name == 'pull_request' && github.ref || github.run_id }}" + cancel-in-progress: true + +jobs: + validator-unit-and-schema: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + with: + path: sof-topologies + + - name: Install Python test dependencies + run: | + sudo apt-get update + sudo apt-get -y install python3-construct python3-pytest + + - name: Cross-check topology2 tokens against kernel schema (advisory) + continue-on-error: true + run: | + python3 sof-topologies/validator/schema/check_tokens_conf.py -v + + - name: Run validator unit tests + run: | + pytest -v sof-topologies/validator/tests + + validator-integration: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + with: + path: sof-topologies + + - name: Install build dependencies + run: | + sudo apt-get update + sudo apt-get -y install ninja-build cmake m4 \ + automake autoconf libtool gettext libasound2-dev \ + pkg-config python3-construct python3-pytest + + - name: Install autoconf 2.72 + run: | + cd "${GITHUB_WORKSPACE}" + wget -q https://ftp.gnu.org/gnu/autoconf/autoconf-2.72.tar.gz + tar xf autoconf-2.72.tar.gz + cd autoconf-2.72 + ./configure --prefix=/usr/local + make -j"$(nproc)" + sudo make install + hash -r + + - name: Build ALSA lib & utils (alsatplg) + run: | + SOF_WORKSPACE="${GITHUB_WORKSPACE}" ./sof-topologies/scripts/build-alsa-tools.sh + + - name: Run validator pytest suite (with alsatplg) + env: + ALSATPLG: ${{ github.workspace }}/tools/bin/alsatplg + run: | + pytest -v sof-topologies/validator/tests + + - name: Build & validate all topology2 binaries (TPLG_VALIDATE=ON) + run: | + cmake -GNinja -S "${GITHUB_WORKSPACE}/sof-topologies" \ + -B "${GITHUB_WORKSPACE}/build-validate" \ + -DALSATPLG_CMD="${GITHUB_WORKSPACE}/tools/bin/alsatplg" \ + -DBUILD_TOPOLOGY1=OFF \ + -DBUILD_TOPOLOGY2=ON \ + -DBUILD_DEV_TOPOLOGIES=ON \ + -DTPLG_VALIDATE=ON + cmake --build "${GITHUB_WORKSPACE}/build-validate" --target topologies2 -j"$(nproc)" + find "${GITHUB_WORKSPACE}/build-validate/topology2/production" \ + "${GITHUB_WORKSPACE}/build-validate/topology2/development" \ + -maxdepth 1 -name "*.tplg" -print0 \ + | xargs -0 python3 "${GITHUB_WORKSPACE}/sof-topologies/validator/tplg_validate.py" \ + --waivers "${GITHUB_WORKSPACE}/sof-topologies/validator/known-issues.txt" diff --git a/CMakeLists.txt b/CMakeLists.txt index 29508fa..0b7cc28 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -220,6 +220,25 @@ if(Python3_Interpreter_FOUND) ) endif() endif() + execute_process( + COMMAND ${Python3_EXECUTABLE} -c "import construct" + RESULT_VARIABLE _validator_construct_ok + OUTPUT_QUIET ERROR_QUIET + ) + if(_validator_construct_ok EQUAL 0) + execute_process( + COMMAND ${Python3_EXECUTABLE} -m pytest --version + RESULT_VARIABLE _validator_pytest_ok + OUTPUT_QUIET ERROR_QUIET + ) + if(_validator_pytest_ok EQUAL 0) + add_test( + NAME validate_validator_suite + COMMAND ${CMAKE_COMMAND} -E env "ALSATPLG=${ALSATPLG_CMD}" + ${Python3_EXECUTABLE} -m pytest "${PROJECT_SOURCE_DIR}/validator/tests" + ) + endif() + endif() add_test( NAME validate_packages COMMAND ${Python3_EXECUTABLE} "${PROJECT_SOURCE_DIR}/tools/validate-package.py" diff --git a/README.md b/README.md index c3dc1f8..7f449d7 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ ALSA topology files describe the audio DSP graph (pipelines, widgets, routes, DA | :--- | :--- | | [`topology1/`](topology1/README.md) | Legacy (v1) `m4`-based IPC3 topology sources (`i.MX8`, `i.MX8MP`, `i.MX8ULP`, `i.MX93`, `i.MX95`, `MediaTek MT8186/8188/8195/8196/8365`, `AMD ACP`, `CAVS nocodec`) | | [`topology2/`](topology2/README.md) | Class-based (v2) `alsatplg -p` IPC4 & IPC3 topology sources (`Intel CAVS 2.5`, `ACE 1.x/2.x/3.x/4.x`, `HDA generic`, `SDCA generic`, `i.MX8`, `CHT`, and `sof-testbench4` development/benchmark graphs) | +| [`validator/`](validator/README.md) | Offline IPC4 topology binary validator and kernel token schema checker (`tplg_validate.py`) | | [`test/topology/`](test/topology/) | Automated component, SSP, and DMIC test topology matrix (`tplg-build.sh`) | | [`include/kernel/abi.h`](include/kernel/abi.h) | Standalone SOF ABI version header used when generating topology manifests | | [`tools/`](tools/) | Topology developer tools: [`tplgtool2.py`](tools/tplgtool2.py) (binary `.tplg` parser/graph dumper) and [`pretty-macro.sh`](tools/pretty-macro.sh) | diff --git a/cmake/alsatplg.cmake b/cmake/alsatplg.cmake index 5611ef0..3d5a5a1 100644 --- a/cmake/alsatplg.cmake +++ b/cmake/alsatplg.cmake @@ -50,6 +50,34 @@ if(NOT ALSATPLG_CMD) set(ALSATPLG_CMD "alsatplg") endif() +# Check every topology2 binary like the Linux SOF driver would when +# loading it, see validator/README.md. Errors fail the build, warnings +# are only counted. Needs the python3 construct module. +option(TPLG_VALIDATE "Validate topology2 binaries after building them" ON) +set(TPLG_VALIDATOR "${PROJECT_SOURCE_DIR}/validator/tplg_validate.py") +set(TPLG_VALIDATE_WAIVERS "${PROJECT_SOURCE_DIR}/validator/known-issues.txt") +set(TPLG_VALIDATE_ENABLED FALSE) +if(TPLG_VALIDATE) + find_package(Python3 COMPONENTS Interpreter) + if(Python3_Interpreter_FOUND) + execute_process(COMMAND ${Python3_EXECUTABLE} -c "import construct" + RESULT_VARIABLE construct_status OUTPUT_QUIET ERROR_QUIET) + endif() + if(Python3_Interpreter_FOUND AND construct_status EQUAL 0) + set(TPLG_VALIDATE_ENABLED TRUE) + message(STATUS "topology validation: enabled") + # recheck the binaries when the rules, the kernel schema or the + # waivers change + file(GLOB_RECURSE TPLG_VALIDATE_DEPENDS CONFIGURE_DEPENDS + "${PROJECT_SOURCE_DIR}/validator/*.py") + list(FILTER TPLG_VALIDATE_DEPENDS EXCLUDE REGEX "/tests/") + list(APPEND TPLG_VALIDATE_DEPENDS ${TPLG_VALIDATE_WAIVERS}) + else() + message(WARNING "topology validation skipped: python3 with the construct " + "module not found (install python3-construct or set -DTPLG_VALIDATE=OFF)") + endif() +endif() + get_filename_component(_alsatplg_bin_dir "${ALSATPLG_CMD}" DIRECTORY) if(_alsatplg_bin_dir AND EXISTS "${_alsatplg_bin_dir}/../lib") get_filename_component(SOF_ALSA_LIB_DIR "${_alsatplg_bin_dir}/../lib" ABSOLUTE) @@ -131,4 +159,22 @@ macro(add_alsatplg2_command conf_header conf_target input_name output_name inclu -I ${include_path} -D "'${defines}'" -p -c ${output_name}.conf -o ${output_name}.tplg ${TPLG_USES_TERMINAL} ) + + # Files the topology target must depend on, for the callers + set(tplg2_outputs ${output_name}.tplg) + + # Validate in a separate command, so that a change to the validator + # or the waivers rechecks the binary without rebuilding it. A failed + # check leaves no stamp file, so the check is repeated next time. + if (TPLG_VALIDATE_ENABLED) + add_custom_command( + OUTPUT ${output_name}.tplg.validated + DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${output_name}.tplg ${TPLG_VALIDATE_DEPENDS} + COMMAND ${Python3_EXECUTABLE} ${TPLG_VALIDATOR} --quiet + --waivers ${TPLG_VALIDATE_WAIVERS} ${output_name}.tplg + COMMAND ${CMAKE_COMMAND} -E touch ${output_name}.tplg.validated + ${TPLG_USES_TERMINAL} + ) + list(APPEND tplg2_outputs ${output_name}.tplg.validated) + endif() endmacro() diff --git a/topology1/CMakeLists.txt b/topology1/CMakeLists.txt index 2ed0ed7..dd5fe90 100644 --- a/topology1/CMakeLists.txt +++ b/topology1/CMakeLists.txt @@ -59,6 +59,7 @@ set(TPLGS "sof-imx8-wm8960\;sof-imx8mp-eap-wm8960\;-DCODEC=wm8960\;-DRATE=48000\;-DPPROC=eap\;-DSAI_INDEX=3" "sof-imx8-wm8960\;sof-imx8mp-wm8904\;-DCODEC=wm8904\;-DRATE=44100\;-DPPROC=volume\;-DSAI_INDEX=3" "sof-imx8-wm8960\;sof-imx8mp-wm8962\;-DCODEC=wm8962\;-DRATE=48000\;-DPPROC=volume\;-DSAI_INDEX=3" + "sof-imx8-wm8960\;sof-imx8mp-tlv320\;-DCODEC=tlv320\;-DRATE=48000\;-DPPROC=volume\;-DSAI_INDEX=2" "sof-imx8-wm8960\;sof-imx8mp-eq-iir-wm8960\;-DCODEC=wm8960\;-DRATE=48000\;-DPPROC=eq-iir-volume\;-DSAI_INDEX=3" "sof-imx8-wm8960\;sof-imx8mp-eq-iir-wm8962\;-DCODEC=wm8962\;-DRATE=48000\;-DPPROC=eq-iir-volume\;-DSAI_INDEX=3" "sof-imx8-wm8960\;sof-imx8mp-eq-fir-wm8960\;-DCODEC=wm8960\;-DRATE=48000\;-DPPROC=eq-fir-volume\;-DSAI_INDEX=3" diff --git a/topology1/sof-acp_7_x_sdw_pdm.m4 b/topology1/sof-acp_7_x_sdw_pdm.m4 index 1ade5d5..f837c59 100644 --- a/topology1/sof-acp_7_x_sdw_pdm.m4 +++ b/topology1/sof-acp_7_x_sdw_pdm.m4 @@ -101,7 +101,10 @@ PCM_PLAYBACK_ADD(ACP-SW0-PIN4-Playback-SPK, 2, PIPELINE_PCM_2) #/**********************************************************************************/ # Capture pipeline 6 on PCM 3 using max 2 channels of s32le. # DAI index PDM_INDEX (0 = PDM0, 1 = PDM1), BE acp-dmic-codec, DAI link id 5. -PIPELINE_PCM_ADD(sof/pipe-passthrough-capture.m4, +# Uses the volume/switch pipeline so the "Master Capture Switch" kcontrol can +# mute the PDM capture stream from user-space (amixer) without stopping the +# DMA, avoiding boot/transient noise being recorded. +PIPELINE_PCM_ADD(sof/pipe-volume-switch-capture.m4, 6, 3, 2, s32le, 2000, 0, 0, PDM_RATE, PDM_RATE, PDM_RATE) diff --git a/topology1/sof-imx8-wm8960.m4 b/topology1/sof-imx8-wm8960.m4 index 289493c..4ef19a9 100644 --- a/topology1/sof-imx8-wm8960.m4 +++ b/topology1/sof-imx8-wm8960.m4 @@ -1,7 +1,7 @@ # # Topology for i.MX8QM/i.MX8QXP/i.MX8MP board with 'CODEC' codec # -# CODEC: wm8960, wm8962 +# CODEC: wm8960, wm8962, wm8904, tlv320 (tlv320aic3007) # # Include topology builder @@ -57,6 +57,7 @@ define(`STREAM_NAME', `ifelse(CODEC, `wm8960', `-wm8960-hifi', CODEC, `wm8904', `-wm8904-hifi', CODEC, `wm8962', `-wm8962', + CODEC, `tlv320', `-tlv320', `fatal_error(`Codec not supported.')')') # define DAI BE dai_link name @@ -108,4 +109,10 @@ ifelse( SAI_CLOCK(fsync, RATE, codec_provider), SAI_TDM(2, 32, 3, 3), SAI_CONFIG_DATA(SAI, SAI_INDEX, 0)))', + CODEC, `tlv320', ` + SAI_CONFIG(I2S, SAI_CLOCK(mclk, 12288000, codec_mclk_in), + SAI_CLOCK(bclk, 3072000, codec_consumer), + SAI_CLOCK(fsync, RATE, codec_consumer), + SAI_TDM(2, 32, 3, 3), + SAI_CONFIG_DATA(SAI, SAI_INDEX, 0)))', ) diff --git a/topology2/README.md b/topology2/README.md index 8002a75..ad10dd7 100644 --- a/topology2/README.md +++ b/topology2/README.md @@ -14,6 +14,22 @@ Topology v2 introduces an object-oriented pre-processing layer directly into the Building topologies requires `alsatplg` version 1.2.7 or later. The version check is enforced in `CMakeLists.txt` at configure time. +### HDA benchmarks + +The generic HDA benchmark (`BENCH_CONFIG=benchmark,HDA_CONFIG=benchmark`) +provides its own DAI pipelines. The default component-benchmark DAI gateways +are only instantiated with `HDA_CONFIG=none` to avoid duplicate widget names +and overlapping pipeline IDs. + +The MFCC and MFCC-mel HDA benchmarks use 16 kHz throughout, including the HDA +link. Their copiers convert sample formats, not sample rates. Use 16 kHz when +running these benchmarks; MFCC output carries feature data, not listenable +audio. + +The HDA mix topology uses a 40 Hz capture high-pass at both 48 kHz and +96 kHz. At 96 kHz it reuses the 20 Hz / 48 kHz coefficients, which have +the same normalized cutoff. + ## Key Advantages - **Object-Oriented Syntax**: Topology v2 allows for the definition of classes (`Class.Widget`, `Class.Pipeline`) and object instantiation, making the topology files much easier to read, maintain, and extend. @@ -143,6 +159,14 @@ To build a specific topology target: make sof-lnl-sdw-cs42l43-l0-cs35l56-l12 ``` +Each built binary is checked by the [topology validator](../validator/README.md), which repeats +the checks the Linux SOF driver does when loading a topology. A validation error fails the +build of that topology. To check a binary by hand, for example to see warnings too: + +```bash +validator/tplg_validate.py build/topology2/production/sof-mtl-rt711-4ch.tplg +``` + ## Best Practices for Adding New Topology Definitions ### Topology Structure @@ -242,13 +266,14 @@ default ID ranges for the same endpoint types. | Jack Echo Ref | 11 | `SDW_JACK_ECHO_REF_PCM_ID` | | Speaker Echo Ref | 12 | `SDW_SPK_ECHO_REF_PCM_ID` | | Bluetooth | 2 or 20 | `BT_PCM_ID` | -| USB Audio Offload (UAOL0) | 21 | `UAOL_PCM_ID` | -| USB Audio Offload (UAOL1) | 22 | `UAOL_PCM1_ID` | -| Deepbuffer UAOL0 | 23 | `UAOL_DB_PCM_ID` | -| Deepbuffer UAOL1 | 24 | `UAOL_DB1_PCM_ID` | -| Deep Buffer (Jack) | 31 | `DEEP_BUFFER_PCM_ID` | -| Deep Buffer (Speaker) | 35 | `DEEP_BUFFER_PCM_ID_2` | -| DMIC Deep Buffer | 46 | `DMIC0_DEEP_BUFFER_PCM_ID` | +| USB Offload 0 (playback/capture) | 21 | `UAOL_PCM_ID` | +| USB Offload 1 (playback/capture) | 22 | `UAOL_PCM1_ID` | +| Deepbuffer USB Offload 0 | 23 | `UAOL_DB_PCM_ID` | +| Deepbuffer USB Offload 1 | 24 | `UAOL_DB1_PCM_ID` | +| Deepbuffer Jack Out | 31 | `DEEP_BUFFER_PCM_ID` | +| Deepbuffer Speaker | 35 | `DEEP_BUFFER_PCM_ID_2` | +| Deepbuffer Bluetooth | 36 | `BT_DEEP_BUFFER_PCM_ID` | +| Deepbuffer DMIC | 46 | `DMIC0_DEEP_BUFFER_PCM_ID` | | Compress Jack Out | 50 | `COMPR_PCM_ID` | | Compress Speaker | 52 | `COMPR_2_PCM_ID` | @@ -265,9 +290,38 @@ default ID ranges for the same endpoint types. | HDMI 2 | 4 | `HDMI2_PCM_ID` | | HDMI 3 | 5 | `HDMI3_PCM_ID` | | DMIC0 | 6 | `DMIC0_PCM_ID` | -| Deep Buffer | 31 | `DEEP_BUFFER_PCM_ID` | +| Bluetooth | 20 | `BT_PCM_ID` | +| USB Offload 0 (playback/capture) | 21 | `UAOL_PCM_ID` | +| USB Offload 1 (playback/capture) | 22 | `UAOL_PCM1_ID` | +| Deepbuffer USB Offload 0 | 23 | `UAOL_DB_PCM_ID` | +| Deepbuffer USB Offload 1 | 24 | `UAOL_DB1_PCM_ID` | +| Deepbuffer HDA Analog | 31 | `DEEP_BUFFER_PCM_ID` | +| Deepbuffer Bluetooth | 36 | `BT_DEEP_BUFFER_PCM_ID` | | Compress HDA Analog | 50 | `COMPR_PCM_ID` | +**Intel HDA Backend DAI Link IDs:** + +These IDs match the fixed backend DAI-link IDs defined by the kernel machine +driver. They are independent of PCM IDs and pipeline indexes. The kernel defines +base IDs for iDisp HDMI, HDA, and UAOL. The HDA helper increments the iDisp and +HDA base IDs when it creates additional links; UAOL stream backends also use +consecutive IDs. + +| Backend | DAI Link ID | Kernel Define | Topology Variable | +|---|---:|---|---| +| iDisp HDMI 1 | 1 | `IDISP_HDMI_BE_ID` | `HDMI1_ID` | +| iDisp HDMI 2 | 2 | `IDISP_HDMI_BE_ID + 1` | `HDMI2_ID` | +| iDisp HDMI 3 | 3 | `IDISP_HDMI_BE_ID + 2` | `HDMI3_ID` | +| HDA Analog | 4 | `HDA_BE_ID` | Hard-coded as `id 4` | +| HDA Digital | 5 | `HDA_BE_ID + 1` | — | +| DMIC01 | 6 | `DMIC01_BE_ID` | `DMIC0_ID` | +| DMIC 16 kHz | 7 | `DMIC16K_BE_ID` | `DMIC1_ID` | +| Bluetooth Offload | 8 | `BT_OFFLOAD_BE_ID` | Not used by HDA generic | +| UAOL Play0 | 9 | `UAOL_BE_ID` | `UAOL_PB_BE_ID` | +| UAOL Cap0 | 10 | `UAOL_BE_ID + 1` | `UAOL_CP_BE_ID` | +| UAOL Play1 | 11 | `UAOL_BE_ID + 2` | `UAOL_PB1_BE_ID` | +| UAOL Cap1 | 12 | `UAOL_BE_ID + 3` | `UAOL_CP1_BE_ID` | + Key rules: * PCM ID 0 is always the primary playback endpoint @@ -305,6 +359,9 @@ is at N1 (50/51, 60/61, 70/71, 80/81). | HDMI 4 Host / DAI | 80 / 81 | `HDMI4_HOST_PIPELINE_ID` / `HDMI4_DAI_PIPELINE_ID` | | Compress Jack / Speaker | 90 / 92 | `COMPR_PIPELINE_ID` / `COMPR_2_PIPELINE_ID` | | PCH DMIC0 Host / DAI | 100 / 101 | `DMIC0_HOST_PIPELINE_ID` / `DMIC0_DAI_PIPELINE_ID` | +| Bluetooth Playback Host / DAI | 200 / 201 | `BT_PB_HOST_PIPELINE_ID` / `BT_PB_DAI_PIPELINE_ID` | +| Bluetooth Capture Host / DAI | 202 / 203 | `BT_CP_HOST_PIPELINE_ID` / `BT_CP_DAI_PIPELINE_ID` | +| Bluetooth Deepbuffer | 204 | `BT_DEEP_BUFFER_PIPELINE_ID` | | UAOL0 Playback Host / DAI | 210 / 211 | `UAOL_PB_HOST_PIPELINE_ID` / `UAOL_PB_DAI_PIPELINE_ID` | | UAOL0 Capture Host / DAI | 212 / 213 | `UAOL_CP_HOST_PIPELINE_ID` / `UAOL_CP_DAI_PIPELINE_ID` | | UAOL0 Deepbuffer | 214 | `UAOL_DB_PIPELINE_ID` | diff --git a/topology2/cavs-benchmark-hda.conf b/topology2/cavs-benchmark-hda.conf index d1357ca..84c3c29 100644 --- a/topology2/cavs-benchmark-hda.conf +++ b/topology2/cavs-benchmark-hda.conf @@ -37,6 +37,7 @@ + @@ -79,6 +80,15 @@ IncludeByKey.PLATFORM { "ptl" "platform/intel/ptl.conf" } +IncludeByKey.BENCH_CONFIG { + "^mfcc(mel)?(16|24|32)$" { + Define { + HDA_ANALOG_CAPTURE_RATE 16000 + HDA_ANALOG_PLAYBACK_RATE 16000 + } + } +} + Object.Widget.virtual [ { name 'codec0_in' @@ -212,102 +222,114 @@ Object.PCM.pcm [ } ] -Object.Pipeline { - io-gateway [ - { - index $BENCH_PLAYBACK_DAI_PIPELINE - direction playback - Object.Widget.dai-copier.1 { - node_type $HDA_LINK_OUTPUT_CLASS - stream_name $HDA_ANALOG_DAI_NAME - dai_type "HDA" - copier_type "HDA" - num_input_pins 1 - num_input_audio_formats 1 - num_output_audio_formats 1 - IncludeByKey.BENCH_MODULE_FORMAT { - "s16" { - Object.Base.input_audio_format [ - { - in_bit_depth 16 - in_valid_bit_depth 16 +IncludeByKey.HDA_CONFIG { + "none" { + Object.Pipeline { + io-gateway [ + { + index $BENCH_PLAYBACK_DAI_PIPELINE + direction playback + Object.Widget.dai-copier.1 { + node_type $HDA_LINK_OUTPUT_CLASS + stream_name $HDA_ANALOG_DAI_NAME + dai_type "HDA" + copier_type "HDA" + num_input_pins 1 + num_input_audio_formats 1 + num_output_audio_formats 1 + IncludeByKey.BENCH_MODULE_FORMAT { + "s16" { + Object.Base.input_audio_format [ + { + in_rate $HDA_ANALOG_PLAYBACK_RATE + in_bit_depth 16 + in_valid_bit_depth 16 + } + ] } - ] - } - "s24" { - Object.Base.input_audio_format [ + "s24" { + Object.Base.input_audio_format [ + { + in_rate $HDA_ANALOG_PLAYBACK_RATE + in_bit_depth 32 + in_valid_bit_depth 24 + } + ] + } + "s32" { + Object.Base.input_audio_format [ + { + in_rate $HDA_ANALOG_PLAYBACK_RATE + in_bit_depth 32 + in_valid_bit_depth 32 + } + ] + } + } + Object.Base.output_audio_format [ { - in_bit_depth 32 - in_valid_bit_depth 24 + out_rate $HDA_ANALOG_PLAYBACK_RATE + out_bit_depth 32 + out_valid_bit_depth 32 } ] } - "s32" { + } + ] + io-gateway-capture [ + { + index $BENCH_CAPTURE_DAI_PIPELINE + direction capture + Object.Widget.dai-copier.1 { + dai_type "HDA" + type "dai_out" + copier_type "HDA" + stream_name $HDA_ANALOG_DAI_NAME + node_type $HDA_LINK_INPUT_CLASS + num_output_pins 1 + num_input_audio_formats 1 + num_output_audio_formats 1 Object.Base.input_audio_format [ { + in_rate $HDA_ANALOG_CAPTURE_RATE in_bit_depth 32 in_valid_bit_depth 32 } ] - } - } - Object.Base.output_audio_format [ - { - out_bit_depth 32 - out_valid_bit_depth 32 - } - ] - } - } - ] - io-gateway-capture [ - { - index $BENCH_CAPTURE_DAI_PIPELINE - direction capture - Object.Widget.dai-copier.1 { - dai_type "HDA" - type "dai_out" - copier_type "HDA" - stream_name $HDA_ANALOG_DAI_NAME - node_type $HDA_LINK_INPUT_CLASS - num_output_pins 1 - num_input_audio_formats 1 - num_output_audio_formats 1 - Object.Base.input_audio_format [ - { - in_bit_depth 32 - in_valid_bit_depth 32 - } - ] - IncludeByKey.BENCH_MODULE_FORMAT { - "s16" { - Object.Base.output_audio_format [ - { - out_bit_depth 16 - out_valid_bit_depth 16 + IncludeByKey.BENCH_MODULE_FORMAT { + "s16" { + Object.Base.output_audio_format [ + { + out_rate $HDA_ANALOG_CAPTURE_RATE + out_bit_depth 16 + out_valid_bit_depth 16 + } + ] } - ] - } - "s24" { - Object.Base.output_audio_format [ - { - out_bit_depth 32 - out_valid_bit_depth 24 + "s24" { + Object.Base.output_audio_format [ + { + out_rate $HDA_ANALOG_CAPTURE_RATE + out_bit_depth 32 + out_valid_bit_depth 24 + } + ] } - ] - } - "s32" { - Object.Base.output_audio_format [ - { - out_bit_depth 32 - out_valid_bit_depth 32 + "s32" { + Object.Base.output_audio_format [ + { + out_rate $HDA_ANALOG_CAPTURE_RATE + out_bit_depth 32 + out_valid_bit_depth 32 + } + ] } - ] + } } } - } + ] } - ] + } } IncludeByKey.BENCH_CONFIG { @@ -1026,4 +1048,8 @@ IncludeByKey.BENCH_CONFIG { "template_comp32" { } + + "ffmpeg_dec32" { + + } } diff --git a/topology2/cavs-benchmark-sdw.conf b/topology2/cavs-benchmark-sdw.conf index b19a26d..3cc3603 100644 --- a/topology2/cavs-benchmark-sdw.conf +++ b/topology2/cavs-benchmark-sdw.conf @@ -36,6 +36,7 @@ + @@ -629,4 +630,8 @@ IncludeByKey.BENCH_CONFIG { "template_comp32" { } + + "ffmpeg_dec32" { + + } } \ No newline at end of file diff --git a/topology2/cavs-mixin-mixout-hda.conf b/topology2/cavs-mixin-mixout-hda.conf index 50a4fc5..1c7aa23 100644 --- a/topology2/cavs-mixin-mixout-hda.conf +++ b/topology2/cavs-mixin-mixout-hda.conf @@ -17,10 +17,32 @@ Define { COMPR_FFMPEG_CODEC 'flac' HDA_ANALOG_CAPTURE_RATE 48000 HDA_ANALOG_PLAYBACK_RATE 48000 + HDA_CAPTURE_HIGHPASS '48k' EFX_FIR_PARAMS 'passthrough' EFX_IIR_PARAMS 'passthrough' EFX_DRC_PARAMS 'passthrough' HDA_MIC_ENHANCED_CAPTURE 'false' + + # Compress capture (encode) via the FFmpeg encoder (ffmpeg_enc). The PCM + # name overrides the generic compr-default.conf default. COMPR_ENC_SOURCE + # is the capture-BE fan-out tap: when COMPR_FFMPEG_ENC is enabled the + # capture path is rebuilt around a mixin (mixin.4.1) that fans out - via the + # proven mixer path - to both the normal analog capture FE (mixout.3.1) and + # the encoder FE (mixout.93.1). A copier's 2nd output pin does not deliver + # data across a pipeline boundary, which starved the encoder; mixin->mixout + # does. + COMPR_ENC_PCM_NAME 'Compress Capture HDA Analog' + COMPR_ENC_SOURCE 'mixin.4.1' +} + +# The 20 Hz / 48 kHz coefficients have the same normalized cutoff as +# 40 Hz / 96 kHz. +IncludeByKey.HDA_ANALOG_CAPTURE_RATE { + "96000" { + Define { + HDA_CAPTURE_HIGHPASS '96k' + } + } } # include deep buffer config if buffer size is in 1 - 1000 ms. @@ -36,6 +58,12 @@ IncludeByKey.COMPR_FFMPEG { "true" "platform/intel/compr-ffmpeg.conf" } +IncludeByKey.COMPR_FFMPEG_ENC { + "true" { + + } +} + Object.Dai.HDA [ { name $HDA_ANALOG_DAI_NAME @@ -97,17 +125,75 @@ Object.Pipeline { } ] } + Object.Widget.mixout.1 { + Object.Base.input_audio_format [ + { + in_rate $HDA_ANALOG_PLAYBACK_RATE + in_bit_depth 32 + in_valid_bit_depth 32 + } + ] + Object.Base.output_audio_format [ + { + out_rate $HDA_ANALOG_PLAYBACK_RATE + out_bit_depth 32 + out_valid_bit_depth 32 + } + ] + } Object.Widget.eqiir.1 { + Object.Base.input_audio_format [ + { + in_rate $HDA_ANALOG_PLAYBACK_RATE + in_bit_depth 32 + in_valid_bit_depth 32 + } + ] + Object.Base.output_audio_format [ + { + out_rate $HDA_ANALOG_PLAYBACK_RATE + out_bit_depth 32 + out_valid_bit_depth 32 + } + ] Object.Control.bytes."1" { name 'Post Mixer $ANALOG_PLAYBACK_PCM IIR Eq bytes' } } Object.Widget.eqfir.1 { + Object.Base.input_audio_format [ + { + in_rate $HDA_ANALOG_PLAYBACK_RATE + in_bit_depth 32 + in_valid_bit_depth 32 + } + ] + Object.Base.output_audio_format [ + { + out_rate $HDA_ANALOG_PLAYBACK_RATE + out_bit_depth 32 + out_valid_bit_depth 32 + } + ] Object.Control.bytes."1" { name 'Post Mixer $ANALOG_PLAYBACK_PCM FIR Eq bytes' } } Object.Widget.drc.1 { + Object.Base.input_audio_format [ + { + in_rate $HDA_ANALOG_PLAYBACK_RATE + in_bit_depth 32 + in_valid_bit_depth 32 + } + ] + Object.Base.output_audio_format [ + { + out_rate $HDA_ANALOG_PLAYBACK_RATE + out_bit_depth 32 + out_valid_bit_depth 32 + } + ] Object.Control { bytes."1" { name 'Post Mixer $ANALOG_PLAYBACK_PCM DRC bytes' @@ -158,136 +244,203 @@ Object.Pipeline { Object.Widget.gain.1 { Object.Control.mixer.1 { name 'Pre Mixer $ANALOG_PLAYBACK_PCM Volume' - num_input_audio_formats 1 - num_output_audio_formats 1 - Object.Base.input_audio_format [ - { - in_rate $HDA_ANALOG_PLAYBACK_RATE - in_bit_depth 32 - in_valid_bit_depth 32 - } - ] - Object.Base.output_audio_format [ - { - out_rate $HDA_ANALOG_PLAYBACK_RATE - out_bit_depth 32 - out_valid_bit_depth 32 - } - ] } - } - } - ] - - host-gateway-capture [ - { - index 3 - Object.Widget.host-copier.1 { - stream_name $ANALOG_CAPTURE_PCM - pcm_id 0 - num_input_audio_formats 1 - num_output_audio_formats 3 Object.Base.input_audio_format [ { - in_rate $HDA_ANALOG_CAPTURE_RATE + in_rate $HDA_ANALOG_PLAYBACK_RATE in_bit_depth 32 in_valid_bit_depth 32 } ] Object.Base.output_audio_format [ { - out_rate $HDA_ANALOG_CAPTURE_RATE - out_bit_depth 16 - out_valid_bit_depth 16 - } - { - out_rate $HDA_ANALOG_CAPTURE_RATE - out_bit_depth 32 - out_valid_bit_depth 24 - } - { - out_rate $HDA_ANALOG_CAPTURE_RATE + out_rate $HDA_ANALOG_PLAYBACK_RATE out_bit_depth 32 out_valid_bit_depth 32 } ] } - } - ] - - dai-copier-eqiir-module-copier-capture [ - { - index 4 - - Object.Widget.dai-copier."1" { - dai_type "HDA" - type "dai_out" - copier_type "HDA" - stream_name $HDA_ANALOG_DAI_NAME - node_type $HDA_LINK_INPUT_CLASS - num_output_pins 1 - num_input_audio_formats 1 - num_output_audio_formats 1 + Object.Widget.mixin.1 { Object.Base.input_audio_format [ { - in_rate $HDA_ANALOG_CAPTURE_RATE - in_bit_depth 32 - in_valid_bit_depth 32 + in_rate $HDA_ANALOG_PLAYBACK_RATE + in_bit_depth 32 + in_valid_bit_depth 32 } ] Object.Base.output_audio_format [ { - out_rate $HDA_ANALOG_CAPTURE_RATE - out_bit_depth 32 - out_valid_bit_depth 32 + out_rate $HDA_ANALOG_PLAYBACK_RATE + out_bit_depth 32 + out_valid_bit_depth 32 } ] } - Object.Widget.eqiir.1 { - Object.Control.bytes."1" { - name '$ANALOG_CAPTURE_PCM IIR Eq' - - } - num_input_audio_formats 1 - num_output_audio_formats 1 - Object.Base.input_audio_format [ - { - in_rate $HDA_ANALOG_CAPTURE_RATE - in_bit_depth 32 - in_valid_bit_depth 32 - } - ] - Object.Base.output_audio_format [ - { - out_rate $HDA_ANALOG_CAPTURE_RATE - out_bit_depth 32 - out_valid_bit_depth 32 - } - ] - } - Object.Widget.module-copier."2" { - stream_name $HDA_ANALOG_DAI_NAME - num_input_audio_formats 1 - num_output_audio_formats 1 - Object.Base.input_audio_format [ - { - in_rate $HDA_ANALOG_CAPTURE_RATE - in_bit_depth 32 - in_valid_bit_depth 32 - } - ] - Object.Base.output_audio_format [ - { - out_rate $HDA_ANALOG_CAPTURE_RATE - out_bit_depth 32 - out_valid_bit_depth 32 - } - ] - } - } + } ] } +# Capture path. Default (COMPR_FFMPEG_ENC=false) keeps the stock +# dai-copier -> eqiir -> module-copier -> host-copier.0 chain. When the FFmpeg +# encoder FE is enabled the capture is rebuilt around the mixer so a single +# mixin (mixin.4.1) fans out to both the normal capture FE (mixout.3.1) and the +# encoder FE (mixout.93.1): a module-copier 2nd output pin does not deliver data +# across a pipeline boundary, whereas mixin->mixout (the playback mix path) does. +IncludeByKey.COMPR_FFMPEG_ENC { +"false" { + Object.Pipeline { + host-gateway-capture [ + { + index 3 + Object.Widget.host-copier.1 { + stream_name $ANALOG_CAPTURE_PCM + pcm_id 0 + num_input_audio_formats 1 + num_output_audio_formats 3 + Object.Base.input_audio_format [ + { + in_rate $HDA_ANALOG_CAPTURE_RATE + in_bit_depth 32 + in_valid_bit_depth 32 + } + ] + Object.Base.output_audio_format [ + { + out_rate $HDA_ANALOG_CAPTURE_RATE + out_bit_depth 16 + out_valid_bit_depth 16 + } + { + out_rate $HDA_ANALOG_CAPTURE_RATE + out_bit_depth 32 + out_valid_bit_depth 24 + } + { + out_rate $HDA_ANALOG_CAPTURE_RATE + out_bit_depth 32 + out_valid_bit_depth 32 + } + ] + } + } + ] + + dai-copier-eqiir-module-copier-capture [ + { + index 4 + + Object.Widget.dai-copier."1" { + dai_type "HDA" + type "dai_out" + copier_type "HDA" + stream_name $HDA_ANALOG_DAI_NAME + node_type $HDA_LINK_INPUT_CLASS + num_output_pins 1 + num_input_audio_formats 1 + num_output_audio_formats 1 + Object.Base.input_audio_format [ + { + in_rate $HDA_ANALOG_CAPTURE_RATE + in_bit_depth 32 + in_valid_bit_depth 32 + } + ] + Object.Base.output_audio_format [ + { + out_rate $HDA_ANALOG_CAPTURE_RATE + out_bit_depth 32 + out_valid_bit_depth 32 + } + ] + } + Object.Widget.eqiir.1 { + Object.Control.bytes."1" { + name '$ANALOG_CAPTURE_PCM IIR Eq' + IncludeByKey.HDA_CAPTURE_HIGHPASS { + "48k" "include/components/eqiir/highpass_40hz_0db_48khz.conf" + "96k" "include/components/eqiir/highpass_20hz_0db_48khz.conf" + } + } + num_input_audio_formats 1 + num_output_audio_formats 1 + Object.Base.input_audio_format [ + { + in_rate $HDA_ANALOG_CAPTURE_RATE + in_bit_depth 32 + in_valid_bit_depth 32 + } + ] + Object.Base.output_audio_format [ + { + out_rate $HDA_ANALOG_CAPTURE_RATE + out_bit_depth 32 + out_valid_bit_depth 32 + } + ] + } + Object.Widget.module-copier."2" { + stream_name $HDA_ANALOG_DAI_NAME + num_input_audio_formats 1 + num_output_audio_formats 1 + Object.Base.input_audio_format [ + { + in_rate $HDA_ANALOG_CAPTURE_RATE + in_bit_depth 32 + in_valid_bit_depth 32 + } + ] + Object.Base.output_audio_format [ + { + out_rate $HDA_ANALOG_CAPTURE_RATE + out_bit_depth 32 + out_valid_bit_depth 32 + } + ] + } + } + ] + } +} +"true" { + # BE: HDA analog capture -> gain -> mixin.4.1 (the fan-out point). + # FE1 (normal analog capture, pcm0c): mixout.3.1 -> gain -> host-copier.0. + # FE2 (encoder, pcm51): mixin.4.1 -> mixout.93.1 -> ffmpeg_enc -> host-copier.51, + # declared in platform/intel/compr-capture-ffmpeg.conf. + Object.Pipeline { + mixout-gain-host-copier-capture [ + { + index 3 + Object.Widget.host-copier.1 { + stream_name $ANALOG_CAPTURE_PCM + pcm_id 0 + } + Object.Widget.gain.1 { + Object.Control.mixer.1 { + name 'Analog Capture Post Mixer Volume' + } + } + } + ] + + dai-copier-gain-mixin-capture [ + { + index 4 + Object.Widget.dai-copier.1 { + dai_type "HDA" + copier_type "HDA" + stream_name $HDA_ANALOG_DAI_NAME + } + Object.Widget.gain.1 { + Object.Control.mixer.1 { + name 'Analog Capture Pre Mixer Volume' + } + } + } + ] + } +} +} + IncludeByKey.HDA_MIC_ENHANCED_CAPTURE { "true" { Object.Widget.tdfb.1 { @@ -383,6 +536,7 @@ Object.PCM.pcm [ direction "playback" name $ANALOG_PLAYBACK_PCM formats 'S32_LE,S24_LE,S16_LE' + rates "8000,11025,16000,22050,24000,32000,44100,48000,64000,88200,96000,176400,192000" rate_min $HDA_ANALOG_PLAYBACK_RATE rate_max $HDA_ANALOG_PLAYBACK_RATE } @@ -390,6 +544,7 @@ Object.PCM.pcm [ direction "capture" name $ANALOG_CAPTURE_PCM formats 'S32_LE,S24_LE,S16_LE' + rates "8000,11025,16000,22050,24000,32000,44100,48000,64000,88200,96000,176400,192000" rate_min $HDA_ANALOG_CAPTURE_RATE rate_max $HDA_ANALOG_CAPTURE_RATE } @@ -407,39 +562,92 @@ Object.Base.route [ source 'mixin.1.1' sink 'mixout.2.1' } - { - source 'dai-copier.HDA.$HDA_ANALOG_DAI_NAME.capture' - sink 'eqiir.4.1' - } { source 'host-copier.0.playback' sink 'gain.1.1' } ] -IncludeByKey.HDA_MIC_ENHANCED_CAPTURE { - "true" { - Object.Base.route [ - { - source 'module-copier.4.2' - sink 'tdfb.3.1' - } - { - source 'tdfb.3.1' - sink 'drc.3.1' - } - { - source 'drc.3.1' - sink 'host-copier.0.capture' - } - ] - } - "false" { - Object.Base.route [ - { - source 'module-copier.4.2' - sink 'host-copier.0.capture' - } - ] - } +IncludeByKey.COMPR_FFMPEG_ENC { +"false" { + # stock capture BE processing chain feeding the normal analog capture FE + Object.Base.route [ + { + source 'dai-copier.HDA.$HDA_ANALOG_DAI_NAME.capture' + sink 'eqiir.4.1' + } + ] + IncludeByKey.HDA_MIC_ENHANCED_CAPTURE { + "true" { + Object.Base.route [ + { + source 'module-copier.4.2' + sink 'tdfb.3.1' + } + { + source 'tdfb.3.1' + sink 'drc.3.1' + } + { + source 'drc.3.1' + sink 'host-copier.0.capture' + } + ] + } + "false" { + Object.Base.route [ + { + source 'module-copier.4.2' + sink 'host-copier.0.capture' + } + ] + } + } +} +"true" { + # BE dai -> gain -> mixin.4.1; the mixin fans out to mixout.3.1 (normal FE) + # and to mixout.93.1 (encoder FE - that tap is in compr-capture-ffmpeg.conf). + # The gain->mixin (BE) and mixout->gain->host-copier.0 (FE) hops are provided + # by the dai-copier-gain-mixin-capture / mixout-gain-host-copier-capture classes. + Object.Base.route [ + { + source 'dai-copier.HDA.$HDA_ANALOG_DAI_NAME.capture' + sink 'gain.4.1' + } + { + source 'mixin.4.1' + sink 'mixout.3.1' + } + { + source 'mixout.3.1' + sink 'gain.3.1' + } + ] + IncludeByKey.HDA_MIC_ENHANCED_CAPTURE { + "true" { + Object.Base.route [ + { + source 'gain.3.1' + sink 'tdfb.3.1' + } + { + source 'tdfb.3.1' + sink 'drc.3.1' + } + { + source 'drc.3.1' + sink 'host-copier.0.capture' + } + ] + } + "false" { + Object.Base.route [ + { + source 'gain.3.1' + sink 'host-copier.0.capture' + } + ] + } + } +} } diff --git a/topology2/cavs-sdw-src-gain-mixin.conf b/topology2/cavs-sdw-src-gain-mixin.conf index 57f2fcc..316ca54 100644 --- a/topology2/cavs-sdw-src-gain-mixin.conf +++ b/topology2/cavs-sdw-src-gain-mixin.conf @@ -150,8 +150,7 @@ Object.Widget { { out_bit_depth 32 out_valid_bit_depth 32 - out_sample_type $SAMPLE_TYPE_MSB_INTEGER - out_fmt_cfg "$[($out_channels | ($out_valid_bit_depth * 256))]" + out_sample_type $SAMPLE_TYPE_LSB_INTEGER } ] } diff --git a/topology2/cavs-sdw.conf b/topology2/cavs-sdw.conf index 7edd097..5070efe 100644 --- a/topology2/cavs-sdw.conf +++ b/topology2/cavs-sdw.conf @@ -12,6 +12,7 @@ + @@ -61,9 +62,15 @@ + + + + + + Define { PLATFORM "none" @@ -133,6 +140,7 @@ Define { SDW_AMP_PIPELINE_SRC "generic" SDW_JACK_PIPELINE_SRC "generic" SDW_ECHO_REF_DAI "false" + SDW_SPK_AEC_CAPTURE_PCM "false" } # override defaults with platform-specific config @@ -273,6 +281,10 @@ IncludeByKey.SDW_SPK_ECHO_REF { "true" "platform/intel/sdw-amp-echo-ref.conf" } +IncludeByKey.SDW_SPK_AEC_CAPTURE_PCM { + "true" "platform/intel/sdw-amp-aec.conf" +} + IncludeByKey.SDW_JACK_AUDIO_FEATURE_CAPTURE { "true" "platform/intel/sdw-jack-audio-feature.conf" } diff --git a/topology2/cavs-uaol.conf b/topology2/cavs-uaol.conf index a351ca1..85ee38b 100644 --- a/topology2/cavs-uaol.conf +++ b/topology2/cavs-uaol.conf @@ -42,8 +42,8 @@ Define { - UAOL_PLAYBACK_PCM 'UAOL0 Playback' - UAOL_CAPTURE_PCM 'UAOL0 Capture' + UAOL_PLAYBACK_PCM 'USB Offload 0 Playback' + UAOL_CAPTURE_PCM 'USB Offload 0 Capture' # The two directions are separate DAI links so that the format fixup of # a link is decided by the DAI copier of that direction alone, and the # link carries two streams per direction, each with a backend of its @@ -59,7 +59,7 @@ Define { UAOL_CP_BE_ID 10 # UAOL_DAI_INDEX is the UAOL link the DSP uses, only link 0 is addressable UAOL_DAI_INDEX 0 - UAOL_PCM_NAME 'UAOL0' + UAOL_PCM_NAME 'USB Offload 0' UAOL_PCM_ID 21 UAOL_PB_HOST_PIPELINE_ID 210 UAOL_PB_DAI_PIPELINE_ID 211 @@ -68,13 +68,13 @@ Define { # Second stream pair of the link, on its own PCM UAOL_NUM_STREAMS 2 - UAOL_PLAYBACK1_PCM 'UAOL1 Playback' - UAOL_CAPTURE1_PCM 'UAOL1 Capture' + UAOL_PLAYBACK1_PCM 'USB Offload 1 Playback' + UAOL_CAPTURE1_PCM 'USB Offload 1 Capture' UAOL_PB1_DAI_NAME 'UAOL0-Play1' UAOL_CP1_DAI_NAME 'UAOL0-Cap1' UAOL_PB1_BE_ID 11 UAOL_CP1_BE_ID 12 - UAOL_PCM1_NAME 'UAOL1' + UAOL_PCM1_NAME 'USB Offload 1' UAOL_PCM1_ID 22 UAOL_PB1_HOST_PIPELINE_ID 215 UAOL_PB1_DAI_PIPELINE_ID 216 @@ -94,10 +94,10 @@ Define { # The deep buffer PCMs feed the same mixer as the normal playback PCM of # their stream UAOL_DEEP_BUFFER 'true' - UAOL_DB_PCM_NAME 'Deepbuffer UAOL0' + UAOL_DB_PCM_NAME 'Deepbuffer USB Offload 0' UAOL_DB_PCM_ID 23 UAOL_DB_PIPELINE_ID 214 - UAOL_DB1_PCM_NAME 'Deepbuffer UAOL1' + UAOL_DB1_PCM_NAME 'Deepbuffer USB Offload 1' UAOL_DB1_PCM_ID 24 UAOL_DB1_PIPELINE_ID 219 } diff --git a/topology2/development/CMakeLists.txt b/topology2/development/CMakeLists.txt index 89737c7..af5eef0 100644 --- a/topology2/development/CMakeLists.txt +++ b/topology2/development/CMakeLists.txt @@ -23,6 +23,27 @@ foreach(tplg ${TPLGS}) "${CMAKE_CURRENT_SOURCE_DIR}/../${input}" "${output}" "${CMAKE_CURRENT_SOURCE_DIR}/../" "${defines}") - add_custom_target(topology2_dev_${output} DEPENDS ${output}.tplg) + add_custom_target(topology2_dev_${output} DEPENDS ${tplg2_outputs}) add_dependencies(topology2_dev topology2_dev_${output}) endforeach() + +foreach(link ${SYMLINKS}) + list(LENGTH link length) + if(NOT length EQUAL 2) + message(FATAL_ERROR "SYMLINKS entry '${link}' must have exactly 2 elements (link_name;link_target), got ${length}") + endif() + + list(GET link 0 link_name) + list(GET link 1 link_target) + + add_custom_command( + OUTPUT ${link_name}.tplg + COMMAND ${CMAKE_COMMAND} -E create_symlink "${link_target}.tplg" "${link_name}.tplg" + DEPENDS ${link_target}.tplg + VERBATIM + ) + + add_custom_target(topology2_dev_${link_name} DEPENDS ${link_name}.tplg) + add_dependencies(topology2_dev_${link_name} topology2_dev_${link_target}) + add_dependencies(topology2_dev topology2_dev_${link_name}) +endforeach() diff --git a/topology2/development/cavs-nocodec-webrtc-ns.conf b/topology2/development/cavs-nocodec-webrtc-ns.conf index 59c1784..017a9b7 100644 --- a/topology2/development/cavs-nocodec-webrtc-ns.conf +++ b/topology2/development/cavs-nocodec-webrtc-ns.conf @@ -58,6 +58,7 @@ Define { PLATFORM "none" SSP0_PCM_ID 0 SSP0_PCM_NAME "Port0" + WEBRTC_VAD_RATE 16000 } IncludeByKey.PLATFORM { @@ -216,8 +217,8 @@ Object.Pipeline.io-gateway-capture [ Object.Base.output_audio_format [ { out_rate 16000 - out_bit_depth 16 - out_valid_bit_depth 16 + out_bit_depth 32 + out_valid_bit_depth 32 } ] } diff --git a/topology2/development/sof-hda-generic-uaol.conf b/topology2/development/sof-hda-generic-uaol.conf index bb3ffcd..d997a90 100644 --- a/topology2/development/sof-hda-generic-uaol.conf +++ b/topology2/development/sof-hda-generic-uaol.conf @@ -34,8 +34,8 @@ Define { - UAOL_PLAYBACK_PCM 'UAOL0 Playback' - UAOL_CAPTURE_PCM 'UAOL0 Capture' + UAOL_PLAYBACK_PCM 'USB Offload 0 Playback' + UAOL_CAPTURE_PCM 'USB Offload 0 Capture' # The two directions are separate DAI links so that the format fixup of # a link is decided by the DAI copier of that direction alone, and the # link carries two streams per direction, each with a backend of its @@ -52,7 +52,7 @@ Define { UAOL_CP_BE_ID 10 # UAOL_DAI_INDEX is the UAOL link the DSP uses, only link 0 is addressable UAOL_DAI_INDEX 0 - UAOL_PCM_NAME 'UAOL0' + UAOL_PCM_NAME 'USB Offload 0' UAOL_PCM_ID 21 UAOL_PB_HOST_PIPELINE_ID 210 UAOL_PB_DAI_PIPELINE_ID 211 @@ -64,13 +64,13 @@ Define { # routes point at it and the second PCM fails with EBUSY while the first # one runs, a second device or a second PCM of the first lets both run UAOL_NUM_STREAMS 2 - UAOL_PLAYBACK1_PCM 'UAOL1 Playback' - UAOL_CAPTURE1_PCM 'UAOL1 Capture' + UAOL_PLAYBACK1_PCM 'USB Offload 1 Playback' + UAOL_CAPTURE1_PCM 'USB Offload 1 Capture' UAOL_PB1_DAI_NAME 'UAOL0-Play1' UAOL_CP1_DAI_NAME 'UAOL0-Cap1' UAOL_PB1_BE_ID 11 UAOL_CP1_BE_ID 12 - UAOL_PCM1_NAME 'UAOL1' + UAOL_PCM1_NAME 'USB Offload 1' UAOL_PCM1_ID 22 UAOL_PB1_HOST_PIPELINE_ID 215 UAOL_PB1_DAI_PIPELINE_ID 216 @@ -90,10 +90,10 @@ Define { # The deep buffer PCMs feed the same mixer as the normal playback PCM of # their stream, next to the one the HDA playback has UAOL_DEEP_BUFFER 'true' - UAOL_DB_PCM_NAME 'Deepbuffer UAOL0' + UAOL_DB_PCM_NAME 'Deepbuffer USB Offload 0' UAOL_DB_PCM_ID 23 UAOL_DB_PIPELINE_ID 214 - UAOL_DB1_PCM_NAME 'Deepbuffer UAOL1' + UAOL_DB1_PCM_NAME 'Deepbuffer USB Offload 1' UAOL_DB1_PCM_ID 24 UAOL_DB1_PIPELINE_ID 219 } diff --git a/topology2/development/tplg-targets-bench.cmake b/topology2/development/tplg-targets-bench.cmake index 2dd4f28..f3bd0f9 100644 --- a/topology2/development/tplg-targets-bench.cmake +++ b/topology2/development/tplg-targets-bench.cmake @@ -73,10 +73,12 @@ set(component_parameters_s24 set(components_s32 "micsel_multich" + "ffmpeg_dec" ) set(component_parameters_s32 "BENCH_MICSEL_PARAMS=default" + "BENCH_FFMPEG_DEC_PARAMS=default" ) set (plat "mtl") diff --git a/topology2/development/tplg-targets.cmake b/topology2/development/tplg-targets.cmake index ffcffdb..07f9166 100644 --- a/topology2/development/tplg-targets.cmake +++ b/topology2/development/tplg-targets.cmake @@ -221,11 +221,29 @@ DEEPBUFFER_FW_DMA_MS=false,HDA_ANALOG_CAPTURE_RATE=96000,HDA_ANALOG_PLAYBACK_RAT # HDA generic with a compress PCM driven by the FFmpeg (libavcodec) decoder # widget (ffmpeg_dec) instead of the Cadence decoder. COMPR_FFMPEG gates # compr-ffmpeg.conf independently of COMPRESSED (which gates the Cadence +# compr.conf), so the stock compress path stays off here. # Default (COMPR_FFMPEG_CODEC=flac) carries the FLAC STREAMINFO codec-setup -# control; the mp3 and aac variants omit it (both are self-describing streams). +# control; the mp3, aac, and opus variants omit it. "sof-hda-generic\;sof-hda-generic-ffmpeg-compr\;HDA_CONFIG=mix,COMPR_FFMPEG=true" "sof-hda-generic\;sof-hda-generic-ffmpeg-mp3-compr\;HDA_CONFIG=mix,COMPR_FFMPEG=true,COMPR_FFMPEG_CODEC=mp3" "sof-hda-generic\;sof-hda-generic-ffmpeg-aac-compr\;HDA_CONFIG=mix,COMPR_FFMPEG=true,COMPR_FFMPEG_CODEC=aac,COMPR_FFMPEG_DEC_HEAP=901120" +"sof-hda-generic\;sof-hda-generic-ffmpeg-opus-compr\;HDA_CONFIG=mix,COMPR_FFMPEG=true,COMPR_FFMPEG_CODEC=opus,COMPR_FFMPEG_DEC_HEAP=524288" +"sof-hda-generic\;sof-hda-generic-ffmpeg-alac-compr\;HDA_CONFIG=mix,COMPR_FFMPEG=true,COMPR_FFMPEG_CODEC=alac" +"sof-hda-generic\;sof-hda-generic-ffmpeg-sbc-compr\;HDA_CONFIG=mix,COMPR_FFMPEG=true,COMPR_FFMPEG_CODEC=sbc" +"sof-hda-generic\;sof-hda-generic-ffmpeg-g722-compr\;HDA_CONFIG=mix,COMPR_FFMPEG=true,COMPR_FFMPEG_CODEC=g722" +"sof-hda-generic\;sof-hda-generic-ffmpeg-aptx-compr\;HDA_CONFIG=mix,COMPR_FFMPEG=true,COMPR_FFMPEG_CODEC=aptx" +# Compress capture (encode: PCM -> MP3 via libshine, AAC-LC via vo-aacenc, +# lossless FLAC/ALAC, or Bluetooth/voice SBC/G.722/aptX via libavcodec) driven +# by ffmpeg_enc. COMPR_FFMPEG_ENC +# gates compr-capture-ffmpeg.conf, which taps the HDA analog capture BE, so it +# may be built alongside or independently of the decode COMPR_FFMPEG path above. +"sof-hda-generic\;sof-hda-generic-ffmpeg-mp3-enc-compr\;HDA_CONFIG=mix,COMPR_FFMPEG_ENC=true" +"sof-hda-generic\;sof-hda-generic-ffmpeg-aac-enc-compr\;HDA_CONFIG=mix,COMPR_FFMPEG_ENC=true" +"sof-hda-generic\;sof-hda-generic-ffmpeg-flac-enc-compr\;HDA_CONFIG=mix,COMPR_FFMPEG_ENC=true" +"sof-hda-generic\;sof-hda-generic-ffmpeg-alac-enc-compr\;HDA_CONFIG=mix,COMPR_FFMPEG_ENC=true" +"sof-hda-generic\;sof-hda-generic-ffmpeg-sbc-enc-compr\;HDA_CONFIG=mix,COMPR_FFMPEG_ENC=true" +"sof-hda-generic\;sof-hda-generic-ffmpeg-g722-enc-compr\;HDA_CONFIG=mix,COMPR_FFMPEG_ENC=true" +"sof-hda-generic\;sof-hda-generic-ffmpeg-aptx-enc-compr\;HDA_CONFIG=mix,COMPR_FFMPEG_ENC=true" # SDW + DMIC + HDMI, with 16 kHz DMIC1 "cavs-sdw\;sof-mtl-sdw-cs42l42-l0-max98363-l2-4ch-48k-16k\;PLATFORM=mtl,\ @@ -440,6 +458,10 @@ EFX_DMIC0_TDFB_PARAMS=line2_generic_pm10deg,EFX_DMIC0_DRC_PARAMS=dmic_default" NUM_DMICS=4,PDM1_MIC_A_ENABLE=1,PDM1_MIC_B_ENABLE=1,DMIC0_DEEP_BUFFER=true,DEEPBUFFER_FW_DMA_MS=10,\ DMIC0_ENHANCED_CAPTURE=true,EFX_DMIC0_TDFB_PARAMS=line4_pass,EFX_DMIC0_DRC_PARAMS=dmic_default" +"sof-hda-generic\;sof-hda-generic-ace3-hdmi-in-port12\;PLATFORM=ptl,HDA_CONFIG=mix,HDMI_IN_CAPTURE=true,\ +HDMI_IN_1_INDEX=1,HDMI_IN_2_INDEX=2,HDMI_IN_1_NAME=SSP1-HDMI,HDMI_IN_1_ID=13,HDMI_IN_2_ID=14,\ +PREPROCESS_PLUGINS=nhlt,NHLT_BIN=nhlt-sof-hda-generic-ace3-hdmi-in-port12.bin" + # Deep buffer DMIC0 with tplg NHLT for PTL, 2ch and 4ch "sof-hda-generic\;sof-hda-generic-ace3-2ch-dmicdeepbuf\;PLATFORM=ptl,HDA_CONFIG=mix,NUM_DMICS=2,\ PREPROCESS_PLUGINS=nhlt,NHLT_BIN=nhlt-sof-hda-generic-ace3-2ch-dmicdeepbuf.bin,\ @@ -471,6 +493,13 @@ PREPROCESS_PLUGINS=nhlt,NHLT_BIN=nhlt-sof-ptl-rt721-4ch-echoref.bin,DMIC0_ENHANC EFX_DMIC0_TDFB_PARAMS=line4_pass,EFX_DMIC0_DRC_PARAMS=dmic_default,\ DEEPBUFFER_FW_DMA_MS=10,DEEP_BUF_SPK=true,SDW_JACK_ECHO_REF=true,SDW_SPK_ECHO_REF=true,SDW_ECHO_REF_DAI=true" +# RT713 headset on link 3 and RT1320 amplifiers on links 1 and 2 with mono +# 16 kHz WebRTC AEC of the SoundWire DMIC against the speaker echo reference +"cavs-sdw\;sof-ptl-rt713-l3-rt1320-l12-aec\;PLATFORM=ptl,SDW_DMIC=1,NUM_SDW_AMP_LINKS=2,\ +SDW_AMP_FEEDBACK=false,SDW_SPK_STREAM=Playback-SmartAmp,SDW_DMIC_STREAM=Capture-SmartMic,\ +SDW_JACK_OUT_STREAM=Playback-SimpleJack,SDW_JACK_IN_STREAM=Capture-SimpleJack,\ +SDW_SPK_ECHO_REF=true,SDW_ECHO_REF_DAI=true,SDW_SPK_AEC_CAPTURE_PCM=true" + # RT721 eval board with PCH-DMIC, sof_sdw_quirk_table with SOC_SDW_PCH_DMIC # Enable echo reference capture from jack and speaker output # Enable SSP2 BT @@ -555,4 +584,144 @@ COMPRESSED_1=true,COMPRESSED_2=false" "cavs-sdw\;sof-sdca-amp-compr\;SDW_JACK=false,NUM_HDMIS=0,COMPRESSED=true,\ COMPRESSED_1=false,COMPRESSED_2=true" +# Bluetooth SSP2-BT offload development topologies for HDA platforms +"sof-hda-generic\;sof-hda-generic-ace1-bt\;PLATFORM=mtl,HDA_CONFIG=mix,HDA_MIC_ENHANCED_CAPTURE=true,\ +PREPROCESS_PLUGINS=nhlt,NHLT_BIN=nhlt-sof-hda-generic-ace1-bt.bin,\ +BT_PCM_ID=20,BT_ID=8,BT_PCM_NAME=Bluetooth,ADD_BT=true,BT_DEEP_BUFFER=true,BT_SSP_DUPLEX=true,\ +BT_PB_HOST_PIPELINE_ID=200,BT_PB_DAI_PIPELINE_ID=201,BT_CP_HOST_PIPELINE_ID=202,BT_CP_DAI_PIPELINE_ID=203,\ +EFX_HDA_MIC_TDFB_PARAMS=line2_pass,EFX_HDA_MIC_DRC_PARAMS=passthrough" + +"sof-hda-generic\;sof-hda-generic-ace3-bt\;PLATFORM=ptl,HDA_CONFIG=mix,HDA_MIC_ENHANCED_CAPTURE=true,\ +PREPROCESS_PLUGINS=nhlt,NHLT_BIN=nhlt-sof-hda-generic-ace3-bt.bin,\ +BT_PCM_ID=20,BT_ID=8,BT_PCM_NAME=Bluetooth,ADD_BT=true,BT_DEEP_BUFFER=true,BT_SSP_DUPLEX=true,\ +BT_PB_HOST_PIPELINE_ID=200,BT_PB_DAI_PIPELINE_ID=201,BT_CP_HOST_PIPELINE_ID=202,BT_CP_DAI_PIPELINE_ID=203,\ +EFX_HDA_MIC_TDFB_PARAMS=line2_pass,EFX_HDA_MIC_DRC_PARAMS=passthrough" + +"sof-hda-generic\;sof-hda-generic-ace3-2ch-bt\;PLATFORM=ptl,HDA_CONFIG=mix,NUM_DMICS=2,\ +BT_PCM_ID=20,BT_ID=8,BT_PCM_NAME=Bluetooth,ADD_BT=true,BT_DEEP_BUFFER=true,BT_SSP_DUPLEX=true,\ +BT_PB_HOST_PIPELINE_ID=200,BT_PB_DAI_PIPELINE_ID=201,BT_CP_HOST_PIPELINE_ID=202,BT_CP_DAI_PIPELINE_ID=203,\ +PREPROCESS_PLUGINS=nhlt,NHLT_BIN=nhlt-sof-hda-generic-ace3-2ch-bt.bin,\ +DMIC0_ENHANCED_CAPTURE=true,EFX_DMIC0_TDFB_PARAMS=line2_generic_pm10deg,\ +EFX_DMIC0_DRC_PARAMS=dmic_default" + +"sof-hda-generic\;sof-hda-generic-ace3-4ch-bt\;PLATFORM=ptl,HDA_CONFIG=mix,NUM_DMICS=4,\ +PDM1_MIC_A_ENABLE=1,PDM1_MIC_B_ENABLE=1,\ +BT_PCM_ID=20,BT_ID=8,BT_PCM_NAME=Bluetooth,ADD_BT=true,BT_DEEP_BUFFER=true,BT_SSP_DUPLEX=true,\ +BT_PB_HOST_PIPELINE_ID=200,BT_PB_DAI_PIPELINE_ID=201,BT_CP_HOST_PIPELINE_ID=202,BT_CP_DAI_PIPELINE_ID=203,\ +PREPROCESS_PLUGINS=nhlt,NHLT_BIN=nhlt-sof-hda-generic-ace3-4ch-bt.bin,DMIC0_ENHANCED_CAPTURE=true,\ +EFX_DMIC0_TDFB_PARAMS=line4_pass,EFX_DMIC0_DRC_PARAMS=dmic_default" + +# SOF Bluetooth Transparent codec development topologies for ACE3 HDA platforms +"sof-hda-generic\;sof-hda-generic-ace3-bt-lc3\;PLATFORM=ptl,HDA_CONFIG=mix,HDA_MIC_ENHANCED_CAPTURE=true,\ +PREPROCESS_PLUGINS=nhlt,NHLT_BIN=nhlt-sof-hda-generic-ace3-bt-lc3.bin,\ +BT_PCM_ID=20,BT_ID=8,BT_PCM_NAME=Bluetooth,ADD_BT=true,BT_DEEP_BUFFER=true,BT_SSP_DUPLEX=true,BT_TRANSP_CODEC=lc3,\ +BT_PB_HOST_PIPELINE_ID=200,BT_PB_DAI_PIPELINE_ID=201,BT_CP_HOST_PIPELINE_ID=202,BT_CP_DAI_PIPELINE_ID=203,\ +EFX_HDA_MIC_TDFB_PARAMS=line2_pass,EFX_HDA_MIC_DRC_PARAMS=passthrough" + +"sof-hda-generic\;sof-hda-generic-ace3-bt-msbc\;PLATFORM=ptl,HDA_CONFIG=mix,HDA_MIC_ENHANCED_CAPTURE=true,\ +PREPROCESS_PLUGINS=nhlt,NHLT_BIN=nhlt-sof-hda-generic-ace3-bt-msbc.bin,\ +BT_PCM_ID=20,BT_ID=8,BT_PCM_NAME=Bluetooth,ADD_BT=true,BT_DEEP_BUFFER=true,BT_SSP_DUPLEX=true,BT_TRANSP_CODEC=msbc,\ +BT_PB_HOST_PIPELINE_ID=200,BT_PB_DAI_PIPELINE_ID=201,BT_CP_HOST_PIPELINE_ID=202,BT_CP_DAI_PIPELINE_ID=203,\ +EFX_HDA_MIC_TDFB_PARAMS=line2_pass,EFX_HDA_MIC_DRC_PARAMS=passthrough" + +"sof-hda-generic\;sof-hda-generic-ace3-bt-g722\;PLATFORM=ptl,HDA_CONFIG=mix,HDA_MIC_ENHANCED_CAPTURE=true,\ +PREPROCESS_PLUGINS=nhlt,NHLT_BIN=nhlt-sof-hda-generic-ace3-bt-g722.bin,\ +BT_PCM_ID=20,BT_ID=8,BT_PCM_NAME=Bluetooth,ADD_BT=true,BT_DEEP_BUFFER=true,BT_SSP_DUPLEX=true,BT_TRANSP_CODEC=g722,\ +BT_PB_HOST_PIPELINE_ID=200,BT_PB_DAI_PIPELINE_ID=201,BT_CP_HOST_PIPELINE_ID=202,BT_CP_DAI_PIPELINE_ID=203,\ +EFX_HDA_MIC_TDFB_PARAMS=line2_pass,EFX_HDA_MIC_DRC_PARAMS=passthrough" + +"sof-hda-generic\;sof-hda-generic-ace3-bt-sb4\;PLATFORM=ptl,HDA_CONFIG=mix,HDA_MIC_ENHANCED_CAPTURE=true,\ +PREPROCESS_PLUGINS=nhlt,NHLT_BIN=nhlt-sof-hda-generic-ace3-bt-sb4.bin,\ +BT_PCM_ID=20,BT_ID=8,BT_PCM_NAME=Bluetooth,ADD_BT=true,BT_DEEP_BUFFER=true,BT_SSP_DUPLEX=true,BT_TRANSP_CODEC=sb4,\ +BT_PB_HOST_PIPELINE_ID=200,BT_PB_DAI_PIPELINE_ID=201,BT_CP_HOST_PIPELINE_ID=202,BT_CP_DAI_PIPELINE_ID=203,\ +EFX_HDA_MIC_TDFB_PARAMS=line2_pass,EFX_HDA_MIC_DRC_PARAMS=passthrough" + +# Bluetooth SSP2-BT offload and Transparent codec development topologies for ACE3 RT722 / SSP2 +"cavs-sdw\;sof-ptl-rt722-4ch-bt\;PLATFORM=ptl,SDW_DMIC=1,NUM_SDW_AMP_LINKS=1,NUM_DMICS=4,\ +PDM1_MIC_A_ENABLE=1,PDM1_MIC_B_ENABLE=1,DMIC0_ID=5,DMIC1_ID=6,HDMI1_ID=7,HDMI2_ID=8,HDMI3_ID=9,\ +SDW_AMP_FEEDBACK=false,SDW_SPK_STREAM=Playback-SmartAmp,SDW_DMIC_STREAM=Capture-SmartMic,\ +SDW_JACK_OUT_STREAM=Playback-SimpleJack,SDW_JACK_IN_STREAM=Capture-SimpleJack,\ +PREPROCESS_PLUGINS=nhlt,NHLT_BIN=nhlt-sof-ptl-rt722-4ch-bt.bin,DMIC0_ENHANCED_CAPTURE=true,\ +EFX_DMIC0_TDFB_PARAMS=line4_pass,EFX_DMIC0_DRC_PARAMS=dmic_default,\ +BT_PCM_ID=20,BT_ID=10,BT_PCM_NAME=Bluetooth,ADD_BT=true,BT_DEEP_BUFFER=true,BT_SSP_DUPLEX=true,\ +BT_PB_HOST_PIPELINE_ID=200,BT_PB_DAI_PIPELINE_ID=201,BT_CP_HOST_PIPELINE_ID=202,BT_CP_DAI_PIPELINE_ID=203" + +"cavs-sdw\;sof-ptl-rt722-4ch-bt-lc3\;PLATFORM=ptl,SDW_DMIC=1,NUM_SDW_AMP_LINKS=1,NUM_DMICS=4,\ +PDM1_MIC_A_ENABLE=1,PDM1_MIC_B_ENABLE=1,DMIC0_ID=5,DMIC1_ID=6,HDMI1_ID=7,HDMI2_ID=8,HDMI3_ID=9,\ +SDW_AMP_FEEDBACK=false,SDW_SPK_STREAM=Playback-SmartAmp,SDW_DMIC_STREAM=Capture-SmartMic,\ +SDW_JACK_OUT_STREAM=Playback-SimpleJack,SDW_JACK_IN_STREAM=Capture-SimpleJack,\ +PREPROCESS_PLUGINS=nhlt,NHLT_BIN=nhlt-sof-ptl-rt722-4ch-bt-lc3.bin,DMIC0_ENHANCED_CAPTURE=true,\ +EFX_DMIC0_TDFB_PARAMS=line4_pass,EFX_DMIC0_DRC_PARAMS=dmic_default,\ +BT_PCM_ID=20,BT_ID=10,BT_PCM_NAME=Bluetooth,ADD_BT=true,BT_DEEP_BUFFER=true,BT_SSP_DUPLEX=true,BT_TRANSP_CODEC=lc3,\ +BT_PB_HOST_PIPELINE_ID=200,BT_PB_DAI_PIPELINE_ID=201,BT_CP_HOST_PIPELINE_ID=202,BT_CP_DAI_PIPELINE_ID=203" + +"cavs-sdw\;sof-ptl-rt722-4ch-bt-msbc\;PLATFORM=ptl,SDW_DMIC=1,NUM_SDW_AMP_LINKS=1,NUM_DMICS=4,\ +PDM1_MIC_A_ENABLE=1,PDM1_MIC_B_ENABLE=1,DMIC0_ID=5,DMIC1_ID=6,HDMI1_ID=7,HDMI2_ID=8,HDMI3_ID=9,\ +SDW_AMP_FEEDBACK=false,SDW_SPK_STREAM=Playback-SmartAmp,SDW_DMIC_STREAM=Capture-SmartMic,\ +SDW_JACK_OUT_STREAM=Playback-SimpleJack,SDW_JACK_IN_STREAM=Capture-SimpleJack,\ +PREPROCESS_PLUGINS=nhlt,NHLT_BIN=nhlt-sof-ptl-rt722-4ch-bt-msbc.bin,DMIC0_ENHANCED_CAPTURE=true,\ +EFX_DMIC0_TDFB_PARAMS=line4_pass,EFX_DMIC0_DRC_PARAMS=dmic_default,\ +BT_PCM_ID=20,BT_ID=10,BT_PCM_NAME=Bluetooth,ADD_BT=true,BT_DEEP_BUFFER=true,BT_SSP_DUPLEX=true,BT_TRANSP_CODEC=msbc,\ +BT_PB_HOST_PIPELINE_ID=200,BT_PB_DAI_PIPELINE_ID=201,BT_CP_HOST_PIPELINE_ID=202,BT_CP_DAI_PIPELINE_ID=203" + +"cavs-sdw\;sof-ptl-rt722-4ch-bt-g722\;PLATFORM=ptl,SDW_DMIC=1,NUM_SDW_AMP_LINKS=1,NUM_DMICS=4,\ +PDM1_MIC_A_ENABLE=1,PDM1_MIC_B_ENABLE=1,DMIC0_ID=5,DMIC1_ID=6,HDMI1_ID=7,HDMI2_ID=8,HDMI3_ID=9,\ +SDW_AMP_FEEDBACK=false,SDW_SPK_STREAM=Playback-SmartAmp,SDW_DMIC_STREAM=Capture-SmartMic,\ +SDW_JACK_OUT_STREAM=Playback-SimpleJack,SDW_JACK_IN_STREAM=Capture-SimpleJack,\ +PREPROCESS_PLUGINS=nhlt,NHLT_BIN=nhlt-sof-ptl-rt722-4ch-bt-g722.bin,DMIC0_ENHANCED_CAPTURE=true,\ +EFX_DMIC0_TDFB_PARAMS=line4_pass,EFX_DMIC0_DRC_PARAMS=dmic_default,\ +BT_PCM_ID=20,BT_ID=10,BT_PCM_NAME=Bluetooth,ADD_BT=true,BT_DEEP_BUFFER=true,BT_SSP_DUPLEX=true,BT_TRANSP_CODEC=g722,\ +BT_PB_HOST_PIPELINE_ID=200,BT_PB_DAI_PIPELINE_ID=201,BT_CP_HOST_PIPELINE_ID=202,BT_CP_DAI_PIPELINE_ID=203" + +"cavs-sdw\;sof-ptl-rt722-4ch-bt-sb4\;PLATFORM=ptl,SDW_DMIC=1,NUM_SDW_AMP_LINKS=1,NUM_DMICS=4,\ +PDM1_MIC_A_ENABLE=1,PDM1_MIC_B_ENABLE=1,DMIC0_ID=5,DMIC1_ID=6,HDMI1_ID=7,HDMI2_ID=8,HDMI3_ID=9,\ +SDW_AMP_FEEDBACK=false,SDW_SPK_STREAM=Playback-SmartAmp,SDW_DMIC_STREAM=Capture-SmartMic,\ +SDW_JACK_OUT_STREAM=Playback-SimpleJack,SDW_JACK_IN_STREAM=Capture-SimpleJack,\ +PREPROCESS_PLUGINS=nhlt,NHLT_BIN=nhlt-sof-ptl-rt722-4ch-bt-sb4.bin,DMIC0_ENHANCED_CAPTURE=true,\ +EFX_DMIC0_TDFB_PARAMS=line4_pass,EFX_DMIC0_DRC_PARAMS=dmic_default,\ +BT_PCM_ID=20,BT_ID=10,BT_PCM_NAME=Bluetooth,ADD_BT=true,BT_DEEP_BUFFER=true,BT_SSP_DUPLEX=true,BT_TRANSP_CODEC=sb4,\ +BT_PB_HOST_PIPELINE_ID=200,BT_PB_DAI_PIPELINE_ID=201,BT_CP_HOST_PIPELINE_ID=202,BT_CP_DAI_PIPELINE_ID=203" + +"cavs-sdw\;sof-ptl-ssp2-bt-id10\;PLATFORM=ptl,ADD_BT=true,BT_DEEP_BUFFER=true,BT_SSP_DUPLEX=true,\ +SDW_JACK=false,NUM_HDMIS=0,HEADSET_CODEC=false,HDMI_IN_CAPTURE=false,BT_ID=10,BT_PCM_ID=20,BT_PCM_NAME=Bluetooth,\ +BT_PB_HOST_PIPELINE_ID=200,BT_PB_DAI_PIPELINE_ID=201,BT_CP_HOST_PIPELINE_ID=202,BT_CP_DAI_PIPELINE_ID=203,\ +PREPROCESS_PLUGINS=nhlt,NHLT_BIN=nhlt-sof-ptl-ssp2-bt-id10.bin" + +"cavs-sdw\;sof-ptl-ssp2-bt-id10-lc3\;PLATFORM=ptl,ADD_BT=true,BT_DEEP_BUFFER=true,BT_SSP_DUPLEX=true,\ +SDW_JACK=false,NUM_HDMIS=0,HEADSET_CODEC=false,HDMI_IN_CAPTURE=false,BT_ID=10,BT_PCM_ID=20,BT_PCM_NAME=Bluetooth,\ +BT_PB_HOST_PIPELINE_ID=200,BT_PB_DAI_PIPELINE_ID=201,BT_CP_HOST_PIPELINE_ID=202,BT_CP_DAI_PIPELINE_ID=203,\ +PREPROCESS_PLUGINS=nhlt,NHLT_BIN=nhlt-sof-ptl-ssp2-bt-id10-lc3.bin,\ +BT_TRANSP_CODEC=lc3" + +"cavs-sdw\;sof-ptl-ssp2-bt-id10-msbc\;PLATFORM=ptl,ADD_BT=true,BT_DEEP_BUFFER=true,BT_SSP_DUPLEX=true,\ +SDW_JACK=false,NUM_HDMIS=0,HEADSET_CODEC=false,HDMI_IN_CAPTURE=false,BT_ID=10,BT_PCM_ID=20,BT_PCM_NAME=Bluetooth,\ +BT_PB_HOST_PIPELINE_ID=200,BT_PB_DAI_PIPELINE_ID=201,BT_CP_HOST_PIPELINE_ID=202,BT_CP_DAI_PIPELINE_ID=203,\ +PREPROCESS_PLUGINS=nhlt,NHLT_BIN=nhlt-sof-ptl-ssp2-bt-id10-msbc.bin,\ +BT_TRANSP_CODEC=msbc" + +"cavs-sdw\;sof-ptl-ssp2-bt-id10-g722\;PLATFORM=ptl,ADD_BT=true,BT_DEEP_BUFFER=true,BT_SSP_DUPLEX=true,\ +SDW_JACK=false,NUM_HDMIS=0,HEADSET_CODEC=false,HDMI_IN_CAPTURE=false,BT_ID=10,BT_PCM_ID=20,BT_PCM_NAME=Bluetooth,\ +BT_PB_HOST_PIPELINE_ID=200,BT_PB_DAI_PIPELINE_ID=201,BT_CP_HOST_PIPELINE_ID=202,BT_CP_DAI_PIPELINE_ID=203,\ +PREPROCESS_PLUGINS=nhlt,NHLT_BIN=nhlt-sof-ptl-ssp2-bt-id10-g722.bin,\ +BT_TRANSP_CODEC=g722" + +"cavs-sdw\;sof-ptl-ssp2-bt-id10-sb4\;PLATFORM=ptl,ADD_BT=true,BT_DEEP_BUFFER=true,BT_SSP_DUPLEX=true,\ +SDW_JACK=false,NUM_HDMIS=0,HEADSET_CODEC=false,HDMI_IN_CAPTURE=false,BT_ID=10,BT_PCM_ID=20,BT_PCM_NAME=Bluetooth,\ +BT_PB_HOST_PIPELINE_ID=200,BT_PB_DAI_PIPELINE_ID=201,BT_CP_HOST_PIPELINE_ID=202,BT_CP_DAI_PIPELINE_ID=203,\ +PREPROCESS_PLUGINS=nhlt,NHLT_BIN=nhlt-sof-ptl-ssp2-bt-id10-sb4.bin,\ +BT_TRANSP_CODEC=sb4" + +) + +list(APPEND SYMLINKS +"sof-wcl-rt722-4ch-bt\;sof-ptl-rt722-4ch-bt" +"sof-wcl-rt722-4ch-bt-lc3\;sof-ptl-rt722-4ch-bt-lc3" +"sof-wcl-rt722-4ch-bt-msbc\;sof-ptl-rt722-4ch-bt-msbc" +"sof-wcl-rt722-4ch-bt-g722\;sof-ptl-rt722-4ch-bt-g722" +"sof-wcl-rt722-4ch-bt-sb4\;sof-ptl-rt722-4ch-bt-sb4" +"sof-wcl-ssp2-bt-id10\;sof-ptl-ssp2-bt-id10" +"sof-wcl-ssp2-bt-id10-lc3\;sof-ptl-ssp2-bt-id10-lc3" +"sof-wcl-ssp2-bt-id10-msbc\;sof-ptl-ssp2-bt-id10-msbc" +"sof-wcl-ssp2-bt-id10-g722\;sof-ptl-ssp2-bt-id10-g722" +"sof-wcl-ssp2-bt-id10-sb4\;sof-ptl-ssp2-bt-id10-sb4" ) diff --git a/topology2/include/bench/ffmpeg_dec_controls_playback.conf b/topology2/include/bench/ffmpeg_dec_controls_playback.conf new file mode 100644 index 0000000..478f172 --- /dev/null +++ b/topology2/include/bench/ffmpeg_dec_controls_playback.conf @@ -0,0 +1,17 @@ + # Created initially with script "bench_comp_generate.sh ffmpeg_dec" + # may need edits to modify controls + Object.Control { + # Un-comment the supported controls in FFMPEG_DEC + #bytes."1" { + # name '$ANALOG_PLAYBACK_PCM FFMPEG_DEC bytes' + # IncludeByKey.BENCH_FFMPEG_DEC_PARAMS { + # "default" "include/components/ffmpeg_dec/default.conf" + # } + #} + #mixer."1" { + # name '$ANALOG_PLAYBACK_PCM FFMPEG_DEC switch or volume' + #} + #enum."1" { + # name '$ANALOG_PLAYBACK_PCM FFMPEG_DEC enum' + #} + } diff --git a/topology2/include/bench/ffmpeg_dec_route.conf b/topology2/include/bench/ffmpeg_dec_route.conf new file mode 100644 index 0000000..f558431 --- /dev/null +++ b/topology2/include/bench/ffmpeg_dec_route.conf @@ -0,0 +1,15 @@ + # Created with script "bench_comp_generate.sh ffmpeg_dec" + Object.Base.route [ + { + sink '$BENCH_PLAYBACK_DAI_COPIER' + source 'ffmpeg_dec.$BENCH_PLAYBACK_HOST_PIPELINE.1' + } + { + sink 'ffmpeg_dec.$BENCH_PLAYBACK_HOST_PIPELINE.1' + source 'host-copier.0.playback' + } + { + source '$BENCH_CAPTURE_DAI_COPIER' + sink 'host-copier.0.capture' + } + ] diff --git a/topology2/include/bench/ffmpeg_dec_s16.conf b/topology2/include/bench/ffmpeg_dec_s16.conf new file mode 100644 index 0000000..1e341be --- /dev/null +++ b/topology2/include/bench/ffmpeg_dec_s16.conf @@ -0,0 +1,11 @@ + # Created with script "bench_comp_generate.sh ffmpeg_dec" + Object.Widget.ffmpeg_dec.1 { + index $BENCH_PLAYBACK_HOST_PIPELINE + scheduler_domain "DP" + stack_bytes_requirement 65536 + heap_bytes_requirement 524288 + + + } + + diff --git a/topology2/include/bench/ffmpeg_dec_s24.conf b/topology2/include/bench/ffmpeg_dec_s24.conf new file mode 100644 index 0000000..537c5c6 --- /dev/null +++ b/topology2/include/bench/ffmpeg_dec_s24.conf @@ -0,0 +1,11 @@ + # Created with script "bench_comp_generate.sh ffmpeg_dec" + Object.Widget.ffmpeg_dec.1 { + index $BENCH_PLAYBACK_HOST_PIPELINE + scheduler_domain "DP" + stack_bytes_requirement 65536 + heap_bytes_requirement 524288 + + + } + + diff --git a/topology2/include/bench/ffmpeg_dec_s32.conf b/topology2/include/bench/ffmpeg_dec_s32.conf new file mode 100644 index 0000000..c0cf5ee --- /dev/null +++ b/topology2/include/bench/ffmpeg_dec_s32.conf @@ -0,0 +1,11 @@ + # Created with script "bench_comp_generate.sh ffmpeg_dec" + Object.Widget.ffmpeg_dec.1 { + index $BENCH_PLAYBACK_HOST_PIPELINE + scheduler_domain "DP" + stack_bytes_requirement 65536 + heap_bytes_requirement 524288 + + + } + + diff --git a/topology2/include/components/bt-codec-formats.conf b/topology2/include/components/bt-codec-formats.conf new file mode 100644 index 0000000..3de7166 --- /dev/null +++ b/topology2/include/components/bt-codec-formats.conf @@ -0,0 +1,28 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Capture Transparent decoder audio formats: +# 8 kHz 1ch S16_LE SSP wire input -> 8 kHz or 16 kHz 1ch S16_LE host output. + num_input_audio_formats 1 + num_output_audio_formats 2 + Object.Base.input_audio_format [ + { + in_rate 8000 + in_bit_depth 16 + in_valid_bit_depth 16 + in_channels 1 + in_ch_cfg $CHANNEL_CONFIG_MONO + in_ch_map $CHANNEL_MAP_MONO + } + ] + CombineArrays.Object.Base.output_audio_format [ + { + out_rate [ + 8000 + 16000 + ] + out_bit_depth [ 16 ] + out_valid_bit_depth [ 16 ] + out_channels [ 1 ] + out_ch_cfg [ $CHANNEL_CONFIG_MONO ] + out_ch_map [ $CHANNEL_MAP_MONO ] + } + ] diff --git a/topology2/include/components/bt-g722.conf b/topology2/include/components/bt-g722.conf new file mode 100644 index 0000000..7bb4640 --- /dev/null +++ b/topology2/include/components/bt-g722.conf @@ -0,0 +1,44 @@ +# SPDX-License-Identifier: BSD-3-Clause +# +# Bluetooth Transparent Mode G.722 DSP Codec component (ITU-T G.722 64 kbps SB-ADPCM) +# + +Class.Widget."bt_g722" { + DefineAttribute."index" { + type "integer" + } + + DefineAttribute."instance" { + type "integer" + } + + + + attributes { + !constructor [ + "index" + "instance" + ] + !mandatory [ + "num_input_pins" + "num_output_pins" + "num_input_audio_formats" + "num_output_audio_formats" + ] + !immutable [ + "uuid" + "type" + ] + !deprecated [ + "preload_count" + ] + unique "instance" + } + + # 47373232-b700-4a10-8000010203040503 + uuid "32:32:37:47:00:b7:10:4a:80:00:01:02:03:04:05:03" + type "effect" + no_pm "true" + num_input_pins 1 + num_output_pins 1 +} diff --git a/topology2/include/components/bt-lc3.conf b/topology2/include/components/bt-lc3.conf new file mode 100644 index 0000000..f6aabd5 --- /dev/null +++ b/topology2/include/components/bt-lc3.conf @@ -0,0 +1,44 @@ +# SPDX-License-Identifier: BSD-3-Clause +# +# Bluetooth Transparent Mode LC3 DSP Codec component (Zephyr liblc3) +# + +Class.Widget."bt_lc3" { + DefineAttribute."index" { + type "integer" + } + + DefineAttribute."instance" { + type "integer" + } + + + + attributes { + !constructor [ + "index" + "instance" + ] + !mandatory [ + "num_input_pins" + "num_output_pins" + "num_input_audio_formats" + "num_output_audio_formats" + ] + !immutable [ + "uuid" + "type" + ] + !deprecated [ + "preload_count" + ] + unique "instance" + } + + # 4c433301-b700-4a10-8000010203040501 + uuid "01:33:43:4c:00:b7:10:4a:80:00:01:02:03:04:05:01" + type "effect" + no_pm "true" + num_input_pins 1 + num_output_pins 1 +} diff --git a/topology2/include/components/bt-msbc.conf b/topology2/include/components/bt-msbc.conf new file mode 100644 index 0000000..13f49e7 --- /dev/null +++ b/topology2/include/components/bt-msbc.conf @@ -0,0 +1,44 @@ +# SPDX-License-Identifier: BSD-3-Clause +# +# Bluetooth Transparent Mode mSBC DSP Codec component (HFP H2-framed mSBC) +# + +Class.Widget."bt_msbc" { + DefineAttribute."index" { + type "integer" + } + + DefineAttribute."instance" { + type "integer" + } + + + + attributes { + !constructor [ + "index" + "instance" + ] + !mandatory [ + "num_input_pins" + "num_output_pins" + "num_input_audio_formats" + "num_output_audio_formats" + ] + !immutable [ + "uuid" + "type" + ] + !deprecated [ + "preload_count" + ] + unique "instance" + } + + # 4d534243-b700-4a10-8000010203040502 + uuid "43:42:53:4d:00:b7:10:4a:80:00:01:02:03:04:05:02" + type "effect" + no_pm "true" + num_input_pins 1 + num_output_pins 1 +} diff --git a/topology2/include/components/bt-sb4.conf b/topology2/include/components/bt-sb4.conf new file mode 100644 index 0000000..9a6313d --- /dev/null +++ b/topology2/include/components/bt-sb4.conf @@ -0,0 +1,44 @@ +# SPDX-License-Identifier: BSD-3-Clause +# +# Bluetooth Transparent Mode SB4 DSP Codec component (experimental 4-band QMF ADPCM) +# + +Class.Widget."bt_sb4" { + DefineAttribute."index" { + type "integer" + } + + DefineAttribute."instance" { + type "integer" + } + + + + attributes { + !constructor [ + "index" + "instance" + ] + !mandatory [ + "num_input_pins" + "num_output_pins" + "num_input_audio_formats" + "num_output_audio_formats" + ] + !immutable [ + "uuid" + "type" + ] + !deprecated [ + "preload_count" + ] + unique "instance" + } + + # 53423401-b700-4a10-8000010203040504 + uuid "01:34:42:53:00:b7:10:4a:80:00:01:02:03:04:05:04" + type "effect" + no_pm "true" + num_input_pins 1 + num_output_pins 1 +} diff --git a/topology2/include/components/ffmpeg_enc.conf b/topology2/include/components/ffmpeg_enc.conf new file mode 100644 index 0000000..c04307e --- /dev/null +++ b/topology2/include/components/ffmpeg_enc.conf @@ -0,0 +1,109 @@ +# +# Common widget ffmpeg_enc +# +# A generic FFmpeg (libavcodec) encoder widget. It wraps the SAME firmware +# module as ffmpeg_dec (identical UUID) but carries the DAPM widget type +# "encoder" instead of "decoder". All attributes defined herein are namespaced +# by alsatplg to "Object.Widget.ffmpeg_enc.N.attribute_name". +# +# Usage: this component can be used by instantiating it in the parent object. i.e. +# +# Object.Widget.ffmpeg_enc."N" { +# index 1 +# type "encoder" +# } +# +# Where N is the unique instance number for the ffmpeg_enc object within the +# same alsaconf node. +# +# The module encodes interleaved PCM to a compressed elementary stream (MP3 via +# libshine or AAC-LC via vo-aacenc). Both streams are self-describing (MPEG +# audio frame headers / ADTS headers), so no codec-setup (extradata) control is +# needed on the widget. +# + +Class.Widget."ffmpeg_enc" { + # + # Pipeline ID for the ffmpeg_dec widget object + # + DefineAttribute."index" { + type "integer" + } + + # + # Unique instance for ffmpeg_dec widget + # + DefineAttribute."instance" { + type "integer" + } + + #include common component definition + + + DefineAttribute."cpc" { + # Token set reference name and type + token_ref "comp.word" + } + + # NOTE: this is a 1-in/1-out module-adapter with the DAPM widget type + # "encoder" (snd_soc_dapm_encoder). The compress kernel path + # (sof_ipc4_compr_get_module) only recognises the codec module in a + # compress pipeline when its DAPM id is decoder/encoder, so the type must + # be "encoder" (not "effect") for the module to be found and configured. + # MP3 and ADTS AAC are self-describing, so unlike a decoder no codec-setup + # (extradata) bytes control is needed here. + + # Attribute categories + attributes { + # + # The ffmpeg_dec widget name is constructed from the index and instance. + # + !constructor [ + "index" + "instance" + ] + + # + # mandatory attributes that must be provided when the class is instantiated + # + !mandatory [ + "no_pm" + "uuid" + "num_input_audio_formats" + "num_output_audio_formats" + ] + + # + # immutable attributes cannot be modified in the object instance + # + !immutable [ + "type" + ] + + # + # deprecated attributes should not be added in the object instance + # + !deprecated [ + "preload_count" + ] + + # + # ffmpeg_dec widget objects instantiated within the same alsaconf node + # must have a unique instance attribute + # + unique "instance" + } + + # Default attribute values for the ffmpeg_dec widget. + # + # UUID (registry name "ffmpeg_dec") in SOF topology byte order. Must match the + # UUID the firmware registers for this module. Can be overridden in the + # top-level topology file. + uuid "73:af:07:12:c0:f9:65:4f:92:b4:9d:45:17:8f:c9:a8" + type "encoder" + no_pm "true" + core_id 0 + cpc 5000 + num_input_pins 1 + num_output_pins 1 +} diff --git a/topology2/include/components/webrtc-aec.conf b/topology2/include/components/webrtc-aec.conf index f83f8cd..99c628a 100644 --- a/topology2/include/components/webrtc-aec.conf +++ b/topology2/include/components/webrtc-aec.conf @@ -61,6 +61,7 @@ Class.Widget."webrtc-aec" { !immutable [ "uuid" "type" + "scheduler_domain" ] !deprecated [ @@ -135,10 +136,13 @@ Class.Widget."webrtc-aec" { ] # UUID: e5da7b5b-133a-ba46-b517651d6300bb83 - uuid "5b:7b:da:e5:3a:13:46:ba:b5:17:65:1d:63:00:bb:83" - type "effect" - no_pm "true" - cpc 2000 + uuid "5b:7b:da:e5:3a:13:46:ba:b5:17:65:1d:63:00:bb:83" + type "effect" + no_pm "true" + cpc 2000 + scheduler_domain "DP" + stack_bytes_requirement 16384 + heap_bytes_requirement 262144 num_input_pins 2 num_output_pins 1 } diff --git a/topology2/include/components/webrtc-agc.conf b/topology2/include/components/webrtc-agc.conf index e0a2e9b..9cc0ce4 100644 --- a/topology2/include/components/webrtc-agc.conf +++ b/topology2/include/components/webrtc-agc.conf @@ -3,7 +3,7 @@ # # WebRTC Digital Automatic Gain Control widget (fixed-point). # Single input, single output. Dynamically normalizes speech levels (+9 dB boost, limiter). -# Supports 8 kHz and 16 kHz, S16 and S32 formats. +# Supports 8, 16, 32, and 48 kHz, S16 and S32 formats. # # Usage: # Object.Widget.webrtc-agc."N" { @@ -70,10 +70,34 @@ Class.Widget."webrtc-agc" { } } - num_input_audio_formats 4 - num_output_audio_formats 4 + num_input_audio_formats 8 + num_output_audio_formats 8 Object.Base.input_audio_format [ + # S16 stereo 48 kHz + { + in_rate 48000 + in_bit_depth 16 + in_valid_bit_depth 16 + } + # S32 stereo 48 kHz + { + in_rate 48000 + in_bit_depth 32 + in_valid_bit_depth 32 + } + # S16 stereo 32 kHz + { + in_rate 32000 + in_bit_depth 16 + in_valid_bit_depth 16 + } + # S32 stereo 32 kHz + { + in_rate 32000 + in_bit_depth 32 + in_valid_bit_depth 32 + } # S16 stereo 16 kHz { in_rate 16000 @@ -101,6 +125,26 @@ Class.Widget."webrtc-agc" { ] Object.Base.output_audio_format [ + { + out_rate 48000 + out_bit_depth 16 + out_valid_bit_depth 16 + } + { + out_rate 48000 + out_bit_depth 32 + out_valid_bit_depth 32 + } + { + out_rate 32000 + out_bit_depth 16 + out_valid_bit_depth 16 + } + { + out_rate 32000 + out_bit_depth 32 + out_valid_bit_depth 32 + } { out_rate 16000 out_bit_depth 16 diff --git a/topology2/include/components/webrtc-vad.conf b/topology2/include/components/webrtc-vad.conf index 03c7adb..908a19d 100644 --- a/topology2/include/components/webrtc-vad.conf +++ b/topology2/include/components/webrtc-vad.conf @@ -10,6 +10,7 @@ # index 1 # no_pm "true" # } +# Set WEBRTC_VAD_RATE to the pipeline rate; it defaults to 48000 Hz. # # UUID: c790b11d-5d14-e54e-be36ba4ad732cc14 (webrtc_vad in uuid-registry.txt) # Topology byte order (little-endian fields): @@ -18,6 +19,10 @@ # e54e → 4e:e5 # be36ba4ad732cc14 (last 8 bytes, as-is) +Define { + WEBRTC_VAD_RATE 48000 +} + Class.Widget."webrtc-vad" { # # Pipeline ID for the webrtc-vad widget @@ -60,23 +65,26 @@ Class.Widget."webrtc-vad" { unique "instance" } - # Supports S16 and S32 at any rate (8/16/32/48 kHz), mono or stereo. + # Supports S16 and S32 at the selected rate (8/16/32/48 kHz), mono or stereo. num_input_audio_formats 4 num_output_audio_formats 4 Object.Base.input_audio_format [ # S16 stereo { + in_rate $WEBRTC_VAD_RATE in_bit_depth 16 in_valid_bit_depth 16 } # S32 stereo { + in_rate $WEBRTC_VAD_RATE in_bit_depth 32 in_valid_bit_depth 32 } # S16 mono { + in_rate $WEBRTC_VAD_RATE in_bit_depth 16 in_valid_bit_depth 16 in_channels 1 @@ -85,6 +93,7 @@ Class.Widget."webrtc-vad" { } # S32 mono { + in_rate $WEBRTC_VAD_RATE in_bit_depth 32 in_valid_bit_depth 32 in_channels 1 @@ -95,14 +104,17 @@ Class.Widget."webrtc-vad" { Object.Base.output_audio_format [ { + out_rate $WEBRTC_VAD_RATE out_bit_depth 16 out_valid_bit_depth 16 } { + out_rate $WEBRTC_VAD_RATE out_bit_depth 32 out_valid_bit_depth 32 } { + out_rate $WEBRTC_VAD_RATE out_bit_depth 16 out_valid_bit_depth 16 out_channels 1 @@ -110,6 +122,7 @@ Class.Widget."webrtc-vad" { out_ch_map $CHANNEL_MAP_MONO } { + out_rate $WEBRTC_VAD_RATE out_bit_depth 32 out_valid_bit_depth 32 out_channels 1 diff --git a/topology2/include/dais/alh.conf b/topology2/include/dais/alh.conf index 4f49084..4f9f5d2 100644 --- a/topology2/include/dais/alh.conf +++ b/topology2/include/dais/alh.conf @@ -31,7 +31,7 @@ Class.Dai."ALH" { DefineAttribute."direction" { type "string" - token_ref "dai.word" + token_ref "dai.string" constraints { !valid_values [ "playback" diff --git a/topology2/include/formats/bt_host_input_audio_formats.conf b/topology2/include/formats/bt_host_input_audio_formats.conf new file mode 100644 index 0000000..351af10 --- /dev/null +++ b/topology2/include/formats/bt_host_input_audio_formats.conf @@ -0,0 +1,76 @@ +# SPDX-License-Identifier: BSD-3-Clause + # Bluetooth playback host-copier input formats: + # - Controller offload ("none"): 8 kHz 1ch, 16 kHz 1ch, and 48 kHz 2ch. + # - SOF Transparent DSP codecs ("lc3|msbc|g722|sb4"): 8 kHz 1ch and 16 kHz 1ch. + IncludeByKey.BT_TRANSP_CODEC { + "none" { + num_input_audio_formats 9 + CombineArrays.Object.Base.input_audio_format [ + { + in_rate [ + 8000 + 16000 + ] + in_bit_depth [ 16 ] + in_valid_bit_depth [ 16 ] + in_channels [ 1 ] + in_ch_cfg [ $CHANNEL_CONFIG_MONO ] + in_ch_map [ $CHANNEL_MAP_MONO ] + } + { + in_rate [ + 8000 + 16000 + ] + in_bit_depth [ 32 ] + in_valid_bit_depth [ 24 32 ] + in_channels [ 1 ] + in_ch_cfg [ $CHANNEL_CONFIG_MONO ] + in_ch_map [ $CHANNEL_MAP_MONO ] + } + { + in_rate [ 48000 ] + in_bit_depth [ 16 ] + in_valid_bit_depth [ 16 ] + in_channels [ 2 ] + in_ch_cfg [ $CHANNEL_CONFIG_STEREO ] + in_ch_map [ $CHANNEL_MAP_STEREO ] + } + { + in_rate [ 48000 ] + in_bit_depth [ 32 ] + in_valid_bit_depth [ 24 32 ] + in_channels [ 2 ] + in_ch_cfg [ $CHANNEL_CONFIG_STEREO ] + in_ch_map [ $CHANNEL_MAP_STEREO ] + } + ] + } + "(lc3|msbc|g722|sb4)" { + num_input_audio_formats 6 + CombineArrays.Object.Base.input_audio_format [ + { + in_rate [ + 8000 + 16000 + ] + in_bit_depth [ 16 ] + in_valid_bit_depth [ 16 ] + in_channels [ 1 ] + in_ch_cfg [ $CHANNEL_CONFIG_MONO ] + in_ch_map [ $CHANNEL_MAP_MONO ] + } + { + in_rate [ + 8000 + 16000 + ] + in_bit_depth [ 32 ] + in_valid_bit_depth [ 24 32 ] + in_channels [ 1 ] + in_ch_cfg [ $CHANNEL_CONFIG_MONO ] + in_ch_map [ $CHANNEL_MAP_MONO ] + } + ] + } + } diff --git a/topology2/include/formats/bt_s32_input_audio_formats.conf b/topology2/include/formats/bt_s32_input_audio_formats.conf new file mode 100644 index 0000000..b012ae0 --- /dev/null +++ b/topology2/include/formats/bt_s32_input_audio_formats.conf @@ -0,0 +1,47 @@ +# SPDX-License-Identifier: BSD-3-Clause + # Bluetooth S32_LE internal pipeline input formats (gain, mixin, mixout, + # and Transparent bt_codec playback input): + # - Controller offload ("none"): 8 kHz 1ch, 16 kHz 1ch, and 48 kHz 2ch. + # - SOF Transparent DSP codecs ("lc3|msbc|g722|sb4"): 8 kHz 1ch and 16 kHz 1ch. + IncludeByKey.BT_TRANSP_CODEC { + "none" { + num_input_audio_formats 3 + CombineArrays.Object.Base.input_audio_format [ + { + in_rate [ + 8000 + 16000 + ] + in_bit_depth [ 32 ] + in_valid_bit_depth [ 32 ] + in_channels [ 1 ] + in_ch_cfg [ $CHANNEL_CONFIG_MONO ] + in_ch_map [ $CHANNEL_MAP_MONO ] + } + { + in_rate [ 48000 ] + in_bit_depth [ 32 ] + in_valid_bit_depth [ 32 ] + in_channels [ 2 ] + in_ch_cfg [ $CHANNEL_CONFIG_STEREO ] + in_ch_map [ $CHANNEL_MAP_STEREO ] + } + ] + } + "(lc3|msbc|g722|sb4)" { + num_input_audio_formats 2 + CombineArrays.Object.Base.input_audio_format [ + { + in_rate [ + 8000 + 16000 + ] + in_bit_depth [ 32 ] + in_valid_bit_depth [ 32 ] + in_channels [ 1 ] + in_ch_cfg [ $CHANNEL_CONFIG_MONO ] + in_ch_map [ $CHANNEL_MAP_MONO ] + } + ] + } + } diff --git a/topology2/include/formats/bt_s32_output_audio_formats.conf b/topology2/include/formats/bt_s32_output_audio_formats.conf new file mode 100644 index 0000000..c73be7b --- /dev/null +++ b/topology2/include/formats/bt_s32_output_audio_formats.conf @@ -0,0 +1,47 @@ +# SPDX-License-Identifier: BSD-3-Clause + # Bluetooth S32_LE internal pipeline output formats (host-copier output, + # gain, mixin, and mixout): + # - Controller offload ("none"): 8 kHz 1ch, 16 kHz 1ch, and 48 kHz 2ch. + # - SOF Transparent DSP codecs ("lc3|msbc|g722|sb4"): 8 kHz 1ch and 16 kHz 1ch. + IncludeByKey.BT_TRANSP_CODEC { + "none" { + num_output_audio_formats 3 + CombineArrays.Object.Base.output_audio_format [ + { + out_rate [ + 8000 + 16000 + ] + out_bit_depth [ 32 ] + out_valid_bit_depth [ 32 ] + out_channels [ 1 ] + out_ch_cfg [ $CHANNEL_CONFIG_MONO ] + out_ch_map [ $CHANNEL_MAP_MONO ] + } + { + out_rate [ 48000 ] + out_bit_depth [ 32 ] + out_valid_bit_depth [ 32 ] + out_channels [ 2 ] + out_ch_cfg [ $CHANNEL_CONFIG_STEREO ] + out_ch_map [ $CHANNEL_MAP_STEREO ] + } + ] + } + "(lc3|msbc|g722|sb4)" { + num_output_audio_formats 2 + CombineArrays.Object.Base.output_audio_format [ + { + out_rate [ + 8000 + 16000 + ] + out_bit_depth [ 32 ] + out_valid_bit_depth [ 32 ] + out_channels [ 1 ] + out_ch_cfg [ $CHANNEL_CONFIG_MONO ] + out_ch_map [ $CHANNEL_MAP_MONO ] + } + ] + } + } diff --git a/topology2/include/formats/bt_ssp_s16_output_audio_formats.conf b/topology2/include/formats/bt_ssp_s16_output_audio_formats.conf new file mode 100644 index 0000000..e9e91ff --- /dev/null +++ b/topology2/include/formats/bt_ssp_s16_output_audio_formats.conf @@ -0,0 +1,43 @@ +# SPDX-License-Identifier: BSD-3-Clause + # Bluetooth SSP wire S16_LE output formats: + # - Controller offload ("none"): BT-SCO-NB 8k 1ch, BT-SCO-WB 16k 1ch, BT-A2DP 48k 2ch. + # - SOF Transparent DSP codecs ("lc3|msbc|g722|sb4"): fixed BT-SCO-NB 8k 1ch S16_LE wire link. + IncludeByKey.BT_TRANSP_CODEC { + "none" { + num_output_audio_formats 3 + CombineArrays.Object.Base.output_audio_format [ + { + out_rate [ + 8000 + 16000 + ] + out_bit_depth [ 16 ] + out_valid_bit_depth [ 16 ] + out_channels [ 1 ] + out_ch_cfg [ $CHANNEL_CONFIG_MONO ] + out_ch_map [ $CHANNEL_MAP_MONO ] + } + { + out_rate [ 48000 ] + out_bit_depth [ 16 ] + out_valid_bit_depth [ 16 ] + out_channels [ 2 ] + out_ch_cfg [ $CHANNEL_CONFIG_STEREO ] + out_ch_map [ $CHANNEL_MAP_STEREO ] + } + ] + } + "(lc3|msbc|g722|sb4)" { + num_output_audio_formats 1 + Object.Base.output_audio_format [ + { + out_rate 8000 + out_bit_depth 16 + out_valid_bit_depth 16 + out_channels 1 + out_ch_cfg $CHANNEL_CONFIG_MONO + out_ch_map $CHANNEL_MAP_MONO + } + ] + } + } diff --git a/topology2/include/formats/compr_input_audio_formats.conf b/topology2/include/formats/compr_input_audio_formats.conf index 8d56944..0f532ee 100644 --- a/topology2/include/formats/compr_input_audio_formats.conf +++ b/topology2/include/formats/compr_input_audio_formats.conf @@ -1,11 +1,15 @@ # All input formats for e.g. host-copier, decoder, # and module-copier - num_input_audio_formats 40 + num_input_audio_formats 72 CombineArrays.Object.Base.input_audio_format [ { in_channels [ 1 ] in_rate [ 8000 + 16000 + 22050 + 24000 + 32000 44100 48000 96000 @@ -21,6 +25,10 @@ in_channels [ 1 ] in_rate [ 8000 + 16000 + 22050 + 24000 + 32000 44100 48000 96000 @@ -35,6 +43,10 @@ in_channels [ 1 ] in_rate [ 8000 + 16000 + 22050 + 24000 + 32000 44100 48000 96000 @@ -49,6 +61,10 @@ in_channels [ 1 ] in_rate [ 8000 + 16000 + 22050 + 24000 + 32000 44100 48000 96000 @@ -62,6 +78,10 @@ { in_rate [ 8000 + 16000 + 22050 + 24000 + 32000 44100 48000 96000 @@ -74,6 +94,10 @@ { in_rate [ 8000 + 16000 + 22050 + 24000 + 32000 44100 48000 96000 @@ -85,6 +109,10 @@ { in_rate [ 8000 + 16000 + 22050 + 24000 + 32000 44100 48000 96000 @@ -96,6 +124,10 @@ { in_rate [ 8000 + 16000 + 22050 + 24000 + 32000 44100 48000 96000 diff --git a/topology2/include/formats/compr_output_audio_formats.conf b/topology2/include/formats/compr_output_audio_formats.conf index 98d11fa..98b0a9a 100644 --- a/topology2/include/formats/compr_output_audio_formats.conf +++ b/topology2/include/formats/compr_output_audio_formats.conf @@ -1,10 +1,14 @@ # Output audio formats for e.g. host-copier and decoder - num_output_audio_formats 40 + num_output_audio_formats 72 CombineArrays.Object.Base.output_audio_format [ { out_channels [ 1 ] out_rate [ 8000 + 16000 + 22050 + 24000 + 32000 44100 48000 96000 @@ -20,6 +24,10 @@ out_channels [ 1 ] out_rate [ 8000 + 16000 + 22050 + 24000 + 32000 44100 48000 96000 @@ -34,6 +42,10 @@ out_channels [ 1 ] out_rate [ 8000 + 16000 + 22050 + 24000 + 32000 44100 48000 96000 @@ -48,6 +60,10 @@ out_channels [ 1 ] out_rate [ 8000 + 16000 + 22050 + 24000 + 32000 44100 48000 96000 @@ -61,6 +77,10 @@ { out_rate [ 8000 + 16000 + 22050 + 24000 + 32000 44100 48000 96000 @@ -73,6 +93,10 @@ { out_rate [ 8000 + 16000 + 22050 + 24000 + 32000 44100 48000 96000 @@ -84,6 +108,10 @@ { out_rate [ 8000 + 16000 + 22050 + 24000 + 32000 44100 48000 96000 @@ -95,6 +123,10 @@ { out_rate [ 8000 + 16000 + 22050 + 24000 + 32000 44100 48000 96000 diff --git a/topology2/include/formats/compr_output_audio_formats_s32.conf b/topology2/include/formats/compr_output_audio_formats_s32.conf index e377afa..9d5d432 100644 --- a/topology2/include/formats/compr_output_audio_formats_s32.conf +++ b/topology2/include/formats/compr_output_audio_formats_s32.conf @@ -1,10 +1,14 @@ # Output audio formats e.g. module-copier - num_output_audio_formats 10 + num_output_audio_formats 18 CombineArrays.Object.Base.output_audio_format [ { out_channels [ 1 ] out_rate [ 8000 + 16000 + 22050 + 24000 + 32000 44100 48000 96000 @@ -18,6 +22,10 @@ { out_rate [ 8000 + 16000 + 22050 + 24000 + 32000 44100 48000 96000 diff --git a/topology2/include/pipelines/cavs/compr-capture-ffmpeg.conf b/topology2/include/pipelines/cavs/compr-capture-ffmpeg.conf new file mode 100644 index 0000000..c5cfa79 --- /dev/null +++ b/topology2/include/pipelines/cavs/compr-capture-ffmpeg.conf @@ -0,0 +1,85 @@ +# +# FE capture pipeline: compr-capture-ffmpeg +# +# Mirror of compr-playback-ffmpeg, but for the ENCODE direction: interleaved PCM +# arrives from a capture BE (the HDA analog capture DAI) and the FFmpeg +# (libavcodec) encoder widget "ffmpeg_enc" compresses it to an MP3 or AAC-LC +# elementary stream that the aif_out host-copier DMAs to the host (read via +# crecord). +# +# ffmpeg_enc is the same firmware module as ffmpeg_dec built in encode mode; it +# carries the DAPM type "encoder" so the compress kernel path +# (sof_ipc4_compr_get_module) finds and configures it. Although libshine and +# vo-aacenc are lightweight fixed-point encoders, the widget runs on the DP +# (data-processing) domain like the decoder: MP3 needs a full 1152-sample +# (24 ms) frame and AAC-LC needs a full 1024-sample (21.33 ms) frame of input +# before emitting a packet, and the DP ring can be sized to buffer that many +# samples ahead, which a 2 ms low-latency buffer cannot. core_id / stack sizing +# are set on the platform instance. +# +# This pipeline holds only the DP encoder and the aif_out host-copier. Its PCM +# input is delivered by an EXTERNAL mixout that lives in its own timer-scheduled +# mixout-capture pipeline (see platform/intel/compr-capture-ffmpeg.conf): the +# capture BE fans PCM out via a single mixin (mixin.4.1) to two mixouts - one in +# the normal analog capture FE and one that feeds this encoder - using the +# proven mixer fan-out (the same mix path playback uses). A module-copier's 2nd +# output pin does NOT deliver data across a pipeline boundary, which starved the +# encoder in the earlier copier-fan-out design; mixin->mixout does deliver. +# +# The tap mixout is isolated in its own LL pipeline because a DP module breaks +# the LL copy walk: a mixout sharing this pipeline would sit on the far side of +# the break from the pipeline's sink scheduler and never run. Standalone, the +# mixout self-schedules on the timer and its output crosses the boundary into +# this DP module's input ring, mirroring how the decode pipeline's LL +# host-copier feeds ffmpeg_dec. +# +# The mixin->mixout, mixout->ffmpeg_enc and ffmpeg_enc->host-copier routes are +# declared in the platform conf (platform/intel/compr-capture-ffmpeg.conf) +# because they depend on the capture BE fan-out tap (COMPR_ENC_SOURCE) and the +# compress PCM id. +# +# All attributes defined herein are namespaced by alsatplg to +# "Object.Pipeline.compr-capture-ffmpeg.N.attribute_name". +# + + + + + + + +Class.Pipeline."compr-capture-ffmpeg" { + + + + attributes { + !constructor [ + "index" + ] + + unique "instance" + } + + Object.Widget { + ffmpeg_enc."1" { + scheduler_domain "DP" + no_pm "true" + } + + host-copier."1" { + type "aif_out" + node_type $HDA_HOST_INPUT_CLASS + num_input_pins 1 + num_output_pins 1 + } + + pipeline."1" { + priority 0 + lp_mode 0 + } + } + + direction "capture" + dynamic_pipeline 1 + time_domain "timer" +} diff --git a/topology2/include/pipelines/cavs/mixout-capture.conf b/topology2/include/pipelines/cavs/mixout-capture.conf new file mode 100644 index 0000000..faeaf51 --- /dev/null +++ b/topology2/include/pipelines/cavs/mixout-capture.conf @@ -0,0 +1,50 @@ +# +# Capture pipeline: mixout-capture. +# +# A single mixout that is the sole (source == sink) component of its own +# timer-scheduled pipeline. It exists to give the mixer capture fan-out tap an +# LL scheduling anchor: the pipeline's scheduling component falls back to its +# sink (this mixout), so the LL scheduler runs mixout_process every period, +# draining the feeding mixin into the mixout's sink buffer. +# +# This is needed when the mixout feeds a DP (data-processing) module in a +# downstream pipeline (e.g. the FFmpeg encoder): a DP module breaks the LL copy +# walk, so a mixout placed in the SAME pipeline as the DP module - on the far +# side of the break from the pipeline's DMA-driven scheduling component - is +# never scheduled and never drains its mixin. Isolating the mixout in its own +# timer-scheduled pipeline (the standard mixer pattern) makes it self-schedule; +# its output then crosses the pipeline boundary into the DP module's input ring. +# +# All attributes defined herein are namespaced by alsatplg to +# "Object.Pipeline.mixout-capture.N.attribute_name". +# + + + + +Class.Pipeline."mixout-capture" { + + + + attributes { + !constructor [ + "index" + ] + + unique "instance" + } + + Object.Widget { + mixout."1" {} + + pipeline."1" { + priority 0 + lp_mode 0 + direction "capture" + } + } + + direction "capture" + dynamic_pipeline 1 + time_domain "timer" +} diff --git a/topology2/include/pipelines/cavs/mixout-gain-alh-dai-copier-playback.conf b/topology2/include/pipelines/cavs/mixout-gain-alh-dai-copier-playback.conf index d989971..719e1a4 100644 --- a/topology2/include/pipelines/cavs/mixout-gain-alh-dai-copier-playback.conf +++ b/topology2/include/pipelines/cavs/mixout-gain-alh-dai-copier-playback.conf @@ -52,8 +52,7 @@ Class.Pipeline."mixout-gain-alh-dai-copier-playback" { { in_bit_depth 32 in_valid_bit_depth 32 - in_sample_type $SAMPLE_TYPE_MSB_INTEGER - in_fmt_cfg "$[($in_channels | ($in_valid_bit_depth * 256))]" + in_sample_type $SAMPLE_TYPE_LSB_INTEGER } ] Object.Base.output_audio_format [ diff --git a/topology2/include/pipelines/cavs/mixout-gain-host-copier-capture.conf b/topology2/include/pipelines/cavs/mixout-gain-host-copier-capture.conf index ab18e5b..c0843f1 100644 --- a/topology2/include/pipelines/cavs/mixout-gain-host-copier-capture.conf +++ b/topology2/include/pipelines/cavs/mixout-gain-host-copier-capture.conf @@ -107,13 +107,6 @@ Class.Pipeline."mixout-gain-host-copier-capture" { } } - Object.Base.route [ - { - source gain.$index.1 - sink copier.host.$index.1 - } - ] - direction "capture" dynamic_pipeline 1 time_domain "timer" diff --git a/topology2/platform/intel/bt-deep-buffer.conf b/topology2/platform/intel/bt-deep-buffer.conf new file mode 100644 index 0000000..eb8f567 --- /dev/null +++ b/topology2/platform/intel/bt-deep-buffer.conf @@ -0,0 +1,86 @@ +# SPDX-License-Identifier: BSD-3-Clause +# +# Deep buffer playback FE for Bluetooth audio offload (SSP2-BT). +# +# Included by platform/intel/bt-generic.conf when BT_DEEP_BUFFER is true and +# BT_DEEPBUFFER_FW_DMA_MS is in range (1..1000 ms). Instantiates a dedicated +# deepbuffer-playback pipeline (lp_mode = 1, D0i3 streaming compatible) on the +# BT_DEEP_BUFFER_* variables and routes its mixin into the shared BT playback +# mixout pipeline ($BT_PB_DAI_PIPELINE_ID). + +Object.Pipeline.deepbuffer-playback [ + { + index $BT_DEEP_BUFFER_PIPELINE_ID + + Object.Widget.host-copier.1 { + stream_name $BT_DEEP_BUFFER_PCM_NAME + pcm_id $BT_DEEP_BUFFER_PCM_ID + deep_buffer_dma_ms $BT_DEEPBUFFER_FW_DMA_MS + + + } + Object.Widget.gain.1 { + Object.Control.mixer.1 { + name 'Pre Mixer $BT_DEEP_BUFFER_PCM_NAME Volume' + } + + + } + Object.Widget.mixin.1 { + + + } + } +] + +Object.PCM.pcm [ + { + name $BT_DEEP_BUFFER_PCM_NAME + id $BT_DEEP_BUFFER_PCM_ID + direction playback + playback_compatible_d0i3 $BT_DEEPBUFFER_D0I3_COMPATIBLE + + Object.Base.fe_dai.1 { + name "$BT_DEEP_BUFFER_PCM_NAME" + } + IncludeByKey.BT_TRANSP_CODEC { + "none" { + Object.PCM.pcm_caps.1 { + name $BT_DEEP_BUFFER_PCM_NAME + formats 'S16_LE,S24_LE,S32_LE' + rates '8000,16000,48000' + rate_min 8000 + rate_max 48000 + channels_min 1 + channels_max 2 + # Minimum host buffer >= 2x firmware deep-buffer DMA burst at 8 kHz 1ch S16_LE; + # Linux hda-pcm.c additionally enforces period_time >= (dma_ms + 10 ms) at runtime. + buffer_size_min "$[(((2 * $channels_min) * 8) * $BT_DEEPBUFFER_FW_DMA_MS) * 2]" + } + } + "(lc3|msbc|g722|sb4)" { + Object.PCM.pcm_caps.1 { + name $BT_DEEP_BUFFER_PCM_NAME + formats 'S16_LE,S24_LE,S32_LE' + rates '8000,16000' + rate_min 8000 + rate_max 16000 + channels_min 1 + channels_max 1 + buffer_size_min "$[(((2 * $channels_min) * 8) * $BT_DEEPBUFFER_FW_DMA_MS) * 2]" + } + } + } + } +] + +Object.Base.route [ + { + source mixin.$BT_DEEP_BUFFER_PIPELINE_ID.1 + sink mixout.$BT_PB_DAI_PIPELINE_ID.1 + } + { + source host-copier.$BT_DEEP_BUFFER_PCM_ID.playback + sink gain.$BT_DEEP_BUFFER_PIPELINE_ID.1 + } +] diff --git a/topology2/platform/intel/bt-default.conf b/topology2/platform/intel/bt-default.conf index 2555288..436aa5a 100644 --- a/topology2/platform/intel/bt-default.conf +++ b/topology2/platform/intel/bt-default.conf @@ -19,5 +19,14 @@ Define { BT_PCM_ID 2 BT_PCM_NAME "Port2" + BT_DEEP_BUFFER false + BT_DEEP_BUFFER_PCM_ID 36 + BT_DEEP_BUFFER_PCM_NAME "Deepbuffer Bluetooth" + BT_DEEP_BUFFER_PIPELINE_ID 204 + BT_DEEPBUFFER_FW_DMA_MS 100 + BT_DEEPBUFFER_D0I3_COMPATIBLE true + BT_LOOPBACK_MODE false + BT_SSP_DUPLEX false + BT_TRANSP_CODEC "none" } diff --git a/topology2/platform/intel/bt-generic.conf b/topology2/platform/intel/bt-generic.conf index e1549fb..1e7a0da 100644 --- a/topology2/platform/intel/bt-generic.conf +++ b/topology2/platform/intel/bt-generic.conf @@ -1,252 +1,915 @@ IncludeByKey.BT_LOOPBACK_MODE { "true" "platform/intel/bt-ssp-config-lbm.conf" + "false" { + IncludeByKey.BT_SSP_DUPLEX { + "false" "platform/intel/bt-ssp-config.conf" + "true" "platform/intel/bt-ssp-config-duplex.conf" + } + } } -IncludeByKey.BT_LOOPBACK_MODE { - "false" "platform/intel/bt-ssp-config.conf" -} - +# Capture pipelines (low-latency SSP -> optional Transparent decoder -> host-copier) Object.Pipeline { - # playback pipelines - io-gateway [ + host-gateway-capture [ { - index $BT_PB_DAI_PIPELINE_ID - direction playback + index $BT_CP_HOST_PIPELINE_ID Object.Widget.pipeline.1 { - stream_name "dai-copier.SSP.$BT_NAME.playback" + stream_name "dai-copier.SSP.$BT_NAME.capture" } + Object.Widget.host-copier.1 { + stream_name $BT_CP_PCM_CAPS + pcm_id $BT_PCM_ID + IncludeByKey.BT_TRANSP_CODEC { + "none" { + num_input_audio_formats 3 + num_output_audio_formats 3 + CombineArrays.Object.Base.output_audio_format [ + { + out_rate [ + 8000 + 16000 + ] + out_channels [ 1 ] + } + { + out_bit_depth [ 16 ] + out_valid_bit_depth [ 16 ] + out_channels [ 2 ] + } + ] + CombineArrays.Object.Base.input_audio_format [ + { + in_rate [ + 8000 + 16000 + ] + in_channels [ 1 ] + } + { + in_bit_depth [ 16 ] + in_valid_bit_depth [ 16 ] + in_channels [ 2 ] + } + ] + } + "(lc3|msbc|g722|sb4)" { + num_input_audio_formats 2 + num_output_audio_formats 2 + CombineArrays.Object.Base.output_audio_format [ + { + out_rate [ + 8000 + 16000 + ] + out_bit_depth [ 16 ] + out_valid_bit_depth [ 16 ] + out_channels [ 1 ] + out_ch_cfg [ $CHANNEL_CONFIG_MONO ] + out_ch_map [ $CHANNEL_MAP_MONO ] + } + ] + CombineArrays.Object.Base.input_audio_format [ + { + in_rate [ + 8000 + 16000 + ] + in_bit_depth [ 16 ] + in_valid_bit_depth [ 16 ] + in_channels [ 1 ] + in_ch_cfg [ $CHANNEL_CONFIG_MONO ] + in_ch_map [ $CHANNEL_MAP_MONO ] + } + ] + } + } + } + } + ] - Object.Widget.dai-copier.1 { - dai_index $BT_INDEX - dai_type "SSP" - copier_type "SSP" - stream_name $BT_NAME - node_type $I2S_LINK_OUTPUT_CLASS - num_input_audio_formats 3 - num_output_audio_formats 3 - num_input_pins 1 + io-gateway-capture [ + { + index $BT_CP_DAI_PIPELINE_ID + direction "capture" + Object.Widget.pipeline.1 { + stream_name "dai-copier.SSP.$BT_NAME.capture" + } - CombineArrays.Object.Base.output_audio_format [ - # array of 2ch format with range of rates - { - out_rate [ - 8000 - 16000 + Object.Widget.dai-copier."1" { + dai_index $BT_INDEX + dai_type "SSP" + type dai_out + copier_type "SSP" + stream_name $BT_NAME + node_type $I2S_LINK_INPUT_CLASS + IncludeByKey.BT_TRANSP_CODEC { + "none" { + num_input_audio_formats 3 + num_output_audio_formats 3 + CombineArrays.Object.Base.output_audio_format [ + { + out_rate [ + 8000 + 16000 + ] + out_channels [ 1 ] + } + { + out_bit_depth [ 16 ] + out_valid_bit_depth [ 16 ] + out_channels [ 2 ] + } + ] + CombineArrays.Object.Base.input_audio_format [ + { + in_rate [ + 8000 + 16000 + ] + in_channels [ 1 ] + } + { + in_bit_depth [ 16 ] + in_valid_bit_depth [ 16 ] + in_channels [ 2 ] + } + ] + } + "(lc3|msbc|g722|sb4)" { + num_input_audio_formats 1 + num_output_audio_formats 1 + Object.Base.output_audio_format [ + { + out_rate 8000 + out_bit_depth 16 + out_valid_bit_depth 16 + out_channels 1 + out_ch_cfg $CHANNEL_CONFIG_MONO + out_ch_map $CHANNEL_MAP_MONO + } + ] + Object.Base.input_audio_format [ + { + in_rate 8000 + in_bit_depth 16 + in_valid_bit_depth 16 + in_channels 1 + in_ch_cfg $CHANNEL_CONFIG_MONO + in_ch_map $CHANNEL_MAP_MONO + } ] - out_channels [ 1 ] } - # 2ch 16-bit 48k + } + } + } + ] +} + +IncludeByKey.BT_DEEP_BUFFER { + "false" { + Object.Pipeline { + # Direct passthrough playback pipelines + io-gateway [ + { + index $BT_PB_DAI_PIPELINE_ID + direction playback + Object.Widget.pipeline.1 { + stream_name "dai-copier.SSP.$BT_NAME.playback" + } + + Object.Widget.dai-copier.1 { + dai_index $BT_INDEX + dai_type "SSP" + copier_type "SSP" + stream_name $BT_NAME + node_type $I2S_LINK_OUTPUT_CLASS + num_input_pins 1 + IncludeByKey.BT_TRANSP_CODEC { + "none" { + num_input_audio_formats 3 + num_output_audio_formats 3 + CombineArrays.Object.Base.output_audio_format [ + { + out_rate [ + 8000 + 16000 + ] + out_channels [ 1 ] + } + { + out_bit_depth [ 16 ] + out_valid_bit_depth [ 16 ] + out_channels [ 2 ] + } + ] + CombineArrays.Object.Base.input_audio_format [ + { + in_rate [ + 8000 + 16000 + ] + in_channels [ 1 ] + } + { + in_bit_depth [ 16 ] + in_valid_bit_depth [ 16 ] + in_channels [ 2 ] + } + ] + } + "(lc3|msbc|g722|sb4)" { + num_input_audio_formats 1 + num_output_audio_formats 1 + Object.Base.output_audio_format [ + { + out_rate 8000 + out_bit_depth 16 + out_valid_bit_depth 16 + out_channels 1 + out_ch_cfg $CHANNEL_CONFIG_MONO + out_ch_map $CHANNEL_MAP_MONO + } + ] + Object.Base.input_audio_format [ + { + in_rate 8000 + in_bit_depth 16 + in_valid_bit_depth 16 + in_channels 1 + in_ch_cfg $CHANNEL_CONFIG_MONO + in_ch_map $CHANNEL_MAP_MONO + } + ] + } + } + } + } + ] + + host-gateway-playback [ + { + index $BT_PB_HOST_PIPELINE_ID + Object.Widget.pipeline.1 { + stream_name "dai-copier.SSP.$BT_NAME.playback" + } + Object.Widget.host-copier.1 { + stream_name $BT_PB_PCM_CAPS + pcm_id $BT_PCM_ID + IncludeByKey.BT_TRANSP_CODEC { + "none" { + num_input_audio_formats 3 + num_output_audio_formats 3 + CombineArrays.Object.Base.output_audio_format [ + { + out_rate [ + 8000 + 16000 + ] + out_channels [ 1 ] + } + { + out_bit_depth [ 16 ] + out_valid_bit_depth [ 16 ] + out_channels [ 2 ] + } + ] + CombineArrays.Object.Base.input_audio_format [ + { + in_rate [ + 8000 + 16000 + ] + in_channels [ 1 ] + } + { + in_bit_depth [ 16 ] + in_valid_bit_depth [ 16 ] + in_channels [ 2 ] + } + ] + } + "(lc3|msbc|g722|sb4)" { + num_input_audio_formats 2 + num_output_audio_formats 2 + CombineArrays.Object.Base.output_audio_format [ + { + out_rate [ + 8000 + 16000 + ] + out_bit_depth [ 16 ] + out_valid_bit_depth [ 16 ] + out_channels [ 1 ] + out_ch_cfg [ $CHANNEL_CONFIG_MONO ] + out_ch_map [ $CHANNEL_MAP_MONO ] + } + ] + CombineArrays.Object.Base.input_audio_format [ + { + in_rate [ + 8000 + 16000 + ] + in_bit_depth [ 16 ] + in_valid_bit_depth [ 16 ] + in_channels [ 1 ] + in_ch_cfg [ $CHANNEL_CONFIG_MONO ] + in_ch_map [ $CHANNEL_MAP_MONO ] + } + ] + } + } + } + } + ] + } + + IncludeByKey.BT_TRANSP_CODEC { + "none" { + Object.Base.route [ + { + source "host-copier.$BT_PCM_ID.playback" + sink "dai-copier.SSP.$BT_NAME.playback" + } { - out_bit_depth [ 16 ] - out_valid_bit_depth [ 16 ] - out_channels [ 2 ] + source "dai-copier.SSP.$BT_NAME.capture" + sink "host-copier.$BT_PCM_ID.capture" } ] - CombineArrays.Object.Base.input_audio_format [ - # array of 2ch format with range of rates + } + "lc3" { + Object.Widget.bt_lc3.1 { + index $BT_PB_HOST_PIPELINE_ID + num_input_audio_formats 2 + num_output_audio_formats 1 + CombineArrays.Object.Base.input_audio_format [ + { + in_rate [ 8000 16000 ] + in_bit_depth [ 16 ] + in_valid_bit_depth [ 16 ] + in_channels [ 1 ] + in_ch_cfg [ $CHANNEL_CONFIG_MONO ] + in_ch_map [ $CHANNEL_MAP_MONO ] + } + ] + Object.Base.output_audio_format [ + { + out_rate 8000 + out_bit_depth 16 + out_valid_bit_depth 16 + out_channels 1 + out_ch_cfg $CHANNEL_CONFIG_MONO + out_ch_map $CHANNEL_MAP_MONO + } + ] + } + Object.Widget.bt_lc3.2 { + index $BT_CP_HOST_PIPELINE_ID + + } + Object.Base.route [ { - in_rate [ - 8000 - 16000 - ] - in_channels [ 1 ] + source "host-copier.$BT_PCM_ID.playback" + sink "bt_lc3.$BT_PB_HOST_PIPELINE_ID.1" } - # 2ch 16-bit 48k { - in_bit_depth [ 16 ] - in_valid_bit_depth [ 16 ] - in_channels [ 2 ] + source "bt_lc3.$BT_PB_HOST_PIPELINE_ID.1" + sink "dai-copier.SSP.$BT_NAME.playback" + } + { + source "dai-copier.SSP.$BT_NAME.capture" + sink "bt_lc3.$BT_CP_HOST_PIPELINE_ID.2" + } + { + source "bt_lc3.$BT_CP_HOST_PIPELINE_ID.2" + sink "host-copier.$BT_PCM_ID.capture" } ] } - } - ] - - host-gateway-playback [ - { - index $BT_PB_HOST_PIPELINE_ID - Object.Widget.pipeline.1 { - stream_name "dai-copier.SSP.$BT_NAME.playback" + "msbc" { + Object.Widget.bt_msbc.1 { + index $BT_PB_HOST_PIPELINE_ID + num_input_audio_formats 2 + num_output_audio_formats 1 + CombineArrays.Object.Base.input_audio_format [ + { + in_rate [ 8000 16000 ] + in_bit_depth [ 16 ] + in_valid_bit_depth [ 16 ] + in_channels [ 1 ] + in_ch_cfg [ $CHANNEL_CONFIG_MONO ] + in_ch_map [ $CHANNEL_MAP_MONO ] + } + ] + Object.Base.output_audio_format [ + { + out_rate 8000 + out_bit_depth 16 + out_valid_bit_depth 16 + out_channels 1 + out_ch_cfg $CHANNEL_CONFIG_MONO + out_ch_map $CHANNEL_MAP_MONO + } + ] + } + Object.Widget.bt_msbc.2 { + index $BT_CP_HOST_PIPELINE_ID + + } + Object.Base.route [ + { + source "host-copier.$BT_PCM_ID.playback" + sink "bt_msbc.$BT_PB_HOST_PIPELINE_ID.1" + } + { + source "bt_msbc.$BT_PB_HOST_PIPELINE_ID.1" + sink "dai-copier.SSP.$BT_NAME.playback" + } + { + source "dai-copier.SSP.$BT_NAME.capture" + sink "bt_msbc.$BT_CP_HOST_PIPELINE_ID.2" + } + { + source "bt_msbc.$BT_CP_HOST_PIPELINE_ID.2" + sink "host-copier.$BT_PCM_ID.capture" + } + ] } - Object.Widget.host-copier.1 { - stream_name $BT_PB_PCM_CAPS - pcm_id $BT_PCM_ID - num_input_audio_formats 3 - num_output_audio_formats 3 - CombineArrays.Object.Base.output_audio_format [ - # array of 2ch format with range of rates - { - out_rate [ - 8000 - 16000 - ] - out_channels [ 1 ] + "g722" { + Object.Widget.bt_g722.1 { + index $BT_PB_HOST_PIPELINE_ID + num_input_audio_formats 2 + num_output_audio_formats 1 + CombineArrays.Object.Base.input_audio_format [ + { + in_rate [ 8000 16000 ] + in_bit_depth [ 16 ] + in_valid_bit_depth [ 16 ] + in_channels [ 1 ] + in_ch_cfg [ $CHANNEL_CONFIG_MONO ] + in_ch_map [ $CHANNEL_MAP_MONO ] + } + ] + Object.Base.output_audio_format [ + { + out_rate 8000 + out_bit_depth 16 + out_valid_bit_depth 16 + out_channels 1 + out_ch_cfg $CHANNEL_CONFIG_MONO + out_ch_map $CHANNEL_MAP_MONO + } + ] + } + Object.Widget.bt_g722.2 { + index $BT_CP_HOST_PIPELINE_ID + + } + Object.Base.route [ + { + source "host-copier.$BT_PCM_ID.playback" + sink "bt_g722.$BT_PB_HOST_PIPELINE_ID.1" + } + { + source "bt_g722.$BT_PB_HOST_PIPELINE_ID.1" + sink "dai-copier.SSP.$BT_NAME.playback" + } + { + source "dai-copier.SSP.$BT_NAME.capture" + sink "bt_g722.$BT_CP_HOST_PIPELINE_ID.2" } - # 2ch 16-bit 48k { - out_bit_depth [ 16 ] - out_valid_bit_depth [ 16 ] - out_channels [ 2 ] + source "bt_g722.$BT_CP_HOST_PIPELINE_ID.2" + sink "host-copier.$BT_PCM_ID.capture" } ] - CombineArrays.Object.Base.input_audio_format [ - # array of 2ch format with range of rates + } + "sb4" { + Object.Widget.bt_sb4.1 { + index $BT_PB_HOST_PIPELINE_ID + num_input_audio_formats 2 + num_output_audio_formats 1 + CombineArrays.Object.Base.input_audio_format [ + { + in_rate [ 8000 16000 ] + in_bit_depth [ 16 ] + in_valid_bit_depth [ 16 ] + in_channels [ 1 ] + in_ch_cfg [ $CHANNEL_CONFIG_MONO ] + in_ch_map [ $CHANNEL_MAP_MONO ] + } + ] + Object.Base.output_audio_format [ + { + out_rate 8000 + out_bit_depth 16 + out_valid_bit_depth 16 + out_channels 1 + out_ch_cfg $CHANNEL_CONFIG_MONO + out_ch_map $CHANNEL_MAP_MONO + } + ] + } + Object.Widget.bt_sb4.2 { + index $BT_CP_HOST_PIPELINE_ID + + } + Object.Base.route [ { - in_rate [ - 8000 - 16000 - ] - in_channels [ 1 ] + source "host-copier.$BT_PCM_ID.playback" + sink "bt_sb4.$BT_PB_HOST_PIPELINE_ID.1" } - # 2ch 16-bit 48k { - in_bit_depth [ 16 ] - in_valid_bit_depth [ 16 ] - in_channels [ 2 ] + source "bt_sb4.$BT_PB_HOST_PIPELINE_ID.1" + sink "dai-copier.SSP.$BT_NAME.playback" + } + { + source "dai-copier.SSP.$BT_NAME.capture" + sink "bt_sb4.$BT_CP_HOST_PIPELINE_ID.2" + } + { + source "bt_sb4.$BT_CP_HOST_PIPELINE_ID.2" + sink "host-copier.$BT_PCM_ID.capture" } ] } } - ] - # capture pipelines - host-gateway-capture [ - { - index $BT_CP_HOST_PIPELINE_ID - Object.Widget.pipeline.1 { - stream_name "dai-copier.SSP.$BT_NAME.capture" + Object.PCM.pcm [ + { + name $BT_PCM_NAME + id $BT_PCM_ID + direction "duplex" + + Object.Base.fe_dai.1 { + } + + IncludeByKey.BT_TRANSP_CODEC { + "none" { + Object.PCM.pcm_caps.1 { + direction "playback" + name $BT_PB_PCM_CAPS + formats 'S16_LE' + rates '8000,16000,48000' + channels_min 1 + channels_max 2 + } + + Object.PCM.pcm_caps.2 { + direction "capture" + name $BT_CP_PCM_CAPS + formats 'S16_LE' + rates '8000,16000,48000' + channels_min 1 + channels_max 2 + } + } + "(lc3|msbc|g722|sb4)" { + Object.PCM.pcm_caps.1 { + direction "playback" + name $BT_PB_PCM_CAPS + formats 'S16_LE' + rates '8000,16000' + rate_min 8000 + rate_max 16000 + channels_min 1 + channels_max 1 + } + + Object.PCM.pcm_caps.2 { + direction "capture" + name $BT_CP_PCM_CAPS + formats 'S16_LE' + rates '8000,16000' + rate_min 8000 + rate_max 16000 + channels_min 1 + channels_max 1 + } + } + } } - Object.Widget.host-copier.1 { - stream_name $BT_CP_PCM_CAPS - pcm_id $BT_PCM_ID - num_input_audio_formats 3 - num_output_audio_formats 3 - CombineArrays.Object.Base.output_audio_format [ - # array of 2ch format with range of rates - { - out_rate [ - 8000 - 16000 - ] - out_channels [ 1 ] + ] + } + + "true" { + # Deepbuffer playback FE ($BT_DEEP_BUFFER_PCM_ID -> mixin.$BT_DEEP_BUFFER_PIPELINE_ID.1) + IncludeByKey.BT_DEEPBUFFER_FW_DMA_MS { + "([1-9]|[1-9][0-9]|[1-9][0-9][0-9]|1000)" "platform/intel/bt-deep-buffer.conf" + } + + # Low-latency playback FE ($BT_PCM_ID) + shared S32_LE BE mixer into SSP + Object.Pipeline { + host-copier-gain-mixin-playback [ + { + index $BT_PB_HOST_PIPELINE_ID + + Object.Widget.host-copier.1 { + stream_name $BT_PB_PCM_CAPS + pcm_id $BT_PCM_ID + + + } + Object.Widget.gain.1 { + Object.Control.mixer.1 { + name 'Pre Mixer $BT_PCM_NAME Playback Volume' + } + + + } + Object.Widget.mixin.1 { + + + } + } + ] + + mixout-gain-dai-copier-playback [ + { + index $BT_PB_DAI_PIPELINE_ID + + Object.Widget.mixout.1 { + + + } + Object.Widget.gain.1 { + Object.Control.mixer.1 { + name 'Post Mixer $BT_PCM_NAME Playback Volume' + } + + + } + Object.Widget.dai-copier.1 { + dai_index $BT_INDEX + dai_type "SSP" + copier_type "SSP" + stream_name $BT_NAME + node_type $I2S_LINK_OUTPUT_CLASS + IncludeByKey.BT_TRANSP_CODEC { + "none" { + + } + "(lc3|msbc|g722|sb4)" { + num_input_audio_formats 1 + Object.Base.input_audio_format [ + { + in_rate 8000 + in_bit_depth 32 + in_valid_bit_depth 32 + in_channels 1 + in_ch_cfg $CHANNEL_CONFIG_MONO + in_ch_map $CHANNEL_MAP_MONO + } + ] + } + } + + } + } + ] + } + + Object.Base.route [ + { + source "host-copier.$BT_PCM_ID.playback" + sink "gain.$BT_PB_HOST_PIPELINE_ID.1" + } + { + source "mixin.$BT_PB_HOST_PIPELINE_ID.1" + sink "mixout.$BT_PB_DAI_PIPELINE_ID.1" + } + ] + + IncludeByKey.BT_TRANSP_CODEC { + "none" { + Object.Base.route [ + { + source "gain.$BT_PB_DAI_PIPELINE_ID.1" + sink "dai-copier.SSP.$BT_NAME.playback" } - # 2ch 16-bit 48k { - out_bit_depth [ 16 ] - out_valid_bit_depth [ 16 ] - out_channels [ 2 ] + source "dai-copier.SSP.$BT_NAME.capture" + sink "host-copier.$BT_PCM_ID.capture" } ] - CombineArrays.Object.Base.input_audio_format [ - # array of 2ch format with range of rates + } + "lc3" { + Object.Widget.bt_lc3.1 { + index $BT_PB_DAI_PIPELINE_ID + + num_output_audio_formats 1 + Object.Base.output_audio_format [ + { + out_rate 8000 + out_bit_depth 32 + out_valid_bit_depth 32 + out_channels 1 + out_ch_cfg $CHANNEL_CONFIG_MONO + out_ch_map $CHANNEL_MAP_MONO + } + ] + } + Object.Widget.bt_lc3.2 { + index $BT_CP_HOST_PIPELINE_ID + + } + Object.Base.route [ { - in_rate [ - 8000 - 16000 - ] - in_channels [ 1 ] + source "gain.$BT_PB_DAI_PIPELINE_ID.1" + sink "bt_lc3.$BT_PB_DAI_PIPELINE_ID.1" + } + { + source "bt_lc3.$BT_PB_DAI_PIPELINE_ID.1" + sink "dai-copier.SSP.$BT_NAME.playback" + } + { + source "dai-copier.SSP.$BT_NAME.capture" + sink "bt_lc3.$BT_CP_HOST_PIPELINE_ID.2" } - # 2ch 16-bit 48k { - in_bit_depth [ 16 ] - in_valid_bit_depth [ 16 ] - in_channels [ 2 ] + source "bt_lc3.$BT_CP_HOST_PIPELINE_ID.2" + sink "host-copier.$BT_PCM_ID.capture" } ] } - } - ] - - io-gateway-capture [ - { - index $BT_CP_DAI_PIPELINE_ID - direction "capture" - Object.Widget.pipeline.1 { - stream_name "dai-copier.SSP.$BT_NAME.capture" + "msbc" { + Object.Widget.bt_msbc.1 { + index $BT_PB_DAI_PIPELINE_ID + + num_output_audio_formats 1 + Object.Base.output_audio_format [ + { + out_rate 8000 + out_bit_depth 32 + out_valid_bit_depth 32 + out_channels 1 + out_ch_cfg $CHANNEL_CONFIG_MONO + out_ch_map $CHANNEL_MAP_MONO + } + ] + } + Object.Widget.bt_msbc.2 { + index $BT_CP_HOST_PIPELINE_ID + + } + Object.Base.route [ + { + source "gain.$BT_PB_DAI_PIPELINE_ID.1" + sink "bt_msbc.$BT_PB_DAI_PIPELINE_ID.1" + } + { + source "bt_msbc.$BT_PB_DAI_PIPELINE_ID.1" + sink "dai-copier.SSP.$BT_NAME.playback" + } + { + source "dai-copier.SSP.$BT_NAME.capture" + sink "bt_msbc.$BT_CP_HOST_PIPELINE_ID.2" + } + { + source "bt_msbc.$BT_CP_HOST_PIPELINE_ID.2" + sink "host-copier.$BT_PCM_ID.capture" + } + ] } - - Object.Widget.dai-copier."1" { - dai_index $BT_INDEX - dai_type "SSP" - type dai_out - copier_type "SSP" - stream_name $BT_NAME - node_type $I2S_LINK_INPUT_CLASS - num_input_audio_formats 3 - num_output_audio_formats 3 - CombineArrays.Object.Base.output_audio_format [ - # array of 2ch format with range of rates - { - out_rate [ - 8000 - 16000 - ] - out_channels [ 1 ] + "g722" { + Object.Widget.bt_g722.1 { + index $BT_PB_DAI_PIPELINE_ID + + num_output_audio_formats 1 + Object.Base.output_audio_format [ + { + out_rate 8000 + out_bit_depth 32 + out_valid_bit_depth 32 + out_channels 1 + out_ch_cfg $CHANNEL_CONFIG_MONO + out_ch_map $CHANNEL_MAP_MONO + } + ] + } + Object.Widget.bt_g722.2 { + index $BT_CP_HOST_PIPELINE_ID + + } + Object.Base.route [ + { + source "gain.$BT_PB_DAI_PIPELINE_ID.1" + sink "bt_g722.$BT_PB_DAI_PIPELINE_ID.1" + } + { + source "bt_g722.$BT_PB_DAI_PIPELINE_ID.1" + sink "dai-copier.SSP.$BT_NAME.playback" } - # 2ch 16-bit 48k { - out_bit_depth [ 16 ] - out_valid_bit_depth [ 16 ] - out_channels [ 2 ] + source "dai-copier.SSP.$BT_NAME.capture" + sink "bt_g722.$BT_CP_HOST_PIPELINE_ID.2" + } + { + source "bt_g722.$BT_CP_HOST_PIPELINE_ID.2" + sink "host-copier.$BT_PCM_ID.capture" } ] - CombineArrays.Object.Base.input_audio_format [ - # array of 2ch format with range of rates + } + "sb4" { + Object.Widget.bt_sb4.1 { + index $BT_PB_DAI_PIPELINE_ID + + num_output_audio_formats 1 + Object.Base.output_audio_format [ + { + out_rate 8000 + out_bit_depth 32 + out_valid_bit_depth 32 + out_channels 1 + out_ch_cfg $CHANNEL_CONFIG_MONO + out_ch_map $CHANNEL_MAP_MONO + } + ] + } + Object.Widget.bt_sb4.2 { + index $BT_CP_HOST_PIPELINE_ID + + } + Object.Base.route [ { - in_rate [ - 8000 - 16000 - ] - in_channels [ 1 ] + source "gain.$BT_PB_DAI_PIPELINE_ID.1" + sink "bt_sb4.$BT_PB_DAI_PIPELINE_ID.1" + } + { + source "bt_sb4.$BT_PB_DAI_PIPELINE_ID.1" + sink "dai-copier.SSP.$BT_NAME.playback" + } + { + source "dai-copier.SSP.$BT_NAME.capture" + sink "bt_sb4.$BT_CP_HOST_PIPELINE_ID.2" } - # 2ch 16-bit 48k { - in_bit_depth [ 16 ] - in_valid_bit_depth [ 16 ] - in_channels [ 2 ] + source "bt_sb4.$BT_CP_HOST_PIPELINE_ID.2" + sink "host-copier.$BT_PCM_ID.capture" } ] } } - ] -} -Object.Base.route [ - { - source "host-copier.$BT_PCM_ID.playback" - sink "dai-copier.SSP.$BT_NAME.playback" - } - { - source "dai-copier.SSP.$BT_NAME.capture" - sink "host-copier.$BT_PCM_ID.capture" - } -] + Object.PCM.pcm [ + { + name $BT_PCM_NAME + id $BT_PCM_ID + direction "duplex" -Object.PCM.pcm [ - { - name $BT_PCM_NAME - id $BT_PCM_ID - direction "duplex" + Object.Base.fe_dai.1 { + name "$BT_PCM_NAME" + } - Object.Base.fe_dai.1 { - } + IncludeByKey.BT_TRANSP_CODEC { + "none" { + Object.PCM.pcm_caps.1 { + direction "playback" + name $BT_PB_PCM_CAPS + formats 'S16_LE,S24_LE,S32_LE' + rates '8000,16000,48000' + rate_min 8000 + rate_max 48000 + channels_min 1 + channels_max 2 + } - Object.PCM.pcm_caps.1 { - direction "playback" - name $BT_PB_PCM_CAPS - formats 'S16_LE' - rates '8000,16000,48000' - channels_min 1 - channels_max 2 - } + Object.PCM.pcm_caps.2 { + direction "capture" + name $BT_CP_PCM_CAPS + formats 'S16_LE' + rates '8000,16000,48000' + rate_min 8000 + rate_max 48000 + channels_min 1 + channels_max 2 + } + } + "(lc3|msbc|g722|sb4)" { + Object.PCM.pcm_caps.1 { + direction "playback" + name $BT_PB_PCM_CAPS + formats 'S16_LE,S24_LE,S32_LE' + rates '8000,16000' + rate_min 8000 + rate_max 16000 + channels_min 1 + channels_max 1 + } - Object.PCM.pcm_caps.2 { - direction "capture" - name $BT_CP_PCM_CAPS - formats 'S16_LE' - rates '8000,16000,48000' - channels_min 1 - channels_max 2 - } + Object.PCM.pcm_caps.2 { + direction "capture" + name $BT_CP_PCM_CAPS + formats 'S16_LE' + rates '8000,16000' + rate_min 8000 + rate_max 16000 + channels_min 1 + channels_max 1 + } + } + } + } + ] } -] +} diff --git a/topology2/platform/intel/bt-ssp-config-duplex.conf b/topology2/platform/intel/bt-ssp-config-duplex.conf new file mode 100644 index 0000000..964d7a1 --- /dev/null +++ b/topology2/platform/intel/bt-ssp-config-duplex.conf @@ -0,0 +1,70 @@ +Object.Dai.SSP [ + { + id $BT_ID + dai_index $BT_INDEX + direction "duplex" + name $BT_NAME + default_hw_conf_id 0 + sample_bits 16 + io_clk $BT_MCLK + Object.Base.hw_config.1 { + id 0 + name "BT-SCO-WB" + mclk_freq $BT_MCLK + bclk_freq 256000 + bclk_invert true + tdm_slot_width 16 + format "DSP_A" + bclk "codec_provider" + fsync "codec_provider" + fsync_freq 16000 + tdm_slots 1 + tx_slots 1 + rx_slots 1 + # link_config ignored for mixin.4.1 --> mixout (own LL pipeline) +# --> ffmpeg_enc (DP, PCM -> MP3 / AAC-LC) +# --> aif_out host-copier --> host +# +# PCM arrives already converted to S32 48 kHz 2ch at the capture BE fan-out tap. +# In cavs-mixin-mixout-hda.conf the capture BE (when COMPR_FFMPEG_ENC is set) is +# rebuilt around a single mixin (mixin.4.1) that fans out to two mixouts via the +# proven mixer path: mixout.3.1 in the normal analog capture FE, and the encoder +# tap mixout (COMPR_ENC_SOURCE -> mixout.$COMPR_ENC_MIXOUT_PIPELINE_ID.1). That +# tap mixout lives in its OWN timer-scheduled pipeline (mixout-capture, id +# COMPR_ENC_MIXOUT_PIPELINE_ID) rather than in the encoder pipeline: a DP module +# breaks the LL copy walk, so a mixout sharing the encoder pipeline would sit on +# the far side of the break from that pipeline's sink scheduler and never run. +# The standalone mixout self-schedules on the timer, drains the mixin, and its +# output crosses the pipeline boundary into the DP encoder's input ring. The +# encoder compresses to an MP3 or ADTS AAC-LC elementary stream that the aif_out +# host-copier DMAs to the host (read with crecord). Both streams are +# self-describing, so no codec-setup / extradata control is needed here. +# +# Why a mixin fan-out and not a copier 2nd output pin: a module-copier's second +# output pin does not deliver data across a pipeline boundary (the encoder DP +# module starved on an empty input ring), whereas mixin->mixout - the same node +# playback uses to mix/route across pipelines - does deliver. +# +# Gated on its own IncludeByKey.COMPR_FFMPEG_ENC so the stock capture path and the +# decode compr-ffmpeg path are unaffected. Uses its own COMPR_ENC_* defines +# (pipeline id 91, pcm id 51) so it can coexist with the decode compress PCM. +# +# COMPR_ENC_SOURCE is the capture-BE mixin fan-out tap; it is platform specific +# and set in cavs-mixin-mixout-hda.conf, where the capture BE is rebuilt around +# the mixer when COMPR_FFMPEG_ENC is enabled. +# + +IncludeByKey.COMPR_FFMPEG_ENC { +"true" { + # Standalone timer-scheduled mixout that taps the capture-BE mixin + # fan-out and feeds the DP encoder pipeline across a pipeline boundary. + # It must be its own pipeline: a DP module (ffmpeg_enc) breaks the LL + # copy walk, so a mixout sharing the encoder pipeline would sit on the + # far side of the break from that pipeline's sink scheduler and never + # run. Alone, the mixout is its pipeline's sink (== scheduling comp) and + # self-schedules on the timer, draining the mixin every period. + Object.Pipeline.mixout-capture [ + { + index $COMPR_ENC_MIXOUT_PIPELINE_ID + Object.Widget.mixout.1 {} + } + ] + + Object.Pipeline.compr-capture-ffmpeg [ + { + index $COMPR_ENC_PIPELINE_ID + + Object.Widget.host-copier.1 { + stream_name $COMPR_ENC_PCM_NAME + pcm_id $COMPR_ENC_PCM_ID + + + } + + Object.Widget.ffmpeg_enc.1 { + # Encoder runs on the DP thread, core $COMPR_ENCODER_CORE_ID. + # MP3 (1152 samples, 24 ms) and AAC-LC (1024 samples, + # 21.33 ms) must accumulate a full frame before emitting a + # packet, so the DP ring supplies headroom a 2 ms LL buffer + # lacks. + core_id $COMPR_ENCODER_CORE_ID + stack_bytes_requirement $COMPR_FFMPEG_ENC_STACK + heap_bytes_requirement $COMPR_FFMPEG_ENC_HEAP + + + } + } + ] + + Object.PCM.pcm [ + { + name $COMPR_ENC_PCM_NAME + id $COMPR_ENC_PCM_ID + direction capture + compress "true" + + Object.Base.fe_dai.1 { + name "$COMPR_ENC_PCM_NAME" + } + + Object.PCM.pcm_caps.1 { + name $COMPR_ENC_PCM_NAME + formats 'S32_LE' + rates '8000' + } + } + ] + + Object.Base.route [ + { + # capture-BE mixin fan-out tap -> the standalone LL mixout + source $COMPR_ENC_SOURCE + sink mixout.$COMPR_ENC_MIXOUT_PIPELINE_ID.1 + } + { + # LL mixout -> DP encoder, crossing the pipeline boundary + source mixout.$COMPR_ENC_MIXOUT_PIPELINE_ID.1 + sink ffmpeg_enc.$COMPR_ENC_PIPELINE_ID.1 + } + { + source ffmpeg_enc.$COMPR_ENC_PIPELINE_ID.1 + sink host-copier.$COMPR_ENC_PCM_ID.capture + } + ] +} +} diff --git a/topology2/platform/intel/compr-default.conf b/topology2/platform/intel/compr-default.conf index e5b8554..73df2eb 100644 --- a/topology2/platform/intel/compr-default.conf +++ b/topology2/platform/intel/compr-default.conf @@ -8,11 +8,12 @@ Define { COMPR_PCM_ID 50 COMPR_PIPELINE_ID 90 - # Core for the Cadence decoder (DP) widget. The decoder is offloaded - # to core 1, while the host-copier and the rest of the compress - # pipeline run on the pipeline core (0). This makes the bind between - # them a cross-core bind, which requires CONFIG_CROSS_CORE_STREAM in - # firmware. Set to 0 for firmware without cross-core stream support. + # Core for the compress decoder (DP) widget (Cadence or FFmpeg). The + # decoder is offloaded to core 1, while the host-copier and the rest of + # the compress pipeline run on the pipeline core (0). This makes the + # bind between them a cross-core bind, which requires + # CONFIG_CROSS_CORE_STREAM in firmware. Set to 0 for firmware without + # cross-core stream support. COMPR_DECODER_CORE_ID 1 # When true, the compress PCM is driven by the FFmpeg (libavcodec) @@ -20,9 +21,35 @@ Define { # instead of COMPRESSED_1 (they share the COMPR_* pcm/pipeline defines). COMPR_FFMPEG false COMPR_FFMPEG_DEC_STACK 65536 - # Modular LLEXT heap requirement (mod_alloc): FLAC/MP3/Opus fit within - # 48-64 KiB; AAC-LC requires 880 KiB (av_tx float MDCT tables ~541 KiB). - COMPR_FFMPEG_DEC_HEAP 49152 + # Modular heap requirement (mod_alloc): up to 192 KiB DP output ring + + # 64 KiB PCM staging buffer + 4 KiB input bounce buffer + 4 KiB + # extradata + 32 KiB packet scratch + FLAC/MP3/Opus decoder working set + # fit within 512 KiB; AAC-LC requires 880 KiB (av_tx float MDCT tables + # ~541 KiB). + COMPR_FFMPEG_DEC_HEAP 524288 + + # When true, adds a compress *capture* PCM driven by the FFmpeg encoder + # (ffmpeg_enc, PCM -> MP3 via libshine or AAC-LC via vo-aacenc). + # Independent of the decode COMPR_FFMPEG path above; uses its own + # pcm/pipeline ids so both may be built into one topology. The + # platform-specific capture-BE tap source (COMPR_ENC_SOURCE) and the + # HDA-specific PCM name are set where the BE is defined + # (cavs-mixin-mixout-hda.conf). + COMPR_FFMPEG_ENC false + COMPR_ENC_PCM_NAME 'Compress Capture' + COMPR_ENC_PCM_ID 51 + COMPR_ENC_PIPELINE_ID 91 + # LL mixout that taps the capture-BE mixin fan-out and feeds the DP + # encoder pipeline (COMPR_ENC_PIPELINE_ID) across a pipeline boundary. + COMPR_ENC_MIXOUT_PIPELINE_ID 93 + COMPR_ENCODER_CORE_ID 0 + COMPR_FFMPEG_ENC_STACK 65536 + # Modular heap requirement (mod_alloc): 48 KiB DP output ring (3x 16 KiB) + + # 48 KiB LL->DP input ring (3x 16 KiB) + 80 KiB FFmpeg libshine packet buffer + + # ~32 KiB staging (pcm_in, out_stage, pcm_s16 / AVFrame) + ~48 KiB libshine / + # vo-aacenc state + AVCodecContext/AVPacket/AVFrame and allocator overhead + # fits within 384 KiB. + COMPR_FFMPEG_ENC_HEAP 393216 COMPRESSED_2 false diff --git a/topology2/platform/intel/compr-ffmpeg.conf b/topology2/platform/intel/compr-ffmpeg.conf index 8d31a0a..cc80c07 100644 --- a/topology2/platform/intel/compr-ffmpeg.conf +++ b/topology2/platform/intel/compr-ffmpeg.conf @@ -27,24 +27,12 @@ IncludeByKey.COMPR_FFMPEG { } Object.Widget.ffmpeg_dec.1 { - # Offload ffmpeg_dec to core 1 to free core-0 headroom (core 0 - # also runs DRC/IIR). The cross-core bind (host-copier/mixer on - # core 0) takes the IDC get_attribute path, whose remote handler - # used to memcpy ipc4_base_module_cfg straight into a COHERENT - # (uncached) buffer -- a struct-width store to the uncached alias - # faults EXCCAUSE 9 on Xtensa. Fixed in firmware (idc.c / - # component_ext.h ipc4_coherent_copy32: fill a local cacheable - # copy, publish with aligned 32-bit stores). Requires that fw. - core_id 1 - # This sizes the DP (data-processing) thread stack. It runs - # both the per-frame decode AND the one-time, deferred - # avcodec_open2: prepare() deliberately skips the open (running - # it on the core's single IDC worker would stall a cross-core - # prepare/trigger), so the first process() on this DP thread - # builds the codec tables. AAC-LC float -- the av_tx MDCT table - # build plus per-frame imdct1024 / windowing / float_dsp -- is - # the deepest path and needs 256 KiB; fixed-point FLAC/MP3 are - # far shallower but share this stack. + # Offload ffmpeg_dec to COMPR_DECODER_CORE_ID (default core 1) + # to free core-0 headroom for LL pipelines. + core_id $COMPR_DECODER_CORE_ID + # Sizes the DP (data-processing) thread stack and module heap. + # The DP thread runs both the one-time deferred avcodec_open2() + # (after container header stripping) and per-frame decoding. stack_bytes_requirement $COMPR_FFMPEG_DEC_STACK heap_bytes_requirement $COMPR_FFMPEG_DEC_HEAP # Optional codec setup control: extradata may be delivered via diff --git a/topology2/platform/intel/dmic-default.conf b/topology2/platform/intel/dmic-default.conf index 7e11a7a..5b09a3c 100644 --- a/topology2/platform/intel/dmic-default.conf +++ b/topology2/platform/intel/dmic-default.conf @@ -48,7 +48,7 @@ Define { DMIC0_PCM_CHANNELS 0 # Deep buffer capture - DMIC0_DEEP_BUFFER_PCM_NAME "DMIC Deep Buffer" + DMIC0_DEEP_BUFFER_PCM_NAME "Deepbuffer DMIC" DMIC0_DEEP_BUFFER_PIPELINE_ID 18 DMIC0_DEEP_BUFFER_PCM_ID 46 DMIC0_DEEP_BUFFER false diff --git a/topology2/platform/intel/sdw-amp-aec.conf b/topology2/platform/intel/sdw-amp-aec.conf new file mode 100644 index 0000000..ec11b6c --- /dev/null +++ b/topology2/platform/intel/sdw-amp-aec.conf @@ -0,0 +1,337 @@ +# SPDX-License-Identifier: BSD-3-Clause +# +# Mono 16 kHz WebRTC AEC for SoundWire DMIC with speaker echo reference. +# +# module-copier.41.0 (SDW DMIC, 48 kHz stereo) -> micsel.141.1 (L+R)/2 -> +# src.141.1 (48 -> 16 kHz) -> webrtc-aec.140.1 pin 0 +# speaker echo reference siggen.120.1 (48 kHz stereo) -> micsel.120.1 (L+R)/2 -> +# src.120.1 (48 -> 16 kHz) -> webrtc-aec.140.1 pin 1 +# webrtc-aec.140.1 -> host-copier PCM "Microphone AEC Capture" (16 kHz mono) +# +# Included from sdw-amp-echo-ref.conf when SDW_SPK_AEC_CAPTURE_PCM is true. The echo +# reference DAI (SDW_ECHO_REF_DAI) must be enabled. + +Class.Pipeline."sdw-aec-capture" { + + + attributes { + !constructor [ + "index" + ] + unique "instance" + } + + Object.Widget.pipeline."1" { + priority 0 + lp_mode 0 + } + + period 1000 + direction "capture" + time_domain "timer" + dynamic_pipeline 1 +} + +Define { + SDW_AEC_PCM_ID 14 + SDW_AEC_PCM_NAME "Microphone AEC Capture" + SDW_AEC_PIPELINE_ID 140 + SDW_AEC_MIC_PIPELINE_ID 141 +} + +# Echo reference: siggen -> micsel stereo to mono -> SRC 48 kHz to 16 kHz +Object.Pipeline."sdw-aec-capture" [ + { + index $SDW_SPK_ECHO_REF_PIPELINE_ID + + Object.Widget.siggen.1 { + num_input_pins 1 + num_output_pins 1 + num_input_audio_formats 1 + num_output_audio_formats 1 + Object.Base.input_audio_format [ + { + in_bit_depth 32 + in_valid_bit_depth 32 + } + ] + Object.Base.output_audio_format [ + { + out_bit_depth 32 + out_valid_bit_depth 32 + } + ] + } + + Object.Widget.micsel.1 { + num_input_audio_formats 1 + num_output_audio_formats 1 + Object.Control.bytes."1" { + name "AEC reference micsel bytes" + + } + Object.Base.input_audio_format [ + { + in_rate 48000 + in_channels 2 + in_ch_cfg $CHANNEL_CONFIG_STEREO + in_ch_map $CHANNEL_MAP_STEREO + in_bit_depth 32 + in_valid_bit_depth 32 + } + ] + Object.Base.output_audio_format [ + { + out_rate 48000 + out_channels 1 + out_ch_cfg $CHANNEL_CONFIG_MONO + out_ch_map $CHANNEL_MAP_MONO + out_bit_depth 32 + out_valid_bit_depth 32 + } + ] + } + + Object.Widget.src.1 { + num_input_audio_formats 1 + num_output_audio_formats 1 + Object.Base.input_audio_format [ + { + in_rate 48000 + in_channels 1 + in_ch_cfg $CHANNEL_CONFIG_MONO + in_ch_map $CHANNEL_MAP_MONO + in_bit_depth 32 + in_valid_bit_depth 32 + } + ] + Object.Base.output_audio_format [ + { + out_rate 16000 + out_channels 1 + out_ch_cfg $CHANNEL_CONFIG_MONO + out_ch_map $CHANNEL_MAP_MONO + out_bit_depth 32 + out_valid_bit_depth 32 + } + ] + } + } +] + +# Microphone: micsel stereo to mono -> SRC 48 kHz to 16 kHz +Object.Pipeline."sdw-aec-capture" [ + { + index $SDW_AEC_MIC_PIPELINE_ID + + Object.Widget.micsel.1 { + num_input_audio_formats 1 + num_output_audio_formats 1 + Object.Control.bytes."1" { + name "AEC microphone micsel bytes" + + } + Object.Base.input_audio_format [ + { + in_rate 48000 + in_channels 2 + in_ch_cfg $CHANNEL_CONFIG_STEREO + in_ch_map $CHANNEL_MAP_STEREO + in_bit_depth 32 + in_valid_bit_depth 32 + } + ] + Object.Base.output_audio_format [ + { + out_rate 48000 + out_channels 1 + out_ch_cfg $CHANNEL_CONFIG_MONO + out_ch_map $CHANNEL_MAP_MONO + out_bit_depth 32 + out_valid_bit_depth 32 + } + ] + } + + Object.Widget.src.1 { + num_input_audio_formats 1 + num_output_audio_formats 1 + Object.Base.input_audio_format [ + { + in_rate 48000 + in_channels 1 + in_ch_cfg $CHANNEL_CONFIG_MONO + in_ch_map $CHANNEL_MAP_MONO + in_bit_depth 32 + in_valid_bit_depth 32 + } + ] + Object.Base.output_audio_format [ + { + out_rate 16000 + out_channels 1 + out_ch_cfg $CHANNEL_CONFIG_MONO + out_ch_map $CHANNEL_MAP_MONO + out_bit_depth 32 + out_valid_bit_depth 32 + } + ] + } + } +] + +# AEC and host capture +Object.Pipeline.host-gateway-capture [ + { + index $SDW_AEC_PIPELINE_ID + + Object.Widget.host-copier.1 { + stream_name $SDW_AEC_PCM_NAME + pcm_id $SDW_AEC_PCM_ID + num_input_audio_formats 1 + num_output_audio_formats 2 + Object.Base.input_audio_format [ + { + in_rate 16000 + in_channels 1 + in_ch_cfg $CHANNEL_CONFIG_MONO + in_ch_map $CHANNEL_MAP_MONO + in_bit_depth 32 + in_valid_bit_depth 32 + } + ] + Object.Base.output_audio_format [ + { + out_rate 16000 + out_channels 1 + out_ch_cfg $CHANNEL_CONFIG_MONO + out_ch_map $CHANNEL_MAP_MONO + out_bit_depth 16 + out_valid_bit_depth 16 + } + { + out_rate 16000 + out_channels 1 + out_ch_cfg $CHANNEL_CONFIG_MONO + out_ch_map $CHANNEL_MAP_MONO + out_bit_depth 32 + out_valid_bit_depth 32 + } + ] + } + } +] + +Object.Widget.webrtc-aec.1 { + index $SDW_AEC_PIPELINE_ID + num_input_pins 2 + + Object.Control { + mixer."1" { + name "AEC switch" + } + mixer."2" { + name "AEC high suppression switch" + } + } + + Object.Base.input_pin_binding.1 { + input_pin_binding_name "src.$SDW_AEC_MIC_PIPELINE_ID.1" + } + Object.Base.input_pin_binding.2 { + input_pin_binding_name "src.$SDW_SPK_ECHO_REF_PIPELINE_ID.1" + } + + Object.Base.input_audio_format [ + { + input_pin_index 0 + in_rate 16000 + in_channels 1 + in_ch_cfg $CHANNEL_CONFIG_MONO + in_ch_map $CHANNEL_MAP_MONO + in_bit_depth 32 + in_valid_bit_depth 32 + ibs 640 + } + { + input_pin_index 1 + in_rate 16000 + in_channels 1 + in_ch_cfg $CHANNEL_CONFIG_MONO + in_ch_map $CHANNEL_MAP_MONO + in_bit_depth 32 + in_valid_bit_depth 32 + ibs 640 + } + ] + Object.Base.output_audio_format [ + { + out_rate 16000 + out_channels 1 + out_ch_cfg $CHANNEL_CONFIG_MONO + out_ch_map $CHANNEL_MAP_MONO + out_bit_depth 32 + out_valid_bit_depth 32 + obs 640 + } + ] +} + +Object.PCM.pcm [ + { + name $SDW_AEC_PCM_NAME + id $SDW_AEC_PCM_ID + direction "capture" + Object.Base.fe_dai.1 { + name $SDW_AEC_PCM_NAME + } + Object.PCM.pcm_caps.1 { + name $SDW_AEC_PCM_NAME + formats 'S16_LE,S32_LE' + rates "16000" + rate_min 16000 + rate_max 16000 + channels_min 1 + channels_max 1 + } + } +] + +Object.Base.route [ + { + source "alh-copier.Loopback_Virtual.25" + sink "siggen.$SDW_SPK_ECHO_REF_PIPELINE_ID.1" + } + { + source "module-copier.21.22" + sink "siggen.$SDW_SPK_ECHO_REF_PIPELINE_ID.1" + } + { + source "siggen.$SDW_SPK_ECHO_REF_PIPELINE_ID.1" + sink "micsel.$SDW_SPK_ECHO_REF_PIPELINE_ID.1" + } + { + source "micsel.$SDW_SPK_ECHO_REF_PIPELINE_ID.1" + sink "src.$SDW_SPK_ECHO_REF_PIPELINE_ID.1" + } + { + source "src.$SDW_SPK_ECHO_REF_PIPELINE_ID.1" + sink "webrtc-aec.$SDW_AEC_PIPELINE_ID.1" + } + { + source "module-copier.41.0" + sink "micsel.$SDW_AEC_MIC_PIPELINE_ID.1" + } + { + source "micsel.$SDW_AEC_MIC_PIPELINE_ID.1" + sink "src.$SDW_AEC_MIC_PIPELINE_ID.1" + } + { + source "src.$SDW_AEC_MIC_PIPELINE_ID.1" + sink "webrtc-aec.$SDW_AEC_PIPELINE_ID.1" + } + { + source "webrtc-aec.$SDW_AEC_PIPELINE_ID.1" + sink "host-copier.$SDW_AEC_PCM_ID.capture" + } +] diff --git a/topology2/platform/intel/sdw-amp-echo-ref.conf b/topology2/platform/intel/sdw-amp-echo-ref.conf index abde205..1f43e63 100644 --- a/topology2/platform/intel/sdw-amp-echo-ref.conf +++ b/topology2/platform/intel/sdw-amp-echo-ref.conf @@ -5,6 +5,9 @@ Define { IncludeByKey.SDW_SPK_ECHO_REF { "true" { + # With SDW_SPK_AEC_CAPTURE_PCM the reference feeds webrtc-aec instead of a host PCM + IncludeByKey.SDW_SPK_AEC_CAPTURE_PCM { + "false" { Object.Pipeline { siggen-host-copier-capture [ { @@ -48,5 +51,7 @@ IncludeByKey.SDW_SPK_ECHO_REF { sink "host-copier.$SDW_SPK_ECHO_REF_PCM_ID.capture" } ] + } # SDW_SPK_AEC_CAPTURE_PCM false + } } # SDW_SPK_ECHO_REF true } diff --git a/topology2/platform/intel/sdw-amp-xover.conf b/topology2/platform/intel/sdw-amp-xover.conf index 3347d49..3e2b75d 100644 --- a/topology2/platform/intel/sdw-amp-xover.conf +++ b/topology2/platform/intel/sdw-amp-xover.conf @@ -72,7 +72,8 @@ Object.Pipeline { } in_bit_depth 32 in_valid_bit_depth 32 - in_fmt_cfg "$[($in_channels | ($in_valid_bit_depth * 256))]" + in_sample_type $SAMPLE_TYPE_LSB_INTEGER + in_fmt_cfg "$[($in_channels | ($in_valid_bit_depth * 256)) | ($in_sample_type * 65536)]" } ] num_output_audio_formats 1 @@ -127,6 +128,7 @@ Object.Pipeline { { in_bit_depth 32 in_valid_bit_depth 32 + in_fmt_cfg "$[($in_channels | ($in_valid_bit_depth * 256)) | ($in_sample_type * 65536)]" } ] num_output_audio_formats 1 @@ -442,7 +444,6 @@ IncludeByKey.NUM_SDW_AMP_LINKS { } in_bit_depth 32 in_valid_bit_depth 32 - in_fmt_cfg "$[($in_channels | ($in_valid_bit_depth * 256))]" } ] Object.Base.output_audio_format [ diff --git a/topology2/platform/intel/uaol-deep-buffer.conf b/topology2/platform/intel/uaol-deep-buffer.conf index 572c9fc..1d2f6cc 100644 --- a/topology2/platform/intel/uaol-deep-buffer.conf +++ b/topology2/platform/intel/uaol-deep-buffer.conf @@ -15,11 +15,19 @@ Object.Pipeline.deepbuffer-playback [ Object.Widget.host-copier.1 { stream_name $UAOL_DB_PCM_NAME pcm_id $UAOL_DB_PCM_ID + + } Object.Widget.gain.1 { Object.Control.mixer.1 { name 'Pre Mixer $UAOL_DB_PCM_NAME Volume' } + + + } + Object.Widget.mixin.1 { + + } } ] @@ -37,14 +45,19 @@ Object.PCM.pcm [ Object.PCM.pcm_caps.1 { name $UAOL_DB_PCM_NAME formats 'S16_LE,S24_LE,S32_LE' + channels_min $UAOL_CHANNELS_MIN + channels_max $UAOL_CHANNELS_MAX + rates $UAOL_RATES + rate_min $UAOL_RATE_MIN + rate_max $UAOL_RATE_MAX # To avoid DMA spinning on a buffer we need bigger # buffer than the host buffer size, let's say twice as # big - # (S16_LE, Stereo, 48KHz, DEEPBUFFER_FW_DMA_MS) * 2 + # (S16_LE, minimum channels/rate, DEEPBUFFER_FW_DMA_MS) * 2 # # Note: The lower limit for the buffer size is rate # dependent - buffer_size_min "$[(((2 * $channels_min) * 48) * $DEEPBUFFER_FW_DMA_MS) * 2]" + buffer_size_min "$[(((((2 * $channels_min) * $rate_min) * $DEEPBUFFER_FW_DMA_MS) * 2) / 1000)]" } } ] diff --git a/topology2/platform/intel/uaol-deep-buffer1.conf b/topology2/platform/intel/uaol-deep-buffer1.conf index 2429123..61c3ca3 100644 --- a/topology2/platform/intel/uaol-deep-buffer1.conf +++ b/topology2/platform/intel/uaol-deep-buffer1.conf @@ -11,11 +11,19 @@ Object.Pipeline.deepbuffer-playback [ Object.Widget.host-copier.1 { stream_name $UAOL_DB1_PCM_NAME pcm_id $UAOL_DB1_PCM_ID + + } Object.Widget.gain.1 { Object.Control.mixer.1 { name 'Pre Mixer $UAOL_DB1_PCM_NAME Volume' } + + + } + Object.Widget.mixin.1 { + + } } ] @@ -33,14 +41,19 @@ Object.PCM.pcm [ Object.PCM.pcm_caps.1 { name $UAOL_DB1_PCM_NAME formats 'S16_LE,S24_LE,S32_LE' + channels_min $UAOL_CHANNELS_MIN + channels_max $UAOL_CHANNELS_MAX + rates $UAOL_RATES + rate_min $UAOL_RATE_MIN + rate_max $UAOL_RATE_MAX # To avoid DMA spinning on a buffer we need bigger # buffer than the host buffer size, let's say twice as # big - # (S16_LE, Stereo, 48KHz, DEEPBUFFER_FW_DMA_MS) * 2 + # (S16_LE, minimum channels/rate, DEEPBUFFER_FW_DMA_MS) * 2 # # Note: The lower limit for the buffer size is rate # dependent - buffer_size_min "$[(((2 * $channels_min) * 48) * $DEEPBUFFER_FW_DMA_MS) * 2]" + buffer_size_min "$[(((((2 * $channels_min) * $rate_min) * $DEEPBUFFER_FW_DMA_MS) * 2) / 1000)]" } } ] diff --git a/topology2/platform/intel/uaol-generic.conf b/topology2/platform/intel/uaol-generic.conf index 41816ca..378ce32 100644 --- a/topology2/platform/intel/uaol-generic.conf +++ b/topology2/platform/intel/uaol-generic.conf @@ -28,9 +28,8 @@ # goes. The kernel narrows the PCM down to what the connected device actually # supports. # -# The deep buffer PCM is left at 48 kHz stereo, the default of the -# deepbuffer-playback pipeline. It can only join the mixer while the normal -# playback PCM runs at that format, or is not running at all. +# The deep buffer PCM carries the same formats as normal playback. Both PCMs +# can join the mixer when their rates and channel counts match. # Deep buffer playback, included when UAOL_DEEP_BUFFER is true and the DMA # buffer is 1 - 1000 ms. The deep buffers of the UAOL streams are instances of diff --git a/topology2/production/CMakeLists.txt b/topology2/production/CMakeLists.txt index cc07aed..eabda67 100644 --- a/topology2/production/CMakeLists.txt +++ b/topology2/production/CMakeLists.txt @@ -30,7 +30,7 @@ foreach(tplg ${TPLGS}) "${CMAKE_CURRENT_SOURCE_DIR}/../${input}" "${output}" "${CMAKE_CURRENT_SOURCE_DIR}/../" "${defines}") - add_custom_target(topology2_prod_${output} DEPENDS ${output}.tplg) + add_custom_target(topology2_prod_${output} DEPENDS ${tplg2_outputs}) add_dependencies(topology2_prod topology2_prod_${output}) endforeach() @@ -51,6 +51,8 @@ foreach(link ${SYMLINKS}) ) add_custom_target(topology2_prod_${link_name} DEPENDS ${link_name}.tplg) + # the alias is only as good as its target, build and validate it too + add_dependencies(topology2_prod_${link_name} topology2_prod_${link_target}) add_dependencies(topology2_prod topology2_prod_${link_name}) endforeach() diff --git a/topology2/production/tplg-targets-ace3.cmake b/topology2/production/tplg-targets-ace3.cmake index 1be9cfe..eea1706 100644 --- a/topology2/production/tplg-targets-ace3.cmake +++ b/topology2/production/tplg-targets-ace3.cmake @@ -108,10 +108,6 @@ SDW_JACK_OUT_STREAM=Playback-SimpleJack,SDW_JACK_IN_STREAM=Capture-SimpleJack,\ PREPROCESS_PLUGINS=nhlt,NHLT_BIN=nhlt-sof-ptl-rt722-4ch.bin,DMIC0_ENHANCED_CAPTURE=true,\ EFX_DMIC0_TDFB_PARAMS=line4_pass,EFX_DMIC0_DRC_PARAMS=dmic_default" -# DMIC WoV feature topology; platform-agnostic, shared across PTL/WCL -"dmic-wov-feature\;sof-dmic-4ch-wov\;PLATFORM=none,NUM_DMICS=4,\ -DMIC0_ID=5,DMIC1_ID=6,DMIC1_ENABLE=false,DMIC1_RATE=16000,INCLUDE_WOV=true" - "cavs-sdw\;sof-ptl-rt722-2ch\;PLATFORM=ptl,SDW_DMIC=1,NUM_SDW_AMP_LINKS=1,NUM_DMICS=2,\ PDM1_MIC_A_ENABLE=0,PDM1_MIC_B_ENABLE=0,DMIC0_ID=5,DMIC1_ID=6,HDMI1_ID=7,HDMI2_ID=8,HDMI3_ID=9,\ SDW_AMP_FEEDBACK=false,SDW_SPK_STREAM=Playback-SmartAmp,SDW_DMIC_STREAM=Capture-SmartMic,\ @@ -355,13 +351,10 @@ HEADSET_CODEC=false,HDMI_IN_CAPTURE=false,BT_ID=2,PREPROCESS_PLUGINS=nhlt,\ NHLT_BIN=nhlt-sof-ptl-ssp2-bt-id2.bin" #BT_ID=8, 10 for sdw_sof machine -"cavs-sdw\;sof-ptl-ssp2-bt-id8\;PLATFORM=ptl,ADD_BT=true,SDW_JACK=false,NUM_HDMIS=0,\ +"cavs-sdw\;sof-ptl-ssp2-bt-id8\;PLATFORM=ptl,ADD_BT=true,BT_DEEP_BUFFER=true,SDW_JACK=false,NUM_HDMIS=0,\ HEADSET_CODEC=false,HDMI_IN_CAPTURE=false,BT_ID=8,BT_PCM_ID=20,BT_PCM_NAME=Bluetooth,\ -BT_CP_HOST_PIPELINE_ID=201,PREPROCESS_PLUGINS=nhlt,NHLT_BIN=nhlt-sof-ptl-ssp2-bt-id8.bin" - -"cavs-sdw\;sof-ptl-ssp2-bt-id10\;PLATFORM=ptl,ADD_BT=true,SDW_JACK=false,NUM_HDMIS=0,\ -HEADSET_CODEC=false,HDMI_IN_CAPTURE=false,BT_ID=10,BT_PCM_ID=20,BT_PCM_NAME=Bluetooth,\ -BT_CP_HOST_PIPELINE_ID=201,PREPROCESS_PLUGINS=nhlt,NHLT_BIN=nhlt-sof-ptl-ssp2-bt-id10.bin" +BT_PB_HOST_PIPELINE_ID=200,BT_PB_DAI_PIPELINE_ID=201,BT_CP_HOST_PIPELINE_ID=202,BT_CP_DAI_PIPELINE_ID=203,\ +PREPROCESS_PLUGINS=nhlt,NHLT_BIN=nhlt-sof-ptl-ssp2-bt-id8.bin" ) list(APPEND SYMLINKS diff --git a/topology2/production/tplg-targets-cavs25.cmake b/topology2/production/tplg-targets-cavs25.cmake index 977cc29..dfe429d 100644 --- a/topology2/production/tplg-targets-cavs25.cmake +++ b/topology2/production/tplg-targets-cavs25.cmake @@ -10,6 +10,10 @@ list(APPEND TPLGS "cavs-sdw\;sof-adl-rt711-l0-rt1316-l13-rt714-l2\;NUM_SDW_AMP_LINKS=2,\ SDW_DMIC=1,SDW_DMIC_STREAM=SDW2-Capture" +"cavs-sdw\;sof-rpl-rt711-l2-rt1316-l01-rt714-l3\;NUM_SDW_AMP_LINKS=2,SDW_DMIC=1,\ +SDW_JACK_OUT_STREAM=SDW2-Playback,SDW_JACK_IN_STREAM=SDW2-Capture,\ +SDW_SPK_STREAM=SDW0-Playback,SDW_SPK_IN_STREAM=SDW0-Capture" + # IPC4 topology for TGL/ADL rt711 Headset + rt1308 Amplifier + rt715 DMIC "cavs-sdw\;sof-tgl-rt711-rt1308-rt715\;NUM_SDW_AMP_LINKS=2,SDW_DMIC=1,SDW_AMP_FEEDBACK=false" diff --git a/topology2/sof-hda-generic.conf b/topology2/sof-hda-generic.conf index c915ffd..968d463 100644 --- a/topology2/sof-hda-generic.conf +++ b/topology2/sof-hda-generic.conf @@ -23,11 +23,14 @@ + + + @@ -37,21 +40,29 @@ + - + + + + + + + Define { HDA_CONFIG "none" PLATFORM "none" NUM_DMICS 0 + ADD_BT false # doesn't it need to define DMIC0_HOST_PIPELINE_SINK and DMIC0_DAI_PIPELINE_SRC? DMIC0_HOST_PIPELINE_SINK 'host-copier.6.capture' DMIC0_DAI_PIPELINE_SRC 'module-copier.12.2' @@ -67,6 +78,10 @@ IncludeByKey.PLATFORM { "ptl" "platform/intel/ptl.conf" } +IncludeByKey.ADD_BT { + "true" "platform/intel/bt-generic.conf" +} + # include HDA config if needed. IncludeByKey.HDA_CONFIG { "mix" "cavs-mixin-mixout-hda.conf" @@ -96,6 +111,10 @@ IncludeByKey.NUM_HDMIS { "[3-4]" "platform/intel/hdmi-generic.conf" } +IncludeByKey.HDMI_IN_CAPTURE { + "true" "platform/intel/hdmi-in-capture.conf" +} + Object.Widget.virtual [ { name 'codec0_in' diff --git a/validator/README.md b/validator/README.md new file mode 100644 index 0000000..fcdc40a --- /dev/null +++ b/validator/README.md @@ -0,0 +1,184 @@ +# Topology validator (`validator/`) + +`tplg_validate.py` checks SOF IPC4 topology binaries (`.tplg`) offline, without +target hardware. It parses the binary and repeats what the Linux SOF driver +does when it loads the topology, so that problems show up at build time +instead of on a device. `alsatplg` accepts many topologies that the kernel +rejects; for instance it prints `undefined sink widget` for a dangling route +and still exits successfully. + +```bash +# check topologies, print errors and warnings +validator/tplg_validate.py build/topology2/production/sof-mtl-rt711-4ch.tplg + +# also print informational findings, check core IDs against a 5 core DSP +tplg_validate.py -v --num-cores 5 *.tplg + +# list the rules and the kernel functions they mirror +tplg_validate.py --list-rules + +# print the decoded topology with kernel token names +tplg_validate.py --dump foo.tplg + +# check a feature topology on top of the topologies loaded before it, in load order +tplg_validate.py --base sof-sdca-1amp-id2.tplg --base sof-sdca-jack-id0.tplg \ + --base sof-sdca-jack-ref-dai.tplg sof-sdca-amp-ref.tplg +``` + +Exit status is 1 if any error is found (`--werror`: any warning). Python 3.8+ +and the `construct` module (`python3-construct`) are required. + +## Build integration + +`add_alsatplg2_command` in `cmake/alsatplg.cmake` runs the validator +after `alsatplg` for every topology v2 target, unless configured with +`-DTPLG_VALIDATE=OFF` or `construct` is missing. A successful check writes a +`.tplg.validated` stamp file. An error fails the target and leaves no +stamp, so the check reruns on the next build. Changes to the validator sources +or to `known-issues.txt` recheck all topologies without rebuilding them. + +Known errors are listed in `known-issues.txt` as ` ` +pairs and reported as warnings. Do not add entries to silence new errors: +fix the topology. Remove entries when a topology is fixed. + +Feature topologies are listed there as well. The kernel loads them into the +same component after the function topologies and after the feature +topologies given before them, and their routes may refer to widgets of those +topologies. They are checked alone at build time, so check them by hand with +`--base`, giving the topologies loaded before them in load order. + +## What is checked + +Rules are grouped in layers by how closely they follow kernel code: + +| Layer | Mirrors | Examples | +|-------|---------|----------| +| L1 | `sound/soc/soc-topology.c` | headers, element sizes, names, kcontrol handler IDs, TLV types | +| L2 | `sound/soc/sof/topology.c` tuple engine | kernel parse errors, tuple types, audio format blocks vs. counts | +| L3 | `topology.c`, `ipc4-topology.c` setup | routes, pipelines, chain DMA, DAI types, pins, bytes controls, PCM binding | +| L4 | `sof-audio.c` path walk, format selection | PCM formats vs. host formats (advisory), pin compatibility, copier selection contract | + +`F003` checks each firmware route's actual output/input pin pair. Single-pin +endpoints use pin 0; multi-pin endpoints require explicit bindings. Disjoint +declared format sets produce an error naming both pins and their formats, and +fail validation without `--werror`. +Comparison requires matching rate, channel count and valid-bit depth, with +sample types treated according to their declared representations. Signed +integer alignment variants share a format for 16/20/24 valid bits; at 32/32, +MSB, LSB and signed integer representations share the same full-width +two's-complement format. Other integer layouts and non-integer representations +remain distinct. `T008` also rejects unknown types, valid depths larger than +their containers, unsigned integer other than 8/8, float other than 32/32, and +A-law or mu-law other than 8/8. In SOF firmware, internal 24-bit MSB and LSB +integer declarations both use the same DSP format; copier gateway conversion +handles external alignment. The check validates declared format compatibility, +not the behavior of a particular kernel version or the sample alignment +performed at runtime. It does not validate container/layout compatibility +between pins or simulate runtime format selection: overlapping sets only +establish possible compatibility, not that every PCM configuration works. + +Unresolved pins or missing formats are informational (`-v`), not guessed. +Mixer outputs share the module's output formats across pins. Undeclared +secondary copier outputs are configured from the sink at bind time; +they are not constrained to pin 0. Process output pins without declarations +use the pin-0 fallback. Missing process extension formats remain covered by +`W008`. Chain-DMA and DAPM-only routes are skipped. An unbound siggen input +has no firmware route to check. Feature routes use widgets from `--base`. + +### Copier output selection (F004) + +F004 checks a topology declaration contract, not the behavior of every kernel +version. A copier cannot resample. For each declared input pin 0 alternative, +each checked output pin must be selectable at that input rate: + +1. Consider only output alternatives at the input rate. +2. If they all declare the same channel count, use that count; otherwise preserve + the input channel count. +3. If they all declare the same sample representation (valid bits and the + normalized type/representation used by F003), use it; otherwise preserve the + input representation. +4. The resulting **complete combination** must exist in the output declarations. + Selecting individual fields must not invent an undeclared combination. + +This permits a fixed output conversion, broad format-preserving UAOL tables, +and fixed S32 conversion with input-dependent stereo/4-channel output. Each pin +is evaluated independently; a fixed format on one output does not constrain the +others. Output pin 0 must be selectable even if the first path prepared leaves +on a secondary output, because input 0 and output 0 are configured at init. + +The rule checks module-copier output 0 and declared secondary outputs of module, +host and DAI copiers. Gateway output 0 is excluded: its selection can depend on +FE/BE parameters and gateway-specific container handling. Undeclared secondary +outputs are reported as INFO, not rejected: their formats come from the sink at +bind time, so this check cannot establish prepare/bind consistency. Incomplete +declarations also produce INFO rather than a speculative selection error. +Chain-DMA pipelines are skipped. + +All declared input alternatives are checked, not just combinations reachable at +runtime. Like F003, this does not validate container/layout compatibility or +firmware converter availability. F003 checks overlap between connected pins; +F004 checks selection within a copier. Passing both does not prove whole-path +compatibility or that a given kernel propagates the selected format correctly. + +Every finding names the rule and the relevant kernel path it models. These +references explain how topology objects and connections are interpreted; they +do not make findings predictions about how a specific kernel version handles +an invalid or incompatible topology. For example: + +``` +foo.tplg: error: G001 route 'mixin.90.1' -> 'mixout.1.1': sink widget 'mixout.1.1' does not exist (kernel: snd_soc_dapm_add_routes, sof_route_load) +``` + +Severities: `error` means the topology fails validation, usually because the +kernel fails to load it or an affected PCM fails when used. `F003` also treats +disjoint declared pin formats as errors, and `F004` rejects declarations that +violate the copier selection contract, without simulating firmware behavior. +`warning` means a likely mistake, or a failure that depends on runtime state the +validator cannot know. `info` lists observations (`-v`). + +Not checked, because the data only exists on the target: firmware module +UUIDs and module types from the firmware manifest, ACPI NHLT blobs, machine +driver BE links, and the DSP's answers to IPC messages. + +## Keeping up with the kernel + +The kernel driver is the reference. The validator follows it in two ways: + +- **Generated token schema.** `schema/kernel_tokens.py` is generated from a + kernel tree by `schema/gen_kernel_tokens.py`. It holds the `SOF_TKN_*` IDs, the + `struct sof_topology_token` tables with token types, the per widget type + token lists of `tplg_ipc4_widget_ops`, the DAI type names and the kcontrol + handler IDs. `tplgparse/kernel_engine.py` emulates the kernel tuple parser + (`sof_parse_token_sets()`, `sof_copy_tuples()`, `sof_update_ipc_object()`) + on top of these tables. New tokens or widget types only need a + regeneration: + + ```bash + schema/gen_kernel_tokens.py --kernel ~/linux # update kernel_tokens.py + schema/gen_kernel_tokens.py --kernel ~/linux --check # CI: fail on drift + ``` + +- **Hand written rules** in `checks/`. Each rule names the kernel function it + mirrors (`--list-rules`). Changes that add or remove topology checks in + `sound/soc/sof/ipc4-topology.c` or `topology.c` should get a matching rule + update here. + +`schema/check_tokens_conf.py` cross-checks `topology2/include/common/tokens.conf` +and the `token_ref` attributes of the topology2 classes against the kernel schema. + +## Layout + +``` +tplg_validate.py command line tool +tplgparse/binary.py ALSA topology binary format (ported from sof-test tplgtool2.py) +tplgparse/model.py typed view, vendor tuples decoded as written +tplgparse/kernel_engine.py kernel tuple engine emulation +schema/ generated kernel token schema and its generator +checks/ rules, one module per layer +tests/ pytest suite; tplgbuild.py builds test topologies +known-issues.txt waived errors +``` + +Run the tests with `pytest validator/tests`. Set `ALSATPLG` +to select the `alsatplg` binary for the integration tests and `KERNEL_TREE` +to include the schema drift check. diff --git a/validator/checks/__init__.py b/validator/checks/__init__.py new file mode 100644 index 0000000..1e1efcb --- /dev/null +++ b/validator/checks/__init__.py @@ -0,0 +1,126 @@ +# SPDX-License-Identifier: BSD-3-Clause +# +# Copyright(c) 2026 Intel Corporation. All rights reserved. + +"""Rule registry and runner. + +A rule is a generator function taking a Context and yielding +(where, message) or (where, message, severity) tuples. Each rule names +the kernel function it mirrors so that it can be reviewed against kernel +changes, see `tplg_validate.py --list-rules`. + +Layers: + L1 binary structure, generic ASoC loader (soc-topology.c) + L2 vendor tuples as read by the SOF tuple engine (topology.c) + L3 IPC4 load time and pipeline setup rules (topology.c, ipc4-topology.c) + L4 PCM path and audio format simulation (sof-audio.c, ipc4-topology.c) +""" + +import importlib +from dataclasses import dataclass, field + +from tplgparse import kernel_engine + +ERROR, WARNING, INFO = "error", "warning", "info" +SEVERITIES = (ERROR, WARNING, INFO) + + +@dataclass +class Rule: + id: str + layer: str + severity: str + kernel: str + summary: str + func: object + + +@dataclass +class Finding: + rule: str + severity: str + where: str + message: str + kernel: str + + def format(self) -> str: + return f"{self.severity}: {self.rule} {self.where}: {self.message} (kernel: {self.kernel})" + + +@dataclass +class Options: + num_cores: int = 0 # 0: unknown, do not check + verbose: bool = False + + +@dataclass +class Context: + tplg: object + options: Options + _kernel_widgets: dict = field(default_factory=dict) + + def kw(self, widget) -> kernel_engine.KernelWidget: + "Kernel view of a widget, computed once." + key = id(widget) + if key not in self._kernel_widgets: + self._kernel_widgets[key] = kernel_engine.widget_ready(widget) + return self._kernel_widgets[key] + + def pipeline_widget(self, widget): + """The scheduler widget sof_complete() binds the widget to. + + Widgets are matched by section index, swidget->pipeline_id. + """ + for w in self.tplg.widgets + self.tplg.base_widgets: + if w.type_name == "scheduler" and w.index == widget.index: + return w + return None + + +RULES = [] + +MODULES = ("structure", "tokens", "ipc4", "paths") + + +def rule(rule_id, layer, severity, kernel, summary): + "Register a rule function." + def wrap(func): + RULES.append(Rule(rule_id, layer, severity, kernel, summary, func)) + return func + return wrap + + +def load_rules(): + for mod in MODULES: + importlib.import_module(f"checks.{mod}") + return RULES + + +def run(tplg, options: Options, selected=None) -> list: + """Run all (or the selected) rules over a topology. + + A rule only runs when every finding of the layers below it is clean + enough for its input to make sense: L2+ is skipped if L1 found errors, + since the parsed model may be incomplete. + """ + ctx = Context(tplg, options) + findings = [] + l1_errors = False + for r in load_rules(): + if selected is not None and r.id not in selected: + continue + if r.layer != "L1" and l1_errors: + continue + try: + for item in r.func(ctx) or (): + where, message = item[0], item[1] + sev = item[2] if len(item) > 2 else r.severity + findings.append(Finding(r.id, sev, where, message, r.kernel)) + if r.layer == "L1" and sev == ERROR: + l1_errors = True + except Exception as e: # pylint: disable=broad-except + # malformed input must fail this file, not stop the validator + findings.append(Finding(r.id, ERROR, "file", + f"validator internal error: {type(e).__name__}: {e}", + r.kernel)) + return findings diff --git a/validator/checks/ipc4.py b/validator/checks/ipc4.py new file mode 100644 index 0000000..b62e754 --- /dev/null +++ b/validator/checks/ipc4.py @@ -0,0 +1,605 @@ +# SPDX-License-Identifier: BSD-3-Clause +# +# Copyright(c) 2026 Intel Corporation. All rights reserved. + +"""L3: IPC4 load time and pipeline setup rules. + +Mirrors sound/soc/sof/topology.c (sof_widget_ready, sof_route_load, +sof_complete, sof_link_load, spcm_bind) and sound/soc/sof/ipc4-topology.c +(the ipc_setup callbacks, control setup, route setup, manifest parsing). +""" + +import struct +from collections import Counter + +from schema import kernel_tokens as kt +from tplgparse import binary +from tplgparse.binary import TplgType + +from . import ERROR, INFO, WARNING, rule +from .paths import fmt_key, host_copier, routes_on_pcm_paths + +VIRTUAL_TYPES = ("input", "output", "out_drv") # skipped by sof_route_setup() +AUDIO_FMT_TYPES = ("aif_in", "aif_out", "dai_in", "dai_out", "buffer", "pga", "mixer", + "src", "asrc", "effect", "decoder", "encoder") +PROCESS_TYPES = ("effect", "decoder", "encoder") +DAI_WIDGET_TYPES = ("dai_in", "dai_out") +IPC4_DAI_CONFIG_TYPES = ("SOF_DAI_INTEL_HDA", "SOF_DAI_INTEL_ALH", "SOF_DAI_INTEL_DMIC", + "SOF_DAI_INTEL_SSP") # sof_ipc4_dai_config() +CHAIN_DMA_DAI_TYPES = ("SOF_DAI_INTEL_HDA",) # hda_is_chain_dma_supported() + +TKN_SCHED_USE_CHAIN_DMA = 209 +TKN_SCHED_DYNAMIC_PIPELINE = 206 +TKN_SCHED_CORE = 203 +TKN_COMP_CORE_ID = 404 +TKN_COMP_UUID = 405 +TKN_DAI_TYPE = 154 +TKN_IN_PIN_INDEX = 1909 +TKN_OUT_PIN_INDEX = 1939 + +SNDRV_CTL_ELEM_ACCESS_VOLATILE = 1 << 2 +SND_SOC_TPLG_CTL_VOLSW, SND_SOC_TPLG_CTL_VOLSW_SX, SND_SOC_TPLG_CTL_VOLSW_XR_SX = 1, 2, 3 +SND_SOC_TPLG_CTL_ENUM, SND_SOC_TPLG_CTL_BYTES, SND_SOC_TPLG_CTL_ENUM_VALUE = 4, 5, 6 +VOLUME_INFO = (SND_SOC_TPLG_CTL_VOLSW, SND_SOC_TPLG_CTL_VOLSW_SX, SND_SOC_TPLG_CTL_VOLSW_XR_SX) +ENUM_INFO = (SND_SOC_TPLG_CTL_ENUM, SND_SOC_TPLG_CTL_ENUM_VALUE) +MAX_CHAN = 8 +INT_MAX = 0x7fffffff + +SOF_ABI_HDR_SIZE = 32 # struct sof_abi_hdr +SOF_IPC4_ABI_MAGIC = 0x34464F53 +SOF_IPC4_TPLG_ABI_SIZE = 6 +SOF_IPC4_MANIFEST_SIZE = 8 # struct sof_manifest without items +SOF_MANIFEST_DATA_TYPE_NHLT = 1 + + +def pipeline_info(ctx, sched): + """(use_chain_dma, dynamic) of a scheduler widget as set by + sof_ipc4_widget_setup_comp_pipeline(). With chain DMA the function + returns before parsing SOF_PIPELINE_TOKENS, so dynamic stays 0.""" + kw = ctx.kw(sched) + chain = bool(kw.update("SOF_SCHED_TOKENS")[0].get(TKN_SCHED_USE_CHAIN_DMA, 0)) + dynamic = False if chain else \ + bool(kw.update("SOF_PIPELINE_TOKENS")[0].get(TKN_SCHED_DYNAMIC_PIPELINE, 0)) + return chain, dynamic + + +def dai_type(ctx, widget): + "SOF_DAI_* name of a DAI copier, via find_dai()." + name = ctx.kw(widget).update("SOF_DAI_TOKENS")[0].get(TKN_DAI_TYPE) + return name, kt.DAI_TYPES.get(name, "SOF_DAI_INTEL_NONE") + + +def kernel_routes(ctx): + """Routes that can reach sof_ipc4_route_setup(): both ends exist and are + IPC4 modules. Virtual widgets are skipped by sof_route_setup(), widgets + without IPC4 widget ops (e.g. siggen) have no firmware module.""" + t = ctx.tplg + for r in t.routes: + src, sink = t.widget(r.source), t.widget(r.sink) + if src and sink and src.type_name in kt.IPC4_WIDGET_TOKEN_LISTS and \ + sink.type_name in kt.IPC4_WIDGET_TOKEN_LISTS: + yield r, src, sink + + +# --- graph and pipelines ------------------------------------------------- + +@rule("G001", "L3", ERROR, "snd_soc_dapm_add_routes, sof_route_load", + "route source and sink widgets exist") +def route_endpoints(ctx): + t = ctx.tplg + for r in t.routes: + for end, name in (("source", r.source), ("sink", r.sink)): + if t.widget(name) is None: + hint = "" if t.base_widgets else \ + " (for a feature topology, give the topologies loaded before it with --base)" + yield r.label, f"{end} widget '{name}' does not exist{hint}" + + +def enum_texts(control) -> list: + "Enum control entries, as matched by dapm_connect_mux()." + items = min(control.body["items"], len(control.body.texts)) + return [binary.decode_name(txt) for txt in control.body.texts[:items]] + + +@rule("G002", "L3", ERROR, "snd_soc_dapm_add_path, dapm_connect_mux, dapm_connect_mixer", + "route controls match the sink widget the way DAPM connects them") +def route_controls(ctx): + t = ctx.tplg + for r in t.routes: + sink = t.widget(r.sink) + if not r.control or sink is None: + continue + if sink.type_name == "mux": + # the control names an entry of the mux's first enum control + enum = sink.kcontrols[0] if sink.kcontrols else None + if enum is None or enum.kind != TplgType.ENUM: + yield r.label, "mux sink has no enum kcontrol to connect the route with" + elif r.control not in enum_texts(enum): + yield r.label, f"'{r.control}' is not an entry of mux control '{enum.name}'" + elif sink.type_name in ("mixer", "switch"): + if r.control not in [k.name for k in sink.kcontrols]: + yield r.label, f"{sink.type_name} sink has no kcontrol '{r.control}'" + # DAPM ignores the control for other sink types + + +@rule("G003", "L3", WARNING, "snd_soc_dapm_new_controls", + "widget names are unique") +def duplicate_widgets(ctx): + t = ctx.tplg + for name, n in Counter(w.name for w in t.widgets).items(): + if n > 1: + yield f"widget '{name}'", f"defined {n} times, routes resolve to the first one" + base = {w.name for w in t.base_widgets} + for w in t.widgets: + if w.name in base: + yield w.label, "also defined by a base topology" + + +@rule("G004", "L3", WARNING, "sof-audio.c pipeline walk", + "every non-scheduler widget is connected to a route") +def unconnected(ctx): + t = ctx.tplg + routed = {n for r in t.routes for n in (r.source, r.sink)} + for w in t.widgets: + if w.type_name != "scheduler" and w.name not in routed: + yield w.label, "not connected to any route" + + +@rule("G005", "L3", ERROR, "sof_complete, sof_widget_setup_unlocked", + "every widget has a scheduler widget with the same pipeline index") +def widget_pipeline(ctx): + t = ctx.tplg + scheds = Counter(w.index for w in t.widgets if w.type_name == "scheduler") + base_scheds = {w.index for w in t.base_widgets if w.type_name == "scheduler"} + for w in t.widgets: + if w.type_name == "scheduler": + if scheds[w.index] > 1: + yield w.label, f"{scheds[w.index]} scheduler widgets share pipeline " \ + f"index {w.index}", WARNING + elif w.index not in scheds and w.index not in base_scheds and \ + w.type_name in kt.IPC4_WIDGET_TOKEN_LISTS: + # only widgets with IPC4 widget ops are set up in the firmware, + # DAPM-only widgets like mux, adc and dac need no pipeline + yield w.label, (f"no scheduler widget for pipeline index {w.index}; the widget " + f"is never set up") + + +@rule("G006", "L3", ERROR, "sof_ipc4_route_setup", + "chain DMA is enabled on both pipelines of a route or on neither") +def chain_dma_routes(ctx): + for r, src, sink in kernel_routes(ctx): + ps, pk = ctx.pipeline_widget(src), ctx.pipeline_widget(sink) + if ps is None or pk is None or ps is pk: + continue + cs, ck = pipeline_info(ctx, ps)[0], pipeline_info(ctx, pk)[0] + if cs != ck: + yield r.label, (f"use_chain_dma is {int(cs)} on '{ps.name}' but {int(ck)} " + f"on '{pk.name}'") + + +@rule("G007", "L3", ERROR, "sof_set_widget_pipeline", + "widgets in dynamic pipelines have no volatile kcontrols") +def dynamic_volatile(ctx): + for w in ctx.tplg.widgets: + sched = ctx.pipeline_widget(w) + if sched is None or w is sched or not pipeline_info(ctx, sched)[1]: + continue + for k in w.kcontrols: + if k.hdr.access & SNDRV_CTL_ELEM_ACCESS_VOLATILE: + yield w.label, f"volatile {k.label} in dynamic pipeline '{sched.name}'" + + +# --- widgets --------------------------------------------------------------- + +@rule("W001", "L3", ERROR, "sof_widget_ready", + "process widgets have private data, volume widgets have a kcontrol") +def widget_basics(ctx): + for w in ctx.tplg.widgets: + if w.type_name in PROCESS_TYPES and not w.priv.data: + yield w.label, "process tokens not found (empty private data)" + if w.type_name == "pga" and not w.raw.num_kcontrols: + yield w.label, "volume widget without kcontrols" + + +@rule("W002", "L3", ERROR, "sof_ipc4_get_audio_fmt, sof_ipc4_widget_setup_comp_src", + "modules declare audio formats; SRC/ASRC have input and output formats") +def audio_format_counts(ctx): + for w in ctx.tplg.widgets: + kw = ctx.kw(w) + if kw.error or w.type_name not in AUDIO_FMT_TYPES or ctx.pipeline_widget(w) is None: + continue + n_in, n_out, _, _ = kw.audio_formats() + if not n_in and not n_out: + yield w.label, "no input/output pin formats set in topology" + elif w.type_name in ("src", "asrc") and (not n_in or not n_out): + yield w.label, f"{w.type_name} needs at least one input and one output format " \ + f"(has {n_in} and {n_out})" + + +@rule("W003", "L3", ERROR, "sof_ipc4_widget_set_module_info", + "module widgets have a UUID to look up the firmware module") +def module_uuid(ctx): + for w in ctx.tplg.widgets: + if w.type_name not in AUDIO_FMT_TYPES or ctx.pipeline_widget(w) is None: + continue + uuid = ctx.kw(w).comp_ext.get(TKN_COMP_UUID) + if not uuid or not any(uuid): + yield w.label, "no module UUID, the firmware module lookup will fail" + + +@rule("W004", "L3", ERROR, "find_dai, sof_ipc4_dai_config", + "DAI copiers have a DAI type supported by the IPC4 driver") +def dai_types(ctx): + for w in ctx.tplg.widgets: + if w.type_name not in DAI_WIDGET_TYPES or ctx.kw(w).error: + continue + name, dtype = dai_type(ctx, w) + if dtype == "SOF_DAI_INTEL_NONE": + yield w.label, f"unknown DAI type {name!r}" + elif dtype not in IPC4_DAI_CONFIG_TYPES: + yield w.label, f"DAI type {name} ({dtype}) is not supported by the IPC4 driver" + + +@rule("W005", "L3", ERROR, "sof_ipc4_widget_setup_comp_dai, snd_sof_is_chain_dma_supported", + "chain DMA pipelines only use DAI types supporting chain DMA") +def chain_dma_dai(ctx): + for w in ctx.tplg.widgets: + if w.type_name not in DAI_WIDGET_TYPES or ctx.kw(w).error: + continue + sched = ctx.pipeline_widget(w) + if sched is None or not pipeline_info(ctx, sched)[0]: + continue + name, dtype = dai_type(ctx, w) + if dtype not in CHAIN_DMA_DAI_TYPES: + yield w.label, f"chain DMA is not supported with DAI type {name}" + + +@rule("W006", "L3", WARNING, "sof_widget_ready", + "core IDs are within the DSP core count (--num-cores)") +def core_ids(ctx): + n = ctx.options.num_cores + if not n: + return + for w in ctx.tplg.widgets: + kw = ctx.kw(w) + if w.type_name == "scheduler": + core = kw.update("SOF_SCHED_TOKENS")[0].get(TKN_SCHED_CORE) + else: + core = kw.comp_ext.get(TKN_COMP_CORE_ID) + if core is not None and core >= n: + yield w.label, f"core {core} does not exist on a {n} core DSP, the kernel " \ + f"moves it to core 0" + + +@rule("W007", "L3", ERROR, "sof_parse_pin_binding, sof_ipc4_get_queue_id", + "pin bindings are complete and match the routes") +def pin_bindings(ctx): + t = ctx.tplg + for w in t.widgets: + kw = ctx.kw(w) + for side, binding in (("input", kw.input_pin_binding), ("output", kw.output_pin_binding)): + if binding is None: + continue + for i, name in enumerate(binding): + if name is None: + yield w.label, f"{side} pin {i} has no binding, the kernel " \ + f"dereferences NULL when matching routes" + elif t.widget(name) is None: + yield w.label, f"{side} pin {i} is bound to unknown widget '{name}'", \ + WARNING + + # queue IDs are allocated when a route is set up for a PCM, which depends + # on the DAPM walk; the path model is approximate, so these are warnings + on_path = routes_on_pcm_paths(ctx) + fan = Counter() + for r, src, sink in kernel_routes(ctx): + sev = WARNING + pcms = on_path.get(id(r)) + when = f" (fails when PCM {', '.join(pcms)} is opened)" if pcms else "" + ps, pk = ctx.pipeline_widget(src), ctx.pipeline_widget(sink) + if ps is None or pk is None or pipeline_info(ctx, ps)[0] or pipeline_info(ctx, pk)[0]: + continue # no binding for chain DMA routes + for side, w, peer in (("output", src, sink), ("input", sink, src)): + kw = ctx.kw(w) + pins = kw.num_output_pins if side == "output" else kw.num_input_pins + binding = kw.output_pin_binding if side == "output" else kw.input_pin_binding + fan[(w.name, side)] += 1 + if pins < 1: + yield r.label, f"'{w.name}' has {pins} {side} pins{when}", sev + elif pins > 1 and binding is not None and peer.name not in binding: + yield r.label, f"'{peer.name}' is not in the {side} pin binding of " \ + f"'{w.name}'{when}", sev + + for (name, side), n in fan.items(): + kw = ctx.kw(t.widget(name)) + pins = kw.num_output_pins if side == "output" else kw.num_input_pins + if pins >= 1 and n > pins: + yield f"widget '{name}'", f"{n} {side} routes but only {pins} {side} pins", WARNING + + +@rule("W008", "L3", WARNING, "sof_ipc4_process_set_pin_formats", + "process modules with several pins have a format for every pin index") +def process_pin_formats(ctx): + for w in ctx.tplg.widgets: + kw = ctx.kw(w) + if w.type_name not in PROCESS_TYPES or kw.error: + continue + _, _, ins, outs = kw.audio_formats() + for side, pins, fmts, tok in (("input", kw.num_input_pins, ins, TKN_IN_PIN_INDEX), + ("output", kw.num_output_pins, outs, TKN_OUT_PIN_INDEX)): + have = {f.get(tok, 0) for f in fmts} + missing = [i for i in range(1, pins) if i not in have] + if missing: + yield w.label, (f"no {side} format for pin {', '.join(map(str, missing))}; " + f"required if the firmware module uses extended init") + + +def connection_pin(kw, peer, output): + "Resolve a queue without guessing the allocation order of unbound pins." + pins = kw.num_output_pins if output else kw.num_input_pins + binding = kw.output_pin_binding if output else kw.input_pin_binding + if pins == 1: + return 0 + if pins > 1 and binding is not None and binding.count(peer.name) == 1: + return binding.index(peer.name) + return None + + +def connection_formats(widget, kw, pin, output): + """Formats declared for this pin, accounting for shared module formats. + + An undeclared secondary copier output is configured from the sink at + bind time, not constrained by the copier's pin-0 output formats. + """ + _, _, ins, outs = kw.audio_formats() + fmts = outs if output else ins + rate, cfg, index, depth = (1930, 1937, TKN_OUT_PIN_INDEX, 1931) if output else \ + (1900, 1907, TKN_IN_PIN_INDEX, 1901) + if output and widget.type_name == "mixer": + # The kernel selects a single mixer output format without a pin filter. + selected = fmts + else: + selected = [f for f in fmts if f.get(index, 0) == pin] + if not selected and output and pin > 0 and widget.type_name in PROCESS_TYPES: + selected = [f for f in fmts if not f.get(index, 0)] + # Do not infer incompatibility from incomplete format declarations. + if not selected or any(not f.get(rate) or not f.get(depth) or + not (f.get(cfg, 0) & 0xff) or + not ((f.get(cfg, 0) >> 8) & 0xff) for f in selected): + return set() + + def key(fmt): + stype = (fmt[cfg] >> 16) & 0xff + representation = 1 if stype in (0, 1, 2) else stype + return fmt_key(fmt, rate, cfg, depth) + (representation,) + + return {key(f) for f in selected} + + +def describe_formats(formats): + return ", ".join(f"{rate}Hz/{channels}ch/{bits}bit/kernel-type{stype}/repr{representation}" + for rate, channels, bits, stype, representation in sorted(formats)) + + +@rule("F003", "L4", ERROR, + "sof_ipc4_route_setup, sof_ipc4_set_copier_sink_format, sof_ipc4_get_input_pin_audio_fmt", + "connected output and input pins have a common declared format") +def connection_pin_formats(ctx): + for r, src, sink in kernel_routes(ctx): + ps, pk = ctx.pipeline_widget(src), ctx.pipeline_widget(sink) + if ps is None or pk is None or pipeline_info(ctx, ps)[0] or pipeline_info(ctx, pk)[0]: + continue + src_kw, sink_kw = ctx.kw(src), ctx.kw(sink) + if src_kw.error or sink_kw.error: + continue + out_pin = connection_pin(src_kw, sink, True) + in_pin = connection_pin(sink_kw, src, False) + if out_pin is None or in_pin is None: + yield r.label, ("cannot statically resolve the connected pins; explicit " + "bindings are needed for multi-pin endpoints"), INFO + continue + outs = connection_formats(src, src_kw, out_pin, True) + ins = connection_formats(sink, sink_kw, in_pin, False) + if not outs or not ins: + yield r.label, (f"output pin {out_pin} -> input pin {in_pin}: " + "no static format comparison; one or both pins have no " + "complete declared formats"), INFO + elif outs.isdisjoint(ins): + yield r.label, (f"output pin {out_pin} [{describe_formats(outs)}] has no " + f"compatible format with input pin {in_pin} " + f"[{describe_formats(ins)}]") + + +@rule("F004", "L4", ERROR, + "sof_ipc4_init_output_audio_fmt, sof_ipc4_set_copier_sink_format", + "declared copier outputs are selectable using fixed or input-preserving parameters") +def copier_output_selection(ctx): + for w in ctx.tplg.widgets: + if w.type_name not in ("buffer", "aif_in", "aif_out", "dai_in", "dai_out"): + continue + kw = ctx.kw(w) + sched = ctx.pipeline_widget(w) + if kw.error or (sched is not None and pipeline_info(ctx, sched)[0]): + continue + ni, no, ins, outs = kw.audio_formats() + pins = {f.get(TKN_OUT_PIN_INDEX, 0) for f in outs} + pins.update(range(kw.num_output_pins)) + if w.type_name == "buffer": + pins.add(0) + else: + pins.discard(0) # Gateway pin 0 has endpoint-specific selection rules. + if not pins: + continue + inputs = connection_formats(w, kw, 0, False) + if len(ins) != ni or len(outs) != no or not inputs: + yield w.label, "incomplete format declarations; copier selection not checked", INFO + continue + for pin in sorted(pins): + where = f"output pin {pin}" + if not any(f.get(TKN_OUT_PIN_INDEX, 0) == pin for f in outs): + if pin > 0: + yield w.label, (f"{where} has no declared formats; selected at bind " + "time, prepare/bind consistency is not checked"), INFO + else: + yield w.label, f"{where} has incomplete formats; selection not checked", INFO + continue + outputs = connection_formats(w, kw, pin, True) + if not outputs: + yield w.label, f"{where} has incomplete formats; selection not checked", INFO + continue + bad = [] + for incoming in sorted(inputs): + rate, channels, bits, stype, representation = incoming + candidates = {f for f in outputs if f[0] == rate} + if not candidates: + bad.append(f"{rate}Hz: no output at input rate") + continue + channel_counts = {f[1] for f in candidates} + representations = {f[2:] for f in candidates} + if len(channel_counts) == 1: + channels = next(iter(channel_counts)) + if len(representations) == 1: + bits, stype, representation = next(iter(representations)) + if (rate, channels, bits, stype, representation) not in candidates: + bad.append(f"{describe_formats({incoming})}: ambiguous output; fixed " + "and input-preserving parameters select no declared format") + if bad: + more = f"; and {len(bad) - 3} more input alternatives" if len(bad) > 3 else "" + yield w.label, f"{where}: {'; '.join(bad[:3])}{more}" + + +# --- controls ---------------------------------------------------------------- + +@rule("C001", "L3", ERROR, "sof_control_load_volume, sof_control_load_enum", + "volume and enum controls have valid channel counts, ranges and TLV") +def volume_enum_controls(ctx): + for c in ctx.tplg.controls: + info = c.hdr.ops.info + if c.kind == TplgType.MIXER and info in VOLUME_INFO: + b = c.body + lo, hi = b.min & 0xffffffff, b.max & 0xffffffff # compared as u32 + if b.num_channels > MAX_CHAN: + yield c.label, f"{b.num_channels} channels, maximum is {MAX_CHAN}" + if lo > hi or hi >= INT_MAX: + yield c.label, f"invalid range min {lo} max {hi}" + elif hi != 1: + # only max == 1 (a switch) skips the volume table, and + # soc_tplg_create_tlv() only sets kc->tlv.p for dB scale TLVs + access = c.hdr.access + if not access & 0x30 or access & (1 << 28) or c.hdr.tlv.type != 1: + yield c.label, f"max {hi} needs a dB scale TLV for the volume table" + elif c.kind == TplgType.ENUM and info in ENUM_INFO and c.body.num_channels > MAX_CHAN: + yield c.label, f"{c.body.num_channels} channels, maximum is {MAX_CHAN}" + + +@rule("C002", "L3", ERROR, "sof_ipc4_control_load_bytes", + "bytes controls have a valid size and IPC4 ABI header") +def bytes_controls(ctx): + for c in ctx.tplg.controls: + if c.kind != TplgType.BYTES or c.hdr.ops.info != SND_SOC_TPLG_CTL_BYTES: + continue + max_size, data = c.body.max, c.priv.data + if max_size < SOF_ABI_HDR_SIZE: + yield c.label, f"max size {max_size} is less than the ABI header" + continue + if len(data) > max_size: + yield c.label, f"initial data size {len(data)} exceeds max {max_size}" + continue + if not data: + continue + if len(data) < SOF_ABI_HDR_SIZE: + yield c.label, f"initial data size {len(data)} is less than the ABI header" + continue + magic, _type, size = struct.unpack_from(" 8: + yield link.label, f"{n} hw configs, maximum is 8" + continue + ids = [hw.id for hw in link.hw_configs] + if n and link.raw.default_hw_config_id not in ids: + yield link.label, (f"default hw config id {link.raw.default_hw_config_id} is not " + f"one of {ids}, no DAI format is applied"), INFO + + +@rule("M001", "L3", ERROR, "sof_ipc4_parse_manifest", + "manifest private data has the ABI version and well formed TLVs") +def manifest(ctx): + m = ctx.tplg.manifest + if m is None: + return + data = m.data.priv + if len(data) < SOF_IPC4_TPLG_ABI_SIZE: + yield "manifest", f"private data of {len(data)} bytes has no ABI version" + return + if len(data) <= SOF_IPC4_TPLG_ABI_SIZE: + return + if len(data) < SOF_IPC4_MANIFEST_SIZE: + # the kernel reads the TLV count past the end of the private data + yield "manifest", (f"private data of {len(data)} bytes has no complete TLV count, " + f"{SOF_IPC4_MANIFEST_SIZE} bytes needed") + return + _maj, _min, _patch, count = struct.unpack_from(" len(data): + yield "manifest", f"TLV {i} header is past the end of the private data" + return + typ, size = struct.unpack_from(" len(data): + yield "manifest", f"TLV {i} of {size} bytes is past the end of the private data" + return + if typ != SOF_MANIFEST_DATA_TYPE_NHLT: + yield "manifest", f"TLV {i} has unknown type {typ}, the kernel skips it", WARNING diff --git a/validator/checks/paths.py b/validator/checks/paths.py new file mode 100644 index 0000000..7ccdea4 --- /dev/null +++ b/validator/checks/paths.py @@ -0,0 +1,196 @@ +# SPDX-License-Identifier: BSD-3-Clause +# +# Copyright(c) 2026 Intel Corporation. All rights reserved. + +"""L4: PCM path and audio format simulation (advisory).""" + +from dataclasses import dataclass, field + +from . import INFO, WARNING, rule + +PLAYBACK, CAPTURE = 0, 1 +DIR_NAME = ("playback", "capture") +HOST_TYPE = ("aif_in", "aif_out") +DAI_TYPE = ("dai_in", "dai_out") + + +@dataclass +class PcmPath: + "Widgets and routes the kernel walks for one PCM direction." + pcm: object + direction: int + host: object + widgets: list = field(default_factory=list) # in walk order, host first + routes: list = field(default_factory=list) # [(route, src, sink)] + + +def host_copier(t, direction: int, stream: str): + """The host copier a PCM direction binds to, like snd_sof_find_swidget_sname(). + + The kernel searches the widgets of all topologies loaded into the + component, so base topologies count too. + """ + return next((w for w in t.widgets + t.base_widgets + if w.type_name == HOST_TYPE[direction] and w.sname == stream), None) + + +def pcm_paths(ctx) -> list: + """Mirror snd_soc_dapm_dai_get_connected_widgets() with dpcm_end_walk_at_be + as used by sof_widget_list_setup(): starting from the host copier bound + by spcm_bind(), follow routes downstream for playback and upstream for + capture, stopping at DAI widgets (the BE end).""" + cache = getattr(ctx, "_pcm_paths", None) + if cache is not None: + return cache + + t = ctx.tplg + down, up = {}, {} + for r in t.routes + t.base_routes: + src, sink = t.widget(r.source), t.widget(r.sink) + if src and sink: + down.setdefault(src.name, []).append((r, src, sink)) + up.setdefault(sink.name, []).append((r, src, sink)) + + paths = [] + for p in t.pcms: + for d, enabled in ((PLAYBACK, p.raw.playback), (CAPTURE, p.raw.capture)): + if not enabled: + continue + name = p.raw.caps[d].name.split(b"\0", 1)[0].decode("ascii", "replace") + host = host_copier(t, d, name) + if host is None: + continue # reported by P001 + path = PcmPath(p, d, host, [host]) + seen = {host.name} + todo = [host] + while todo: + w = todo.pop(0) + if w is not host and w.type_name in DAI_TYPE: + continue + for r, src, sink in (down if d == PLAYBACK else up).get(w.name, ()): + path.routes.append((r, src, sink)) + nxt = sink if d == PLAYBACK else src + if nxt.name not in seen: + seen.add(nxt.name) + path.widgets.append(nxt) + todo.append(nxt) + paths.append(path) + + ctx._pcm_paths = paths + return paths + + +def routes_on_pcm_paths(ctx) -> dict: + "id(route) -> sorted names of the PCMs whose path includes the route" + out = {} + for p in pcm_paths(ctx): # PCMs of the validated topology only + for r, _s, _k in p.routes: + out.setdefault(id(r), set()).add(f"'{p.pcm.name}' {DIR_NAME[p.direction]}") + return {k: sorted(v) for k, v in out.items()} + + +# --- format simulation ------------------------------------------------------- + +# SNDRV_PCM_RATE_* bit -> rate (include/sound/pcm.h) +PCM_RATES = {0: 5512, 1: 8000, 2: 11025, 3: 16000, 4: 22050, 5: 32000, 6: 44100, 7: 48000, + 8: 64000, 9: 88200, 10: 96000, 11: 176400, 12: 192000, 13: 352800, 14: 384000, + 15: 705600, 16: 768000, 17: 12000, 18: 24000, 19: 128000} + +# SOF_IPC4_TYPE_* (sound/soc/sof/ipc4-topology.h) +TYPE_LSB_INTEGER, TYPE_UNSIGNED_INTEGER, TYPE_FLOAT, TYPE_A_LAW, TYPE_MU_LAW = 1, 3, 4, 5, 6 + +# SNDRV_PCM_FMTBIT_* bit -> (name, valid bits, IPC4 type), per +# sof_ipc4_get_valid_bits() and sof_ipc4_get_sample_type() +PCM_FORMATS = { + 1: ("U8", 8, TYPE_UNSIGNED_INTEGER), + 2: ("S16_LE", 16, TYPE_LSB_INTEGER), + 6: ("S24_LE", 24, TYPE_LSB_INTEGER), + 10: ("S32_LE", 32, TYPE_LSB_INTEGER), + 14: ("FLOAT_LE", 32, TYPE_FLOAT), + 20: ("MU_LAW", 8, TYPE_MU_LAW), + 21: ("A_LAW", 8, TYPE_A_LAW), +} + +MAX_PCM_CHANNELS = 256 # channels fit in the 8-bit IPC4 FMT_CFG field + +TKN_IN_RATE, TKN_IN_FMT_CFG, TKN_IN_PIN = 1900, 1907, 1909 +TKN_OUT_RATE, TKN_OUT_FMT_CFG, TKN_OUT_PIN = 1930, 1937, 1939 + + +def fmt_key(fmt: dict, rate_tok, cfg_tok, depth_tok): + """Canonical rate/channel/valid-bit/type key for declared IPC4 formats.""" + cfg = fmt.get(cfg_tok, 0) + bits = (cfg >> 8) & 0xff + stype = (cfg >> 16) & 0xff + if bits == 32 and fmt.get(depth_tok, 0) == 32 and stype in (0, 2): + stype = TYPE_LSB_INTEGER + elif bits not in (8, 32): + stype = TYPE_LSB_INTEGER + return fmt.get(rate_tok, 0), cfg & 0xff, bits, stype + + +def caps_params(caps): + "All (rate, channels, format name, valid bits, type) a PCM caps entry allows." + rates = [r for bit, r in PCM_RATES.items() if caps.rates & (1 << bit)] + if caps.rate_min or caps.rate_max: + rates = [r for r in rates if caps.rate_min <= r <= (caps.rate_max or r)] + formats = [f for bit, f in PCM_FORMATS.items() if caps.formats & (1 << bit)] + # channels come from the topology, bound them to what ALSA can describe + for ch in range(caps.channels_min, min(caps.channels_max, MAX_PCM_CHANNELS) + 1): + for rate in rates: + for name, bits, stype in formats: + yield rate, ch, name, bits, stype + + +@rule("F001", "L4", INFO, "sof_ipc4_init_input_audio_fmt, sof_pcm_open", + "every rate/format/channel combination a PCM allows matches a host copier format " + "(advisory: DPCM may narrow rates and channels further)") +def pcm_host_formats(ctx): + for path in pcm_paths(ctx): + kw = ctx.kw(path.host) + if kw.error: + continue + _ni, _no, ins, outs = kw.audio_formats() + if path.direction == PLAYBACK: + fmts, keys = ins, (TKN_IN_RATE, TKN_IN_FMT_CFG, TKN_IN_PIN, 1901) + else: + fmts, keys = outs, (TKN_OUT_RATE, TKN_OUT_FMT_CFG, TKN_OUT_PIN, 1931) + if not fmts: + continue + avail = [fmt_key(f, keys[0], keys[1], keys[3]) for f in fmts if not f.get(keys[2], 0)] + if len({a[:3] for a in avail}) <= 1: + continue # single format: the kernel uses it without matching + bad = [(rate, ch, name) for rate, ch, name, bits, stype in + caps_params(path.pcm.raw.caps[path.direction]) + if (rate, ch, bits, stype) not in avail] + if bad: + shown = ", ".join(f"{r}Hz {n} {c}ch" for r, c, n in bad[:4]) + more = f" and {len(bad) - 4} more" if len(bad) > 4 else "" + yield path.pcm.label, (f"{DIR_NAME[path.direction]}: host copier " + f"'{path.host.name}' has no format for {shown}{more}; " + f"hw_params fails with 'Unsupported audio format'") + + +@rule("F002", "L4", WARNING, "sof_ipc4_init_input_audio_fmt, sof_pcm_open", + "every sample format a PCM allows has a host copier format") +def pcm_host_sample_formats(ctx): + for path in pcm_paths(ctx): + kw = ctx.kw(path.host) + if kw.error: + continue + _ni, _no, ins, outs = kw.audio_formats() + if path.direction == PLAYBACK: + fmts, keys = ins, (TKN_IN_RATE, TKN_IN_FMT_CFG, TKN_IN_PIN, 1901) + else: + fmts, keys = outs, (TKN_OUT_RATE, TKN_OUT_FMT_CFG, TKN_OUT_PIN, 1931) + avail = [fmt_key(f, keys[0], keys[1], keys[3]) for f in fmts if not f.get(keys[2], 0)] + if len({a[:3] for a in avail}) <= 1: + continue + have = {(bits, stype) for _r, _c, bits, stype in avail} + caps = path.pcm.raw.caps[path.direction] + missing = [name for bit, (name, bits, stype) in PCM_FORMATS.items() + if caps.formats & (1 << bit) and (bits, stype) not in have] + if missing: + yield path.pcm.label, (f"{DIR_NAME[path.direction]}: PCM allows " + f"{', '.join(missing)} but host copier " + f"'{path.host.name}' has no such format") diff --git a/validator/checks/structure.py b/validator/checks/structure.py new file mode 100644 index 0000000..ba3304a --- /dev/null +++ b/validator/checks/structure.py @@ -0,0 +1,169 @@ +# SPDX-License-Identifier: BSD-3-Clause +# +# Copyright(c) 2026 Intel Corporation. All rights reserved. + +"""L1: binary structure as checked by sound/soc/soc-topology.c.""" + +from schema import kernel_tokens as kt +from tplgparse import binary +from tplgparse.binary import DapmType, TplgType + +from . import ERROR, WARNING, rule + +SNDRV_CTL_ELEM_ACCESS_TLV_READ = 1 << 4 +SNDRV_CTL_ELEM_ACCESS_TLV_WRITE = 1 << 5 +SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE = SNDRV_CTL_ELEM_ACCESS_TLV_READ | \ + SNDRV_CTL_ELEM_ACCESS_TLV_WRITE +SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK = 1 << 28 +SNDRV_CTL_TLVT_DB_SCALE = 1 +SND_SOC_TPLG_CTL_BYTES = 5 + +# soc_tplg_load_header(): types with a loader, everything else is vendor data +LOADED_TYPES = {TplgType.MIXER, TplgType.ENUM, TplgType.BYTES, TplgType.DAPM_GRAPH, + TplgType.DAPM_WIDGET, TplgType.PCM, TplgType.DAI, TplgType.DAI_LINK, + TplgType.BACKEND_LINK, TplgType.MANIFEST} + + +def at(offset): + return f"offset 0x{offset:x}" + + +@rule("S001", "L1", ERROR, "soc_tplg_valid_header, soc_tplg_check_elem_count", + "section headers and element counts are consistent with the file") +def binary_issues(ctx): + for issue in ctx.tplg.raw.issues: + sev = WARNING if issue.code == "payload-trailing" else ERROR + yield at(issue.offset), issue.message, sev + + +@rule("S002", "L1", ERROR, "soc_tplg_vendor_load", + "no section types without a kernel loader (SOF has no vendor_load)") +def vendor_sections(ctx): + for sec in ctx.tplg.raw.sections: + if sec.hdr.type not in LOADED_TYPES: + yield at(sec.offset), f"{sec.type_name} section: no vendor load callback in SOF" + + +@rule("S003", "L1", ERROR, "soc_tplg_*_elems_load, soc_tplg_manifest_load", + "element size fields match the kernel structure sizes") +def struct_sizes(ctx): + t = ctx.tplg + checks = [] + checks += [(w.label, w.raw.size, binary.SIZEOF["widget"]) for w in t.widgets] + checks += [(c.label, c.hdr.size, binary.SIZEOF["ctl_hdr"]) for c in t.controls] + checks += [(p.label, p.raw.size, binary.SIZEOF["pcm"]) for p in t.pcms] + checks += [(link.label, link.raw.size, binary.SIZEOF["link"]) for link in t.links] + checks += [(d.label, d.raw.size, binary.SIZEOF["dai"]) for d in t.dais] + if t.manifest is not None: + checks.append(("manifest", t.manifest.data.size, binary.SIZEOF["manifest"])) + for where, size, expected in checks: + if size != expected: + yield where, f"structure size {size}, kernel expects {expected}" + + +@rule("S004", "L1", ERROR, "soc_tplg_check_name, soc_tplg_dapm_widget_create", + "names are NUL terminated within 44 bytes") +def names_terminated(ctx): + t = ctx.tplg + fields = [] + for w in t.widgets: + fields += [(w.label, "name", w.raw.name), (w.label, "stream name", w.raw.sname)] + for c in t.controls: + fields.append((c.label, "name", c.hdr.name)) + if c.kind == TplgType.ENUM: + items = min(c.body["items"], binary.NUM_TEXTS) + fields += [(c.label, f"text {i}", txt) for i, txt in enumerate(c.body.texts[:items])] + for p in t.pcms: + fields += [(p.label, "pcm name", p.raw.pcm_name), (p.label, "dai name", p.raw.dai_name)] + fields += [(p.label, f"caps {i} name", cap.name) for i, cap in enumerate(p.raw.caps)] + for link in t.links: + fields += [(link.label, "name", link.raw.name), + (link.label, "stream name", link.raw.stream_name)] + for r in t.routes: + fields += [(r.label, "sink", r.raw.sink), (r.label, "source", r.raw.source), + (r.label, "control", r.raw.control)] + for where, what, raw in fields: + if not binary.name_terminated(raw): + yield where, f"{what} is not NUL terminated" + + +@rule("S005", "L1", ERROR, "get_widget_id", "widget types are known to the kernel") +def widget_types(ctx): + for w in ctx.tplg.widgets: + if w.id not in DapmType.__members__.values(): + yield w.label, f"unknown widget type {w.id}" + + +@rule("S006", "L1", ERROR, "soc_tplg_denum_create", + "enum controls have at most SND_SOC_TPLG_NUM_TEXTS items") +def enum_items(ctx): + for c in ctx.tplg.controls: + if c.kind == TplgType.ENUM and c.body["items"] > binary.NUM_TEXTS: + yield c.label, f"{c.body['items']} items, maximum is {binary.NUM_TEXTS}" + + +@rule("S007", "L1", ERROR, "soc_tplg_create_tlv", + "TLV controls without a TLV callback use a dB scale TLV") +def tlv_type(ctx): + for c in ctx.tplg.controls: + access = c.hdr.access + if access & SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE and \ + not access & SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK and \ + c.hdr.tlv.type != SNDRV_CTL_TLVT_DB_SCALE: + yield c.label, f"unsupported TLV type {c.hdr.tlv.type}" + + +def _bind(ids, tables): + "Return the set of handler names ('get', 'put', 'info') resolved for the IDs." + found = set() + for table in tables: + for entry in table: + for name, idx in (("get", 1), ("put", 2), ("info", 3)): + if name not in found and len(entry) > idx and entry[idx] and \ + entry[0] == ids[name]: + found.add(name) + return found + + +@rule("S008", "L1", ERROR, "soc_tplg_kcontrol_bind_io", + "kcontrol get/put/info handler IDs bind to kernel handlers") +def kcontrol_io(ctx): + for c in ctx.tplg.controls: + access = c.hdr.access + ops = {n: c.hdr.ops[n] for n in ("get", "put", "info")} + if c.kind == TplgType.BYTES and ops["info"] == SND_SOC_TPLG_CTL_BYTES and \ + access & SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE and \ + access & SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK: + ext = {"get": c.body.ext_ops["get"], "put": c.body.ext_ops["put"], "info": None} + bound = _bind(ext, [kt.SOF_BYTES_EXT_OPS]) + if access & SNDRV_CTL_ELEM_ACCESS_TLV_READ and "get" not in bound: + yield c.label, f"no bytes ext get handler for ID {ext['get']}" + if access & SNDRV_CTL_ELEM_ACCESS_TLV_WRITE and "put" not in bound: + yield c.label, f"no bytes ext put handler for ID {ext['put']}" + continue + bound = _bind(ops, [kt.SOF_IO_OPS, kt.STD_IO_OPS]) + missing = [f"{n} ID {ops[n]}" for n in ("get", "put", "info") if n not in bound] + if missing: + yield c.label, f"no kcontrol handler for {', '.join(missing)}" + + +@rule("S009", "L1", WARNING, "soc_tplg_manifest_load", + "manifest element counts match the file contents") +def manifest_counts(ctx): + t = ctx.tplg + if t.manifest is None: + yield "file", "no manifest section", ERROR + return + m = t.manifest.data + actual = { + "control": len(t.controls), + "widget": len(t.widgets), + "graph": len(t.routes), + "pcm": len(t.pcms), + "dai_link": len(t.links), + "dai": len(t.dais), + } + for name, count in actual.items(): + declared = m[f"{name}_elems"] + if declared != count: + yield "manifest", f"declares {declared} {name} elements, file has {count}" diff --git a/validator/checks/tokens.py b/validator/checks/tokens.py new file mode 100644 index 0000000..09f24eb --- /dev/null +++ b/validator/checks/tokens.py @@ -0,0 +1,250 @@ +# SPDX-License-Identifier: BSD-3-Clause +# +# Copyright(c) 2026 Intel Corporation. All rights reserved. + +"""L2: vendor tuples as read by the SOF driver tuple engine.""" + +from schema import kernel_tokens as kt +from tplgparse import kernel_engine as ke +from tplgparse.binary import TplgType, TupleType + +from . import ERROR, INFO, WARNING, rule + +TKN_IN_RATE = 1900 +TKN_OUT_RATE = 1930 + +FORMAT_GROUPS = ( + ("input", "SOF_IN_AUDIO_FORMAT_TOKENS", TKN_IN_RATE), + ("output", "SOF_OUT_AUDIO_FORMAT_TOKENS", TKN_OUT_RATE), +) + +# rate, bit depth, channel map, FMT_CFG and pin index tokens per direction, +# for readable messages +FORMAT_FIELDS = { + TKN_IN_RATE: (1900, 1901, 1904, 1907, 1909), + TKN_OUT_RATE: (1930, 1931, 1934, 1937, 1939), +} +SAMPLE_TYPES = {0: " MSB-integer", 1: "", 2: " signed", 3: " unsigned", 4: " float", + 5: " A-law", 6: " mu-law"} + + +def tname(token: int) -> str: + return kt.TOKEN_NAMES.get(token, f"token {token}") + + +def category(tuple_type: str) -> str: + "Element layout the kernel uses for a token type." + return {"STRING": "string", "UUID": "uuid"}.get(tuple_type, "value") + + +def array_category(ttype: TupleType) -> str: + return category(ttype.name) + + +def consumed_tables(ctx, widget): + "All token tables the kernel applies to this widget's private data." + gt = kt.GENERIC_TABLES + tables = [gt["dapm_widget_tokens"], gt["comp_pin_tokens"], + gt["comp_input_pin_binding_tokens"], gt["comp_output_pin_binding_tokens"]] + tables += [ke.group(g) for g in ctx.kw(widget).token_groups] + return tables + + +def kernel_types(tables) -> dict: + "token -> set of element layouts the kernel reads it with" + types = {} + for table in tables: + for tok, typ, _getter in table: + types.setdefault(tok, set()).add(category(typ)) + return types + + +def tuple_objects(ctx): + """(object, private data, token tables) for all tuple carrying objects.""" + t = ctx.tplg + gt = kt.GENERIC_TABLES + for w in t.widgets: + yield w, w.priv, consumed_tables(ctx, w) + for p in t.pcms: + yield p, p.priv, [gt["stream_tokens"]] + for link in t.links: + yield link, link.priv, [gt["common_dai_link_tokens"]] + for c in t.controls: + if c.kind == TplgType.MIXER and c.priv.data: + yield c, c.priv, [gt["led_tokens"]] + + +@rule("T001", "L2", ERROR, "sof_widget_ready, sof_widget_parse_tokens", + "widget tuples parse without kernel errors") +def widget_parse_errors(ctx): + for w in ctx.tplg.widgets: + err = ctx.kw(w).error + if err: + yield w.label, f"{err} (in {err.kernel_ref})" + + +@rule("T002", "L2", ERROR, "sof_copy_tuples, sof_parse_token_sets", + "the kernel reads every value from the tuple it was meant to come from") +def misreads(ctx): + for w in ctx.tplg.widgets: + genuine = {(t.offset, t.token, array_category(t.type)) for t in w.priv.tuples} + seen = set() + for r in ctx.kw(w).trace.reads: + if (r.offset, r.token, r.kind) in genuine or (r.offset, r.token) in seen: + continue + seen.add((r.offset, r.token)) + yield w.label, (f"kernel reads {tname(r.token)} = {r.value!r} from private data " + f"offset {r.offset}, which is not such a tuple in the topology") + + +@rule("T003", "L2", ERROR, "sof_parse_token_sets", + "vendor arrays are well formed") +def array_issues(ctx): + # mixer controls are included: sof_control_load_volume() parses LED tokens + for obj, priv, _tables in tuple_objects(ctx): + for issue in priv.issues: + yield obj.label, f"private data offset {issue.offset}: {issue.message}" + + +@rule("T004", "L2", WARNING, "include/uapi/sound/sof/tokens.h", + "all tuple tokens are known to the kernel") +def unknown_tokens(ctx): + for obj, priv, _tables in tuple_objects(ctx): + unknown = sorted({t.token for t in priv.tuples if t.token not in kt.TOKEN_NAMES}) + if unknown: + yield obj.label, f"tokens unknown to the kernel: {', '.join(map(str, unknown))}" + + +@rule("T005", "L2", ERROR, "sof_parse_token_sets, sof_copy_tuples", + "tuple types match the token types the kernel expects") +def type_mismatch(ctx): + for obj, priv, tables in tuple_objects(ctx): + expected = kernel_types(tables) + for t in priv.tuples: + want = expected.get(t.token) + if want and array_category(t.type) not in want: + yield obj.label, (f"{tname(t.token)} is in a {t.type.name} tuple array, the " + f"kernel reads it as {'/'.join(sorted(want))} and will " + f"not see this value") + + +def format_blocks(priv, tokens) -> list: + """Split the tuples of one direction into audio format blocks. + + Vendor array boundaries are not format boundaries: alsatplg emits one + array per format, but an array may hold several. A block ends where one + of its tokens repeats, which is also how the kernel assigns the n-th + occurrence of each token to format n. + """ + blocks, cur = [], {} + for t in priv.tuples: + if t.token not in tokens: + continue + if t.token in cur: + blocks.append(cur) + cur = {} + cur[t.token] = t.value + if cur: + blocks.append(cur) + return blocks + + +def describe(block: dict, rate_token: int, detail=False) -> str: + "Format summary from the values the kernel uses, valid bits etc. from FMT_CFG." + rate, depth, ch_map, cfg, pin = (block.get(t, 0) for t in FORMAT_FIELDS[rate_token]) + stype = (cfg >> 16) & 0xff + text = (f"{rate}Hz {depth}/{(cfg >> 8) & 0xff}bit" + f"{SAMPLE_TYPES.get(stype, f' type {stype}')} {cfg & 0xff}ch") + if detail: + text += f" fmt_cfg 0x{cfg:x} ch_map 0x{ch_map:x}" + (f" pin {pin}" if pin else "") + return text + + +@rule("T006", "L2", WARNING, "sof_widget_parse_tokens, sof_ipc4_get_audio_fmt", + "number of audio format blocks matches NUM_INPUT/OUTPUT_AUDIO_FORMATS") +def format_counts(ctx): + for w in ctx.tplg.widgets: + kw = ctx.kw(w) + if kw.error: + continue + n_in, n_out, ins, outs = kw.audio_formats() + for (direction, grp, rate_token), num, sets in zip(FORMAT_GROUPS, (n_in, n_out), + (ins, outs)): + if grp not in kw.token_groups: + continue + group_tokens = [tok for tok, _typ, _g in ke.group(grp)] + blocks = format_blocks(w.priv, set(group_tokens)) + if len(blocks) < num: + yield w.label, (f"declares {num} {direction} formats but defines " + f"{len(blocks)}"), ERROR + continue + # the kernel fills format n from the n-th occurrence of each token, + # fields without a value stay 0 from kzalloc() + for i, (kset, block) in enumerate(zip(sets, blocks)): + diff = [tok for tok in group_tokens if kset.get(tok, 0) != block.get(tok, 0)] + if diff: + yield w.label, (f"{direction} format {i} as read by the kernel differs " + f"from the topology in {', '.join(map(tname, diff))}; " + f"a format block is missing tokens"), ERROR + break + if len(blocks) <= num: + continue + + # compare what the kernel would use, not the descriptions + def key(block): + return tuple(block.get(tok, 0) for tok in group_tokens) + used = {key(b) for b in blocks[:num]} + new = list({key(b): b for b in blocks[num:] if key(b) not in used}.values()) + if not new: + yield w.label, (f"defines {len(blocks)} {direction} formats but declares " + f"{num}; the extra ones duplicate used formats"), INFO + continue + short = [describe(b, rate_token) for b in blocks[:num] + new] + detail = len(set(short)) < len(short) # distinct formats, same summary + yield w.label, (f"defines {len(blocks)} {direction} formats but declares {num}; " + f"the kernel ignores " + f"{', '.join(describe(b, rate_token, detail) for b in new)}") + + +@rule("T007", "L2", INFO, "tplg_ipc4_widget_ops token lists", + "tokens that the IPC4 kernel driver does not use for this widget type") +def unused_tokens(ctx): + for w in ctx.tplg.widgets: + used = kernel_types(consumed_tables(ctx, w)) + unused = sorted({t.token for t in w.priv.tuples + if t.token in kt.TOKEN_NAMES and t.token not in used}) + if unused: + yield w.label, f"{w.type_name}: {', '.join(map(tname, unused))}" + + +@rule("T008", "L2", ERROR, "sof_ipc4_get_audio_fmt, audio_stream_fmt_conversion", + "audio format sample types and bit depths are valid") +def audio_format_types(ctx): + for w in ctx.tplg.widgets: + kw = ctx.kw(w) + if kw.error: + continue + _, _, ins, outs = kw.audio_formats() + for direction, fmts, rate_token in (("input", ins, TKN_IN_RATE), + ("output", outs, TKN_OUT_RATE)): + _, depth_tok, _, cfg_tok, _ = FORMAT_FIELDS[rate_token] + for i, fmt in enumerate(fmts): + cfg, depth = fmt.get(cfg_tok, 0), fmt.get(depth_tok, 0) + if not cfg: + continue + bits, stype = (cfg >> 8) & 0xff, (cfg >> 16) & 0xff + if stype not in SAMPLE_TYPES: + problem = f"unknown sample type {stype}" + elif not depth or not bits: + continue + elif bits > depth: + problem = f"valid bit depth {bits} exceeds container depth {depth}" + elif stype == 4 and (depth, bits) != (32, 32): + problem = f"float requires 32/32 bits, got {depth}/{bits}" + elif stype == 3 and (depth, bits) != (8, 8): + problem = f"unsigned integer requires 8/8 bits, got {depth}/{bits}" + elif stype in (5, 6) and (depth, bits) != (8, 8): + problem = f"{SAMPLE_TYPES[stype].strip()} requires 8/8 bits, got {depth}/{bits}" + else: + continue + yield w.label, f"{direction} format {i}: {problem}" diff --git a/validator/known-issues.txt b/validator/known-issues.txt new file mode 100644 index 0000000..72aa955 --- /dev/null +++ b/validator/known-issues.txt @@ -0,0 +1,34 @@ +# Known validation errors, reported as warnings so that they do not fail +# the build. Format: [# reason] +# +# Do not add new entries to silence new errors; fix the topology instead. +# Remove entries when the topology is fixed. + +# cavs-benchmark-sdw.conf has no BENCH_CONFIG cases for these modules, so +# no host pipelines are built and the PCMs cannot bind to a host copier +sof-mtl-sdw-benchmark-dolby-dax* P001 +sof-mtl-sdw-benchmark-mfcc* P001 + +# Feature topologies: the kernel loads them into the same component after +# the function topologies, and after the feature topologies given before +# them in the feature_topologies module parameter. Their routes refer to +# widgets of those topologies, so check them with --base in load order, +# e.g. for sof-sdca-amp-ref: --base sof-sdca-1amp-id2.tplg +# --base sof-sdca-jack-id0.tplg --base sof-sdca-jack-ref-dai.tplg +sof-sdca-amp-compr G001 # mixout.21.1 of an amp function topology +sof-sdca-amp-ref G001 # module-copier.21.22 of an amp function topology and + # the loopback DAI copier of sof-sdca-jack-ref-dai +sof-sdca-amp-ref-dai G001 # module-copier.21.22 of an amp function topology +sof-sdca-jack-compr G001 # mixout.1.1 of sof-sdca-jack-id0 +sof-sdca-jack-ref-dai G001 # module-copier.1.12 of sof-sdca-jack-id0 + +# UAOL DAI type is not known to the upstream kernel find_dai() table +sof-hda-generic*uaol W004 +sof-uaol-id* W004 + +# SAI DAI copier lacks UUID and DAI type and is not in a pipeline; SAI is +# not handled by sof_ipc4_dai_config(); gain.1.1 declares 3 input formats +# but defines 2 +sof-imx8mp-wm8960 G005 +sof-imx8mp-wm8960 W004 +sof-imx8mp-wm8960 T006 diff --git a/validator/schema/__init__.py b/validator/schema/__init__.py new file mode 100644 index 0000000..dde388e --- /dev/null +++ b/validator/schema/__init__.py @@ -0,0 +1 @@ +# SPDX-License-Identifier: BSD-3-Clause diff --git a/validator/schema/check_tokens_conf.py b/validator/schema/check_tokens_conf.py new file mode 100755 index 0000000..29a9e40 --- /dev/null +++ b/validator/schema/check_tokens_conf.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: BSD-3-Clause +# +# Copyright(c) 2026 Intel Corporation. All rights reserved. + +"""Cross-check topology2 token definitions against the kernel schema. + +Reports, using schema/kernel_tokens.py: + - tokens the IPC4 kernel driver reads that tokens.conf does not define + - tokens.conf entries unknown to the kernel (informational) + - token_ref attributes in topology2 classes naming undefined token sets + +Exit status is 1 for missing kernel tokens or undefined token sets. +""" + +import argparse +import pathlib +import re +import sys + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +# pylint: disable=wrong-import-position +from schema import kernel_tokens as kt # noqa: E402 + +TOPOLOGY2 = pathlib.Path(__file__).resolve().parents[2] / "topology2" + + +def parse_tokens_conf(path: pathlib.Path) -> dict: + "set name -> {token name: id}" + sets, current = {}, None + for line in path.read_text().splitlines(): + line = line.split("#", 1)[0].strip() + m = re.match(r'name\s+"(\w+)"', line) + if m: + current = sets.setdefault(m.group(1), {}) + continue + m = re.match(r"(\w+)\s+(\d+)$", line) + if m and current is not None: + current[m.group(1)] = int(m.group(2)) + return sets + + +def kernel_ipc4_tokens() -> set: + tokens = {tok for _desc, table in kt.IPC4_TOKEN_LIST.values() for tok, _t, _g in table} + for table in kt.GENERIC_TABLES.values(): + tokens |= {tok for tok, _t, _g in table} + return tokens + + +def token_refs(root: pathlib.Path): + for conf in sorted(root.rglob("*.conf")): + for lineno, line in enumerate(conf.read_text(errors="replace").splitlines(), 1): + m = re.search(r'token_ref\s+"(\w+)\.(\w+)"', line.split("#", 1)[0]) + if m: + yield conf, lineno, m.group(1), m.group(2) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--topology2", type=pathlib.Path, default=TOPOLOGY2) + ap.add_argument("-v", "--verbose", action="store_true", help="also list unknown tokens") + args = ap.parse_args() + + sets = parse_tokens_conf(args.topology2 / "include/common/tokens.conf") + defined = {tid for s in sets.values() for tid in s.values()} + failed = False + + for tok in sorted(kernel_ipc4_tokens() - defined): + print(f"error: kernel reads {kt.TOKEN_NAMES.get(tok, tok)} ({tok}), " + f"tokens.conf does not define it") + failed = True + + unknown = sorted(defined - set(kt.TOKEN_NAMES)) + if unknown and args.verbose: + print(f"info: tokens.conf IDs unknown to the kernel: {', '.join(map(str, unknown))}") + + for conf, lineno, set_name, ttype in token_refs(args.topology2): + if set_name not in sets: + print(f"error: {conf.relative_to(args.topology2)}:{lineno}: token_ref " + f"'{set_name}.{ttype}' names an undefined token set") + failed = True + + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/validator/schema/gen_kernel_tokens.py b/validator/schema/gen_kernel_tokens.py new file mode 100755 index 0000000..c537f4e --- /dev/null +++ b/validator/schema/gen_kernel_tokens.py @@ -0,0 +1,240 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: BSD-3-Clause +# +# Copyright(c) 2026 Intel Corporation. All rights reserved. + +"""Generate kernel_tokens.py from a Linux kernel source tree. + +The SOF driver describes which vendor tuples it consumes with static +tables of struct sof_topology_token. This script extracts those tables +so that the validator follows the kernel without hand-copied token +lists. Run it against a kernel tree when the SOF driver token handling +changes, or with --check in CI to detect drift. + + gen_kernel_tokens.py --kernel ~/linux # rewrite kernel_tokens.py + gen_kernel_tokens.py --kernel ~/linux --check # exit 1 if out of date +""" + +import argparse +import pathlib +import pprint +import re +import subprocess +import sys + +OUTPUT = pathlib.Path(__file__).with_name("kernel_tokens.py") + +TOKENS_H = "include/uapi/sound/sof/tokens.h" +SOF_AUDIO_H = "sound/soc/sof/sof-audio.h" +TOPOLOGY_C = "sound/soc/sof/topology.c" +IPC4_TOPOLOGY_C = "sound/soc/sof/ipc4-topology.c" +ASOC_H = "include/uapi/sound/asoc.h" +SOC_TOPOLOGY_C = "sound/soc/soc-topology.c" + +# Tables in topology.c that are parsed for every IPC version +GENERIC_TABLES = ( + "dapm_widget_tokens", + "comp_pin_tokens", + "comp_input_pin_binding_tokens", + "comp_output_pin_binding_tokens", + "stream_tokens", + "led_tokens", + "common_dai_link_tokens", +) + + +def strip_comments(src: str) -> str: + src = re.sub(r"/\*.*?\*/", " ", src, flags=re.S) + return re.sub(r"//[^\n]*", " ", src) + + +def block(src: str, decl: str) -> str: + "Return the brace enclosed initializer of a top level declaration." + m = re.search(r"^" + decl + r"\s*=\s*\{", src, flags=re.M) + if not m: + raise ValueError(f"declaration not found: {decl}") + depth, i = 1, m.end() + while depth: + depth += {"{": 1, "}": -1}.get(src[i], 0) + i += 1 + return src[m.end():i - 1] + + +def parse_token_ids(src: str) -> dict: + ids = {} + for name, val in re.findall(r"^#define\s+(SOF_TKN_\w+)\s+(\w+)", src, flags=re.M): + ids[name] = ids[val] if val in ids else int(val, 0) # aliases like SOF_TKN_EFFECT_TYPE + return ids + + +def parse_enum(src: str, name: str) -> list: + body = re.search(r"enum " + name + r"\s*\{(.*?)\}", src, flags=re.S).group(1) + return [m for m in re.findall(r"(\w+)\s*,", body) if m != "SOF_TOKEN_COUNT"] + + +def parse_token_tables(src: str) -> dict: + "All top level 'static const struct sof_topology_token x[]' tables." + tables = {} + for name in re.findall(r"^static const struct sof_topology_token (\w+)\[\]", src, flags=re.M): + body = block(src, r"static const struct sof_topology_token " + name + r"\[\]") + tables[name] = [ + (tok, typ, getter) for tok, typ, getter in re.findall( + r"\{\s*(SOF_TKN_\w+)\s*,\s*SND_SOC_TPLG_TUPLE_TYPE_(\w+)\s*,\s*(\w+)", body)] + return tables + + +def parse_token_lists(src: str) -> dict: + "All top level 'static enum sof_tokens x[]' widget token lists." + lists = {} + for name in re.findall(r"^static enum sof_tokens (\w+)\[\]", src, flags=re.M): + body = block(src, r"static enum sof_tokens " + name + r"\[\]") + lists[name] = re.findall(r"(SOF_\w+_TOKENS)", body) + return lists + + +def parse_token_info(src: str, name: str) -> dict: + "struct sof_token_info x[SOF_TOKEN_COUNT]: token group -> (description, table)" + body = block(src, r"static const struct sof_token_info " + name + r"\[SOF_TOKEN_COUNT\]") + return {grp: (desc, table) for grp, desc, table in re.findall( + r"\[(SOF_\w+_TOKENS)\]\s*=\s*\{\s*\"([^\"]*)\"\s*,\s*(\w+)", body)} + + +def parse_widget_ops(src: str, name: str) -> dict: + "struct sof_ipc_tplg_widget_ops x[]: dapm type -> (setup, token list)" + body = block(src, r"static const struct sof_ipc_tplg_widget_ops " + name + + r"\[SND_SOC_DAPM_TYPE_COUNT\]") + return {wtype: (setup, tlist if tlist != "NULL" else None) for wtype, setup, _free, tlist in + re.findall(r"\[snd_soc_dapm_(\w+)\]\s*=\s*\{\s*(\w+)\s*,\s*(\w+)\s*,\s*(\w+)", body)} + + +def parse_dai_types(src: str) -> dict: + body = block(src, r"static const struct sof_dai_types sof_dais\[\]") + return dict(re.findall(r"\{\s*\"(\w+)\"\s*,\s*(SOF_DAI_\w+)\s*\}", body)) + + +def parse_int_defines(src: str) -> dict: + return {name: int(val, 0) for name, val in + re.findall(r"^#define\s+(\w+)\s+(\d+|0x[0-9a-fA-F]+)\b", src, flags=re.M)} + + +def parse_ops(src: str, decl: str, defines: dict) -> list: + """Kcontrol handler tables: [(id, has_get, has_put[, has_info])]. + + Entries are {ID, get, put} or {ID, get, put, info}, missing ones are NULL. + """ + out = [] + for entry in re.findall(r"\{([^{}]*)\}", block(src, decl)): + fields = [f.strip() for f in entry.split(",") if f.strip()] + out.append((defines[fields[0]],) + tuple(f != "NULL" for f in fields[1:])) + return out + + +def kernel_version(kernel: pathlib.Path) -> str: + try: + return subprocess.run(["git", "-C", str(kernel), "describe", "--always", "--abbrev=12"], + capture_output=True, text=True, check=True).stdout.strip() + except (OSError, subprocess.CalledProcessError): + return "unknown" + + +def generate(kernel: pathlib.Path) -> dict: + def read(rel): + return strip_comments((kernel / rel).read_text()) + + tokens_h = read(TOKENS_H) + token_ids = parse_token_ids(tokens_h) + topology_c = read(TOPOLOGY_C) + ipc4_c = read(IPC4_TOPOLOGY_C) + defines = parse_int_defines(read(ASOC_H)) + defines.update(parse_int_defines(tokens_h)) + + tables = parse_token_tables(topology_c) + ipc4_tables = parse_token_tables(ipc4_c) + ipc4_info = parse_token_info(ipc4_c, "ipc4_token_list") + ipc4_lists = parse_token_lists(ipc4_c) + ipc4_ops = parse_widget_ops(ipc4_c, "tplg_ipc4_widget_ops") + + def resolve(table): + out = [] + for tok, typ, getter in table: + if tok not in token_ids: + raise ValueError(f"{tok} not defined in {TOKENS_H}") + out.append((token_ids[tok], typ, getter)) + return out + + token_names = {} + for name, tid in token_ids.items(): + token_names.setdefault(tid, name) # first definition wins over aliases + + return { + "KERNEL_VERSION": kernel_version(kernel), + "TOKEN_NAMES": dict(sorted(token_names.items())), + "TOKEN_GROUPS": parse_enum(read(SOF_AUDIO_H), "sof_tokens"), + "GENERIC_TABLES": {name: resolve(tables[name]) for name in GENERIC_TABLES}, + "IPC4_TOKEN_LIST": {grp: (desc, resolve(ipc4_tables[table])) + for grp, (desc, table) in ipc4_info.items()}, + "IPC4_WIDGET_TOKEN_LISTS": { + wtype: (setup, ipc4_lists[tlist] if tlist else []) + for wtype, (setup, tlist) in ipc4_ops.items()}, + "DAI_TYPES": parse_dai_types(topology_c), + # soc_tplg_kcontrol_bind_io(): standard and SOF kcontrol handlers by ID + "STD_IO_OPS": parse_ops(read(SOC_TOPOLOGY_C), + r"static const struct snd_soc_tplg_kcontrol_ops io_ops\[\]", + defines), + "SOF_IO_OPS": parse_ops(topology_c, + r"static const struct snd_soc_tplg_kcontrol_ops sof_io_ops\[\]", + defines), + "SOF_BYTES_EXT_OPS": parse_ops( + topology_c, r"static const struct snd_soc_tplg_bytes_ext_ops sof_bytes_ext_ops\[\]", + defines), + } + + +HEADER = '''\ +# SPDX-License-Identifier: BSD-3-Clause +# +# Copyright(c) 2026 Intel Corporation. All rights reserved. +# +# GENERATED by gen_kernel_tokens.py from the Linux SOF driver, do not edit. +# +# Token tables are lists of (token id, SND_SOC_TPLG_TUPLE_TYPE_ name, getter) +# in the order the kernel declares them. +''' + + +def render(data: dict) -> str: + out = [HEADER] + for key, value in data.items(): + out.append(f"\n{key} = {pprint.pformat(value, width=100, sort_dicts=False)}\n") + return "".join(out) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--kernel", required=True, type=pathlib.Path, help="Linux source tree") + ap.add_argument("--check", action="store_true", + help="do not write, exit with 1 if the committed file is out of date") + ap.add_argument("-o", "--output", type=pathlib.Path, default=OUTPUT) + args = ap.parse_args() + + data = generate(args.kernel) + + if args.check: + current = {} + exec(args.output.read_text(), current) # pylint: disable=exec-used + stale = [k for k in data if k != "KERNEL_VERSION" and current.get(k) != data[k]] + if stale: + print(f"{args.output.name} is out of date with kernel {data['KERNEL_VERSION']}: " + f"{', '.join(stale)} differ; rerun without --check", file=sys.stderr) + return 1 + print(f"{args.output.name} matches kernel {data['KERNEL_VERSION']}") + return 0 + + args.output.write_text(render(data)) + print(f"wrote {args.output} from kernel {data['KERNEL_VERSION']}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/validator/schema/kernel_tokens.py b/validator/schema/kernel_tokens.py new file mode 100644 index 0000000..5bd2d13 --- /dev/null +++ b/validator/schema/kernel_tokens.py @@ -0,0 +1,356 @@ +# SPDX-License-Identifier: BSD-3-Clause +# +# Copyright(c) 2026 Intel Corporation. All rights reserved. +# +# GENERATED by gen_kernel_tokens.py from the Linux SOF driver, do not edit. +# +# Token tables are lists of (token id, SND_SOC_TPLG_TUPLE_TYPE_ name, getter) +# in the order the kernel declares them. + +KERNEL_VERSION = 'sound-7.2-rc7-28692-gc6cf13c7c483' + +TOKEN_NAMES = {100: 'SOF_TKN_BUF_SIZE', + 101: 'SOF_TKN_BUF_CAPS', + 102: 'SOF_TKN_BUF_FLAGS', + 154: 'SOF_TKN_DAI_TYPE', + 155: 'SOF_TKN_DAI_INDEX', + 156: 'SOF_TKN_DAI_DIRECTION', + 200: 'SOF_TKN_SCHED_PERIOD', + 201: 'SOF_TKN_SCHED_PRIORITY', + 202: 'SOF_TKN_SCHED_MIPS', + 203: 'SOF_TKN_SCHED_CORE', + 204: 'SOF_TKN_SCHED_FRAMES', + 205: 'SOF_TKN_SCHED_TIME_DOMAIN', + 206: 'SOF_TKN_SCHED_DYNAMIC_PIPELINE', + 207: 'SOF_TKN_SCHED_LP_MODE', + 208: 'SOF_TKN_SCHED_MEM_USAGE', + 209: 'SOF_TKN_SCHED_USE_CHAIN_DMA', + 210: 'SOF_TKN_SCHED_KCPS', + 211: 'SOF_TKN_SCHED_DIRECTION', + 212: 'SOF_TKN_SCHED_DIRECTION_VALID', + 250: 'SOF_TKN_VOLUME_RAMP_STEP_TYPE', + 251: 'SOF_TKN_VOLUME_RAMP_STEP_MS', + 260: 'SOF_TKN_GAIN_RAMP_TYPE', + 261: 'SOF_TKN_GAIN_RAMP_DURATION', + 262: 'SOF_TKN_GAIN_VAL', + 300: 'SOF_TKN_SRC_RATE_IN', + 301: 'SOF_TKN_SRC_RATE_OUT', + 320: 'SOF_TKN_ASRC_RATE_IN', + 321: 'SOF_TKN_ASRC_RATE_OUT', + 322: 'SOF_TKN_ASRC_ASYNCHRONOUS_MODE', + 323: 'SOF_TKN_ASRC_OPERATION_MODE', + 353: 'SOF_TKN_PCM_DMAC_CONFIG', + 400: 'SOF_TKN_COMP_PERIOD_SINK_COUNT', + 401: 'SOF_TKN_COMP_PERIOD_SOURCE_COUNT', + 402: 'SOF_TKN_COMP_FORMAT', + 404: 'SOF_TKN_COMP_CORE_ID', + 405: 'SOF_TKN_COMP_UUID', + 406: 'SOF_TKN_COMP_CPC', + 409: 'SOF_TKN_COMP_IS_PAGES', + 410: 'SOF_TKN_COMP_NUM_AUDIO_FORMATS', + 411: 'SOF_TKN_COMP_NUM_INPUT_PINS', + 412: 'SOF_TKN_COMP_NUM_OUTPUT_PINS', + 413: 'SOF_TKN_COMP_INPUT_PIN_BINDING_WNAME', + 414: 'SOF_TKN_COMP_OUTPUT_PIN_BINDING_WNAME', + 415: 'SOF_TKN_COMP_NUM_INPUT_AUDIO_FORMATS', + 416: 'SOF_TKN_COMP_NUM_OUTPUT_AUDIO_FORMATS', + 417: 'SOF_TKN_COMP_NO_WNAME_IN_KCONTROL_NAME', + 418: 'SOF_TKN_COMP_SCHED_DOMAIN', + 419: 'SOF_TKN_COMP_DOMAIN_ID', + 420: 'SOF_TKN_COMP_STACK_BYTES_REQUIREMENT', + 421: 'SOF_TKN_COMP_HEAP_BYTES_REQUIREMENT', + 500: 'SOF_TKN_INTEL_SSP_CLKS_CONTROL', + 501: 'SOF_TKN_INTEL_SSP_MCLK_ID', + 502: 'SOF_TKN_INTEL_SSP_SAMPLE_BITS', + 503: 'SOF_TKN_INTEL_SSP_FRAME_PULSE_WIDTH', + 504: 'SOF_TKN_INTEL_SSP_QUIRKS', + 505: 'SOF_TKN_INTEL_SSP_TDM_PADDING_PER_SLOT', + 506: 'SOF_TKN_INTEL_SSP_BCLK_DELAY', + 600: 'SOF_TKN_INTEL_DMIC_DRIVER_VERSION', + 601: 'SOF_TKN_INTEL_DMIC_CLK_MIN', + 602: 'SOF_TKN_INTEL_DMIC_CLK_MAX', + 603: 'SOF_TKN_INTEL_DMIC_DUTY_MIN', + 604: 'SOF_TKN_INTEL_DMIC_DUTY_MAX', + 605: 'SOF_TKN_INTEL_DMIC_NUM_PDM_ACTIVE', + 608: 'SOF_TKN_INTEL_DMIC_SAMPLE_RATE', + 609: 'SOF_TKN_INTEL_DMIC_FIFO_WORD_LENGTH', + 610: 'SOF_TKN_INTEL_DMIC_UNMUTE_RAMP_TIME_MS', + 700: 'SOF_TKN_INTEL_DMIC_PDM_CTRL_ID', + 701: 'SOF_TKN_INTEL_DMIC_PDM_MIC_A_Enable', + 702: 'SOF_TKN_INTEL_DMIC_PDM_MIC_B_Enable', + 703: 'SOF_TKN_INTEL_DMIC_PDM_POLARITY_A', + 704: 'SOF_TKN_INTEL_DMIC_PDM_POLARITY_B', + 705: 'SOF_TKN_INTEL_DMIC_PDM_CLK_EDGE', + 706: 'SOF_TKN_INTEL_DMIC_PDM_SKEW', + 800: 'SOF_TKN_TONE_SAMPLE_RATE', + 900: 'SOF_TKN_PROCESS_TYPE', + 1000: 'SOF_TKN_IMX_SAI_MCLK_ID', + 1100: 'SOF_TKN_IMX_ESAI_MCLK_ID', + 1200: 'SOF_TKN_STREAM_PLAYBACK_COMPATIBLE_D0I3', + 1201: 'SOF_TKN_STREAM_CAPTURE_COMPATIBLE_D0I3', + 1202: 'SOF_TKN_STREAM_PLAYBACK_PAUSE_SUPPORTED', + 1203: 'SOF_TKN_STREAM_CAPTURE_PAUSE_SUPPORTED', + 1300: 'SOF_TKN_MUTE_LED_USE', + 1301: 'SOF_TKN_MUTE_LED_DIRECTION', + 1400: 'SOF_TKN_INTEL_ALH_RATE', + 1401: 'SOF_TKN_INTEL_ALH_CH', + 1500: 'SOF_TKN_INTEL_HDA_RATE', + 1501: 'SOF_TKN_INTEL_HDA_CH', + 1600: 'SOF_TKN_MEDIATEK_AFE_RATE', + 1601: 'SOF_TKN_MEDIATEK_AFE_CH', + 1602: 'SOF_TKN_MEDIATEK_AFE_FORMAT', + 1700: 'SOF_TKN_MIXER_TYPE', + 1701: 'SOF_TKN_AMD_ACPI2S_CH', + 1702: 'SOF_TKN_AMD_ACPI2S_TDM_MODE', + 1703: 'SOF_TKN_AMD_ACPI2S_FORMAT', + 1800: 'SOF_TKN_AMD_ACPDMIC_RATE', + 1801: 'SOF_TKN_AMD_ACPDMIC_CH', + 1900: 'SOF_TKN_CAVS_AUDIO_FORMAT_IN_RATE', + 1901: 'SOF_TKN_CAVS_AUDIO_FORMAT_IN_BIT_DEPTH', + 1902: 'SOF_TKN_CAVS_AUDIO_FORMAT_IN_VALID_BIT_DEPTH', + 1903: 'SOF_TKN_CAVS_AUDIO_FORMAT_IN_CHANNELS', + 1904: 'SOF_TKN_CAVS_AUDIO_FORMAT_IN_CH_MAP', + 1905: 'SOF_TKN_CAVS_AUDIO_FORMAT_IN_CH_CFG', + 1906: 'SOF_TKN_CAVS_AUDIO_FORMAT_IN_INTERLEAVING_STYLE', + 1907: 'SOF_TKN_CAVS_AUDIO_FORMAT_IN_FMT_CFG', + 1908: 'SOF_TKN_CAVS_AUDIO_FORMAT_IN_SAMPLE_TYPE', + 1909: 'SOF_TKN_CAVS_AUDIO_FORMAT_INPUT_PIN_INDEX', + 1930: 'SOF_TKN_CAVS_AUDIO_FORMAT_OUT_RATE', + 1931: 'SOF_TKN_CAVS_AUDIO_FORMAT_OUT_BIT_DEPTH', + 1932: 'SOF_TKN_CAVS_AUDIO_FORMAT_OUT_VALID_BIT_DEPTH', + 1933: 'SOF_TKN_CAVS_AUDIO_FORMAT_OUT_CHANNELS', + 1934: 'SOF_TKN_CAVS_AUDIO_FORMAT_OUT_CH_MAP', + 1935: 'SOF_TKN_CAVS_AUDIO_FORMAT_OUT_CH_CFG', + 1936: 'SOF_TKN_CAVS_AUDIO_FORMAT_OUT_INTERLEAVING_STYLE', + 1937: 'SOF_TKN_CAVS_AUDIO_FORMAT_OUT_FMT_CFG', + 1938: 'SOF_TKN_CAVS_AUDIO_FORMAT_OUT_SAMPLE_TYPE', + 1939: 'SOF_TKN_CAVS_AUDIO_FORMAT_OUTPUT_PIN_INDEX', + 1970: 'SOF_TKN_CAVS_AUDIO_FORMAT_IBS', + 1971: 'SOF_TKN_CAVS_AUDIO_FORMAT_OBS', + 1972: 'SOF_TKN_CAVS_AUDIO_FORMAT_DMA_BUFFER_SIZE', + 1980: 'SOF_TKN_INTEL_COPIER_NODE_TYPE', + 1981: 'SOF_TKN_INTEL_COPIER_DEEP_BUFFER_DMA_MS', + 2000: 'SOF_TKN_IMX_MICFIL_RATE', + 2001: 'SOF_TKN_IMX_MICFIL_CH', + 2100: 'SOF_TKN_AMD_ACP_SDW_RATE', + 2101: 'SOF_TKN_AMD_ACP_SDW_CH'} + +TOKEN_GROUPS = ['SOF_PCM_TOKENS', + 'SOF_PIPELINE_TOKENS', + 'SOF_SCHED_TOKENS', + 'SOF_ASRC_TOKENS', + 'SOF_SRC_TOKENS', + 'SOF_COMP_TOKENS', + 'SOF_BUFFER_TOKENS', + 'SOF_VOLUME_TOKENS', + 'SOF_PROCESS_TOKENS', + 'SOF_DAI_TOKENS', + 'SOF_DAI_LINK_TOKENS', + 'SOF_HDA_TOKENS', + 'SOF_SSP_TOKENS', + 'SOF_ALH_TOKENS', + 'SOF_DMIC_TOKENS', + 'SOF_DMIC_PDM_TOKENS', + 'SOF_ESAI_TOKENS', + 'SOF_SAI_TOKENS', + 'SOF_AFE_TOKENS', + 'SOF_CORE_TOKENS', + 'SOF_COMP_EXT_TOKENS', + 'SOF_IN_AUDIO_FORMAT_TOKENS', + 'SOF_OUT_AUDIO_FORMAT_TOKENS', + 'SOF_COPIER_DEEP_BUFFER_TOKENS', + 'SOF_COPIER_TOKENS', + 'SOF_AUDIO_FMT_NUM_TOKENS', + 'SOF_COPIER_FORMAT_TOKENS', + 'SOF_GAIN_TOKENS', + 'SOF_ACPDMIC_TOKENS', + 'SOF_ACPI2S_TOKENS', + 'SOF_MICFIL_TOKENS', + 'SOF_ACP_SDW_TOKENS'] + +GENERIC_TABLES = {'dapm_widget_tokens': [(417, 'BOOL', 'get_w_no_wname_in_long_name')], + 'comp_pin_tokens': [(411, 'WORD', 'get_token_u32'), (412, 'WORD', 'get_token_u32')], + 'comp_input_pin_binding_tokens': [(413, 'STRING', 'get_token_string')], + 'comp_output_pin_binding_tokens': [(414, 'STRING', 'get_token_string')], + 'stream_tokens': [(1200, 'BOOL', 'get_token_u16'), + (1201, 'BOOL', 'get_token_u16'), + (1202, 'BOOL', 'get_token_u16'), + (1203, 'BOOL', 'get_token_u16')], + 'led_tokens': [(1300, 'WORD', 'get_token_u32'), (1301, 'WORD', 'get_token_u32')], + 'common_dai_link_tokens': [(154, 'STRING', 'get_token_dai_type')]} + +IPC4_TOKEN_LIST = {'SOF_DAI_TOKENS': ('DAI tokens', + [(154, 'STRING', 'get_token_dai_type'), (155, 'WORD', 'get_token_u32')]), + 'SOF_PIPELINE_TOKENS': ('Pipeline tokens', [(206, 'BOOL', 'get_token_u16')]), + 'SOF_SCHED_TOKENS': ('Scheduler tokens', + [(207, 'WORD', 'get_token_u32'), + (209, 'BOOL', 'get_token_u16'), + (203, 'WORD', 'get_token_u32'), + (201, 'WORD', 'get_token_u32'), + (211, 'WORD', 'get_token_u32'), + (211, 'BOOL', 'get_token_u16')]), + 'SOF_COMP_EXT_TOKENS': ('Comp extended tokens', + [(405, 'UUID', 'get_token_uuid'), + (404, 'WORD', 'get_token_u32'), + (418, 'STRING', 'get_token_comp_domain'), + (419, 'WORD', 'get_token_u32'), + (421, 'WORD', 'get_token_u32'), + (420, 'WORD', 'get_token_u32')]), + 'SOF_COMP_TOKENS': ('IPC4 Component tokens', [(409, 'WORD', 'get_token_u32')]), + 'SOF_IN_AUDIO_FORMAT_TOKENS': ('IPC4 Input Audio format tokens', + [(1900, 'WORD', 'get_token_u32'), + (1901, 'WORD', 'get_token_u32'), + (1904, 'WORD', 'get_token_u32'), + (1905, 'WORD', 'get_token_u32'), + (1906, 'WORD', 'get_token_u32'), + (1907, 'WORD', 'get_token_u32'), + (1909, 'WORD', 'get_token_u32'), + (1970, 'WORD', 'get_token_u32')]), + 'SOF_OUT_AUDIO_FORMAT_TOKENS': ('IPC4 Output Audio format tokens', + [(1930, 'WORD', 'get_token_u32'), + (1931, 'WORD', 'get_token_u32'), + (1934, 'WORD', 'get_token_u32'), + (1935, 'WORD', 'get_token_u32'), + (1936, 'WORD', 'get_token_u32'), + (1937, 'WORD', 'get_token_u32'), + (1939, 'WORD', 'get_token_u32'), + (1971, 'WORD', 'get_token_u32')]), + 'SOF_COPIER_DEEP_BUFFER_TOKENS': ('IPC4 Copier deep buffer tokens', + [(1981, 'WORD', 'get_token_u32')]), + 'SOF_COPIER_TOKENS': ('IPC4 Copier tokens', [(1980, 'WORD', 'get_token_u32')]), + 'SOF_AUDIO_FMT_NUM_TOKENS': ('IPC4 Audio format number tokens', + [(415, 'WORD', 'get_token_u32'), (416, 'WORD', 'get_token_u32')]), + 'SOF_GAIN_TOKENS': ('Gain tokens', + [(260, 'WORD', 'get_token_u32'), + (261, 'WORD', 'get_token_u32'), + (262, 'WORD', 'get_token_u32')]), + 'SOF_SRC_TOKENS': ('SRC tokens', [(301, 'WORD', 'get_token_u32')]), + 'SOF_ASRC_TOKENS': ('ASRC tokens', + [(321, 'WORD', 'get_token_u32'), (323, 'WORD', 'get_token_u32')])} + +IPC4_WIDGET_TOKEN_LISTS = {'aif_in': ('sof_ipc4_widget_setup_pcm', + ['SOF_COMP_TOKENS', + 'SOF_COPIER_TOKENS', + 'SOF_AUDIO_FMT_NUM_TOKENS', + 'SOF_IN_AUDIO_FORMAT_TOKENS', + 'SOF_OUT_AUDIO_FORMAT_TOKENS', + 'SOF_COMP_EXT_TOKENS', + 'SOF_COPIER_DEEP_BUFFER_TOKENS', + 'SOF_DAI_TOKENS']), + 'aif_out': ('sof_ipc4_widget_setup_pcm', + ['SOF_COMP_TOKENS', + 'SOF_COPIER_TOKENS', + 'SOF_AUDIO_FMT_NUM_TOKENS', + 'SOF_IN_AUDIO_FORMAT_TOKENS', + 'SOF_OUT_AUDIO_FORMAT_TOKENS', + 'SOF_COMP_EXT_TOKENS', + 'SOF_COPIER_DEEP_BUFFER_TOKENS', + 'SOF_DAI_TOKENS']), + 'dai_in': ('sof_ipc4_widget_setup_comp_dai', + ['SOF_COMP_TOKENS', + 'SOF_COPIER_TOKENS', + 'SOF_AUDIO_FMT_NUM_TOKENS', + 'SOF_IN_AUDIO_FORMAT_TOKENS', + 'SOF_OUT_AUDIO_FORMAT_TOKENS', + 'SOF_COMP_EXT_TOKENS', + 'SOF_COPIER_DEEP_BUFFER_TOKENS', + 'SOF_DAI_TOKENS']), + 'dai_out': ('sof_ipc4_widget_setup_comp_dai', + ['SOF_COMP_TOKENS', + 'SOF_COPIER_TOKENS', + 'SOF_AUDIO_FMT_NUM_TOKENS', + 'SOF_IN_AUDIO_FORMAT_TOKENS', + 'SOF_OUT_AUDIO_FORMAT_TOKENS', + 'SOF_COMP_EXT_TOKENS', + 'SOF_COPIER_DEEP_BUFFER_TOKENS', + 'SOF_DAI_TOKENS']), + 'buffer': ('sof_ipc4_widget_setup_pcm', + ['SOF_COMP_TOKENS', + 'SOF_COPIER_TOKENS', + 'SOF_AUDIO_FMT_NUM_TOKENS', + 'SOF_IN_AUDIO_FORMAT_TOKENS', + 'SOF_OUT_AUDIO_FORMAT_TOKENS', + 'SOF_COMP_EXT_TOKENS', + 'SOF_COPIER_DEEP_BUFFER_TOKENS', + 'SOF_DAI_TOKENS']), + 'scheduler': ('sof_ipc4_widget_setup_comp_pipeline', ['SOF_SCHED_TOKENS', 'SOF_PIPELINE_TOKENS']), + 'pga': ('sof_ipc4_widget_setup_comp_pga', + ['SOF_COMP_TOKENS', + 'SOF_GAIN_TOKENS', + 'SOF_AUDIO_FMT_NUM_TOKENS', + 'SOF_IN_AUDIO_FORMAT_TOKENS', + 'SOF_OUT_AUDIO_FORMAT_TOKENS', + 'SOF_COMP_EXT_TOKENS']), + 'mixer': ('sof_ipc4_widget_setup_comp_mixer', + ['SOF_COMP_TOKENS', + 'SOF_AUDIO_FMT_NUM_TOKENS', + 'SOF_IN_AUDIO_FORMAT_TOKENS', + 'SOF_OUT_AUDIO_FORMAT_TOKENS', + 'SOF_COMP_EXT_TOKENS']), + 'src': ('sof_ipc4_widget_setup_comp_src', + ['SOF_COMP_TOKENS', + 'SOF_SRC_TOKENS', + 'SOF_AUDIO_FMT_NUM_TOKENS', + 'SOF_IN_AUDIO_FORMAT_TOKENS', + 'SOF_OUT_AUDIO_FORMAT_TOKENS', + 'SOF_COMP_EXT_TOKENS']), + 'asrc': ('sof_ipc4_widget_setup_comp_asrc', + ['SOF_COMP_TOKENS', + 'SOF_ASRC_TOKENS', + 'SOF_AUDIO_FMT_NUM_TOKENS', + 'SOF_IN_AUDIO_FORMAT_TOKENS', + 'SOF_OUT_AUDIO_FORMAT_TOKENS', + 'SOF_COMP_EXT_TOKENS']), + 'effect': ('sof_ipc4_widget_setup_comp_process', + ['SOF_COMP_TOKENS', + 'SOF_AUDIO_FMT_NUM_TOKENS', + 'SOF_IN_AUDIO_FORMAT_TOKENS', + 'SOF_OUT_AUDIO_FORMAT_TOKENS', + 'SOF_COMP_EXT_TOKENS']), + 'decoder': ('sof_ipc4_widget_setup_comp_process', + ['SOF_COMP_TOKENS', + 'SOF_AUDIO_FMT_NUM_TOKENS', + 'SOF_IN_AUDIO_FORMAT_TOKENS', + 'SOF_OUT_AUDIO_FORMAT_TOKENS', + 'SOF_COMP_EXT_TOKENS']), + 'encoder': ('sof_ipc4_widget_setup_comp_process', + ['SOF_COMP_TOKENS', + 'SOF_AUDIO_FMT_NUM_TOKENS', + 'SOF_IN_AUDIO_FORMAT_TOKENS', + 'SOF_OUT_AUDIO_FORMAT_TOKENS', + 'SOF_COMP_EXT_TOKENS'])} + +DAI_TYPES = {'SSP': 'SOF_DAI_INTEL_SSP', + 'HDA': 'SOF_DAI_INTEL_HDA', + 'DMIC': 'SOF_DAI_INTEL_DMIC', + 'ALH': 'SOF_DAI_INTEL_ALH', + 'SAI': 'SOF_DAI_IMX_SAI', + 'ESAI': 'SOF_DAI_IMX_ESAI', + 'ACPBT': 'SOF_DAI_AMD_BT', + 'ACPSP': 'SOF_DAI_AMD_SP', + 'ACPDMIC': 'SOF_DAI_AMD_DMIC', + 'ACPHS': 'SOF_DAI_AMD_HS', + 'AFE': 'SOF_DAI_MEDIATEK_AFE', + 'ACPSP_VIRTUAL': 'SOF_DAI_AMD_SP_VIRTUAL', + 'ACPHS_VIRTUAL': 'SOF_DAI_AMD_HS_VIRTUAL', + 'MICFIL': 'SOF_DAI_IMX_MICFIL', + 'ACP_SDW': 'SOF_DAI_AMD_SDW', + 'ACPTDM': 'SOF_DAI_AMD_I2S'} + +STD_IO_OPS = [(1, True, True, True), + (2, True, True, False), + (4, True, True, True), + (6, True, True, False), + (5, True, True, True), + (7, True, True, True), + (3, True, True, True), + (8, True, True, False), + (64, True, True, True), + (65, True, True, True), + (66, True, True, False), + (67, True, True, False), + (68, True, True, True)] + +SOF_IO_OPS = [(256, True, True), (258, True, True), (257, True, True), (259, True, True)] + +SOF_BYTES_EXT_OPS = [(258, True, True), (260, True)] diff --git a/validator/tests/conftest.py b/validator/tests/conftest.py new file mode 100644 index 0000000..86f86b3 --- /dev/null +++ b/validator/tests/conftest.py @@ -0,0 +1,9 @@ +# SPDX-License-Identifier: BSD-3-Clause +# +# Copyright(c) 2026 Intel Corporation. All rights reserved. + +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path[:0] = [os.path.dirname(HERE), HERE] diff --git a/validator/tests/test_integration.py b/validator/tests/test_integration.py new file mode 100644 index 0000000..0d0621d --- /dev/null +++ b/validator/tests/test_integration.py @@ -0,0 +1,116 @@ +# SPDX-License-Identifier: BSD-3-Clause +# +# Copyright(c) 2026 Intel Corporation. All rights reserved. + +"""Integration tests against real topology2 sources and a kernel tree. + +ALSATPLG selects the alsatplg binary (default: workspace tools/bin or PATH), +SOF_ABI_HEADER / SOF_ROOT selects the ABI header (default: repo include/kernel/abi.h), +KERNEL_TREE a Linux tree for the token schema drift check. +""" + +import os +import pathlib +import shutil +import subprocess +import sys + +import pytest + +import checks +from tplgparse import model + +VALIDATOR = pathlib.Path(__file__).resolve().parents[1] +REPO_ROOT = VALIDATOR.parent +TOPOLOGY2 = REPO_ROOT / "topology2" + + +def alsatplg(): + workspace = os.environ.get("SOF_WORKSPACE") + candidates = [ + os.environ.get("ALSATPLG"), + os.environ.get("ALSATPLG_CMD"), + pathlib.Path(workspace) / "tools/bin/alsatplg" if workspace else None, + REPO_ROOT.parent / "tools/bin/alsatplg", + shutil.which("alsatplg"), + ] + for cand in candidates: + if cand and os.access(cand, os.X_OK): + return str(cand) + return None + + +def abi_source(): + for candidate in (os.environ.get("SOF_ABI_HEADER"), os.environ.get("SOF_ROOT")): + if candidate and pathlib.Path(candidate).exists(): + return candidate + sib_sof = REPO_ROOT.parent / "sof" + if (sib_sof / "src/include/kernel/abi.h").is_file(): + return str(sib_sof) + return str(REPO_ROOT) + + +def build_topology(tmp_path, conf, defines): + tool = alsatplg() + if tool is None: + pytest.skip("alsatplg not found") + abi = subprocess.run(["bash", str(TOPOLOGY2 / "get_abi.sh"), abi_source(), "ipc4"], + check=True, capture_output=True).stdout + src = tmp_path / "in.conf" + src.write_bytes(abi + (TOPOLOGY2 / conf).read_bytes()) + out = tmp_path / "out.tplg" + env = dict(os.environ, ALSA_CONFIG_DIR=str(TOPOLOGY2)) + lib_dir = pathlib.Path(tool).resolve().parent.parent / "lib" + if lib_dir.is_dir(): + ld_prev = env.get("LD_LIBRARY_PATH", "") + env["LD_LIBRARY_PATH"] = f"{lib_dir}:{ld_prev}" if ld_prev else str(lib_dir) + env.setdefault("ALSA_TOPOLOGY_PLUGIN_DIR", str(lib_dir / "alsa-topology")) + subprocess.run([tool, "-I", str(TOPOLOGY2) + "/", "-D", defines, "-p", "-c", str(src), + "-o", str(out)], env=env, check=True, capture_output=True, cwd=tmp_path) + return out + + +# defines of real targets in topology2/*/tplg-targets*.cmake +MTL_NOCODEC = ("PLATFORM=mtl,NUM_DMICS=4,PDM1_MIC_A_ENABLE=1,PDM1_MIC_B_ENABLE=1," + "PREPROCESS_PLUGINS=nhlt,NHLT_BIN=nhlt.bin") + + +@pytest.mark.parametrize("conf,defines", [ + ("cavs-nocodec.conf", MTL_NOCODEC), + ("sof-hda-generic.conf", "HDA_CONFIG=mix,NUM_HDMIS=3"), +]) +def test_real_topology_has_no_errors(tmp_path, conf, defines): + out = build_topology(tmp_path, conf, defines) + findings = checks.run(model.load(out), checks.Options()) + errors = [f.format() for f in findings if f.severity == checks.ERROR] + assert errors == [] + + +def test_cli_exit_status(tmp_path): + out = build_topology(tmp_path, "cavs-nocodec.conf", MTL_NOCODEC) + res = subprocess.run([sys.executable, str(VALIDATOR / "tplg_validate.py"), "-q", str(out)], + capture_output=True, text=True, check=False) + assert res.returncode == 0, res.stdout + res.stderr + + +def test_siggen_echo_reference_pin_formats(tmp_path): + out = build_topology( + tmp_path, "cavs-sdw.conf", + "PLATFORM=mtl,NUM_SDW_AMP_LINKS=1,SDW_DMIC=1,SDW_AMP_FEEDBACK=false," + "SDW_SPK_STREAM=Playback-SmartAmp,SDW_DMIC_STREAM=Capture-SmartMic," + "SDW_JACK_OUT_STREAM=Playback-SimpleJack,SDW_JACK_IN_STREAM=Capture-SimpleJack," + "COMPRESSED=true,SDW_JACK_ECHO_REF=true,SDW_ECHO_REF_DAI=true") + t = model.load(out) + assert t.widget("siggen.12.1") is not None + findings = checks.run(t, checks.Options(), selected={"F003"}) + assert not [f.format() for f in findings if f.severity != checks.INFO] + + +def test_kernel_schema_is_current(): + kernel = os.environ.get("KERNEL_TREE") + if not kernel: + pytest.skip("KERNEL_TREE not set") + res = subprocess.run([sys.executable, str(VALIDATOR / "schema/gen_kernel_tokens.py"), + "--kernel", kernel, "--check"], capture_output=True, text=True, + check=False) + assert res.returncode == 0, res.stderr diff --git a/validator/tests/test_rules.py b/validator/tests/test_rules.py new file mode 100644 index 0000000..3693b69 --- /dev/null +++ b/validator/tests/test_rules.py @@ -0,0 +1,818 @@ +# SPDX-License-Identifier: BSD-3-Clause +# +# Copyright(c) 2026 Intel Corporation. All rights reserved. + +"""One positive and at least one negative case per rule.""" + +import struct +import sys + +import pytest + +import checks +import tplg_validate +from checks.paths import pcm_paths +from tplgbuild import (Topology, TupleType, in_format, module_tuples, name, out_format, + playback_ssp, tuples, words) +from tplgparse import binary, model + + +def run(data: bytes, num_cores=0): + tplg = model.build(binary.parse_bytes(data), "test.tplg") + return checks.run(tplg, checks.Options(num_cores=num_cores)) + + +def rules(findings, severity=None): + return {f.rule for f in findings if severity is None or f.severity == severity} + + +def widget(t, wname): + return next(w for _i, w, _k in t.widgets if binary.decode_name(w.name) == wname) + + +def test_valid_topology_is_clean(): + assert run(playback_ssp().build()) == [] + + +# --- L1 ----------------------------------------------------------------------- + +def test_s001_truncated_file(): + data = playback_ssp().build() + assert "S001" in rules(run(data[:-10]), checks.ERROR) + + +def test_s001_bad_magic(): + data = bytearray(playback_ssp().build()) + data[0:4] = b"XXXX" + assert "S001" in rules(run(bytes(data)), checks.ERROR) + + +def test_s002_vendor_section(): + t = playback_ssp() + data = t.build() + t._section(binary.TplgType.PDATA, [b"\0" * 8]) + assert "S002" in rules(run(data), checks.ERROR) + + +def test_s003_widget_size(): + t = playback_ssp() + widget(t, "gain.1.1").size = 100 + assert "S003" in rules(run(t.build()), checks.ERROR) + + +def test_s004_unterminated_name(): + t = playback_ssp() + widget(t, "gain.1.1").sname = b"x" * binary.NAME_LEN + assert "S004" in rules(run(t.build()), checks.ERROR) + + +def test_s005_unknown_widget_type(): + t = playback_ssp() + widget(t, "gain.1.1").id = 99 + assert "S005" in rules(run(t.build()), checks.ERROR) + + +def test_s007_tlv_type(): + t = playback_ssp() + t.widgets[2][2][0]["hdr"].tlv.type = 3 # DB_RANGE + assert "S007" in rules(run(t.build()), checks.ERROR) + + +def test_s008_unbound_kcontrol_handler(): + t = playback_ssp() + t.widgets[2][2][0]["hdr"].ops.get = 999 + assert "S008" in rules(run(t.build()), checks.ERROR) + + +# --- L2 ----------------------------------------------------------------------- + +def test_t001_too_many_pins(): + t = playback_ssp() + widget(t, "gain.1.1").priv = module_tuples(in_pins=9) + assert "T001" in rules(run(t.build()), checks.ERROR) + + +def test_t001_missing_format_count(): + t = playback_ssp() + widget(t, "gain.1.1").priv = tuples(words(num_input_pins=1, num_output_pins=1), + (TupleType.UUID, [(405, b"\1" * 16)]), + in_format(), out_format()) + assert "T001" in rules(run(t.build()), checks.ERROR) + + +def test_t003_bad_array_size(): + t = playback_ssp() + priv = bytearray(module_tuples()) + struct.pack_into(" bytes: + raw = s.encode() + return raw + b"\0" * (binary.NAME_LEN - len(raw)) + + +def zero(record): + "All-zero instance of a record whose private data is empty." + fixed = sum(sc.sizeof() for sc in record.subcons if sc.name != "priv") + has_priv = any(sc.name == "priv" for sc in record.subcons) + return record.parse(bytes(fixed + (4 if has_priv else 0))) + + +def vendor_array(ttype: TupleType, elems) -> bytes: + "snd_soc_tplg_vendor_array from [(token, value)]" + body = b"" + for token, value in elems: + if ttype == TupleType.UUID: + body += struct.pack(" bytes: + "Private data from (type, [(token, value)]) arrays." + return b"".join(vendor_array(t, e) for t, e in arrays) + + +def words(**kw) -> tuple: + "A WORD array from token=value keyword arguments, token names as in tokens below." + return (TupleType.WORD, [(TOKENS[k], v) for k, v in kw.items()]) + + +TOKENS = { + "num_input_pins": 411, "num_output_pins": 412, + "num_input_audio_formats": 415, "num_output_audio_formats": 416, + "core": 404, "is_pages": 409, "node_type": 1980, "dai_index": 155, + "lp_mode": 207, "chain_dma": 209, "sched_core": 203, "priority": 201, "dynamic": 206, + "in_rate": 1900, "in_bit_depth": 1901, "in_ch_map": 1904, "in_ch_cfg": 1905, + "in_interleaving": 1906, "in_fmt_cfg": 1907, "in_pin": 1909, "ibs": 1970, + "out_rate": 1930, "out_bit_depth": 1931, "out_ch_map": 1934, "out_ch_cfg": 1935, + "out_interleaving": 1936, "out_fmt_cfg": 1937, "out_pin": 1939, "obs": 1971, +} + +COPIER_UUID = bytes.fromhex("830ca09b12ca834a943c1fa2e82f9dda") + + +def fmt_cfg(channels=2, valid=32, stype=1): + return channels | valid << 8 | stype << 16 + + +def in_format(rate=48000, depth=32, valid=32, channels=2, **extra): + return words(in_rate=rate, in_bit_depth=depth, in_fmt_cfg=fmt_cfg(channels, valid), + in_ch_map=0xffffff10, in_ch_cfg=1, in_interleaving=0, ibs=384, **extra) + + +def out_format(rate=48000, depth=32, valid=32, channels=2, **extra): + return words(out_rate=rate, out_bit_depth=depth, out_fmt_cfg=fmt_cfg(channels, valid), + out_ch_map=0xffffff10, out_ch_cfg=1, out_interleaving=0, obs=384, **extra) + + +def module_tuples(n_in=1, n_out=1, in_pins=1, out_pins=1, ins=None, outs=None, extra=()): + "Typical module private data: pins, format counts, UUID and formats." + ins = [in_format() for _ in range(n_in)] if ins is None else ins + outs = [out_format() for _ in range(n_out)] if outs is None else outs + return tuples(words(is_pages=1, num_input_audio_formats=n_in, num_output_audio_formats=n_out, + num_input_pins=in_pins, num_output_pins=out_pins), + (TupleType.UUID, [(405, COPIER_UUID)]), *extra, *ins, *outs) + + +class Topology: + "Collects records and emits a topology binary." + + def __init__(self): + self.widgets = [] # (index, widget container, [kcontrol containers]) + self.routes = [] # (index, container) + self.pcms = [] + self.links = [] + self.manifest_priv = struct.pack(" bytes: + out = b"" + m = zero(binary.MANIFEST) + m.size = SIZE["manifest"] + m.control_elems = sum(len(k) for _i, _w, k in self.widgets) + m.widget_elems, m.graph_elems = len(self.widgets), len(self.routes) + m.pcm_elems, m.dai_link_elems = len(self.pcms), len(self.links) + m.priv = self.manifest_priv + out += self._section(TplgType.MANIFEST, [binary.MANIFEST.build(m)]) + for index, w, kcontrols in self.widgets: + data = binary.WIDGET.build(w) + b"".join(binary.KCONTROL.build(k) for k in kcontrols) + out += self._section(TplgType.DAPM_WIDGET, [data], index=index) + if self.pcms: + out += self._section(TplgType.PCM, [binary.PCM.build(p) for p in self.pcms]) + for index, r in self.routes: + out += self._section(TplgType.DAPM_GRAPH, [binary.GRAPH_ELEM.build(r)], index=index) + if self.links: + out += self._section(TplgType.BACKEND_LINK, + [binary.LINK_CONFIG.build(link) for link in self.links]) + return out + + +def playback_ssp(chain_dma=0) -> Topology: + """A valid minimal topology: host copier -> gain -> SSP DAI copier, one + PCM, one BE link.""" + t = Topology() + t.pipeline(1, chain_dma=chain_dma) + t.widget("host-copier.0.playback", "aif_in", 1, module_tuples(in_pins=0), + sname="Port0 Playback") + t.widget("gain.1.1", "pga", 1, module_tuples(), + kcontrols=[Topology.kcontrol("Playback Volume", access=0x13, max=45, + num_channels=2)]) + t.widget("dai-copier.SSP.NoCodec-0.playback", "dai_in", 1, + module_tuples(out_pins=0, extra=[(TupleType.STRING, [(154, "SSP")]), + words(dai_index=0, node_type=12)]), + sname="NoCodec-0") + t.route("host-copier.0.playback", "gain.1.1", 1) + t.route("gain.1.1", "dai-copier.SSP.NoCodec-0.playback", 1) + t.pcm("Port0", playback="Port0 Playback") + t.link("NoCodec-0") + return t diff --git a/validator/tplg_validate.py b/validator/tplg_validate.py new file mode 100755 index 0000000..634eff9 --- /dev/null +++ b/validator/tplg_validate.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: BSD-3-Clause +# +# Copyright(c) 2026 Intel Corporation. All rights reserved. + +"""Offline validator for SOF IPC4 topology binaries. + +Parses .tplg files and repeats the checks the Linux SOF driver does when +it loads a topology, without needing the target hardware. Exit status is +1 if any error (or, with --werror, warning) was found. + + tplg_validate.py sof-mtl-nocodec.tplg + tplg_validate.py --werror --num-cores 5 build/*.tplg + tplg_validate.py --list-rules +""" + +import argparse +import fnmatch +import json +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +# pylint: disable=wrong-import-position +import checks # noqa: E402 +from checks import ERROR, INFO, WARNING # noqa: E402 +from schema import kernel_tokens # noqa: E402 +from tplgparse import model # noqa: E402 + + +def load_waivers(path) -> list: + """Waiver file lines: ' [reason]'. + + Waived errors are reported as warnings so that known problems do not + fail the build while new ones do. + """ + waivers = [] + with open(path, encoding="utf-8") as f: + for line in f: + fields = line.split("#", 1)[0].split() + if len(fields) >= 2: + waivers.append((fields[0], fields[1])) + return waivers + + +def apply_waivers(path, findings, waivers): + name = os.path.basename(path) + if name.endswith(".tplg"): + name = name[:-len(".tplg")] + for f in findings: + if f.severity == ERROR and any(fnmatch.fnmatchcase(name, pat) and f.rule == rule + for pat, rule in waivers): + f.severity = WARNING + f.message += " [waived]" + + +def load_bases(paths): + """Load the --base topologies in load order. + + Each one gets the previous one as its base, which already includes all + earlier ones. Returns the last one, or None without bases. + """ + last = None + for path in paths: + base = model.load(path) + if last is not None: + base.add_base(last) + last = base + return last + + +def list_rules(): + for r in checks.load_rules(): + print(f"{r.id} {r.layer} {r.severity:7} {r.summary}") + print(f" kernel: {r.kernel}") + print(f"\ntoken schema generated from kernel {kernel_tokens.KERNEL_VERSION}") + + +def dump(tplg): + "Print the decoded topology with kernel token names." + names = kernel_tokens.TOKEN_NAMES + for w in tplg.widgets: + print(f"widget {w.name!r} type {w.type_name} pipeline {w.index} sname {w.sname!r}") + for a in w.priv.arrays: + for t in a.tuples: + value = model.format_uuid(t.value) if t.type.name == "UUID" else t.value + print(f" {names.get(t.token, t.token)} = {value!r}") + for k in w.kcontrols: + print(f" {k.label} ({k.kind.name})") + for r in tplg.routes: + print(r.label) + for p in tplg.pcms: + print(f"{p.label} playback {p.raw.playback} capture {p.raw.capture}") + for link in tplg.links: + print(f"{link.label} stream {link.stream_name!r} hw_configs {link.raw.num_hw_configs}") + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("files", nargs="*", help="topology binaries") + ap.add_argument("--werror", action="store_true", help="treat warnings as errors") + ap.add_argument("-q", "--quiet", action="store_true", + help="print errors only, plus a one line summary of warnings") + ap.add_argument("-v", "--verbose", action="store_true", help="also print info findings") + ap.add_argument("--num-cores", type=int, default=0, + help="DSP core count for core ID checks (default: not checked)") + ap.add_argument("--rules", help="comma separated rule IDs or layers (L1..L4) to run") + ap.add_argument("--disable", default="", help="comma separated rule IDs to skip") + ap.add_argument("--base", action="append", default=[], metavar="TPLG", + help="topology loaded before the checked ones into the same component, " + "e.g. a function topology under a feature topology; repeat in " + "load order") + ap.add_argument("--waivers", help="file of known errors to report as warnings") + ap.add_argument("--json", action="store_true", help="machine readable output") + ap.add_argument("--dump", action="store_true", help="print the decoded topology") + ap.add_argument("--list-rules", action="store_true", help="list rules and exit") + ap.add_argument("--remove-on-error", action="store_true", + help="delete a topology file that fails validation, so that a build " + "system rebuilds and rechecks it next time") + args = ap.parse_args() + + if args.list_rules: + list_rules() + return 0 + if not args.files: + ap.error("no topology files given") + + all_rules = checks.load_rules() + wanted = set(args.rules.split(",")) if args.rules else None + disabled = set(filter(None, args.disable.split(","))) + selected = {r.id for r in all_rules + if (wanted is None or r.id in wanted or r.layer in wanted) + and r.id not in disabled} + + options = checks.Options(num_cores=args.num_cores, verbose=args.verbose) + waivers = load_waivers(args.waivers) if args.waivers else [] + bases = load_bases(args.base) + failed = False + report = {} + + for path in args.files: + try: + tplg = model.load(path) + except OSError as e: + print(f"{path}: {e}", file=sys.stderr) + failed = True + continue + if bases is not None: + tplg.add_base(bases) + if args.dump: + dump(tplg) + findings = checks.run(tplg, options, selected) + apply_waivers(path, findings, waivers) + counts = {s: sum(1 for f in findings if f.severity == s) for s in (ERROR, WARNING, INFO)} + if counts[ERROR] or (args.werror and counts[WARNING]): + failed = True + if args.remove_on_error: + os.remove(path) + + if args.json: + report[path] = [f.__dict__ for f in findings] + continue + shown = {ERROR} if args.quiet else {ERROR, WARNING} + if args.verbose: + shown.add(INFO) + for f in findings: + if f.severity in shown or (args.werror and f.severity == WARNING): + print(f"{path}: {f.format()}") + if not args.quiet or counts[ERROR] or counts[WARNING]: + print(f"{path}: {counts[ERROR]} errors, {counts[WARNING]} warnings, " + f"{counts[INFO]} info") + + if args.json: + json.dump(report, sys.stdout, indent=1) + print() + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/validator/tplgparse/__init__.py b/validator/tplgparse/__init__.py new file mode 100644 index 0000000..dde388e --- /dev/null +++ b/validator/tplgparse/__init__.py @@ -0,0 +1 @@ +# SPDX-License-Identifier: BSD-3-Clause diff --git a/validator/tplgparse/binary.py b/validator/tplgparse/binary.py new file mode 100644 index 0000000..a098eec --- /dev/null +++ b/validator/tplgparse/binary.py @@ -0,0 +1,483 @@ +# SPDX-License-Identifier: BSD-3-Clause +# +# Copyright(c) 2026 Intel Corporation. All rights reserved. + +"""ALSA topology binary format, ABI 5 (Linux include/uapi/sound/asoc.h). + +The record layouts are ported from sof-test tools/tplgtool2.py. Unlike +tplgtool2 the section loop is driven by hand, mirroring soc_tplg_load() +in Linux sound/soc/soc-topology.c, so that malformed input is reported +as an issue at a file offset instead of an exception from construct. +All values are kept as plain integers and raw bytes; interpretation is +left to the model. +""" + +import enum +import io +from dataclasses import dataclass, field + +import construct +from construct import (Array, Bytes, GreedyBytes, Int8ul, Int16ul, Int32sl, + Int32ul, Int64ul, Prefixed, Struct, Switch, this) + +TPLG_MAGIC = 0x41536F43 # SND_SOC_TPLG_MAGIC, "CoSA" in file byte order +TPLG_MAGIC_BE = 0x436F5341 +TPLG_ABI_VERSION = 5 # SND_SOC_TPLG_ABI_VERSION +TPLG_ABI_VERSION_MIN = 5 # SND_SOC_TPLG_ABI_VERSION_MIN + +NAME_LEN = 44 # SNDRV_CTL_ELEM_ID_NAME_MAXLEN +MAX_CHAN = 8 # SND_SOC_TPLG_MAX_CHAN +STREAM_CONFIG_MAX = 8 # SND_SOC_TPLG_STREAM_CONFIG_MAX +HW_CONFIG_MAX = 8 # SND_SOC_TPLG_HW_CONFIG_MAX +TLV_SIZE = 32 # SND_SOC_TPLG_TLV_SIZE +NUM_TEXTS = 16 # SND_SOC_TPLG_NUM_TEXTS + + +class TplgType(enum.IntEnum): + "SND_SOC_TPLG_TYPE_*" + MIXER = 1 + BYTES = 2 + ENUM = 3 + DAPM_GRAPH = 4 + DAPM_WIDGET = 5 + DAI_LINK = 6 + PCM = 7 + MANIFEST = 8 + CODEC_LINK = 9 + BACKEND_LINK = 10 + PDATA = 11 + DAI = 12 + + +class TupleType(enum.IntEnum): + "SND_SOC_TPLG_TUPLE_TYPE_*" + UUID = 0 + STRING = 1 + BOOL = 2 + BYTE = 3 + WORD = 4 + SHORT = 5 + + +class DapmType(enum.IntEnum): + "SND_SOC_TPLG_DAPM_*" + INPUT = 0 + OUTPUT = 1 + MUX = 2 + MIXER = 3 + PGA = 4 + OUT_DRV = 5 + ADC = 6 + DAC = 7 + SWITCH = 8 + PRE = 9 + POST = 10 + AIF_IN = 11 + AIF_OUT = 12 + DAI_IN = 13 + DAI_OUT = 14 + DAI_LINK = 15 + BUFFER = 16 + SCHEDULER = 17 + EFFECT = 18 + SIGGEN = 19 + SRC = 20 + ASRC = 21 + ENCODER = 22 + DECODER = 23 + + +Name = Bytes(NAME_LEN) + +HDR = Struct( # snd_soc_tplg_hdr + "magic" / Int32ul, + "abi" / Int32ul, + "version" / Int32ul, + "type" / Int32ul, + "size" / Int32ul, + "vendor_type" / Int32ul, + "payload_size" / Int32ul, + "index" / Int32ul, + "count" / Int32ul, +) +HDR_SIZE = HDR.sizeof() + +PRIVATE = Prefixed(Int32ul, GreedyBytes) # snd_soc_tplg_private + +IO_OPS = Struct( # snd_soc_tplg_io_ops + "get" / Int32ul, + "put" / Int32ul, + "info" / Int32ul, +) + +CTL_TLV = Struct( # snd_soc_tplg_ctl_tlv + "size" / Int32ul, + "type" / Int32ul, + "data" / Array(TLV_SIZE, Int32sl), # union with snd_soc_tplg_tlv_dbscale +) + +CTL_HDR = Struct( # snd_soc_tplg_ctl_hdr + "size" / Int32ul, + "type" / Int32ul, + "name" / Name, + "access" / Int32ul, + "ops" / IO_OPS, + "tlv" / CTL_TLV, +) + +CHANNEL = Struct( # snd_soc_tplg_channel + "size" / Int32ul, + "reg" / Int32ul, + "shift" / Int32ul, + "id" / Int32ul, +) + +MIXER_BODY = Struct( # snd_soc_tplg_mixer_control without hdr + "size" / Int32ul, + "min" / Int32sl, + "max" / Int32sl, + "platform_max" / Int32sl, + "invert" / Int32ul, + "num_channels" / Int32ul, + "channel" / Array(MAX_CHAN, CHANNEL), + "priv" / PRIVATE, +) + +ENUM_BODY = Struct( # snd_soc_tplg_enum_control without hdr + "size" / Int32ul, + "num_channels" / Int32ul, + "channel" / Array(MAX_CHAN, CHANNEL), + "items" / Int32ul, + "mask" / Int32ul, + "count" / Int32ul, + "texts" / Array(NUM_TEXTS, Name), + "values" / Array(NUM_TEXTS * NAME_LEN // 4, Int32ul), + "priv" / PRIVATE, +) + +BYTES_BODY = Struct( # snd_soc_tplg_bytes_control without hdr + "size" / Int32ul, + "max" / Int32ul, + "mask" / Int32ul, + "base" / Int32ul, + "num_regs" / Int32ul, + "ext_ops" / IO_OPS, + "priv" / PRIVATE, +) + +KCONTROL = Struct( + "hdr" / CTL_HDR, + "body" / Switch(this.hdr.type, { + TplgType.MIXER: MIXER_BODY, + TplgType.ENUM: ENUM_BODY, + TplgType.BYTES: BYTES_BODY, + }, default=construct.Error), +) + +STREAM_CAPS = Struct( # snd_soc_tplg_stream_caps + "size" / Int32ul, + "name" / Name, + "formats" / Int64ul, + "rates" / Int32ul, + "rate_min" / Int32ul, + "rate_max" / Int32ul, + "channels_min" / Int32ul, + "channels_max" / Int32ul, + "periods_min" / Int32ul, + "periods_max" / Int32ul, + "period_size_min" / Int32ul, + "period_size_max" / Int32ul, + "buffer_size_min" / Int32ul, + "buffer_size_max" / Int32ul, + "sig_bits" / Int32ul, +) + +STREAM = Struct( # snd_soc_tplg_stream + "size" / Int32ul, + "name" / Name, + "format" / Int64ul, + "rate" / Int32ul, + "period_bytes" / Int32ul, + "buffer_bytes" / Int32ul, + "channels" / Int32ul, +) + +HW_CONFIG = Struct( # snd_soc_tplg_hw_config + "size" / Int32ul, + "id" / Int32ul, + "fmt" / Int32ul, + "clock_gated" / Int8ul, + "invert_bclk" / Int8ul, + "invert_fsync" / Int8ul, + "bclk_provider" / Int8ul, + "fsync_provider" / Int8ul, + "mclk_direction" / Int8ul, + "reserved" / Int16ul, + "mclk_rate" / Int32ul, + "bclk_rate" / Int32ul, + "fsync_rate" / Int32ul, + "tdm_slots" / Int32ul, + "tdm_slot_width" / Int32ul, + "tx_slots" / Int32ul, + "rx_slots" / Int32ul, + "tx_channels" / Int32ul, + "tx_chanmap" / Array(MAX_CHAN, Int32ul), + "rx_channels" / Int32ul, + "rx_chanmap" / Array(MAX_CHAN, Int32ul), +) + +MANIFEST = Struct( # snd_soc_tplg_manifest + "size" / Int32ul, + "control_elems" / Int32ul, + "widget_elems" / Int32ul, + "graph_elems" / Int32ul, + "pcm_elems" / Int32ul, + "dai_link_elems" / Int32ul, + "dai_elems" / Int32ul, + "reserved" / Array(20, Int32ul), + "priv" / PRIVATE, +) + +GRAPH_ELEM = Struct( # snd_soc_tplg_dapm_graph_elem + "sink" / Name, + "control" / Name, + "source" / Name, +) + +WIDGET = Struct( # snd_soc_tplg_dapm_widget + "size" / Int32ul, + "id" / Int32ul, + "name" / Name, + "sname" / Name, + "reg" / Int32sl, + "shift" / Int32ul, + "mask" / Int32ul, + "subseq" / Int32ul, + "invert" / Int32ul, + "ignore_suspend" / Int32ul, + "event_flags" / Int16ul, + "event_type" / Int16ul, + "num_kcontrols" / Int32ul, + "priv" / PRIVATE, +) + +PCM = Struct( # snd_soc_tplg_pcm + "size" / Int32ul, + "pcm_name" / Name, + "dai_name" / Name, + "pcm_id" / Int32ul, + "dai_id" / Int32ul, + "playback" / Int32ul, + "capture" / Int32ul, + "compress" / Int32ul, + "stream" / Array(STREAM_CONFIG_MAX, STREAM), + "num_streams" / Int32ul, + "caps" / Array(2, STREAM_CAPS), + "flag_mask" / Int32ul, + "flags" / Int32ul, + "priv" / PRIVATE, +) + +LINK_CONFIG = Struct( # snd_soc_tplg_link_config + "size" / Int32ul, + "id" / Int32ul, + "name" / Name, + "stream_name" / Name, + "stream" / Array(STREAM_CONFIG_MAX, STREAM), + "num_streams" / Int32ul, + "hw_config" / Array(HW_CONFIG_MAX, HW_CONFIG), + "num_hw_configs" / Int32ul, + "default_hw_config_id" / Int32ul, + "flag_mask" / Int32ul, + "flags" / Int32ul, + "priv" / PRIVATE, +) + +DAI = Struct( # snd_soc_tplg_dai + "size" / Int32ul, + "dai_name" / Name, + "dai_id" / Int32ul, + "playback" / Int32ul, + "capture" / Int32ul, + "caps" / Array(2, STREAM_CAPS), + "flag_mask" / Int32ul, + "flags" / Int32ul, + "priv" / PRIVATE, +) + + +def struct_size(record: Struct) -> int: + """sizeof() of a kernel struct ending in snd_soc_tplg_private. + + The flexible private data is not part of the C struct, but its + 32-bit size field is. + """ + fixed = Struct(*[sc for sc in record.subcons if sc.name != "priv"]) + return fixed.sizeof() + (4 if "priv" in record._subcons else 0) + + +SIZEOF = { + "hdr": HDR_SIZE, + "ctl_hdr": CTL_HDR.sizeof(), + "mixer": CTL_HDR.sizeof() + struct_size(MIXER_BODY), + "enum": CTL_HDR.sizeof() + struct_size(ENUM_BODY), + "bytes": CTL_HDR.sizeof() + struct_size(BYTES_BODY), + "manifest": struct_size(MANIFEST), + "widget": struct_size(WIDGET), + "pcm": struct_size(PCM), + "link": struct_size(LINK_CONFIG), + "dai": struct_size(DAI), + "stream_caps": STREAM_CAPS.sizeof(), + "stream": STREAM.sizeof(), + "hw_config": HW_CONFIG.sizeof(), + "channel": CHANNEL.sizeof(), +} + + +@dataclass +class Issue: + "A structural problem found while walking the binary." + code: str + offset: int + message: str + + +@dataclass +class Element: + "One parsed element of a section, with its absolute file offset." + offset: int + data: construct.Container + kcontrols: list = field(default_factory=list) # widgets only: [Element] + + +@dataclass +class Section: + "One snd_soc_tplg_hdr block and its parsed elements." + offset: int + hdr: construct.Container + elements: list = field(default_factory=list) # [Element] + + @property + def type_name(self) -> str: + try: + return TplgType(self.hdr.type).name + except ValueError: + return f"type {self.hdr.type}" + + +@dataclass +class RawTopology: + "Result of walking a topology binary." + size: int + sections: list = field(default_factory=list) # [Section] + issues: list = field(default_factory=list) # [Issue] + + +ELEMENT_RECORD = { + TplgType.MIXER: KCONTROL, + TplgType.ENUM: KCONTROL, + TplgType.BYTES: KCONTROL, + TplgType.DAPM_GRAPH: GRAPH_ELEM, + TplgType.DAPM_WIDGET: WIDGET, + TplgType.PCM: PCM, + TplgType.DAI_LINK: LINK_CONFIG, + TplgType.BACKEND_LINK: LINK_CONFIG, + TplgType.MANIFEST: MANIFEST, + TplgType.DAI: DAI, +} + + +def _parse_elements(raw: RawTopology, sec: Section, payload: bytes): + "Parse hdr.count elements of a known section type from its payload." + base = sec.offset + HDR_SIZE + record = ELEMENT_RECORD[sec.hdr.type] + count = 1 if sec.hdr.type == TplgType.MANIFEST else sec.hdr.count + stream = io.BytesIO(payload) + + for i in range(count): + pos = stream.tell() + try: + elem = Element(base + pos, record.parse_stream(stream)) + if sec.hdr.type == TplgType.DAPM_WIDGET: + for _ in range(elem.data.num_kcontrols): + kpos = stream.tell() + elem.kcontrols.append(Element(base + kpos, KCONTROL.parse_stream(stream))) + except construct.ConstructError as e: + raw.issues.append(Issue( + "elem-truncated", base + pos, + f"{sec.type_name} element {i}/{count} does not fit in the " + f"section payload or is malformed: {str(e).splitlines()[0]}")) + return + sec.elements.append(elem) + + left = len(payload) - stream.tell() + if left: + raw.issues.append(Issue( + "payload-trailing", base + stream.tell(), + f"{sec.type_name} section has {left} unparsed bytes after {count} elements")) + + +def parse_bytes(data: bytes) -> RawTopology: + "Walk all section headers like soc_tplg_process_headers() does." + raw = RawTopology(len(data)) + pos = 0 + + while pos < len(data): + if len(data) - pos < HDR_SIZE: + raw.issues.append(Issue("hdr-truncated", pos, + f"{len(data) - pos} trailing bytes, too short for a header")) + break + + hdr = HDR.parse(data[pos:pos + HDR_SIZE]) + sec = Section(pos, hdr) + + # soc_tplg_valid_header() + fatal = False + if hdr.magic == TPLG_MAGIC_BE: + raw.issues.append(Issue("hdr-magic", pos, "big-endian topology, not supported")) + fatal = True + elif hdr.magic != TPLG_MAGIC: + raw.issues.append(Issue("hdr-magic", pos, f"bad magic 0x{hdr.magic:08x}")) + fatal = True + if hdr.size != HDR_SIZE: + raw.issues.append(Issue("hdr-size", pos, + f"header size {hdr.size}, expected {HDR_SIZE}")) + fatal = True + if fatal: + break + + if not TPLG_ABI_VERSION_MIN <= hdr.abi <= TPLG_ABI_VERSION: + raw.issues.append(Issue("hdr-abi", pos, + f"ABI version {hdr.abi}, kernel supports {TPLG_ABI_VERSION}")) + if hdr.payload_size == 0: + raw.issues.append(Issue("hdr-payload", pos, + f"{sec.type_name} section has empty payload")) + + end = pos + HDR_SIZE + hdr.payload_size + if end > len(data): + raw.issues.append(Issue("hdr-payload", pos, + f"{sec.type_name} payload of {hdr.payload_size} bytes " + f"extends past end of file")) + break + + raw.sections.append(sec) + if hdr.type in ELEMENT_RECORD.keys(): + _parse_elements(raw, sec, data[pos + HDR_SIZE:end]) + pos = end + + return raw + + +def parse_file(path) -> RawTopology: + with open(path, "rb") as f: + return parse_bytes(f.read()) + + +def decode_name(raw: bytes) -> str: + "Decode a fixed size, NUL padded name field." + return raw.split(b"\0", 1)[0].decode("ascii", errors="replace") + + +def name_terminated(raw: bytes) -> bool: + "Mirror strnlen(name, SNDRV_CTL_ELEM_ID_NAME_MAXLEN) < SNDRV_CTL_ELEM_ID_NAME_MAXLEN." + return b"\0" in raw diff --git a/validator/tplgparse/kernel_engine.py b/validator/tplgparse/kernel_engine.py new file mode 100644 index 0000000..525d01e --- /dev/null +++ b/validator/tplgparse/kernel_engine.py @@ -0,0 +1,385 @@ +# SPDX-License-Identifier: BSD-3-Clause +# +# Copyright(c) 2026 Intel Corporation. All rights reserved. + +"""Emulation of the SOF driver vendor tuple engine. + +Mirrors sof_parse_token_sets(), sof_copy_tuples(), sof_update_ipc_object(), +sof_get_token_value(), sof_widget_parse_tokens() and the token parsing part +of sof_widget_ready() in Linux sound/soc/sof/topology.c, driven by the +token tables generated into schema/kernel_tokens.py. + +The point of emulating instead of decoding tuples directly is that the +kernel does not always read tuples the way the topology meant them: +sof_copy_tuples() picks the element layout from the type of the token it +is looking for rather than from the vendor array type, multiple token +sets are filled by occurrence count, and parsing stops once enough tokens +were found. Every value read is recorded with the private data offset it +came from so that checks can compare the kernel view to the intended one. +""" + +import struct +from collections import Counter +from dataclasses import dataclass, field +from typing import Optional + +from schema import kernel_tokens as kt + +from .model import ARRAY_HDR_SIZE, ELEM_SIZE, TupleType + +STRING_ELEM = ELEM_SIZE[TupleType.STRING] +VALUE_ELEM = ELEM_SIZE[TupleType.WORD] +UUID_ELEM = ELEM_SIZE[TupleType.UUID] +NAME_LEN = STRING_ELEM - 4 + +WORD_TYPES = ("WORD", "SHORT", "BYTE", "BOOL") + +SOF_WIDGET_MAX_NUM_PINS = 8 # sound/soc/sof/sof-audio.h + +TKN_NUM_INPUT_PINS = 411 +TKN_NUM_OUTPUT_PINS = 412 +TKN_NUM_INPUT_AUDIO_FORMATS = 415 +TKN_NUM_OUTPUT_AUDIO_FORMATS = 416 + + +class KernelError(Exception): + "The kernel would fail topology load at this point." + + def __init__(self, message, kernel_ref): + super().__init__(message) + self.kernel_ref = kernel_ref + + +@dataclass +class Read: + "One value the kernel picked up from private data." + token: int + kind: str # 'string', 'value' or 'uuid': the element layout the kernel used + value: object + offset: int # element offset within the private data + oob: bool = False # element lies (partly) outside its vendor array + + +@dataclass +class Trace: + "Everything the emulation observed while parsing one private data blob." + reads: list = field(default_factory=list) # [Read], values actually used + oob_reads: list = field(default_factory=list) # [(offset, length, priv_size)] + + +def _u32(data, off): + return struct.unpack_from(" arr_off + asize + if off + esize > len(data): + trace.oob_reads.append((off, esize, len(data))) + return None + token = _u32(data, off) + if kind == "string": + value = _string(data, off + 4) + elif kind == "uuid": + value = bytes(data[off + 4:off + 20]) + else: + value = _u32(data, off + 4) + return token, value, off, oob + + +def parse_token_sets(data: bytes, tokens, instances: int, trace: Trace, + ref="sof_parse_token_sets") -> list: + """sof_parse_token_sets(): returns a list of sets, each {token: value}. + + tokens is a list of (token, type, getter) from the generated schema. + """ + count = len(tokens) + sets = [{}] + found = total = 0 + array_size = len(data) + pos = 0 + + while array_size > 0 and total < count * instances: + if array_size < ARRAY_HDR_SIZE: + raise KernelError("vendor array header does not fit in private data", ref) + asize, atype, num = struct.unpack_from("= count: + sets.append({}) + total += found + found = 0 + + if not sets[-1]: + sets.pop() + return sets + + +def parse_tokens(data: bytes, tokens, trace: Trace, ref="sof_parse_tokens") -> dict: + "sof_parse_tokens(): object_size is 0, so every set lands on the same object." + merged = {} + for s in parse_token_sets(data, tokens, 1, trace, ref): + merged.update(s) + return merged + + +@dataclass +class Tuple: + "struct snd_sof_tuple" + token: int + value: object + + +def copy_tuples(data: bytes, tokens, instances: int, tuples: list, tuples_size: int, + trace: Trace, ref="sof_copy_tuples"): + """sof_copy_tuples(): append matching tuples to the tuples list. + + Element layout is chosen by the kernel token type, not by the vendor + array type, exactly as the kernel does it. + """ + if len(tuples) >= tuples_size: + raise KernelError("no space in tuples array for new tokens", ref) + + num_tokens = len(tokens) + found = 0 + array_size = len(data) + pos = 0 + + while array_size > 0 and found < num_tokens * instances: + if array_size < ARRAY_HDR_SIZE: + # the kernel reads the header anyway; we cannot follow it + trace.oob_reads.append((pos, ARRAY_HDR_SIZE, len(data))) + return + asize, _atype, num = struct.unpack_from(" readable: + trace.oob_reads.append((pos + ARRAY_HDR_SIZE + readable * VALUE_ELEM, + (num - readable) * VALUE_ELEM, len(data))) + for i in range(min(num, readable)): + for tok, typ, _getter in tokens: + if typ not in WORD_TYPES and typ != "STRING": + continue + kind = "string" if typ == "STRING" else "value" + e = _elem(data, pos, asize, kind, i, trace) + if e is None: + continue + token, value, off, oob = e + if token != tok: + continue + tuples.append(Tuple(tok, value)) + trace.reads.append(Read(tok, kind, value, off, oob)) + found += 1 + if len(tuples) == tuples_size: + return + if found == num_tokens * instances: + return + + if asize == 0: + # the kernel would loop forever on the same array + raise KernelError("zero sized vendor array", ref) + pos += asize + + +def get_token_value(token: int, tuples: list) -> int: + "sof_get_token_value(), returns None where the kernel returns -EINVAL." + for t in tuples: + if t.token == token: + return t.value + return None + + +def update_ipc_object(tuples: list, tokens, instances: int) -> list: + """sof_update_ipc_object(): returns sets of {token: value}. + + The n-th occurrence of a token lands in set n, regardless of which + format block it came from in the topology. instances comes from the + topology, so only the sets that can receive a value are returned: + at most `instances`, and no more than the most frequent token occurs. + The kernel leaves the remaining sets zeroed. + """ + occurrences = Counter(t.token for t in tuples) + most = max((occurrences[tok] for tok, _typ, _g in tokens), default=0) + sets = [{} for _ in range(max(min(instances, most), 1))] + for tok, typ, _getter in tokens: + idx = 0 + matched = 0 + for t in tuples: + if t.token != tok: + continue + value = t.value + if typ in ("SHORT", "BOOL") and isinstance(value, int): + value &= 0xffff + if idx < len(sets): + sets[idx].setdefault(tok, value) + matched += 1 + if not matched % max(instances, 1): + break + idx += 1 + return sets + + +def group(name: str): + "Token table of an IPC4 token group, or [] if IPC4 does not define it." + entry = kt.IPC4_TOKEN_LIST.get(name) + return entry[1] if entry else [] + + +@dataclass +class KernelWidget: + "What sof_widget_ready() and sof_widget_parse_tokens() extract." + num_input_pins: int = 0 + num_output_pins: int = 0 + input_pin_binding: Optional[list] = None + output_pin_binding: Optional[list] = None + no_wname_in_kcontrol_name: bool = False + comp_ext: dict = field(default_factory=dict) # token -> value + tuples: list = field(default_factory=list) # [Tuple] + trace: Trace = field(default_factory=Trace) + error: Optional[KernelError] = None + token_groups: list = field(default_factory=list) + + def value(self, token: int, default=None): + v = get_token_value(token, self.tuples) + return default if v is None else v + + def update(self, group_name: str, instances: int = 1) -> list: + return update_ipc_object(self.tuples, group(group_name), instances) + + def audio_formats(self): + """sof_ipc4_get_audio_fmt(): (num_in, num_out, in_sets, out_sets). + + num_in and num_out are the declared counts. The format lists may be + shorter when the topology does not define that many formats. + """ + num = self.update("SOF_AUDIO_FMT_NUM_TOKENS")[0] + n_in = num.get(TKN_NUM_INPUT_AUDIO_FORMATS, 0) + n_out = num.get(TKN_NUM_OUTPUT_AUDIO_FORMATS, 0) + ins = self.update("SOF_IN_AUDIO_FORMAT_TOKENS", n_in)[:n_in] if n_in else [] + outs = self.update("SOF_OUT_AUDIO_FORMAT_TOKENS", n_out)[:n_out] if n_out else [] + return n_in, n_out, ins, outs + + +def widget_ready(widget) -> KernelWidget: + """Token parsing done by sof_widget_ready() for an IPC4 topology. + + Stops at the first point where the kernel would return an error and + records it in KernelWidget.error. + """ + kw = KernelWidget() + data = widget.priv.data + gt = kt.GENERIC_TABLES + try: + d = parse_tokens(data, gt["dapm_widget_tokens"], kw.trace) + kw.no_wname_in_kcontrol_name = bool(d) + + pins = parse_tokens(data, gt["comp_pin_tokens"], kw.trace) + kw.num_input_pins = pins.get(TKN_NUM_INPUT_PINS, 0) + kw.num_output_pins = pins.get(TKN_NUM_OUTPUT_PINS, 0) + if kw.num_input_pins > SOF_WIDGET_MAX_NUM_PINS or \ + kw.num_output_pins > SOF_WIDGET_MAX_NUM_PINS: + raise KernelError(f"invalid pins: input {kw.num_input_pins}, " + f"output {kw.num_output_pins}, max {SOF_WIDGET_MAX_NUM_PINS}", + "sof_widget_ready") + + for attr, num, table in ( + ("input_pin_binding", kw.num_input_pins, "comp_input_pin_binding_tokens"), + ("output_pin_binding", kw.num_output_pins, "comp_output_pin_binding_tokens")): + if num > 1: + sets = parse_token_sets(data, gt[table], num, kw.trace, "sof_parse_pin_binding") + binding = [None] * num + for i, s in enumerate(sets[:num]): + binding[i] = next(iter(s.values()), None) + if binding[0] is not None: + setattr(kw, attr, binding) + + _setup, token_list = kt.IPC4_WIDGET_TOKEN_LISTS.get(widget.type_name, (None, [])) + kw.token_groups = list(token_list) + widget_parse_tokens(data, token_list, kw) + except KernelError as e: + kw.error = e + return kw + + +def widget_parse_tokens(data: bytes, token_list, kw: KernelWidget): + "sof_widget_parse_tokens()" + ref = "sof_widget_parse_tokens" + num_tuples = sum(len(group(g)) for g in token_list) + + for g in token_list: + num_sets = 1 + if g == "SOF_COMP_EXT_TOKENS": + kw.comp_ext = parse_tokens(data, group(g), kw.trace, ref) + continue + if g == "SOF_IN_AUDIO_FORMAT_TOKENS": + num_sets = get_token_value(TKN_NUM_INPUT_AUDIO_FORMATS, kw.tuples) + if num_sets is None: + raise KernelError("invalid input audio format count", ref) + elif g == "SOF_OUT_AUDIO_FORMAT_TOKENS": + num_sets = get_token_value(TKN_NUM_OUTPUT_AUDIO_FORMATS, kw.tuples) + if num_sets is None: + raise KernelError("invalid output audio format count", ref) + + if num_sets > 1: + num_tuples += len(group(g)) * (num_sets - 1) + + if not group(g): + continue # IPC4 defines no tokens for this group + copy_tuples(data, group(g), num_sets, kw.tuples, num_tuples, kw.trace, ref) + + +def private_tokens(priv, table_name: str) -> dict: + "sof_parse_tokens() with one of the generic tables, for PCM/link/control data." + trace = Trace() + try: + return parse_tokens(priv.data, kt.GENERIC_TABLES[table_name], trace) + except KernelError: + return {} diff --git a/validator/tplgparse/model.py b/validator/tplgparse/model.py new file mode 100644 index 0000000..d072c65 --- /dev/null +++ b/validator/tplgparse/model.py @@ -0,0 +1,297 @@ +# SPDX-License-Identifier: BSD-3-Clause +# +# Copyright(c) 2026 Intel Corporation. All rights reserved. + +"""Typed view of a parsed topology binary. + +Vendor tuples are decoded here by the type stored in each +snd_soc_tplg_vendor_array, i.e. the way the topology author meant them. +How the kernel actually reads them is emulated in kernel_engine.py. +""" + +import struct +from dataclasses import dataclass, field +from typing import Optional + +from . import binary +from .binary import DapmType, TplgType, TupleType, decode_name + +ARRAY_HDR_SIZE = 12 # sizeof(struct snd_soc_tplg_vendor_array) +ELEM_SIZE = { + TupleType.UUID: 4 + 16, # snd_soc_tplg_vendor_uuid_elem + TupleType.STRING: 4 + binary.NAME_LEN, # snd_soc_tplg_vendor_string_elem + TupleType.BOOL: 8, # snd_soc_tplg_vendor_value_elem + TupleType.BYTE: 8, + TupleType.WORD: 8, + TupleType.SHORT: 8, +} + + +@dataclass +class VendorTuple: + token: int + type: TupleType + value: object # int, str or 16 bytes for UUID + array: int # index of the vendor array in the private data + offset: int # offset of the element within the private data + + +@dataclass +class VendorArray: + offset: int # within the private data + size: int + type: int + num_elems: int + tuples: list = field(default_factory=list) + + +@dataclass +class PrivIssue: + offset: int # within the private data + message: str + + +@dataclass +class Private: + "snd_soc_tplg_private data interpreted as consecutive vendor arrays." + data: bytes + arrays: list = field(default_factory=list) + issues: list = field(default_factory=list) + + @property + def tuples(self): + return [t for a in self.arrays for t in a.tuples] + + def values(self, token: int) -> list: + return [t.value for t in self.tuples if t.token == token] + + def value(self, token: int, default=None): + vals = self.values(token) + return vals[0] if vals else default + + +def decode_private(data: bytes) -> Private: + "Walk vendor arrays by their declared size and type." + priv = Private(data) + pos = 0 + while pos < len(data): + if len(data) - pos < ARRAY_HDR_SIZE: + priv.issues.append(PrivIssue(pos, f"{len(data) - pos} trailing bytes are too short " + f"for a vendor array header")) + break + size, atype, num = struct.unpack_from(" len(data): + priv.issues.append(PrivIssue(pos, f"vendor array size {size} is invalid " + f"({len(data) - pos} bytes left)")) + break + try: + ttype = TupleType(atype) + except ValueError: + priv.issues.append(PrivIssue(pos, f"unknown vendor array type {atype}")) + pos += size + continue + esize = ELEM_SIZE[ttype] + if ARRAY_HDR_SIZE + num * esize != size: + priv.issues.append(PrivIssue( + pos, f"{ttype.name} vendor array size {size} does not match " + f"{num} elements of {esize} bytes")) + num = min(num, (size - ARRAY_HDR_SIZE) // esize) + for i in range(num): + epos = pos + ARRAY_HDR_SIZE + i * esize + token = struct.unpack_from(" str: + "Format like the kernel's %pUL." + a, b, c = struct.unpack_from(" str: + return f"kcontrol '{self.name}'" + + +@dataclass +class Widget: + index: int # section header index, the kernel's swidget->pipeline_id + id: int # SND_SOC_TPLG_DAPM_* + name: str + sname: str + raw: object + priv: Private + offset: int + kcontrols: list = field(default_factory=list) # [Control] + + @property + def type_name(self) -> str: + "Kernel snd_soc_dapm_* name, e.g. 'aif_in'." + try: + return DapmType(self.id).name.lower() + except ValueError: + return f"type{self.id}" + + @property + def label(self) -> str: + return f"widget '{self.name}'" + + +@dataclass +class Route: + index: int + sink: str + control: str + source: str + raw: object + offset: int + + @property + def label(self) -> str: + ctl = f" via '{self.control}'" if self.control else "" + return f"route '{self.source}' -> '{self.sink}'{ctl}" + + +@dataclass +class Pcm: + name: str + dai_name: str + raw: object + priv: Private + offset: int + + @property + def label(self) -> str: + return f"PCM '{self.name}' (id {self.raw.pcm_id})" + + +@dataclass +class Link: + name: str + stream_name: str + raw: object + priv: Private + offset: int + section_type: TplgType = TplgType.BACKEND_LINK + + @property + def hw_configs(self) -> list: + return list(self.raw.hw_config[:self.raw.num_hw_configs]) + + @property + def label(self) -> str: + return f"link '{self.name}' (id {self.raw.id})" + + +@dataclass +class Dai: + name: str + raw: object + priv: Private + offset: int + + @property + def label(self) -> str: + return f"DAI '{self.name}'" + + +@dataclass +class Topology: + path: str + raw: binary.RawTopology + manifest: Optional[object] = None + widgets: list = field(default_factory=list) + routes: list = field(default_factory=list) + controls: list = field(default_factory=list) # standalone and widget kcontrols + pcms: list = field(default_factory=list) + links: list = field(default_factory=list) + dais: list = field(default_factory=list) + # widgets and routes of topologies loaded before this one into the + # same component, e.g. function topologies under a feature topology + base_widgets: list = field(default_factory=list) + base_routes: list = field(default_factory=list) + + def widget(self, name: str) -> Optional[Widget]: + "Look up a widget by name, including widgets of base topologies." + return self._by_name.get(name) + + def __post_init__(self): + self._by_name = {} + + def index(self): + self._by_name = {} + for w in self.widgets + self.base_widgets: + self._by_name.setdefault(w.name, w) + + def add_base(self, base: "Topology"): + "Make the objects of a topology loaded earlier visible to this one." + self.base_widgets += base.widgets + base.base_widgets + self.base_routes += base.routes + base.base_routes + self.index() + + +def _control(elem: binary.Element, widget=None) -> Control: + hdr, body = elem.data.hdr, elem.data.body + return Control(TplgType(hdr.type), decode_name(hdr.name), hdr, body, + decode_private(body.priv), elem.offset, widget) + + +def build(raw: binary.RawTopology, path: str = "") -> Topology: + tplg = Topology(path, raw) + for sec in raw.sections: + stype = sec.hdr.type + for elem in sec.elements: + d = elem.data + if stype in (TplgType.MIXER, TplgType.ENUM, TplgType.BYTES): + tplg.controls.append(_control(elem)) + elif stype == TplgType.DAPM_WIDGET: + w = Widget(sec.hdr.index, d.id, decode_name(d.name), decode_name(d.sname), d, + decode_private(d.priv), elem.offset) + w.kcontrols = [_control(k, w) for k in elem.kcontrols] + tplg.controls.extend(w.kcontrols) + tplg.widgets.append(w) + elif stype == TplgType.DAPM_GRAPH: + tplg.routes.append(Route(sec.hdr.index, decode_name(d.sink), + decode_name(d.control), decode_name(d.source), d, + elem.offset)) + elif stype == TplgType.PCM: + tplg.pcms.append(Pcm(decode_name(d.pcm_name), decode_name(d.dai_name), d, + decode_private(d.priv), elem.offset)) + elif stype in (TplgType.DAI_LINK, TplgType.BACKEND_LINK): + tplg.links.append(Link(decode_name(d.name), decode_name(d.stream_name), d, + decode_private(d.priv), elem.offset, TplgType(stype))) + elif stype == TplgType.DAI: + tplg.dais.append(Dai(decode_name(d.dai_name), d, decode_private(d.priv), + elem.offset)) + elif stype == TplgType.MANIFEST: + tplg.manifest = elem + tplg.index() + return tplg + + +def load(path) -> Topology: + return build(binary.parse_file(path), str(path))