diff --git a/case-lib/compress.sh b/case-lib/compress.sh new file mode 100644 index 00000000..79fee534 --- /dev/null +++ b/case-lib/compress.sh @@ -0,0 +1,530 @@ +#!/bin/bash +# SPDX-License-Identifier: BSD-3-Clause +# Shared helpers for SOF compressed audio (FFmpeg decoder/encoder) tests. + +export COMPR_DECODE_CODECS_ALL="flac mp3 aac opus alac sbc msbc g722 aptx" +export COMPR_ENCODE_CODECS_ALL="mp3 aac flac alac sbc msbc g722 aptx" + +COMPR_TOOL="${COMPR_TOOL:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/tools/sof-compr-tool.py}" + +# Check whether an external CLI helper is available in PATH or executable +func_compr_has_bin() +{ + local bin="$1" + command -v "$bin" >/dev/null 2>&1 || [ -x "$bin" ] +} + +# Print default test parameters for a codec: +# " " +func_compr_codec_defaults() +{ + local codec="${1,,}" + case "$codec" in + flac) + echo "48000 2 0 S16_LE FLAC 0x0A" + ;; + mp3) + echo "48000 2 192000 S16_LE MP3 0x02" + ;; + aac) + echo "48000 2 192000 S16_LE AAC 0x06" + ;; + opus|opus_raw) + echo "48000 2 128000 S16_LE NONE 0x11" + ;; + alac) + echo "48000 2 0 S16_LE NONE 0x0F" + ;; + sbc) + echo "48000 2 328000 S16_LE NONE 0x12" + ;; + msbc) + echo "16000 1 64000 S16_LE NONE 0x12" + ;; + g722) + echo "16000 1 64000 S16_LE NONE 0x13" + ;; + aptx) + echo "48000 2 384000 S16_LE NONE 0x14" + ;; + *) + dloge "Unknown compressed codec: $codec" + return 1 + ;; + esac +} + +# Parse hardware card and compress device id from pipeline device or /dev/snd node +# Sets global variables COMPR_CARD and COMPR_DEV +func_compr_parse_dev() +{ + local dev_str="$1" + if [[ "$dev_str" =~ comprC([0-9]+)D([0-9]+) ]]; then + COMPR_CARD="${BASH_REMATCH[1]}" + COMPR_DEV="${BASH_REMATCH[2]}" + return 0 + fi + if [[ "$dev_str" =~ ([0-9]+),([0-9]+) ]]; then + COMPR_CARD="${BASH_REMATCH[1]}" + COMPR_DEV="${BASH_REMATCH[2]}" + return 0 + fi + return 1 +} + +# Query whether a compress device advertises support for +# Returns: 0=supported, 1=unsupported codec (rc=2 from tool), 2=device/ioctl error +func_compr_dev_supports_codec() +{ + local snd_dev="$1" + local direction="$2" + local codec="$3" + local caps_out + local rc=0 + + caps_out=$(python3 "$COMPR_TOOL" caps -D "$snd_dev" --direction "$direction" \ + --has-codec "$codec" 2>&1) || rc=$? + if [ "$rc" -eq 0 ]; then + return 0 + fi + if [ "$rc" -eq 2 ]; then + return 1 + fi + dloge "Compress capability query failed on $snd_dev ($direction, codec=$codec, rc=$rc): $caps_out" + return 2 +} + +# Check if cplay supports the given codec +func_compr_cplay_supports() +{ + local codec="${1,,}" + func_compr_has_bin cplay || return 1 + case "$codec" in + mp3|aac) + return 0 + ;; + *) + return 1 + ;; + esac +} + +# Check if crecord supports the given codec +func_compr_crecord_supports() +{ + local codec="${1,,}" + func_compr_has_bin crecord || return 1 + case "$codec" in + flac) + # Upstream tinycompress crecord sets codec.format to S16_LE (0x2); + # among compressed encoders only ffmpeg-enc-flac/alac accept 0x2, + # and crecord only exposes FLAC in its codec name table. + return 0 + ;; + *) + return 1 + ;; + esac +} + +# Generate a compressed sine-wave test vector using ffmpeg +func_compr_gen_vector() +{ + local codec="${1,,}" + local out_file="$2" + local duration="${3:-3}" + local freq="${4:-997}" + + func_compr_has_bin ffmpeg || { + dloge "ffmpeg is required to generate compressed test vectors" + return 1 + } + + local defaults + defaults=$(func_compr_codec_defaults "$codec") || return 1 + local rate ch bitrate + read -r rate ch bitrate _ _ _ <<< "$defaults" + + local src_spec="sine=frequency=${freq}:sample_rate=${rate}:duration=${duration}" + local -a cmd=(ffmpeg -y -v error -f lavfi -i "$src_spec" -ac "$ch" -ar "$rate") + + case "$codec" in + flac) + cmd+=(-c:a flac -f flac "$out_file") + ;; + mp3) + cmd+=(-c:a libmp3lame -b:a "$bitrate" -f mp3 "$out_file") + ;; + aac) + cmd+=(-c:a aac -b:a "$bitrate" -f adts "$out_file") + ;; + opus|opus_raw) + cmd+=(-c:a libopus -b:a "$bitrate" -f opus "$out_file") + ;; + alac) + cmd+=(-c:a alac -f mp4 "$out_file") + ;; + sbc) + cmd+=(-c:a sbc -b:a "$bitrate" -f sbc "$out_file") + ;; + msbc) + cmd+=(-c:a sbc -msbc 1 -f sbc "$out_file") + ;; + g722) + cmd+=(-c:a g722 -f g722 "$out_file") + ;; + aptx) + cmd+=(-c:a aptx -f aptx "$out_file") + ;; + *) + dloge "Unsupported codec for vector generation: $codec" + return 1 + ;; + esac + + "${cmd[@]}" +} + +# Validate encoded compressed stream magic/sync header and decode to WAV via ffmpeg +func_compr_verify_encoded_file() +{ + local codec="${1,,}" + local in_file="$2" + local out_wav="${3:-}" + local min_bytes="${4:-256}" + + [ -s "$in_file" ] || { + dloge "Encoded output file is missing or empty: $in_file" + return 1 + } + + local fsize + fsize=$(stat -c%s "$in_file") + if [ "$fsize" -lt "$min_bytes" ]; then + dloge "Encoded output too small ($fsize B < $min_bytes B): $in_file" + return 1 + fi + + # Check container / bitstream header sync + python3 - "$codec" "$in_file" <<'EOF' || return 1 +import sys + +codec = sys.argv[1].lower() +path = sys.argv[2] +with open(path, "rb") as f: + head = f.read(64) + +if len(head) < 4: + raise SystemExit(f"{codec}: file header shorter than 4 bytes") + +if codec == "flac": + if not head.startswith(b"fLaC"): + raise SystemExit(f"flac: expected b'fLaC' magic, got {head[:8]!r}") +elif codec == "alac": + if b"alac" not in head[:40]: + raise SystemExit(f"alac: expected 'alac' atom in cookie, got {head[:40]!r}") +elif codec == "aac": + if not (head[0] == 0xFF and (head[1] & 0xF0) == 0xF0): + raise SystemExit(f"aac: expected ADTS sync 0xFFFx, got {head[:4].hex()}") +elif codec == "mp3": + is_sync = head[0] == 0xFF and (head[1] & 0xE0) == 0xE0 + if not is_sync and not head.startswith(b"ID3"): + raise SystemExit(f"mp3: expected frame sync/ID3, got {head[:4].hex()}") +elif codec == "sbc": + if head[0] != 0x9C: + raise SystemExit(f"sbc: expected syncword 0x9c, got 0x{head[0]:02x}") +elif codec == "msbc": + if head[0] != 0xAD: + raise SystemExit(f"msbc: expected syncword 0xad, got 0x{head[0]:02x}") +elif codec in ("g722", "aptx", "opus", "opus_raw"): + if all(b == 0 for b in head[:32]): + raise SystemExit(f"{codec}: output begins with 32 zero bytes") +EOF + + func_compr_has_bin ffmpeg || { + dlogw "ffmpeg not found; skipping host decode verification for $codec" + return 0 + } + + local defaults + defaults=$(func_compr_codec_defaults "$codec") || return 1 + local rate ch + read -r rate ch _ _ _ _ <<< "$defaults" + + local tmp_wav="${out_wav:-${in_file}.decoded.wav}" + local -a dec_cmd=(ffmpeg -y -v error) + local dec_input="$in_file" + + case "$codec" in + flac) + dec_cmd+=(-f flac -i "$dec_input") + ;; + mp3) + dec_cmd+=(-f mp3 -i "$dec_input") + ;; + aac) + dec_cmd+=(-f aac -i "$dec_input") + ;; + sbc|msbc) + dec_cmd+=(-f sbc -i "$dec_input") + ;; + g722) + dec_cmd+=(-f g722 -i "$dec_input") + ;; + aptx) + dec_cmd+=(-f aptx -ar "$rate" -ac "$ch" -i "$dec_input") + ;; + alac) + # ffmpeg_enc-alac writes a 36-byte QuickTime 'alac' atom + raw + # variable-size frames; FFmpeg's CAF demuxer requires a 'pakt' + # packet-size table to decode CAF-wrapped variable-size ALAC, so + # only invoke ffmpeg -f caf when the capture already starts with + # a full 'caff' container, and validate the ALAC cookie + payload + # directly for raw SOF ALAC captures. + local caf_file="${in_file}.caf" + local alac_mode + alac_mode=$(python3 - "$in_file" "$caf_file" "$rate" "$ch" <<'EOF' +import struct, sys + +in_path, out_path, rate, ch = sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4]) +with open(in_path, "rb") as f: + raw = f.read() + +if raw[:4] == b"caff": + with open(out_path, "wb") as out: + out.write(raw) + print("caf") + sys.exit(0) + +# Expect 36-byte ALAC magic cookie (atom size + 'alac' + version/flags + 24B config) +if len(raw) < 40 or raw[4:8] != b"alac": + raise SystemExit(f"Unexpected ALAC stream prefix: {raw[:16].hex()}") + +cookie_size = struct.unpack(">I", raw[:4])[0] +if cookie_size != 36: + raise SystemExit(f"Unexpected ALAC atom size {cookie_size}, expected 36") + +cookie = raw[:36] +payload = raw[36:] +frame_len = struct.unpack(">I", cookie[12:16])[0] +bit_depth = cookie[17] +cookie_ch = cookie[21] +cookie_rate = struct.unpack(">I", cookie[32:36])[0] +if frame_len == 0 or bit_depth not in (16, 24, 32): + raise SystemExit(f"Invalid ALAC config frame_len={frame_len} bit_depth={bit_depth}") +if cookie_ch != ch or cookie_rate != rate: + raise SystemExit(f"ALAC header mismatch: ch={cookie_ch} rate={cookie_rate} vs {ch}/{rate}") +if len(payload) < 32 or all(b == 0 for b in payload[:32]): + raise SystemExit(f"Invalid ALAC payload (len={len(payload)})") + +print(f"raw {len(payload)} {frame_len} {bit_depth}") +EOF +) || return 1 + if [ "${alac_mode%% *}" != "caf" ]; then + dlogi "Verified alac magic cookie + raw frames ($fsize B, ${alac_mode#raw })" + [ -n "$out_wav" ] && rm -f "$out_wav" + return 2 + fi + dec_input="$caf_file" + dec_cmd+=(-f caf -i "$dec_input") + ;; + *) + dec_cmd+=(-i "$dec_input") + ;; + esac + + dec_cmd+=("$tmp_wav") + if ! "${dec_cmd[@]}"; then + dloge "ffmpeg failed to decode $codec output ($in_file)" + return 1 + fi + + [ -s "$tmp_wav" ] || { + dloge "Decoded WAV for $codec is empty: $tmp_wav" + return 1 + } + + local wav_dur + wav_dur=$(python3 - "$tmp_wav" <<'EOF' +import sys, wave +with wave.open(sys.argv[1], "rb") as w: + frames = w.getnframes() + rate = w.getframerate() + print(f"{frames / float(rate):.3f}" if rate else "0") +EOF +) + dlogi "Verified $codec encoded stream ($fsize B -> decoded WAV ${wav_dur}s)" + if [ -z "$out_wav" ]; then + rm -f "$tmp_wav" + fi + return 0 +} + +# Verify a WAV file contains an expected tone frequency (used in loopback checks) +func_compr_verify_wav_tone() +{ + local wav_file="$1" + local expected_freq="$2" + local tol_hz="${3:-60}" + local min_rms="${4:-0.005}" + + python3 - "$wav_file" "$expected_freq" "$tol_hz" "$min_rms" <<'EOF' +import math, struct, sys, wave + +path = sys.argv[1] +target_hz = float(sys.argv[2]) +tol_hz = float(sys.argv[3]) +min_rms = float(sys.argv[4]) + +with wave.open(path, "rb") as w: + ch = w.getnchannels() + width = w.getsampwidth() + rate = w.getframerate() + nframes = w.getnframes() + raw = w.readframes(nframes) + +if nframes == 0: + raise SystemExit("WAV has 0 frames") + +fmt_char = {2: "h", 4: "i"}.get(width) +if not fmt_char: + raise SystemExit(f"Unsupported WAV sample width: {width}") + +scale = float(1 << (8 * width - 1)) +samples = struct.unpack(f"<{nframes * ch}{fmt_char}", raw) +mono = [samples[i] / scale for i in range(0, len(samples), ch)] +rms = math.sqrt(sum(s * s for s in mono) / len(mono)) +if rms < min_rms: + raise SystemExit(f"WAV RMS {rms:.5f} below minimum threshold {min_rms}") + +try: + import numpy as np + win = np.array(mono[: min(len(mono), rate * 2)], dtype=np.float64) + win -= np.mean(win) + spec = np.abs(np.fft.rfft(win * np.hanning(len(win)))) + freqs = np.fft.rfftfreq(len(win), 1.0 / rate) + peak_hz = float(freqs[int(np.argmax(spec))]) + if abs(peak_hz - target_hz) > tol_hz: + raise SystemExit(f"Peak freq {peak_hz:.1f}Hz != expected {target_hz:.1f}Hz (+/-{tol_hz})") + print(f"Tone verified: peak={peak_hz:.1f}Hz rms={rms:.4f}") +except ImportError: + print(f"RMS verified (no numpy for FFT): rms={rms:.4f}") +EOF +} + +# Play compressed file with either cplay or sof-compr-tool.py +func_compr_run_play() +{ + local tool_mode="$1" + local snd_dev="$2" + local codec="$3" + local in_file="$4" + local pause_cycles="${5:-0}" + local duration="${6:-0}" + + if [ "$tool_mode" = "cplay" ] && [ "$pause_cycles" -gt 0 ]; then + dloge "cplay mode does not support pause/resume cycles ($pause_cycles); use compr-tool" + return 1 + fi + + local defaults + defaults=$(func_compr_codec_defaults "$codec") || return 1 + local rate ch bitrate fmt cplay_codec _ + read -r rate ch bitrate fmt cplay_codec _ <<< "$defaults" + + local watchdog=30 + if [ "$duration" -gt 0 ] 2>/dev/null; then + watchdog=$((duration + 30)) + fi + if [ "$pause_cycles" -gt 0 ] 2>/dev/null; then + watchdog=$((watchdog + pause_cycles * 2)) + fi + + if [ "$tool_mode" = "cplay" ] || { [ "$tool_mode" = "auto" ] && [ "$pause_cycles" -eq 0 ] && func_compr_cplay_supports "$codec"; }; then + func_compr_parse_dev "$snd_dev" || { + dloge "Cannot parse card/dev from $snd_dev for cplay" + return 1 + } + dlogc "timeout -k 5 -s INT $watchdog cplay -c $COMPR_CARD -d $COMPR_DEV -I $cplay_codec $in_file" + timeout -k 5 -s INT "$watchdog" cplay -c "$COMPR_CARD" -d "$COMPR_DEV" -I "$cplay_codec" "$in_file" + return $? + fi + + local -a cmd=( + timeout -k 5 -s TERM "$watchdog" + python3 "$COMPR_TOOL" play + -D "$snd_dev" -C "$codec" -f "$in_file" + -r "$rate" -n "$ch" -b "$bitrate" --fmt "$fmt" + ) + if [ "$pause_cycles" -gt 0 ]; then + cmd+=(--pause-resume "$pause_cycles") + fi + dlogc "${cmd[*]}" + "${cmd[@]}" +} + +# Record compressed stream with either crecord or sof-compr-tool.py +func_compr_run_record() +{ + local tool_mode="$1" + local snd_dev="$2" + local codec="$3" + local out_file="$4" + local duration="${5:-3}" + + local defaults + defaults=$(func_compr_codec_defaults "$codec") || return 1 + local rate ch bitrate fmt cplay_codec crecord_hex + read -r rate ch bitrate fmt cplay_codec crecord_hex <<< "$defaults" + + local rec_dur="$duration" + if [ "$tool_mode" = "crecord" ] || { [ "$tool_mode" = "auto" ] && func_compr_crecord_supports "$codec"; }; then + func_compr_parse_dev "$snd_dev" || { + dloge "Cannot parse card/dev from $snd_dev for crecord" + return 1 + } + # libtinycompress compress_read() blocks until the full buffer + # (fragments * fragment_size = 6144 B) fills before writing to stdout. + if [ "${codec,,}" = "flac" ] && [ "$rec_dur" -lt 15 ]; then + rec_dur=15 + fi + local crecord_id="$crecord_hex" + [ "$cplay_codec" != "NONE" ] && crecord_id="$cplay_codec" + # Note: crecord computes -l seconds assuming PCM bytes per second and + # refuses filename arguments for non-PCM codecs; redirect stdout and + # stop cleanly via SIGINT timeout. + local -a rec_cmd=( + timeout -s INT "$rec_dur" + crecord -c "$COMPR_CARD" -d "$COMPR_DEV" + -I "$crecord_id" -C "$ch" -R "$rate" -b 6144 -f 3 + ) + dlogc "${rec_cmd[*]} > $out_file" + local rc=0 + "${rec_cmd[@]}" > "$out_file" || rc=$? + # timeout returns 124 (or 130 on SIGINT) when duration expires normally + if [ "$rc" -ne 0 ] && [ "$rc" -ne 124 ] && [ "$rc" -ne 130 ]; then + dloge "crecord failed with exit code $rc" + return "$rc" + fi + return 0 + fi + + # Low-bitrate or high-compression capture (silence) needs >1s to fill one + # 2048-byte compress fragment. + case "${codec,,}" in + flac) + [ "$rec_dur" -lt 5 ] && rec_dur=5 + ;; + alac|msbc|g722) + [ "$rec_dur" -lt 3 ] && rec_dur=3 + ;; + esac + + local -a cmd=( + python3 "$COMPR_TOOL" record + -D "$snd_dev" -C "$codec" -o "$out_file" + -t "$rec_dur" -r "$rate" -n "$ch" -b "$bitrate" --fmt "$fmt" + ) + dlogc "${cmd[*]}" + "${cmd[@]}" +} diff --git a/case-lib/pipeline.sh b/case-lib/pipeline.sh index 03de8967..29037efb 100644 --- a/case-lib/pipeline.sh +++ b/case-lib/pipeline.sh @@ -169,7 +169,7 @@ func_pipeline_export() # If this is a new unique dev, copy pipeline to new index if needed if [ $new_idx -ne "$idx" ]; then # Copy all fields from old index to new index - for key in pcm id dev type fmt fmts rate rates channel channels snd; do + for key in pcm id dev type compress fmt fmts rate rates channel channels snd; do local val; val=$(func_pipeline_parse_value "$idx" "$key") if [[ -n "$val" ]]; then eval "PIPELINE_${new_idx}[$key]=\"$val\"" @@ -200,7 +200,7 @@ func_pipeline_export() # Create temporary copy of all pipelines local -A temp_pipelines for idx in $(seq 0 $((PIPELINE_COUNT - 1))); do - for key in pcm id dev type fmt fmts rate rates channel channels snd; do + for key in pcm id dev type compress fmt fmts rate rates channel channels snd; do local val; val=$(func_pipeline_parse_value "$idx" "$key") [[ -n "$val" ]] && temp_pipelines["${idx}_${key}"]="$val" done @@ -210,7 +210,7 @@ func_pipeline_export() local new_idx=0 for entry in "${sorted_indices[@]}"; do local old_idx="${entry#*:}" - for key in pcm id dev type fmt fmts rate rates channel channels snd; do + for key in pcm id dev type compress fmt fmts rate rates channel channels snd; do local val="${temp_pipelines[${old_idx}_${key}]}" if [[ -n "$val" ]]; then eval "PIPELINE_${new_idx}[$key]=\"$val\"" diff --git a/test-case/check-compr-decode.sh b/test-case/check-compr-decode.sh new file mode 100755 index 00000000..4a16eb09 --- /dev/null +++ b/test-case/check-compr-decode.sh @@ -0,0 +1,191 @@ +#!/bin/bash + +## +## Case Name: check-compr-decode +## Preconditions: +## SOF topology with compressed playback pipeline (ffmpeg_dec) +## Description: +## Validate compressed audio playback (decoding) across FFmpeg codecs +## using cplay and/or sof-compr-tool.py, with optional pause/resume and +## capture loopback verification. +## Case step: +## 1. Parse topology for type:playback & compress:1 pipelines +## 2. Generate compressed sine-wave test vectors via ffmpeg +## 3. Play each supported codec using cplay / sof-compr-tool.py +## 4. Check kernel logs for errors +## Expect result: +## All tested decoders complete cleanly without kernel/DSP errors +## + +set -e + +# shellcheck source=case-lib/lib.sh +source "$(dirname "${BASH_SOURCE[0]}")"/../case-lib/lib.sh +# shellcheck source=case-lib/compress.sh +source "$(dirname "${BASH_SOURCE[0]}")"/../case-lib/compress.sh + +OPT_NAME['t']='tplg' OPT_DESC['t']='tplg file, default value is env TPLG' +OPT_HAS_ARG['t']=1 OPT_VAL['t']="$TPLG" + +OPT_NAME['C']='codecs' OPT_DESC['C']='comma/space separated codec list or auto' +OPT_HAS_ARG['C']=1 OPT_VAL['C']='auto' + +OPT_NAME['m']='mode' OPT_DESC['m']='player mode: auto, cplay, compr-tool, all' +OPT_HAS_ARG['m']=1 OPT_VAL['m']='auto' + +OPT_NAME['d']='duration' OPT_DESC['d']='test vector duration in seconds' +OPT_HAS_ARG['d']=1 OPT_VAL['d']=3 + +OPT_NAME['l']='loop' OPT_DESC['l']='loop count per codec' +OPT_HAS_ARG['l']=1 OPT_VAL['l']=1 + +OPT_NAME['P']='pause_resume' OPT_DESC['P']='pause/resume cycles during playback' +OPT_HAS_ARG['P']=1 OPT_VAL['P']=0 + +OPT_NAME['o']='output' OPT_DESC['o']='working dir for generated vectors' +OPT_HAS_ARG['o']=1 OPT_VAL['o']="$LOG_ROOT/compr-decode" + +OPT_NAME['L']='loopback_pcm' OPT_DESC['L']='optional capture PCM (hw:C,D) for tone verify' +OPT_HAS_ARG['L']=1 OPT_VAL['L']='' + +OPT_NAME['S']='filter_string' OPT_DESC['S']='pipeline filter expression' +OPT_HAS_ARG['S']=1 OPT_VAL['S']='id:any' + +OPT_NAME['s']='sof-logger' OPT_DESC['s']="Open sof-logger trace stored at $LOG_ROOT" +OPT_HAS_ARG['s']=0 OPT_VAL['s']=1 + +func_opt_parse_option "$@" + +tplg=${OPT_VAL['t']} +codec_opt=${OPT_VAL['C']} +tool_mode=${OPT_VAL['m']} +duration=${OPT_VAL['d']} +loop_cnt=${OPT_VAL['l']} +pause_cycles=${OPT_VAL['P']} +work_dir=${OPT_VAL['o']} +loopback_pcm=${OPT_VAL['L']} +filter_str=${OPT_VAL['S']} + +start_test +logger_disabled || func_lib_start_log_collect +func_lib_check_sudo + +if [ "$tool_mode" = "cplay" ] && ! func_compr_has_bin cplay; then + skip_test "cplay binary not found in PATH" +fi + +if [ "$tool_mode" = "cplay" ] && [ "$pause_cycles" -gt 0 ]; then + die "Invalid combination: cplay mode does not support --pause_resume ($pause_cycles)" +fi + +func_pipeline_export "$tplg" "type:playback & compress:1 & ${filter_str}" + +mkdir -p "$work_dir" + +if [ "$codec_opt" = "auto" ]; then + codec_list="$COMPR_DECODE_CODECS_ALL" +else + codec_list="${codec_opt//,/ }" +fi + +tested_count=0 +tone_hz=997 + +for idx in $(seq 0 $((PIPELINE_COUNT - 1))); do + dev=$(func_pipeline_parse_value "$idx" dev) + snd=$(func_pipeline_parse_value "$idx" snd) + pcm=$(func_pipeline_parse_value "$idx" pcm) + + dlogi "Testing compress playback pipeline: $pcm [$dev] ($snd)" + + for codec in $codec_list; do + caps_rc=0 + func_compr_dev_supports_codec "$snd" playback "$codec" || caps_rc=$? + if [ "$caps_rc" -eq 1 ]; then + dlogi "Skipping codec=$codec (not advertised in GET_CAPS on $snd)" + continue + elif [ "$caps_rc" -ne 0 ]; then + die "Failed to query compress playback capabilities on $snd" + fi + + modes_to_run=() + case "$tool_mode" in + cplay) + func_compr_cplay_supports "$codec" || { + dlogi "Skipping codec=$codec (unsupported by cplay)" + continue + } + modes_to_run=(cplay) + ;; + compr-tool) + modes_to_run=(compr-tool) + ;; + all) + if [ "$pause_cycles" -eq 0 ] && func_compr_cplay_supports "$codec"; then + modes_to_run+=(cplay) + elif [ "$pause_cycles" -gt 0 ] && func_compr_cplay_supports "$codec"; then + dlogi "Skipping mode=cplay for codec=$codec (pause/resume unsupported by cplay)" + fi + modes_to_run+=(compr-tool) + ;; + auto) + modes_to_run=(auto) + ;; + *) + die "Invalid mode: $tool_mode (expected auto|cplay|compr-tool|all)" + ;; + esac + + defaults=$(func_compr_codec_defaults "$codec") + read -r rate ch _ _ _ _ <<< "$defaults" + vec_file="${work_dir}/dec_${codec}_${rate}hz_${ch}ch_${duration}s.${codec}" + if [ "$codec" = "alac" ]; then + vec_file="${work_dir}/dec_alac_${rate}hz_${ch}ch_${duration}s.m4a" + elif [ "$codec" = "msbc" ]; then + vec_file="${work_dir}/dec_msbc_${rate}hz_${ch}ch_${duration}s.sbc" + fi + + if [ ! -s "$vec_file" ]; then + func_compr_gen_vector "$codec" "$vec_file" "$duration" "$tone_hz" || \ + die "Failed to generate $codec test vector" + fi + + for mode in "${modes_to_run[@]}"; do + for i in $(seq 1 "$loop_cnt"); do + dlogi "===== Decode: $pcm ($snd) codec=$codec mode=$mode loop=$i/$loop_cnt =====" + cap_pid="" + cap_wav="" + if [ -n "$loopback_pcm" ]; then + cap_wav="${work_dir}/loopback_${codec}_${mode}_${i}.wav" + arecord -D "$loopback_pcm" -f S16_LE -r 48000 -c 2 \ + -d $((duration + 1)) -q "$cap_wav" & + cap_pid=$! + sleep 0.2 + fi + + if ! func_compr_run_play "$mode" "$snd" "$codec" "$vec_file" "$pause_cycles" "$duration"; then + if [ -n "$cap_pid" ]; then + kill "$cap_pid" 2>/dev/null || true + fi + func_lib_lsof_error_dump "$snd" + die "Decode playback failed: codec=$codec mode=$mode dev=$snd" + fi + + if [ -n "$cap_pid" ]; then + wait "$cap_pid" || die "Loopback arecord failed on $loopback_pcm" + func_compr_verify_wav_tone "$cap_wav" "$tone_hz" || \ + die "Loopback tone verification failed for $codec" + fi + tested_count=$((tested_count + 1)) + done + done + done +done + +if [ "$tested_count" -eq 0 ]; then + skip_test "No codecs matched device capabilities and selected mode ($tool_mode)" +fi + +dlogi "Completed $tested_count compressed decode test runs" +sof-kernel-log-check.sh "$KERNEL_CHECKPOINT" +exit $? diff --git a/test-case/check-compr-encode.sh b/test-case/check-compr-encode.sh new file mode 100755 index 00000000..dc37139e --- /dev/null +++ b/test-case/check-compr-encode.sh @@ -0,0 +1,187 @@ +#!/bin/bash + +## +## Case Name: check-compr-encode +## Preconditions: +## SOF topology with compressed capture pipeline (ffmpeg_enc) +## Description: +## Validate compressed audio capture (encoding) across FFmpeg codecs +## using crecord and/or sof-compr-tool.py, verifying container/sync headers +## and host ffmpeg decodability (plus optional playback loopback tone). +## Case step: +## 1. Parse topology for type:capture & compress:1 pipelines +## 2. Capture compressed audio stream for each supported codec +## 3. Verify encoded bitstream headers and decode via host ffmpeg +## 4. Check kernel logs for errors +## Expect result: +## All tested encoders produce valid, decodable compressed streams +## + +set -e + +# shellcheck source=case-lib/lib.sh +source "$(dirname "${BASH_SOURCE[0]}")"/../case-lib/lib.sh +# shellcheck source=case-lib/compress.sh +source "$(dirname "${BASH_SOURCE[0]}")"/../case-lib/compress.sh + +OPT_NAME['t']='tplg' OPT_DESC['t']='tplg file, default value is env TPLG' +OPT_HAS_ARG['t']=1 OPT_VAL['t']="$TPLG" + +OPT_NAME['C']='codecs' OPT_DESC['C']='comma/space separated codec list or auto' +OPT_HAS_ARG['C']=1 OPT_VAL['C']='auto' + +OPT_NAME['m']='mode' OPT_DESC['m']='recorder mode: auto, crecord, compr-tool, all' +OPT_HAS_ARG['m']=1 OPT_VAL['m']='auto' + +OPT_NAME['d']='duration' OPT_DESC['d']='capture duration in seconds' +OPT_HAS_ARG['d']=1 OPT_VAL['d']=3 + +OPT_NAME['l']='loop' OPT_DESC['l']='loop count per codec' +OPT_HAS_ARG['l']=1 OPT_VAL['l']=1 + +OPT_NAME['o']='output' OPT_DESC['o']='output directory for encoded streams' +OPT_HAS_ARG['o']=1 OPT_VAL['o']="$LOG_ROOT/compr-encode" + +OPT_NAME['L']='playback_pcm' OPT_DESC['L']='optional playback PCM (hw:C,D) for loopback tone' +OPT_HAS_ARG['L']=1 OPT_VAL['L']='' + +OPT_NAME['S']='filter_string' OPT_DESC['S']='pipeline filter expression' +OPT_HAS_ARG['S']=1 OPT_VAL['S']='id:any' + +OPT_NAME['s']='sof-logger' OPT_DESC['s']="Open sof-logger trace stored at $LOG_ROOT" +OPT_HAS_ARG['s']=0 OPT_VAL['s']=1 + +func_opt_parse_option "$@" + +tplg=${OPT_VAL['t']} +codec_opt=${OPT_VAL['C']} +tool_mode=${OPT_VAL['m']} +duration=${OPT_VAL['d']} +loop_cnt=${OPT_VAL['l']} +work_dir=${OPT_VAL['o']} +playback_pcm=${OPT_VAL['L']} +filter_str=${OPT_VAL['S']} + +start_test +logger_disabled || func_lib_start_log_collect +func_lib_check_sudo + +if [ "$tool_mode" = "crecord" ] && ! func_compr_has_bin crecord; then + skip_test "crecord binary not found in PATH" +fi + +func_pipeline_export "$tplg" "type:capture & compress:1 & ${filter_str}" + +mkdir -p "$work_dir" + +if [ "$codec_opt" = "auto" ]; then + codec_list="$COMPR_ENCODE_CODECS_ALL" +else + codec_list="${codec_opt//,/ }" +fi + +tested_count=0 +tone_hz=997 +tone_wav="" + +if [ -n "$playback_pcm" ]; then + func_compr_has_bin ffmpeg || die "ffmpeg required to synthesize loopback tone WAV" + tone_wav="${work_dir}/ref_tone_${tone_hz}hz.wav" + ffmpeg -y -v error -f lavfi \ + -i "sine=frequency=${tone_hz}:sample_rate=48000:duration=$((duration + 2))" \ + -ac 2 -c:a pcm_s16le "$tone_wav" +fi + +for idx in $(seq 0 $((PIPELINE_COUNT - 1))); do + dev=$(func_pipeline_parse_value "$idx" dev) + snd=$(func_pipeline_parse_value "$idx" snd) + pcm=$(func_pipeline_parse_value "$idx" pcm) + + dlogi "Testing compress capture pipeline: $pcm [$dev] ($snd)" + + for codec in $codec_list; do + caps_rc=0 + func_compr_dev_supports_codec "$snd" capture "$codec" || caps_rc=$? + if [ "$caps_rc" -eq 1 ]; then + dlogi "Skipping codec=$codec (not advertised in GET_CAPS on $snd)" + continue + elif [ "$caps_rc" -ne 0 ]; then + die "Failed to query compress capture capabilities on $snd" + fi + + modes_to_run=() + case "$tool_mode" in + crecord) + func_compr_crecord_supports "$codec" || { + dlogi "Skipping codec=$codec (unsupported by crecord)" + continue + } + modes_to_run=(crecord) + ;; + compr-tool) + modes_to_run=(compr-tool) + ;; + all) + func_compr_crecord_supports "$codec" && modes_to_run+=(crecord) + modes_to_run+=(compr-tool) + ;; + auto) + modes_to_run=(auto) + ;; + *) + die "Invalid mode: $tool_mode (expected auto|crecord|compr-tool|all)" + ;; + esac + + for mode in "${modes_to_run[@]}"; do + for i in $(seq 1 "$loop_cnt"); do + dlogi "===== Encode: $pcm ($snd) codec=$codec mode=$mode loop=$i/$loop_cnt =====" + enc_file="${work_dir}/enc_${pcm// /_}_${codec}_${mode}_${i}.${codec}" + dec_wav="${work_dir}/dec_${pcm// /_}_${codec}_${mode}_${i}.wav" + play_pid="" + + if [ -n "$tone_wav" ]; then + aplay -D "$playback_pcm" -q "$tone_wav" & + play_pid=$! + sleep 0.2 + fi + + if ! func_compr_run_record "$mode" "$snd" "$codec" "$enc_file" "$duration"; then + if [ -n "$play_pid" ]; then + kill "$play_pid" 2>/dev/null || true + fi + func_lib_lsof_error_dump "$snd" + die "Encode capture failed: codec=$codec mode=$mode dev=$snd" + fi + + if [ -n "$play_pid" ]; then + wait "$play_pid" || true + fi + + rm -f "$dec_wav" + verify_rc=0 + func_compr_verify_encoded_file "$codec" "$enc_file" "${tone_wav:+$dec_wav}" || verify_rc=$? + if [ "$verify_rc" -ne 0 ] && [ "$verify_rc" -ne 2 ]; then + die "Encoded bitstream verification failed for $codec ($mode)" + fi + + if [ -n "$tone_wav" ]; then + if [ "$verify_rc" -eq 2 ]; then + die "Loopback tone verification unsupported for raw header-only $codec stream" + fi + func_compr_verify_wav_tone "$dec_wav" "$tone_hz" || \ + die "Loopback encoded tone check failed for $codec" + fi + tested_count=$((tested_count + 1)) + done + done + done +done + +if [ "$tested_count" -eq 0 ]; then + skip_test "No codecs matched capture capabilities and selected mode ($tool_mode)" +fi + +dlogi "Completed $tested_count compressed encode test runs" +sof-kernel-log-check.sh "$KERNEL_CHECKPOINT" +exit $? diff --git a/test-case/check-compr-roundtrip.sh b/test-case/check-compr-roundtrip.sh new file mode 100755 index 00000000..4c141345 --- /dev/null +++ b/test-case/check-compr-roundtrip.sh @@ -0,0 +1,130 @@ +#!/bin/bash + +## +## Case Name: check-compr-roundtrip +## Preconditions: +## SOF topology with both compressed playback (ffmpeg_dec) and +## compressed capture (ffmpeg_enc) pipelines +## Description: +## Test lossless encode->host-decode fidelity and simultaneous compressed +## playback + compressed capture using both cplay/crecord and sof-compr-tool.py. +## Case step: +## 1. Parse topology for compress:1 playback and capture pipelines +## 2. Generate reference compressed audio vectors +## 3. Run concurrent compress playback and compress capture +## 4. Verify captured stream decodes cleanly on host +## 5. Check kernel logs for errors +## Expect result: +## Concurrent decode/encode pipelines succeed without XRUN or kernel errors +## + +set -e + +# shellcheck source=case-lib/lib.sh +source "$(dirname "${BASH_SOURCE[0]}")"/../case-lib/lib.sh +# shellcheck source=case-lib/compress.sh +source "$(dirname "${BASH_SOURCE[0]}")"/../case-lib/compress.sh + +OPT_NAME['t']='tplg' OPT_DESC['t']='tplg file, default value is env TPLG' +OPT_HAS_ARG['t']=1 OPT_VAL['t']="$TPLG" + +OPT_NAME['C']='codecs' OPT_DESC['C']='codecs to pair for roundtrip (default: flac,mp3,aac,alac)' +OPT_HAS_ARG['C']=1 OPT_VAL['C']='flac,mp3,aac,alac' + +OPT_NAME['d']='duration' OPT_DESC['d']='stream duration in seconds' +OPT_HAS_ARG['d']=1 OPT_VAL['d']=4 + +OPT_NAME['o']='output' OPT_DESC['o']='working directory for test streams' +OPT_HAS_ARG['o']=1 OPT_VAL['o']="$LOG_ROOT/compr-roundtrip" + +OPT_NAME['S']='filter_string' OPT_DESC['S']='pipeline filter expression' +OPT_HAS_ARG['S']=1 OPT_VAL['S']='id:any' + +OPT_NAME['s']='sof-logger' OPT_DESC['s']="Open sof-logger trace stored at $LOG_ROOT" +OPT_HAS_ARG['s']=0 OPT_VAL['s']=1 + +func_opt_parse_option "$@" + +tplg=${OPT_VAL['t']} +codec_opt=${OPT_VAL['C']} +duration=${OPT_VAL['d']} +work_dir=${OPT_VAL['o']} +filter_str=${OPT_VAL['S']} + +start_test +logger_disabled || func_lib_start_log_collect +func_lib_check_sudo + +mkdir -p "$work_dir" + +func_pipeline_export "$tplg" "type:playback & compress:1 & ${filter_str}" +play_snd=$(func_pipeline_parse_value 0 snd) +play_pcm=$(func_pipeline_parse_value 0 pcm) + +func_pipeline_export "$tplg" "type:capture & compress:1 & ${filter_str}" +cap_snd=$(func_pipeline_parse_value 0 snd) +cap_pcm=$(func_pipeline_parse_value 0 pcm) + +dlogi "Roundtrip playback=$play_pcm ($play_snd), capture=$cap_pcm ($cap_snd)" + +tested_count=0 +for codec in ${codec_opt//,/ }; do + play_caps_rc=0 + func_compr_dev_supports_codec "$play_snd" playback "$codec" || play_caps_rc=$? + if [ "$play_caps_rc" -eq 1 ]; then + dlogi "Skipping $codec: playback unsupported on $play_snd" + continue + elif [ "$play_caps_rc" -ne 0 ]; then + die "Failed to query compress playback capabilities on $play_snd" + fi + + cap_caps_rc=0 + func_compr_dev_supports_codec "$cap_snd" capture "$codec" || cap_caps_rc=$? + if [ "$cap_caps_rc" -eq 1 ]; then + dlogi "Skipping $codec: capture unsupported on $cap_snd" + continue + elif [ "$cap_caps_rc" -ne 0 ]; then + die "Failed to query compress capture capabilities on $cap_snd" + fi + + defaults=$(func_compr_codec_defaults "$codec") + read -r rate ch _ _ _ _ <<< "$defaults" + in_vec="${work_dir}/in_${codec}_${duration}s.${codec}" + [ "$codec" = "alac" ] && in_vec="${work_dir}/in_alac_${duration}s.m4a" + [ "$codec" = "msbc" ] && in_vec="${work_dir}/in_msbc_${duration}s.sbc" + if [ ! -s "$in_vec" ]; then + func_compr_gen_vector "$codec" "$in_vec" "$duration" 997 || \ + die "Failed to generate input vector for $codec" + fi + + out_stream="${work_dir}/out_${codec}.${codec}" + + dlogi "===== Simultaneous decode+encode ($codec, ${rate}Hz ${ch}ch) =====" + func_compr_run_record auto "$cap_snd" "$codec" "$out_stream" "$duration" & + rec_pid=$! + sleep 0.2 + + if ! func_compr_run_play auto "$play_snd" "$codec" "$in_vec" 0 "$duration"; then + kill "$rec_pid" 2>/dev/null || true + wait "$rec_pid" 2>/dev/null || true + die "Roundtrip compress playback failed for $codec" + fi + + wait "$rec_pid" || die "Roundtrip compress capture failed for $codec" + + verify_rc=0 + func_compr_verify_encoded_file "$codec" "$out_stream" "" || verify_rc=$? + if [ "$verify_rc" -ne 0 ] && [ "$verify_rc" -ne 2 ]; then + die "Roundtrip captured stream invalid for $codec" + fi + + tested_count=$((tested_count + 1)) +done + +if [ "$tested_count" -eq 0 ]; then + skip_test "No codecs supported by both compress playback and capture pipelines" +fi + +dlogi "Completed $tested_count simultaneous compressed roundtrip tests" +sof-kernel-log-check.sh "$KERNEL_CHECKPOINT" +exit $? diff --git a/test-case/verify-pcm-list.sh b/test-case/verify-pcm-list.sh index 0f4b40c9..bfb1f6bf 100755 --- a/test-case/verify-pcm-list.sh +++ b/test-case/verify-pcm-list.sh @@ -58,12 +58,12 @@ opt="" # Remove leading " & " if present opt="${opt# & }" -# Build sof-tplgreader.py command with filter +# Build sof-tplgreader.py command with filter (exclude compress devs not in /proc/asound/pcm) if [ -n "$opt" ]; then dlogi "Applying pipeline filter: $opt" - tplg_str=$(sof-tplgreader.py "$tplg_files" -f "$opt" -d id pcm type -o) + tplg_str=$(sof-tplgreader.py "$tplg_files" -f "$opt" -b 'compress:1' -d id pcm type -o) else - tplg_str=$(sof-tplgreader.py "$tplg_files" -d id pcm type -o) + tplg_str=$(sof-tplgreader.py "$tplg_files" -b 'compress:1' -d id pcm type -o) fi # Deduplicate exact duplicate lines only, preserve original order. diff --git a/tools/sof-compr-tool.py b/tools/sof-compr-tool.py new file mode 100755 index 00000000..3b338946 --- /dev/null +++ b/tools/sof-compr-tool.py @@ -0,0 +1,806 @@ +#!/usr/bin/env python3 +"""ALSA compress offload CLI tool for SOF encoder/decoder testing. + +Supports capability discovery, compressed playback (decoding), and +compressed capture (encoding) directly via Linux compress offload ioctls, +including codecs and profiles not exposed by tinycompress cplay/crecord +(OPUS_RAW, ALAC, SBC/mSBC, G.722, aptX, and SND_AUDIOCODEC_BESPOKE). +""" + +import argparse +import ctypes +from dataclasses import dataclass +import errno +import fcntl +import os +import re +import select +import signal +import sys +import time + + +# ALSA compress codec IDs from and SOF extensions +SND_AUDIOCODEC_PCM = 0x01 +SND_AUDIOCODEC_MP3 = 0x02 +SND_AUDIOCODEC_AMR = 0x03 +SND_AUDIOCODEC_AMRWB = 0x04 +SND_AUDIOCODEC_AMRWBPLUS = 0x05 +SND_AUDIOCODEC_AAC = 0x06 +SND_AUDIOCODEC_WMA = 0x07 +SND_AUDIOCODEC_REAL = 0x08 +SND_AUDIOCODEC_VORBIS = 0x09 +SND_AUDIOCODEC_FLAC = 0x0A +SND_AUDIOCODEC_IEC61937 = 0x0B +SND_AUDIOCODEC_G723_1 = 0x0C +SND_AUDIOCODEC_G729 = 0x0D +SND_AUDIOCODEC_BESPOKE = 0x0E +SND_AUDIOCODEC_ALAC = 0x0F +SND_AUDIOCODEC_APE = 0x10 +SND_AUDIOCODEC_OPUS_RAW = 0x11 +SND_AUDIOCODEC_SBC = 0x12 +SND_AUDIOCODEC_G722 = 0x13 +SND_AUDIOCODEC_APTX = 0x14 +SND_AUDIOCODEC_APTX_HD = 0x15 +SND_AUDIOCODEC_G726 = 0x16 +SND_AUDIOCODEC_ALAW = 0x17 +SND_AUDIOCODEC_MULAW = 0x18 + +AV_PROFILE_SBC_MSBC = 1 + +# SNDRV_PCM_FORMAT_* values used in snd_codec.format for encoders +PCM_FORMAT_MAP = { + "NONE": 0, + "UNDEFINED": 0, + "S16_LE": 2, + "S24_LE": 6, + "S32_LE": 10, +} + +CODEC_ALIASES = { + "pcm": (SND_AUDIOCODEC_PCM, 0), + "mp3": (SND_AUDIOCODEC_MP3, 0), + "aac": (SND_AUDIOCODEC_AAC, 0), + "vorbis": (SND_AUDIOCODEC_VORBIS, 0), + "flac": (SND_AUDIOCODEC_FLAC, 0), + "iec61937": (SND_AUDIOCODEC_IEC61937, 0), + "bespoke": (SND_AUDIOCODEC_BESPOKE, 0), + "alac": (SND_AUDIOCODEC_ALAC, 0), + "ape": (SND_AUDIOCODEC_APE, 0), + "opus": (SND_AUDIOCODEC_OPUS_RAW, 0), + "opus_raw": (SND_AUDIOCODEC_OPUS_RAW, 0), + "sbc": (SND_AUDIOCODEC_SBC, 0), + "msbc": (SND_AUDIOCODEC_SBC, AV_PROFILE_SBC_MSBC), + "g722": (SND_AUDIOCODEC_G722, 0), + "aptx": (SND_AUDIOCODEC_APTX, 0), + "aptx_hd": (SND_AUDIOCODEC_APTX_HD, 0), + "g726": (SND_AUDIOCODEC_G726, 0), + "alaw": (SND_AUDIOCODEC_ALAW, 0), + "mulaw": (SND_AUDIOCODEC_MULAW, 0), +} + +CODEC_NAMES = { + SND_AUDIOCODEC_PCM: "PCM", + SND_AUDIOCODEC_MP3: "MP3", + SND_AUDIOCODEC_AMR: "AMR", + SND_AUDIOCODEC_AMRWB: "AMRWB", + SND_AUDIOCODEC_AMRWBPLUS: "AMRWBPLUS", + SND_AUDIOCODEC_AAC: "AAC", + SND_AUDIOCODEC_WMA: "WMA", + SND_AUDIOCODEC_REAL: "REAL", + SND_AUDIOCODEC_VORBIS: "VORBIS", + SND_AUDIOCODEC_FLAC: "FLAC", + SND_AUDIOCODEC_IEC61937: "IEC61937", + SND_AUDIOCODEC_G723_1: "G723_1", + SND_AUDIOCODEC_G729: "G729", + SND_AUDIOCODEC_BESPOKE: "BESPOKE", + SND_AUDIOCODEC_ALAC: "ALAC", + SND_AUDIOCODEC_APE: "APE", + SND_AUDIOCODEC_OPUS_RAW: "OPUS_RAW", + SND_AUDIOCODEC_SBC: "SBC", + SND_AUDIOCODEC_G722: "G722", + SND_AUDIOCODEC_APTX: "APTX", + SND_AUDIOCODEC_APTX_HD: "APTX_HD", + SND_AUDIOCODEC_G726: "G726", + SND_AUDIOCODEC_ALAW: "ALAW", + SND_AUDIOCODEC_MULAW: "MULAW", +} + +MAX_NUM_CODECS = 32 + +# Linux ioctl encoding +_IOC_NRBITS = 8 +_IOC_TYPEBITS = 8 +_IOC_SIZEBITS = 14 +_IOC_DIRBITS = 2 + +_IOC_NRSHIFT = 0 +_IOC_TYPESHIFT = _IOC_NRSHIFT + _IOC_NRBITS +_IOC_SIZESHIFT = _IOC_TYPESHIFT + _IOC_TYPEBITS +_IOC_DIRSHIFT = _IOC_SIZESHIFT + _IOC_SIZEBITS + +_IOC_NONE = 0 +_IOC_WRITE = 1 +_IOC_READ = 2 + + +def _ioc(direction, ioc_type, nr, size): + """Build a Linux ioctl request code.""" + return ( + (direction << _IOC_DIRSHIFT) + | (ord(ioc_type) << _IOC_TYPESHIFT) + | (nr << _IOC_NRSHIFT) + | (size << _IOC_SIZESHIFT) + ) + + +# pylint: disable=too-few-public-methods +class SndEncGeneric(ctypes.Structure): + """struct snd_enc_generic from .""" + + _fields_ = [ + ("bw", ctypes.c_uint32), + ("reserved", ctypes.c_int32 * 15), + ] + + +class SndDecOpusChMap(ctypes.Structure): + """struct snd_dec_opus_ch_map from .""" + + _fields_ = [ + ("stream_count", ctypes.c_uint8), + ("coupled_count", ctypes.c_uint8), + ("channel_map", ctypes.c_uint8 * 8), + ] + + +class SndDecOpus(ctypes.Structure): + """struct snd_dec_opus from .""" + + _fields_ = [ + ("version", ctypes.c_uint8), + ("num_channels", ctypes.c_uint8), + ("pre_skip", ctypes.c_uint16), + ("sample_rate", ctypes.c_uint32), + ("output_gain", ctypes.c_uint16), + ("mapping_family", ctypes.c_uint8), + ("chan_map", SndDecOpusChMap), + ] + + +class SndDecAlac(ctypes.Structure): + """struct snd_dec_alac from .""" + + _fields_ = [ + ("frame_length", ctypes.c_uint32), + ("compatible_version", ctypes.c_uint8), + ("pb", ctypes.c_uint8), + ("mb", ctypes.c_uint8), + ("kb", ctypes.c_uint8), + ("max_run", ctypes.c_uint32), + ("max_frame_bytes", ctypes.c_uint32), + ] + + +class SndDecFlac(ctypes.Structure): + """struct snd_dec_flac from .""" + + _fields_ = [ + ("sample_size", ctypes.c_uint16), + ("min_blk_size", ctypes.c_uint16), + ("max_blk_size", ctypes.c_uint16), + ("min_frame_size", ctypes.c_uint16), + ("max_frame_size", ctypes.c_uint16), + ("reserved", ctypes.c_uint16), + ] + + +class SndCodecOptions(ctypes.Union): + """union snd_codec_options from .""" + + _fields_ = [ + ("generic", SndEncGeneric), + ("opus_d", SndDecOpus), + ("alac_d", SndDecAlac), + ("flac_d", SndDecFlac), + ] + + +class SndCodec(ctypes.Structure): + """struct snd_codec from .""" + + _fields_ = [ + ("id", ctypes.c_uint32), + ("ch_in", ctypes.c_uint32), + ("ch_out", ctypes.c_uint32), + ("sample_rate", ctypes.c_uint32), + ("bit_rate", ctypes.c_uint32), + ("rate_control", ctypes.c_uint32), + ("profile", ctypes.c_uint32), + ("level", ctypes.c_uint32), + ("ch_mode", ctypes.c_uint32), + ("format", ctypes.c_uint32), + ("align", ctypes.c_uint32), + ("options", SndCodecOptions), + ("pcm_format", ctypes.c_uint32), + ("reserved", ctypes.c_uint32 * 2), + ] + + +class SndComprBuffer(ctypes.Structure): + """struct snd_compr_buffer from .""" + + _fields_ = [ + ("fragment_size", ctypes.c_uint32), + ("fragments", ctypes.c_uint32), + ] + + +class SndComprParams(ctypes.Structure): + """struct snd_compr_params from .""" + + _fields_ = [ + ("buffer", SndComprBuffer), + ("codec", SndCodec), + ("no_wake_mode", ctypes.c_uint8), + ("reserved", ctypes.c_uint8 * 3), + ] + + +class SndComprCaps(ctypes.Structure): + """struct snd_compr_caps from .""" + + _fields_ = [ + ("num_codecs", ctypes.c_uint32), + ("direction", ctypes.c_uint32), + ("min_fragment_size", ctypes.c_uint32), + ("max_fragment_size", ctypes.c_uint32), + ("min_fragments", ctypes.c_uint32), + ("max_fragments", ctypes.c_uint32), + ("codecs", ctypes.c_uint32 * MAX_NUM_CODECS), + ("reserved", ctypes.c_uint32 * 11), + ] + + +class SndComprTstamp(ctypes.Structure): + """struct snd_compr_tstamp from .""" + + _fields_ = [ + ("byte_offset", ctypes.c_uint32), + ("copied_total", ctypes.c_uint32), + ("pcm_frames", ctypes.c_uint32), + ("pcm_io_frames", ctypes.c_uint32), + ("sampling_rate", ctypes.c_uint32), + ] + + +@dataclass +class BufferConfig: + """Buffer and wrapper setup options.""" + + frag_size: int = 0 + frags: int = 0 + bespoke: str = "auto" + is_capture: bool = False + + +@dataclass +class StreamConfig: + """Resolved compress stream setup parameters.""" + + codec_id: int + profile: int + rate: int + channels: int + bitrate: int + fmt_id: int + buf: BufferConfig +# pylint: enable=too-few-public-methods + + +assert ctypes.sizeof(SndCodec) == 120 +assert ctypes.sizeof(SndComprParams) == 132 +assert ctypes.sizeof(SndComprCaps) == 196 +assert ctypes.sizeof(SndComprTstamp) == 20 + +SNDRV_COMPRESS_GET_CAPS = _ioc( + _IOC_READ | _IOC_WRITE, "C", 0x10, ctypes.sizeof(SndComprCaps) +) +SNDRV_COMPRESS_SET_PARAMS = _ioc( + _IOC_WRITE, "C", 0x12, ctypes.sizeof(SndComprParams) +) +SNDRV_COMPRESS_TSTAMP = _ioc( + _IOC_READ, "C", 0x20, ctypes.sizeof(SndComprTstamp) +) +SNDRV_COMPRESS_PAUSE = _ioc(_IOC_NONE, "C", 0x30, 0) +SNDRV_COMPRESS_RESUME = _ioc(_IOC_NONE, "C", 0x31, 0) +SNDRV_COMPRESS_START = _ioc(_IOC_NONE, "C", 0x32, 0) +SNDRV_COMPRESS_STOP = _ioc(_IOC_NONE, "C", 0x33, 0) +SNDRV_COMPRESS_DRAIN = _ioc(_IOC_NONE, "C", 0x34, 0) + + +def resolve_device_path(device, card, dev): + """Convert -D / hw:C,D / card+dev arguments to /dev/snd/comprCxDy.""" + if device: + match = re.match(r"^(?:hw:|plughw:)?(\d+),(\d+)$", device) + if match: + return f"/dev/snd/comprC{match.group(1)}D{match.group(2)}" + return device + return f"/dev/snd/comprC{card}D{dev}" + + +def resolve_codec(codec_spec): + """Parse codec name or hex/dec integer into (codec_id, profile).""" + key = codec_spec.strip().lower() + if key in CODEC_ALIASES: + return CODEC_ALIASES[key] + try: + return int(key, 0), 0 + except ValueError as exc: + raise ValueError(f"Unsupported codec specification: {codec_spec}") from exc + + +def resolve_pcm_format(fmt_name): + """Parse format name or numeric value into SNDRV_PCM_FORMAT_* int.""" + key = str(fmt_name).strip().upper() + if key in PCM_FORMAT_MAP: + return PCM_FORMAT_MAP[key] + try: + return int(key, 0) + except ValueError as exc: + raise ValueError(f"Unsupported sample format: {fmt_name}") from exc + + +def query_caps(fd, direction=None): + """Issue SNDRV_COMPRESS_GET_CAPS on an open compress fd.""" + caps = SndComprCaps(direction=direction) if direction is not None else SndComprCaps() + fcntl.ioctl(fd, SNDRV_COMPRESS_GET_CAPS, caps) + return caps + + +def open_compress_with_caps(dev_path, flags): + """Open compress device and retrieve capabilities.""" + fd = os.open(dev_path, flags) + try: + direction = 1 if (flags & os.O_ACCMODE) == os.O_RDONLY else 0 + caps = query_caps(fd, direction=direction) + return fd, caps + except Exception: + os.close(fd) + raise + + +def build_params(caps, cfg, use_bespoke=False): + """Construct SndComprParams bounded by reported caps.""" + params = SndComprParams() + + req_frag = cfg.buf.frag_size if cfg.buf.frag_size > 0 else (2048 if cfg.buf.is_capture else 8192) + req_frags = cfg.buf.frags if cfg.buf.frags > 0 else 4 + + min_frag = caps.min_fragment_size or 1024 + max_frag = caps.max_fragment_size or 65536 + min_frags = caps.min_fragments or 2 + max_frags = caps.max_fragments or 16 + + params.buffer.fragment_size = max(min_frag, min(req_frag, max_frag)) + params.buffer.fragments = max(min_frags, min(req_frags, max_frags)) + + codec = params.codec + if use_bespoke: + codec.id = SND_AUDIOCODEC_BESPOKE + codec.options.generic.reserved[0] = cfg.codec_id + else: + codec.id = cfg.codec_id + + codec.ch_in = cfg.channels + codec.ch_out = cfg.channels + codec.sample_rate = cfg.rate + codec.bit_rate = cfg.bitrate + codec.profile = cfg.profile + codec.format = cfg.fmt_id if cfg.codec_id == SND_AUDIOCODEC_PCM else 0 + codec.pcm_format = cfg.fmt_id + + if not use_bespoke and not cfg.buf.is_capture and cfg.codec_id == SND_AUDIOCODEC_OPUS_RAW: + opus_d = codec.options.opus_d + opus_d.version = 1 + opus_d.num_channels = cfg.channels + opus_d.pre_skip = 312 + opus_d.sample_rate = 48000 + opus_d.mapping_family = 0 + opus_d.chan_map.stream_count = 1 + opus_d.chan_map.coupled_count = 1 if cfg.channels >= 2 else 0 + for idx in range(min(cfg.channels, 8)): + opus_d.chan_map.channel_map[idx] = idx + + return params + + +def set_params_with_fallback(fd, caps, cfg): + """Call SNDRV_COMPRESS_SET_PARAMS with optional BESPOKE fallback.""" + if cfg.buf.bespoke == "always": + modes = [True] + elif cfg.buf.bespoke == "never": + modes = [False] + else: + modes = [False, True] if cfg.codec_id > SND_AUDIOCODEC_BESPOKE else [False] + + last_err = None + for use_bespoke in modes: + params = build_params(caps, cfg, use_bespoke=use_bespoke) + try: + fcntl.ioctl(fd, SNDRV_COMPRESS_SET_PARAMS, params) + return params, use_bespoke + except OSError as exc: + last_err = exc + if use_bespoke or exc.errno != errno.EINVAL: + raise + raise last_err + + +def read_tstamp(fd): + """Best-effort query of SNDRV_COMPRESS_TSTAMP.""" + tstamp = SndComprTstamp() + try: + fcntl.ioctl(fd, SNDRV_COMPRESS_TSTAMP, tstamp) + except OSError: + return None + return tstamp + + +def cmd_caps(args): + """Inspect compress device capabilities and optionally check a codec.""" + dev_path = resolve_device_path(args.device, args.card, args.dev) + open_flag = os.O_RDONLY if args.direction == "capture" else os.O_WRONLY + fd, caps = open_compress_with_caps(dev_path, open_flag) + try: + num = min(caps.num_codecs, MAX_NUM_CODECS) + codec_ids = [caps.codecs[i] for i in range(num)] + finally: + os.close(fd) + + names = [f"{CODEC_NAMES.get(cid, 'UNKNOWN')}(0x{cid:02x})" for cid in codec_ids] + print(f"device={dev_path} direction={caps.direction} " + f"frag=[{caps.min_fragment_size},{caps.max_fragment_size}] " + f"frags=[{caps.min_fragments},{caps.max_fragments}] " + f"codecs=[{', '.join(names)}]") + + if args.has_codec: + target_id, _ = resolve_codec(args.has_codec) + if target_id in codec_ids: + return 0 + if SND_AUDIOCODEC_BESPOKE in codec_ids and target_id > SND_AUDIOCODEC_BESPOKE: + print( + f"Codec {args.has_codec} (0x{target_id:02x}) supported via BESPOKE(0x0e)", + file=sys.stderr, + ) + return 0 + return 2 + return 0 + + +def _stream_config_from_args(args, is_capture): + """Build StreamConfig from parsed CLI arguments.""" + codec_id, default_profile = resolve_codec(args.codec) + profile = args.profile if args.profile is not None else default_profile + default_bitrates = { + "flac": 0, + "alac": 0, + "msbc": 64000, + "g722": 64000, + "sbc": 328000, + "aptx": 384000, + "mp3": 192000, + "aac": 192000, + } + bitrate = ( + args.bitrate + if args.bitrate is not None + else default_bitrates.get(args.codec.lower(), 128000) + ) + return StreamConfig( + codec_id=codec_id, + profile=profile, + rate=args.rate, + channels=args.channels, + bitrate=bitrate, + fmt_id=resolve_pcm_format(args.fmt), + buf=BufferConfig( + frag_size=args.frag_size, + frags=args.frags, + bespoke=args.bespoke, + is_capture=is_capture, + ), + ) + + +def _drain_timeout_handler(_signum, _frame): + """Interrupt blocking SNDRV_COMPRESS_DRAIN ioctl on expiry.""" + raise TimeoutError("Timed out waiting for SNDRV_COMPRESS_DRAIN completion") + + +def _drain_with_timeout(fd, timeout_ms): + """Issue SNDRV_COMPRESS_DRAIN bounded by SIGALRM ITIMER_REAL deadline.""" + if timeout_ms <= 0: + fcntl.ioctl(fd, SNDRV_COMPRESS_DRAIN) + return + old_handler = signal.signal(signal.SIGALRM, _drain_timeout_handler) + signal.siginterrupt(signal.SIGALRM, True) + signal.setitimer(signal.ITIMER_REAL, timeout_ms / 1000.0) + try: + fcntl.ioctl(fd, SNDRV_COMPRESS_DRAIN) + finally: + signal.setitimer(signal.ITIMER_REAL, 0) + signal.signal(signal.SIGALRM, old_handler) + + +def _run_pause_resume(fd): + """Exercise one PAUSE -> RESUME cycle.""" + fcntl.ioctl(fd, SNDRV_COMPRESS_PAUSE) + time.sleep(0.25) + fcntl.ioctl(fd, SNDRV_COMPRESS_RESUME) + + +def _stream_playback_data(fd, data, frag_size, frags, args): + """Prefill, start, write remaining frames, and exercise pause/resume.""" + prefill_bytes = min(len(data), frag_size * frags) + offset = 0 + while offset < prefill_bytes: + chunk = data[offset : min(offset + frag_size, prefill_bytes)] + written = os.write(fd, chunk) + if written <= 0: + raise RuntimeError("Short zero-byte write during prefill") + offset += written + + fcntl.ioctl(fd, SNDRV_COMPRESS_START) + poller = select.poll() + poller.register(fd, select.POLLOUT) + paused_done = 0 + + while offset < len(data): + events = poller.poll(args.timeout_ms) + if not events: + raise TimeoutError("Timed out waiting for POLLOUT on compress playback") + if events[0][1] & (select.POLLERR | select.POLLHUP | select.POLLNVAL): + raise RuntimeError(f"Compress playback poll error mask=0x{events[0][1]:x}") + chunk = data[offset : min(offset + frag_size, len(data))] + written = os.write(fd, chunk) + if written <= 0: + raise RuntimeError("Zero-byte write during compress playback") + offset += written + + if ( + paused_done < args.pause_resume + and offset >= len(data) // (args.pause_resume + 1) * (paused_done + 1) + ): + _run_pause_resume(fd) + paused_done += 1 + + while paused_done < args.pause_resume: + _run_pause_resume(fd) + paused_done += 1 + + return offset + + +def _capture_loop(fd, outfile, frag_size, args): + """Poll and read compressed frames until duration or max_bytes.""" + poller = select.poll() + poller.register(fd, select.POLLIN) + total_bytes = 0 + deadline = time.monotonic() + args.duration + + while True: + remaining = deadline - time.monotonic() + if remaining <= 0 or (args.max_bytes and total_bytes >= args.max_bytes): + break + events = poller.poll(max(1, min(int(remaining * 1000), 500))) + if not events: + continue + if events[0][1] & (select.POLLERR | select.POLLNVAL): + raise RuntimeError(f"Compress capture poll error mask=0x{events[0][1]:x}") + if events[0][1] & select.POLLIN: + chunk = os.read(fd, frag_size) + if not chunk: + break + outfile.write(chunk) + total_bytes += len(chunk) + + return total_bytes + + +def cmd_play(args): + """Play a compressed audio file through the compress playback device.""" + dev_path = resolve_device_path(args.device, args.card, args.dev) + cfg = _stream_config_from_args(args, is_capture=False) + + with open(args.file, "rb") as infile: + data = infile.read() + if not data: + raise ValueError(f"Input file is empty: {args.file}") + + fd, caps = open_compress_with_caps(dev_path, os.O_WRONLY) + started = False + try: + params, used_bespoke = set_params_with_fallback(fd, caps, cfg) + frag_size = params.buffer.fragment_size + frags = params.buffer.fragments + print( + f"Playing {args.file} ({len(data)} B) on {dev_path} " + f"codec=0x{cfg.codec_id:02x} profile={cfg.profile} rate={cfg.rate} " + f"ch={cfg.channels} bespoke={used_bespoke} frag={frag_size}x{frags}" + ) + + started = True + offset = _stream_playback_data(fd, data, frag_size, frags, args) + _drain_with_timeout(fd, args.drain_timeout_ms) + tstamp = read_tstamp(fd) + if tstamp: + print( + f"Playback finished: bytes_written={offset} copied_total={tstamp.copied_total} " + f"pcm_frames={tstamp.pcm_frames} rate={tstamp.sampling_rate}" + ) + else: + print(f"Playback finished: bytes_written={offset}") + except Exception: + if started: + try: + fcntl.ioctl(fd, SNDRV_COMPRESS_STOP) + except OSError: + pass + raise + finally: + os.close(fd) + return 0 + + +def cmd_record(args): + """Capture a compressed audio stream from the compress capture device.""" + dev_path = resolve_device_path(args.device, args.card, args.dev) + cfg = _stream_config_from_args(args, is_capture=True) + + fd, caps = open_compress_with_caps(dev_path, os.O_RDONLY) + total_bytes = 0 + started = False + try: + params, used_bespoke = set_params_with_fallback(fd, caps, cfg) + frag_size = params.buffer.fragment_size + print( + f"Recording to {args.output} from {dev_path} duration={args.duration}s " + f"codec=0x{cfg.codec_id:02x} profile={cfg.profile} rate={cfg.rate} " + f"ch={cfg.channels} bitrate={cfg.bitrate} fmt={args.fmt} " + f"bespoke={used_bespoke} frag={frag_size}x{params.buffer.fragments}" + ) + + with open(args.output, "wb") as outfile: + fcntl.ioctl(fd, SNDRV_COMPRESS_START) + started = True + total_bytes = _capture_loop(fd, outfile, frag_size, args) + + if started: + fcntl.ioctl(fd, SNDRV_COMPRESS_STOP) + started = False + + tstamp = read_tstamp(fd) + if tstamp: + print( + f"Capture finished: bytes_captured={total_bytes} " + f"copied_total={tstamp.copied_total} pcm_frames={tstamp.pcm_frames}" + ) + else: + print(f"Capture finished: bytes_captured={total_bytes}") + finally: + if started: + try: + fcntl.ioctl(fd, SNDRV_COMPRESS_STOP) + except OSError: + pass + os.close(fd) + + if total_bytes <= 0: + raise RuntimeError("Captured 0 bytes from compress device") + return 0 + + +def parse_args(): + """Parse CLI arguments.""" + parser = argparse.ArgumentParser( + description="ALSA compress offload test tool for SOF" + ) + subparsers = parser.add_subparsers(dest="subcommand", required=True) + + def add_dev_args(sub): + sub.add_argument("-D", "--device", help="Device path (/dev/snd/comprC0D2 or hw:0,2)") + sub.add_argument("-c", "--card", type=int, default=0, help="ALSA card index") + sub.add_argument("-d", "--dev", type=int, default=0, help="Compress device index") + + p_caps = subparsers.add_parser("caps", help="Query compress device capabilities") + add_dev_args(p_caps) + p_caps.add_argument( + "--direction", + choices=("playback", "capture"), + default="playback", + help="Open mode / stream direction", + ) + p_caps.add_argument( + "--has-codec", + help="Exit 0 if codec is supported, 2 otherwise", + ) + p_caps.set_defaults(func=cmd_caps) + + p_play = subparsers.add_parser("play", help="Play compressed audio file") + add_dev_args(p_play) + p_play.add_argument("-C", "--codec", required=True, help="Codec name or hex id") + p_play.add_argument("-f", "--file", required=True, help="Compressed input file") + p_play.add_argument("-r", "--rate", type=int, default=48000, help="Sample rate") + p_play.add_argument("-n", "--channels", type=int, default=2, help="Channel count") + p_play.add_argument( + "-b", "--bitrate", type=int, default=None, help="Bitrate (bps, default per codec)" + ) + p_play.add_argument("--profile", type=int, default=None, help="Codec profile") + p_play.add_argument("--fmt", default="UNDEFINED", help="Codec format field") + p_play.add_argument("--frag-size", type=int, default=0, help="Buffer fragment size") + p_play.add_argument("--frags", type=int, default=0, help="Buffer fragment count") + p_play.add_argument( + "--bespoke", + choices=("auto", "always", "never"), + default="auto", + help="BESPOKE codec wrapper behavior", + ) + p_play.add_argument( + "--pause-resume", + type=int, + default=0, + help="Number of PAUSE/RESUME cycles during playback", + ) + p_play.add_argument( + "--timeout-ms", + type=int, + default=10000, + help="POLLOUT timeout in milliseconds", + ) + p_play.add_argument( + "--drain-timeout-ms", + type=int, + default=15000, + help="SNDRV_COMPRESS_DRAIN timeout in milliseconds (0 disables)", + ) + p_play.set_defaults(func=cmd_play) + + p_rec = subparsers.add_parser("record", help="Record compressed audio stream") + add_dev_args(p_rec) + p_rec.add_argument("-C", "--codec", required=True, help="Codec name or hex id") + p_rec.add_argument("-o", "--output", required=True, help="Output compressed file") + p_rec.add_argument("-t", "--duration", type=float, default=3.0, help="Duration (s)") + p_rec.add_argument("-r", "--rate", type=int, default=48000, help="Sample rate") + p_rec.add_argument("-n", "--channels", type=int, default=2, help="Channel count") + p_rec.add_argument( + "-b", "--bitrate", type=int, default=None, help="Bitrate (bps, default per codec)" + ) + p_rec.add_argument("--profile", type=int, default=None, help="Codec profile") + p_rec.add_argument("--fmt", default="UNDEFINED", help="Stream/PCM format (UNDEFINED/S16_LE/S32_LE)") + p_rec.add_argument("--frag-size", type=int, default=0, help="Buffer fragment size") + p_rec.add_argument("--frags", type=int, default=0, help="Buffer fragment count") + p_rec.add_argument("--max-bytes", type=int, default=0, help="Stop after N bytes") + p_rec.add_argument( + "--bespoke", + choices=("auto", "always", "never"), + default="auto", + help="BESPOKE codec wrapper behavior", + ) + p_rec.set_defaults(func=cmd_record) + + return parser.parse_args() + + +def main(): + """CLI entrypoint.""" + args = parse_args() + try: + return args.func(args) + except Exception as exc: # pylint: disable=broad-except + print(f"ERROR: {exc}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/sof-tplgreader.py b/tools/sof-tplgreader.py index c6c7d758..092c4696 100755 --- a/tools/sof-tplgreader.py +++ b/tools/sof-tplgreader.py @@ -1,8 +1,12 @@ #!/usr/bin/env python3 +import argparse +import re +import sys + from tplgtool import TplgParser, TplgFormatter from common import format_pipeline, export_pipeline -import re + class clsTPLGReader: def __init__(self): @@ -12,8 +16,8 @@ def __init__(self): self._filter_dict = {} self._block_lst = [] - def __comp_pipeline(self, pipeline): - return int(pipeline['id']) + def __comp_pipeline(self, item): + return int(item['id']) def _key2str(self, cap, key): return cap["%s_min" % (key)], cap["%s_max" % (key)] @@ -25,6 +29,74 @@ def attach_comp_to_pipeline(comps, comp_index, comp_name, pipeline_dict): comp_names = [i['name'] for i in comp] pipeline_dict[comp_name.lower()] = " ".join(comp_names) + def _build_pcm_entry(self, formatter, pcm): + pcm_type = TplgFormatter.get_pcm_type(pcm) + # if we find None type pcm, there must be errors in topology + if pcm_type == "None": + print("type of %s is neither playback nor capture, please check your" + "topology source file" % pcm["pcm_name"]) + sys.exit(1) + + comp_map = { + 'PGA': formatter.find_comp_for_pcm(pcm, 'PGA'), + 'EQ': formatter.find_comp_for_pcm(pcm, 'EQ'), + 'KPBM': formatter.find_comp_for_pcm(pcm, 'KPBM'), + 'kpb': formatter.find_comp_for_pcm(pcm, 'kpb'), + 'ASRC': formatter.find_comp_for_pcm(pcm, 'ASRC'), + 'CODEC_ADAPTER': formatter.find_comp_for_pcm(pcm, 'CODEC_ADAPTER'), + } + formats = TplgFormatter.get_pcm_fmt(pcm) + rates = TplgFormatter.get_pcm_rate_list(pcm) + + def make_entry(dir_idx, entry_type): + entry = { + 'pcm': pcm["pcm_name"], + 'id': str(pcm["pcm_id"]), + 'type': entry_type, + 'compress': str(pcm.get("compress", 0)), + } + cap = pcm["caps"][dir_idx] + entry['cap_name'] = cap['name'] + for comp_name, comps in comp_map.items(): + if dir_idx == 0 and comp_name in ('KPBM', 'kpb'): + continue + clsTPLGReader.attach_comp_to_pipeline(comps, dir_idx, comp_name, entry) + entry['fmts'] = " ".join(formats[dir_idx]) + entry['fmt'] = entry['fmts'].split(' ')[0] + entry['rates'] = " ".join(rates[dir_idx]) + entry['rate_min'], entry['rate_max'] = self._key2str(cap, 'rate') + entry['ch_min'], entry['ch_max'] = self._key2str(cap, 'channels') + return entry + + if pcm_type == "both": + self._pipeline_lst.append(make_entry(0, "playback")) + self._pipeline_lst.append(make_entry(pcm['capture'], "capture")) + else: + self._pipeline_lst.append(make_entry(pcm['capture'], pcm_type)) + + @staticmethod + def _finalize_pipeline_entry(entry, sofcard): + # If rates is available get first sampling rate from the list. + # If rates list doesn't have any, then get it from rate_min or rate_max. + # If none of them is available, then set rate to 0 + if entry['rates']: + entry['rate'] = entry['rates'].split(' ')[0] + elif int(entry['rate_min']) != 0: + entry['rate'] = entry['rate_min'] + elif int(entry['rate_max']) != 0: + entry['rate'] = entry['rate_max'] + else: + entry['rate'] = 0 + entry['channel'] = entry['ch_min'] + entry['dev'] = "hw:" + str(sofcard) + ',' + entry['id'] + if entry.get('compress') == '1': + entry['snd'] = "/dev/snd/comprC" + str(sofcard) + "D" + entry['id'] + else: + # the character devices for PCM under /dev/snd take the form of + # "pcmC + card_number + D + device_number + capability", eg, pcmC0D0p. + entry['snd'] = "/dev/snd/pcmC" + str(sofcard) + "D" + entry['id'] + entry['snd'] += 'p' if entry['type'] == "playback" else 'c' + # fork & split from TplgFormatter def loadFile(self, filename, sofcard=0): tplg_parser = TplgParser() @@ -35,88 +107,11 @@ def loadFile(self, filename, sofcard=0): if "pcm" not in item: continue for pcm in item['pcm']: - pcm_type = TplgFormatter.get_pcm_type(pcm) - # if we find None type pcm, there must be errors in topology - if pcm_type == "None": - print("type of %s is neither playback nor capture, please check your" - "topology source file" % pcm["pcm_name"]) - exit(1) - pgas = formatter.find_comp_for_pcm(pcm, 'PGA') - eqs = formatter.find_comp_for_pcm(pcm, 'EQ') - kwds = formatter.find_comp_for_pcm(pcm, 'KPBM') - kwds_ipc4 = formatter.find_comp_for_pcm(pcm, 'kpb') - asrcs = formatter.find_comp_for_pcm(pcm, 'ASRC') - codec_adapters = formatter.find_comp_for_pcm(pcm, 'CODEC_ADAPTER') - pipeline_dict = {} - pipeline_dict['pcm'] = pcm["pcm_name"] - pipeline_dict['id'] = str(pcm["pcm_id"]) - pipeline_dict['type'] = TplgFormatter.get_pcm_type(pcm) - cap = pcm["caps"][pcm['capture']] - pipeline_dict['cap_name'] = cap['name'] - # acquire component from pipeline graph, and add to pipeline dict - clsTPLGReader.attach_comp_to_pipeline(pgas, pcm['capture'], "PGA", pipeline_dict) - clsTPLGReader.attach_comp_to_pipeline(eqs, pcm['capture'], "EQ", pipeline_dict) - clsTPLGReader.attach_comp_to_pipeline(kwds, pcm['capture'], "KPBM", pipeline_dict) - clsTPLGReader.attach_comp_to_pipeline(kwds_ipc4, pcm['capture'], "kpb", pipeline_dict) - clsTPLGReader.attach_comp_to_pipeline(asrcs, pcm['capture'], "ASRC", pipeline_dict) - clsTPLGReader.attach_comp_to_pipeline(codec_adapters, pcm['capture'], "CODEC_ADAPTER", pipeline_dict) - # supported formats of playback pipeline in formats[0] - # supported formats of capture pipeline in formats[1] - formats = TplgFormatter.get_pcm_fmt(pcm) - rates = TplgFormatter.get_pcm_rate_list(pcm) - # if capture is present, pcm['capture'] = 1, otherwise, pcm['capture'] = 0, - # same thing for pcm['playback'] - pipeline_dict['fmts'] = " ".join(formats[pcm['capture']]) - # use the first supported format for test - pipeline_dict['fmt'] = pipeline_dict['fmts'].split(' ')[0] - pipeline_dict['rates'] = " ".join(rates[pcm['capture']]) - pipeline_dict['rate_min'], pipeline_dict['rate_max'] = self._key2str(cap, 'rate') - pipeline_dict['ch_min'], pipeline_dict['ch_max'] = self._key2str(cap, 'channels') - # for pcm with both playback and capture capabilities, we can extract two pipelines. - # the paramters for capture pipeline is filled above, and the parameters for playback - # pipeline is filled below. - if pcm_type == "both": - pipeline_dict["type"] = "capture" - # copy pipeline and change values - pb_pipeline_dict = pipeline_dict.copy() - pb_pipeline_dict["type"] = "playback" - cap = pcm["caps"][0] - pb_pipeline_dict['cap_name'] = cap['name'] - # with index = 0, we get parameters from playback pipeline - clsTPLGReader.attach_comp_to_pipeline(pgas, 0, "PGA", pb_pipeline_dict) - clsTPLGReader.attach_comp_to_pipeline(eqs, 0, "EQ", pb_pipeline_dict) - clsTPLGReader.attach_comp_to_pipeline(asrcs, 0, "ASRC", pb_pipeline_dict) - clsTPLGReader.attach_comp_to_pipeline(codec_adapters, 0, "CODEC_ADAPTER", pb_pipeline_dict) - pb_pipeline_dict["fmts"] = " ".join(formats[0]) - pb_pipeline_dict['fmt'] = pb_pipeline_dict['fmts'].split(' ')[0] - pb_pipeline_dict['rate_min'], pb_pipeline_dict['rate_max'] = self._key2str(cap, 'rate') - pb_pipeline_dict['ch_min'], pb_pipeline_dict['ch_max'] = self._key2str(cap, 'channels') - self._pipeline_lst.append(pb_pipeline_dict) - self._pipeline_lst.append(pipeline_dict) + self._build_pcm_entry(formatter, pcm) # format pipeline, this change for script direct access 'rate' 'channel' 'dev' 'snd' - for pipeline in self._pipeline_lst: - #pipeline['fmt']=pipeline['fmt'].upper().replace('LE', '_LE') - # If rates is available get first sampling rate from the list. - # If rates list doesn't have any, then get it from rate_min or rate_max. - # If none of them is available, then set rate to 0 - if pipeline['rates']: - pipeline['rate'] = pipeline['rates'].split(' ')[0] - elif int(pipeline['rate_min']) != 0: - pipeline['rate'] = pipeline['rate_min'] - elif int(pipeline['rate_max']) != 0: - pipeline['rate'] = pipeline['rate_max'] - else: - pipeline['rate'] = 0 - pipeline['channel'] = pipeline['ch_min'] - pipeline['dev'] = "hw:" + str(sofcard) + ',' + pipeline['id'] - # the character devices for PCM under /dev/snd take the form of - # "pcmC + card_number + D + device_number + capability", eg, pcmC0D0p. - pipeline['snd'] = "/dev/snd/pcmC" + str(sofcard) + "D" + pipeline['id'] - if pipeline['type'] == "playback": - pipeline['snd'] += 'p' - else: - pipeline['snd'] += 'c' + for entry in self._pipeline_lst: + self._finalize_pipeline_entry(entry, sofcard) return 0 # The following functions re-implement built-in Python sets @@ -185,14 +180,14 @@ def _filterOutput(self, pipelines, filter_dict, bIn): # single key:value and then the break/else is pure confusion. for key, value in filter_dict.items(): if 'any' in value or value == ['']: - check = True if key in line.keys() else False + check = key in line else: # Use full match for numerical values, and use substring # match for string values if str(line[key]).isdigit(): check = str(line[key]) in value else: - check = any([em in str(line[key]) for em in value]) + check = any(em in str(line[key]) for em in value) if check is bIn: break else: @@ -266,45 +261,46 @@ def getPipeline(self, sort=False): self.sortPipeline() return self._output_lst -if __name__ == "__main__": - - def func_getPipeline(tplgObj, tplgName, sdcard_id, sort): - if tplgObj.loadFile(tplgName, sdcard_id) != 0: - print("tplgreader load file %s failed" %(tplgName)) - exit(1) - return tplgObj.getPipeline(sort) - - def parse_filter(filter_str): - """Parse filter input into two structures, one is dict list for each - filter item, and another is logic operation list. For example - "id:2 | pga & id:1" is parsed as: - - { 'filter': [ {'id': ['2']}, {'pga': ['']}, {'id': ['1']} ], - 'op': [ '|', '&' ] - } - """ - filter_lst = [] - op_lst = [] - for filter_elem in filter_str.split('|'): - for item in filter_elem.split('&'): - key, _, value = item.partition(':') - filter_lst.append({key.strip():value.strip().split(',')}) - for char in filter_str: - if char == '|' or char == "&": - op_lst.append(char) - return dict(zip(['filter', 'op'], [filter_lst, op_lst])) - - def parse_and_set_block_keyword(block_str, tplgreader): - block_list = [] - block_strs = block_str.split(';') - block_items = [item.strip() for item in block_strs if item != ""] - for item in block_items: - block_list.append(parse_filter(item)) - tplgreader.setBlock(block_list) - - import argparse - - parser = argparse.ArgumentParser(description='Filters and prints PCMs found in a .tplg file', +def func_getPipeline(tplgObj, tplgName, sdcard_id, sort): + if tplgObj.loadFile(tplgName, sdcard_id) != 0: + print("tplgreader load file %s failed" % (tplgName)) + sys.exit(1) + return tplgObj.getPipeline(sort) + + +def parse_filter(filter_str): + """Parse filter input into two structures, one is dict list for each + filter item, and another is logic operation list. For example + "id:2 | pga & id:1" is parsed as: + + { 'filter': [ {'id': ['2']}, {'pga': ['']}, {'id': ['1']} ], + 'op': [ '|', '&' ] + } + """ + filter_lst = [] + op_lst = [] + for filter_elem in filter_str.split('|'): + for item in filter_elem.split('&'): + key, _, value = item.partition(':') + filter_lst.append({key.strip(): value.strip().split(',')}) + for char in filter_str: + if char in ('|', '&'): + op_lst.append(char) + return dict(zip(['filter', 'op'], [filter_lst, op_lst])) + + +def parse_and_set_block_keyword(block_str, tplgreader): + block_list = [] + block_strs = block_str.split(';') + block_items = [item.strip() for item in block_strs if item != ""] + for item in block_items: + block_list.append(parse_filter(item)) + tplgreader.setBlock(block_list) + + +def _build_arg_parser(): + parser = argparse.ArgumentParser( + description='Filters and prints PCMs found in a .tplg file', add_help=True, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('filename', type=str, help='tplg file name, multi-tplg file name use "," to split it') @@ -351,59 +347,49 @@ def parse_and_set_block_keyword(block_str, tplgreader): parser.add_argument('-t', '--tplgroot', type=str, help="load file from tplg-root folder") parser.add_argument('-o', '--sort', action='store_true', help="sort pipeline by id for the same tplg") parser.add_argument('--version', action='version', version='%(prog)s 1.0') + return parser + + +def _print_pipeline_output(ret_args, pipeline_lst): + if ret_args['export'] is True: + sys.exit(export_pipeline(pipeline_lst)) + if ret_args['count'] is True: + msg = len(pipeline_lst) if ret_args['value'] else "Pipeline Count: %d" % len(pipeline_lst) + print(msg) + return + if ret_args['index'] is not None and ret_args['index'] < len(pipeline_lst): + print(format_pipeline(pipeline_lst[ret_args['index']], ret_args['value'])) + return + for entry in pipeline_lst: + print(format_pipeline(entry, ret_args['value'])) - ret_args = vars(parser.parse_args()) +def main(): + ret_args = vars(_build_arg_parser().parse_args()) tplgreader = clsTPLGReader() - dump_lst = [] - pipeline_lst = [] - tplg_root = "" - - # parse and set filter keyword - if ret_args['filter'] is not None and len(ret_args['filter']) > 0: - filter_dict = parse_filter(ret_args['filter']) - tplgreader.setFilter(filter_dict) - - # If run general test case on WOV pipeline or ECHO REFERENCE capture pipeline, there will be error - # due to no feed data, and they should be blocked in general test case. - default_block_keyword = 'kpbm:any;kpb:any;type:capture & echo;' - # if no filter or block item is specified, the "block_none" here will help to - # block nothing - block_str = "block_none" - # user specified block items from command line - cmd_block_str = ret_args['block'].strip() if ret_args['block'] is not None else '' - if ret_args["filter"] is not None and not re.search('echo|kpb', ret_args["filter"]): + if ret_args['filter']: + tplgreader.setFilter(parse_filter(ret_args['filter'])) + + default_block_keyword = 'kpbm:any;kpb:any;type:capture & echo;compress:1;' + cmd_block_str = ret_args['block'].strip() if ret_args['block'] is not None else '' + if ret_args["filter"] is not None and not re.search('echo|kpb|compress', ret_args["filter"]): block_str = default_block_keyword + cmd_block_str else: - block_str = cmd_block_str if cmd_block_str != '' else block_str - + block_str = cmd_block_str or "block_none" parse_and_set_block_keyword(block_str, tplgreader) - if ret_args['dump'] is not None and len(ret_args['dump']) > 0: - dump_lst = ret_args['dump'] - - if len(dump_lst) > 0: - tplgreader.setField(dump_lst) + if ret_args['dump']: + tplgreader.setField(ret_args['dump']) - if ret_args['tplgroot'] is not None and len(ret_args['tplgroot']) >0: - tplg_root = ret_args['tplgroot'] + tplg_root = ret_args['tplgroot'] or "" + pipeline_lst = [] + for fname in ret_args['filename'].split(','): + path = f"{tplg_root}/{fname}" if tplg_root else fname + pipeline_lst += func_getPipeline(tplgreader, path, ret_args['sofcard'], ret_args['sort'])[:] - for f in ret_args['filename'].split(','): - if len(tplg_root) > 0: - f = tplg_root + "/" + f - pipeline_lst += func_getPipeline(tplgreader, f, ret_args['sofcard'], ret_args['sort'])[:] + _print_pipeline_output(ret_args, pipeline_lst) - if ret_args['export'] is True: - exit(export_pipeline(pipeline_lst)) - if ret_args['count'] is True: - if ret_args['value'] is True: - print(len(pipeline_lst)) - else: - print("Pipeline Count: %d" % (len(pipeline_lst))) - elif ret_args['index'] is not None and ret_args['index'] < len(pipeline_lst): - print(format_pipeline(pipeline_lst[ret_args['index']], ret_args['value'])) - else: - for pipeline in pipeline_lst: - print(format_pipeline(pipeline, ret_args['value'])) +if __name__ == "__main__": + main()