diff --git a/openpilot/selfdrive/ui/translations/app.pot b/openpilot/selfdrive/ui/translations/app.pot index 783ceba9d3..3d956c7e54 100644 --- a/openpilot/selfdrive/ui/translations/app.pot +++ b/openpilot/selfdrive/ui/translations/app.pot @@ -23495,6 +23495,10 @@ msgstr "" msgid "Plays a simulated engine on the car speakers that follows the accelerator pedal, including revving in Park or Neutral. Uses the audio output chosen under Spotify and Phone Audio, and goes quiet while an alert sounds." msgstr "" +#: openpilot/starpilot/engine_sound/profiles.py +msgid "BMW M3" +msgstr "" + #: openpilot/starpilot/engine_sound/profiles.py msgid "BMW M52" msgstr "" @@ -23507,6 +23511,14 @@ msgstr "" msgid "Ferrari F136" msgstr "" +#: openpilot/starpilot/engine_sound/profiles.py +msgid "Hellcat" +msgstr "" + +#: openpilot/starpilot/engine_sound/profiles.py +msgid "Mustang GT" +msgstr "" + #: openpilot/starpilot/engine_sound/profiles.py msgid "LFA" msgstr "" diff --git a/openpilot/selfdrive/ui/translations/app_de.po b/openpilot/selfdrive/ui/translations/app_de.po index f51ca4633a..6849f0d306 100644 --- a/openpilot/selfdrive/ui/translations/app_de.po +++ b/openpilot/selfdrive/ui/translations/app_de.po @@ -23514,6 +23514,10 @@ msgstr "Legt die Lautstärke des Motors vor der Lautstärkeregelung des Fahrzeug msgid "Plays a simulated engine on the car speakers that follows the accelerator pedal, including revving in Park or Neutral. Uses the audio output chosen under Spotify and Phone Audio, and goes quiet while an alert sounds." msgstr "Spielt über die Fahrzeuglautsprecher einen simulierten Motor ab, der dem Gaspedal folgt, auch beim Hochdrehen in Parkstellung oder Neutral. Nutzt die unter Spotify und Telefon-Audio gewählte Audioausgabe und verstummt, solange ein Warnton ertönt." +#: openpilot/starpilot/engine_sound/profiles.py +msgid "BMW M3" +msgstr "BMW M3" + #: openpilot/starpilot/engine_sound/profiles.py msgid "BMW M52" msgstr "BMW M52" @@ -23526,6 +23530,14 @@ msgstr "F1 Car" msgid "Ferrari F136" msgstr "Ferrari F136" +#: openpilot/starpilot/engine_sound/profiles.py +msgid "Hellcat" +msgstr "Hellcat" + +#: openpilot/starpilot/engine_sound/profiles.py +msgid "Mustang GT" +msgstr "Mustang GT" + #: openpilot/starpilot/engine_sound/profiles.py msgid "LFA" msgstr "LFA" diff --git a/openpilot/selfdrive/ui/translations/app_es.po b/openpilot/selfdrive/ui/translations/app_es.po index 6ef39e7822..827195d8a0 100644 --- a/openpilot/selfdrive/ui/translations/app_es.po +++ b/openpilot/selfdrive/ui/translations/app_es.po @@ -23514,6 +23514,10 @@ msgstr "Ajusta el volumen del motor antes del control de volumen del propio coch msgid "Plays a simulated engine on the car speakers that follows the accelerator pedal, including revving in Park or Neutral. Uses the audio output chosen under Spotify and Phone Audio, and goes quiet while an alert sounds." msgstr "Reproduce un motor simulado en los altavoces del coche que sigue el pedal del acelerador, incluso al acelerar en Estacionamiento o Punto muerto. Usa la salida de audio elegida en Spotify y audio del teléfono, y se silencia mientras suena una alerta." +#: openpilot/starpilot/engine_sound/profiles.py +msgid "BMW M3" +msgstr "BMW M3" + #: openpilot/starpilot/engine_sound/profiles.py msgid "BMW M52" msgstr "BMW M52" @@ -23526,6 +23530,14 @@ msgstr "F1 Car" msgid "Ferrari F136" msgstr "Ferrari F136" +#: openpilot/starpilot/engine_sound/profiles.py +msgid "Hellcat" +msgstr "Hellcat" + +#: openpilot/starpilot/engine_sound/profiles.py +msgid "Mustang GT" +msgstr "Mustang GT" + #: openpilot/starpilot/engine_sound/profiles.py msgid "LFA" msgstr "LFA" diff --git a/openpilot/selfdrive/ui/translations/app_fr.po b/openpilot/selfdrive/ui/translations/app_fr.po index beea05711b..103b0aa518 100644 --- a/openpilot/selfdrive/ui/translations/app_fr.po +++ b/openpilot/selfdrive/ui/translations/app_fr.po @@ -23514,6 +23514,10 @@ msgstr "Règle le volume du moteur avant le réglage de volume de la voiture." msgid "Plays a simulated engine on the car speakers that follows the accelerator pedal, including revving in Park or Neutral. Uses the audio output chosen under Spotify and Phone Audio, and goes quiet while an alert sounds." msgstr "Diffuse un moteur simulé sur les haut-parleurs de la voiture qui suit la pédale d'accélérateur, y compris les montées en régime en Parking ou au Point mort. Utilise la sortie audio choisie dans Spotify et audio du téléphone, et se tait pendant une alerte." +#: openpilot/starpilot/engine_sound/profiles.py +msgid "BMW M3" +msgstr "BMW M3" + #: openpilot/starpilot/engine_sound/profiles.py msgid "BMW M52" msgstr "BMW M52" @@ -23526,6 +23530,14 @@ msgstr "F1 Car" msgid "Ferrari F136" msgstr "Ferrari F136" +#: openpilot/starpilot/engine_sound/profiles.py +msgid "Hellcat" +msgstr "Hellcat" + +#: openpilot/starpilot/engine_sound/profiles.py +msgid "Mustang GT" +msgstr "Mustang GT" + #: openpilot/starpilot/engine_sound/profiles.py msgid "LFA" msgstr "LFA" diff --git a/openpilot/selfdrive/ui/translations/app_ja.po b/openpilot/selfdrive/ui/translations/app_ja.po index dc49d7e188..72818dbcd4 100644 --- a/openpilot/selfdrive/ui/translations/app_ja.po +++ b/openpilot/selfdrive/ui/translations/app_ja.po @@ -23510,6 +23510,10 @@ msgstr "車側の音量調整の前に、エンジン音の大きさを設定し msgid "Plays a simulated engine on the car speakers that follows the accelerator pedal, including revving in Park or Neutral. Uses the audio output chosen under Spotify and Phone Audio, and goes quiet while an alert sounds." msgstr "アクセルペダルに合わせて、車のスピーカーで疑似エンジン音を再生します。パーキングやニュートラルでの空ぶかしにも対応します。「Spotifyとスマホ音声」で選んだ音声出力を使い、警告音が鳴っている間は消音します。" +#: openpilot/starpilot/engine_sound/profiles.py +msgid "BMW M3" +msgstr "BMW M3" + #: openpilot/starpilot/engine_sound/profiles.py msgid "BMW M52" msgstr "BMW M52" @@ -23522,6 +23526,14 @@ msgstr "F1 Car" msgid "Ferrari F136" msgstr "Ferrari F136" +#: openpilot/starpilot/engine_sound/profiles.py +msgid "Hellcat" +msgstr "Hellcat" + +#: openpilot/starpilot/engine_sound/profiles.py +msgid "Mustang GT" +msgstr "Mustang GT" + #: openpilot/starpilot/engine_sound/profiles.py msgid "LFA" msgstr "LFA" diff --git a/openpilot/selfdrive/ui/translations/app_ko.po b/openpilot/selfdrive/ui/translations/app_ko.po index 88c2d08e41..3f0cd05488 100644 --- a/openpilot/selfdrive/ui/translations/app_ko.po +++ b/openpilot/selfdrive/ui/translations/app_ko.po @@ -23510,6 +23510,10 @@ msgstr "차량 자체 음량 조절 전에 엔진 소리 크기를 설정합니 msgid "Plays a simulated engine on the car speakers that follows the accelerator pedal, including revving in Park or Neutral. Uses the audio output chosen under Spotify and Phone Audio, and goes quiet while an alert sounds." msgstr "가속 페달에 맞춰 차량 스피커로 가상 엔진 소리를 재생하며, P 또는 N에서 공회전 레브도 지원합니다. Spotify 및 휴대폰 오디오에서 선택한 오디오 출력을 사용하며, 경고음이 울리는 동안에는 소리가 꺼집니다." +#: openpilot/starpilot/engine_sound/profiles.py +msgid "BMW M3" +msgstr "BMW M3" + #: openpilot/starpilot/engine_sound/profiles.py msgid "BMW M52" msgstr "BMW M52" @@ -23522,6 +23526,14 @@ msgstr "F1 Car" msgid "Ferrari F136" msgstr "Ferrari F136" +#: openpilot/starpilot/engine_sound/profiles.py +msgid "Hellcat" +msgstr "Hellcat" + +#: openpilot/starpilot/engine_sound/profiles.py +msgid "Mustang GT" +msgstr "Mustang GT" + #: openpilot/starpilot/engine_sound/profiles.py msgid "LFA" msgstr "LFA" diff --git a/openpilot/selfdrive/ui/translations/app_vi.po b/openpilot/selfdrive/ui/translations/app_vi.po index 7821cc3455..ae7a0dd638 100644 --- a/openpilot/selfdrive/ui/translations/app_vi.po +++ b/openpilot/selfdrive/ui/translations/app_vi.po @@ -23510,6 +23510,10 @@ msgstr "Đặt độ lớn của âm thanh động cơ trước núm âm lượn msgid "Plays a simulated engine on the car speakers that follows the accelerator pedal, including revving in Park or Neutral. Uses the audio output chosen under Spotify and Phone Audio, and goes quiet while an alert sounds." msgstr "Phát âm thanh động cơ mô phỏng trên loa xe theo bàn đạp ga, kể cả khi rồ ga ở số P hoặc N. Dùng đầu ra âm thanh đã chọn trong Spotify và âm thanh điện thoại, và tắt tiếng khi có cảnh báo." +#: openpilot/starpilot/engine_sound/profiles.py +msgid "BMW M3" +msgstr "BMW M3" + #: openpilot/starpilot/engine_sound/profiles.py msgid "BMW M52" msgstr "BMW M52" @@ -23522,6 +23526,14 @@ msgstr "F1 Car" msgid "Ferrari F136" msgstr "Ferrari F136" +#: openpilot/starpilot/engine_sound/profiles.py +msgid "Hellcat" +msgstr "Hellcat" + +#: openpilot/starpilot/engine_sound/profiles.py +msgid "Mustang GT" +msgstr "Mustang GT" + #: openpilot/starpilot/engine_sound/profiles.py msgid "LFA" msgstr "LFA" diff --git a/openpilot/starpilot/engine_sound/banks/LICENSE b/openpilot/starpilot/engine_sound/banks/LICENSE index 91389b622b..63f39472a5 100644 --- a/openpilot/starpilot/engine_sound/banks/LICENSE +++ b/openpilot/starpilot/engine_sound/banks/LICENSE @@ -9,6 +9,12 @@ commit 85f7c3b959a908ed5232ede4f1a4ac7eafe6b630), recorded with tools/esrec: ferrari_f136 assets/engines/atg-video-2/08_ferrari_f136_v8.mr lfa assets/engines/atg-video-2/10_lfa_v10.mr +From recordings of real cars supplied for this project, built with tools/bank_from_recording.py and equalised with +tools/lower_bank.py --pitch 1.0 --off-mix 0 --off-mid 0: + + hellcat hellcat.wav: --cylinders 8 --anchor 14 700 --idle 10.5-17.5 --on 25-94 --off 94-119 + mustang_gt mustanggt.wav: --cylinders 8 --half-orders --anchor 16.5 3456 --on 12.4-33.2 + engine-sim is distributed under the following license: MIT License diff --git a/openpilot/starpilot/engine_sound/banks/hellcat/bank.json b/openpilot/starpilot/engine_sound/banks/hellcat/bank.json new file mode 100644 index 0000000000..dff5acfc58 --- /dev/null +++ b/openpilot/starpilot/engine_sound/banks/hellcat/bank.json @@ -0,0 +1,98 @@ +{ + "version": 1, + "source": "recording hellcat.wav", + "layers": { + "off": [ + { + "rpm": 704, + "file": "off_704.wav" + }, + { + "rpm": 750, + "file": "off_750.wav" + }, + { + "rpm": 1000, + "file": "off_1000.wav" + }, + { + "rpm": 1250, + "file": "off_1250.wav" + }, + { + "rpm": 1500, + "file": "off_1500.wav" + }, + { + "rpm": 1750, + "file": "off_1750.wav" + }, + { + "rpm": 2000, + "file": "off_2000.wav" + }, + { + "rpm": 2250, + "file": "off_2250.wav" + }, + { + "rpm": 2500, + "file": "off_2500.wav" + }, + { + "rpm": 2750, + "file": "off_2750.wav" + }, + { + "rpm": 3000, + "file": "off_3000.wav" + } + ], + "on": [ + { + "rpm": 704, + "file": "on_704.wav" + }, + { + "rpm": 750, + "file": "on_750.wav" + }, + { + "rpm": 1000, + "file": "on_1000.wav" + }, + { + "rpm": 1250, + "file": "on_1250.wav" + }, + { + "rpm": 1500, + "file": "on_1500.wav" + }, + { + "rpm": 1750, + "file": "on_1750.wav" + }, + { + "rpm": 2000, + "file": "on_2000.wav" + }, + { + "rpm": 2250, + "file": "on_2250.wav" + }, + { + "rpm": 2500, + "file": "on_2500.wav" + }, + { + "rpm": 2750, + "file": "on_2750.wav" + }, + { + "rpm": 3000, + "file": "on_3000.wav" + } + ] + } +} diff --git a/openpilot/starpilot/engine_sound/banks/hellcat/off_1000.wav b/openpilot/starpilot/engine_sound/banks/hellcat/off_1000.wav new file mode 100644 index 0000000000..0a19206983 Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/hellcat/off_1000.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/hellcat/off_1250.wav b/openpilot/starpilot/engine_sound/banks/hellcat/off_1250.wav new file mode 100644 index 0000000000..b5bbb2f84b Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/hellcat/off_1250.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/hellcat/off_1500.wav b/openpilot/starpilot/engine_sound/banks/hellcat/off_1500.wav new file mode 100644 index 0000000000..4d1d1db241 Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/hellcat/off_1500.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/hellcat/off_1750.wav b/openpilot/starpilot/engine_sound/banks/hellcat/off_1750.wav new file mode 100644 index 0000000000..a6db545b4d Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/hellcat/off_1750.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/hellcat/off_2000.wav b/openpilot/starpilot/engine_sound/banks/hellcat/off_2000.wav new file mode 100644 index 0000000000..e627115a25 Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/hellcat/off_2000.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/hellcat/off_2250.wav b/openpilot/starpilot/engine_sound/banks/hellcat/off_2250.wav new file mode 100644 index 0000000000..0721145bc0 Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/hellcat/off_2250.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/hellcat/off_2500.wav b/openpilot/starpilot/engine_sound/banks/hellcat/off_2500.wav new file mode 100644 index 0000000000..23e389f124 Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/hellcat/off_2500.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/hellcat/off_2750.wav b/openpilot/starpilot/engine_sound/banks/hellcat/off_2750.wav new file mode 100644 index 0000000000..e029f87e7c Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/hellcat/off_2750.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/hellcat/off_3000.wav b/openpilot/starpilot/engine_sound/banks/hellcat/off_3000.wav new file mode 100644 index 0000000000..902981b771 Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/hellcat/off_3000.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/hellcat/off_704.wav b/openpilot/starpilot/engine_sound/banks/hellcat/off_704.wav new file mode 100644 index 0000000000..27ebcb568e Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/hellcat/off_704.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/hellcat/off_750.wav b/openpilot/starpilot/engine_sound/banks/hellcat/off_750.wav new file mode 100644 index 0000000000..ebb6880544 Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/hellcat/off_750.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/hellcat/on_1000.wav b/openpilot/starpilot/engine_sound/banks/hellcat/on_1000.wav new file mode 100644 index 0000000000..804bd62146 Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/hellcat/on_1000.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/hellcat/on_1250.wav b/openpilot/starpilot/engine_sound/banks/hellcat/on_1250.wav new file mode 100644 index 0000000000..dbbf42d5d3 Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/hellcat/on_1250.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/hellcat/on_1500.wav b/openpilot/starpilot/engine_sound/banks/hellcat/on_1500.wav new file mode 100644 index 0000000000..a8b8e6fcde Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/hellcat/on_1500.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/hellcat/on_1750.wav b/openpilot/starpilot/engine_sound/banks/hellcat/on_1750.wav new file mode 100644 index 0000000000..ad78b70338 Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/hellcat/on_1750.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/hellcat/on_2000.wav b/openpilot/starpilot/engine_sound/banks/hellcat/on_2000.wav new file mode 100644 index 0000000000..c2dc6ffcb7 Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/hellcat/on_2000.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/hellcat/on_2250.wav b/openpilot/starpilot/engine_sound/banks/hellcat/on_2250.wav new file mode 100644 index 0000000000..2d4bcc2d91 Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/hellcat/on_2250.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/hellcat/on_2500.wav b/openpilot/starpilot/engine_sound/banks/hellcat/on_2500.wav new file mode 100644 index 0000000000..442e5f31e0 Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/hellcat/on_2500.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/hellcat/on_2750.wav b/openpilot/starpilot/engine_sound/banks/hellcat/on_2750.wav new file mode 100644 index 0000000000..2d0c37fc4f Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/hellcat/on_2750.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/hellcat/on_3000.wav b/openpilot/starpilot/engine_sound/banks/hellcat/on_3000.wav new file mode 100644 index 0000000000..d3653dcc29 Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/hellcat/on_3000.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/hellcat/on_704.wav b/openpilot/starpilot/engine_sound/banks/hellcat/on_704.wav new file mode 100644 index 0000000000..709f83275d Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/hellcat/on_704.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/hellcat/on_750.wav b/openpilot/starpilot/engine_sound/banks/hellcat/on_750.wav new file mode 100644 index 0000000000..f9379b7333 Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/hellcat/on_750.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/mustang_gt/bank.json b/openpilot/starpilot/engine_sound/banks/mustang_gt/bank.json new file mode 100644 index 0000000000..e793dbd189 --- /dev/null +++ b/openpilot/starpilot/engine_sound/banks/mustang_gt/bank.json @@ -0,0 +1,52 @@ +{ + "version": 1, + "source": "recording mustanggt.wav", + "layers": { + "on": [ + { + "rpm": 1500, + "file": "on_1500.wav" + }, + { + "rpm": 1750, + "file": "on_1750.wav" + }, + { + "rpm": 2000, + "file": "on_2000.wav" + }, + { + "rpm": 2250, + "file": "on_2250.wav" + }, + { + "rpm": 2500, + "file": "on_2500.wav" + }, + { + "rpm": 2750, + "file": "on_2750.wav" + }, + { + "rpm": 3000, + "file": "on_3000.wav" + }, + { + "rpm": 3250, + "file": "on_3250.wav" + }, + { + "rpm": 3500, + "file": "on_3500.wav" + }, + { + "rpm": 3750, + "file": "on_3750.wav" + }, + { + "rpm": 4000, + "file": "on_4000.wav" + } + ] + } +} diff --git a/openpilot/starpilot/engine_sound/banks/mustang_gt/on_1500.wav b/openpilot/starpilot/engine_sound/banks/mustang_gt/on_1500.wav new file mode 100644 index 0000000000..76cf856ce1 Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/mustang_gt/on_1500.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/mustang_gt/on_1750.wav b/openpilot/starpilot/engine_sound/banks/mustang_gt/on_1750.wav new file mode 100644 index 0000000000..dd6f3433cf Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/mustang_gt/on_1750.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/mustang_gt/on_2000.wav b/openpilot/starpilot/engine_sound/banks/mustang_gt/on_2000.wav new file mode 100644 index 0000000000..65218f2507 Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/mustang_gt/on_2000.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/mustang_gt/on_2250.wav b/openpilot/starpilot/engine_sound/banks/mustang_gt/on_2250.wav new file mode 100644 index 0000000000..dbb13d65fb Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/mustang_gt/on_2250.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/mustang_gt/on_2500.wav b/openpilot/starpilot/engine_sound/banks/mustang_gt/on_2500.wav new file mode 100644 index 0000000000..e3ed68b09b Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/mustang_gt/on_2500.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/mustang_gt/on_2750.wav b/openpilot/starpilot/engine_sound/banks/mustang_gt/on_2750.wav new file mode 100644 index 0000000000..ea6b3cf6d4 Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/mustang_gt/on_2750.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/mustang_gt/on_3000.wav b/openpilot/starpilot/engine_sound/banks/mustang_gt/on_3000.wav new file mode 100644 index 0000000000..221b5038e6 Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/mustang_gt/on_3000.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/mustang_gt/on_3250.wav b/openpilot/starpilot/engine_sound/banks/mustang_gt/on_3250.wav new file mode 100644 index 0000000000..71643d4d75 Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/mustang_gt/on_3250.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/mustang_gt/on_3500.wav b/openpilot/starpilot/engine_sound/banks/mustang_gt/on_3500.wav new file mode 100644 index 0000000000..4b4ead684e Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/mustang_gt/on_3500.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/mustang_gt/on_3750.wav b/openpilot/starpilot/engine_sound/banks/mustang_gt/on_3750.wav new file mode 100644 index 0000000000..96a6e2a398 Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/mustang_gt/on_3750.wav differ diff --git a/openpilot/starpilot/engine_sound/banks/mustang_gt/on_4000.wav b/openpilot/starpilot/engine_sound/banks/mustang_gt/on_4000.wav new file mode 100644 index 0000000000..825eb75e70 Binary files /dev/null and b/openpilot/starpilot/engine_sound/banks/mustang_gt/on_4000.wav differ diff --git a/openpilot/starpilot/engine_sound/loops.py b/openpilot/starpilot/engine_sound/loops.py index 13b7e0da6a..70132059cd 100644 --- a/openpilot/starpilot/engine_sound/loops.py +++ b/openpilot/starpilot/engine_sound/loops.py @@ -13,6 +13,7 @@ from pathlib import Path import numpy as np +from openpilot.starpilot.engine_sound.pops import Pops from openpilot.starpilot.engine_sound.profiles import Profile from openpilot.starpilot.engine_sound.synth import SAMPLE_RATE @@ -86,6 +87,7 @@ class LoopSynth: self.rpm = profile.idle_rpm self.load = 0.0 self.gain = 0.0 + self.pops = Pops(profile.pops, profile.idle_rpm, profile.redline_rpm, sample_rate) if profile.pops else None def _layer(self, layer: str, rpm: np.ndarray) -> np.ndarray: points, loops = self.bank[layer] @@ -123,4 +125,7 @@ class LoopSynth: off = self._layer('off', rpm_ramp) out = on * np.sqrt(load_ramp) + off * np.sqrt(1 - load_ramp) self.rpm, self.load, self.gain = rpm, load, target_gain - return np.tanh(out * gain).astype(np.float32) + out = out * gain + if self.pops is not None: + out = out + self.pops.render(rpm, load, frames, volume) + return np.tanh(out).astype(np.float32) diff --git a/openpilot/starpilot/engine_sound/pops.py b/openpilot/starpilot/engine_sound/pops.py new file mode 100644 index 0000000000..cb49683e12 --- /dev/null +++ b/openpilot/starpilot/engine_sound/pops.py @@ -0,0 +1,142 @@ +"""Overrun exhaust pops: burble, pops and crackle after a lift from load at speed, and on downshift blips. + +Each pop is a one-shot from a library built once at start; firing only mixes samples, so the cost per block is small. +""" +from __future__ import annotations + +import numpy as np + +from openpilot.starpilot.engine_sound.synth import SAMPLE_RATE + +LIBRARY_SIZE = 12 # per kind +LIFT_FROM = 0.2 # load a lift must come down from +OVERRUN = 0.08 # at or below this load the engine is on overrun +RESUME = 0.15 # back on the throttle ends the pops +MIN_RPM_SHARE = 0.2 # share of redline below which nothing pops; coast-down downshifts land just above it +WINDOW_SECONDS = (0.7, 2.4) # pop window after a lift, short at low revs and long from high revs and full load +BLIP_RPM_PER_SECOND = 1500.0 # rpm climbing this fast with no load is a downshift blip +BLIP_EXTEND_SECONDS = 0.6 +# Matched to a recording of a real M3 on overrun: 10-15 short thumps a second centred near 350 Hz, +# about 8 dB over the engine, half gone within 5 ms, and almost nothing above 1 kHz. +RATE = 14.0 # pops per second at the start of a strong window +KINDS = ('burble', 'pop', 'crackle') +KIND_SHARES = (0.45, 0.35, 0.2) +LEVEL = 0.3 +TOP_HZ = 1400.0 + + +def _resonator(excitation: np.ndarray, frequency: float, q: float, sample_rate: int) -> np.ndarray: + """Two-pole band-pass applied in the frequency domain; padding keeps the decay from wrapping.""" + size = 1 << int(np.ceil(np.log2(len(excitation) * 2))) + w = 2 * np.pi * np.fft.rfftfreq(size, 1 / sample_rate) / sample_rate + w0 = 2 * np.pi * frequency / sample_rate + alpha = np.sin(w0) / (2 * q) + z = np.exp(-1j * w) + response = (alpha - alpha * z ** 2) / ((1 + alpha) - 2 * np.cos(w0) * z + (1 - alpha) * z ** 2) + return np.fft.irfft(np.fft.rfft(excitation, size) * response, size)[:len(excitation)] + + +def _low_pass(sample: np.ndarray, sample_rate: int) -> np.ndarray: + size = 1 << int(np.ceil(np.log2(len(sample) * 2))) + freq = np.fft.rfftfreq(size, 1 / sample_rate) + return np.fft.irfft(np.fft.rfft(sample, size) / np.sqrt(1 + (freq / TOP_HZ) ** 8), size)[:len(sample)] + + +def _normalised(sample: np.ndarray, sample_rate: int) -> np.ndarray: + sample = _low_pass(sample, sample_rate) + fade = np.ones(len(sample)) + fade[-64:] = np.linspace(1.0, 0.0, 64) + sample = sample * fade + return (sample / np.max(np.abs(sample))).astype(np.float32) + + +def _thump(rng: np.random.Generator, sample_rate: int, centre: tuple[float, float], decay: tuple[float, float]) -> np.ndarray: + length = int(0.08 * sample_rate) + t = np.arange(length) / sample_rate + burst = rng.standard_normal(length) * np.exp(-t / rng.uniform(*decay)) + return _resonator(burst, rng.uniform(*centre), rng.uniform(1.5, 3.0), sample_rate) + + +def _crackle(rng: np.random.Generator, sample_rate: int) -> np.ndarray: + """A quick run of small pops, 25-60 ms apart as in the recording's densest stretches.""" + length = int(0.2 * sample_rate) + out = np.zeros(length) + at = 0 + for _ in range(rng.integers(2, 5)): + pop = _thump(rng, sample_rate, (300.0, 700.0), (0.002, 0.005)) * rng.uniform(0.4, 1.0) + if at + len(pop) > length: + break + out[at:at + len(pop)] += pop + at += int(rng.uniform(0.025, 0.06) * sample_rate) + return _normalised(out, sample_rate) + + +def library(sample_rate: int = SAMPLE_RATE, seed: int = 3) -> dict[str, list[np.ndarray]]: + rng = np.random.default_rng(seed) + return {'burble': [_normalised(_thump(rng, sample_rate, (180.0, 320.0), (0.006, 0.012)), sample_rate) for _ in range(LIBRARY_SIZE)], + 'pop': [_normalised(_thump(rng, sample_rate, (300.0, 480.0), (0.003, 0.007)), sample_rate) for _ in range(LIBRARY_SIZE)], + 'crackle': [_crackle(rng, sample_rate) for _ in range(LIBRARY_SIZE)]} + + +class Pops: + def __init__(self, intensity: float, idle_rpm: float, redline_rpm: float, sample_rate: int = SAMPLE_RATE, seed: int = 5): + self.intensity = intensity + self.min_rpm = max(idle_rpm, MIN_RPM_SHARE * redline_rpm) + self.redline_rpm = redline_rpm + self.sample_rate = sample_rate + self.samples = library(sample_rate) + self.longest = max(len(sample) for samples in self.samples.values() for sample in samples) + self.tail = np.zeros(0, dtype=np.float32) + self.rng = np.random.default_rng(seed) + self.rpm: float | None = None + self.load = 0.0 + self.peak_load = 0.0 + self.armed = False # loaded since the last lift + self.window = 0.0 # seconds of pops left + self.length = 1.0 # length of the current window + self.strength = 0.0 + + def _rpm_share(self, rpm: float) -> float: + return min(max((rpm - self.min_rpm) / (self.redline_rpm - self.min_rpm), 0.0), 1.0) + + def _blip(self, rpm: float, load: float, dt: float) -> bool: + return self.rpm is not None and load <= OVERRUN and (rpm - self.rpm) / dt >= BLIP_RPM_PER_SECOND and rpm >= self.min_rpm + + def _update(self, rpm: float, load: float, dt: float, blip: bool) -> None: + self.peak_load = max(load, self.peak_load * np.exp(-dt / 1.5)) + self.armed = self.armed or load > LIFT_FROM + if load >= RESUME or rpm < 0.8 * self.min_rpm: + self.window = 0.0 + elif load <= OVERRUN and self.armed and rpm >= self.min_rpm: + self.armed = False + share = self._rpm_share(rpm) * self.peak_load + self.length = self.window = WINDOW_SECONDS[0] + (WINDOW_SECONDS[1] - WINDOW_SECONDS[0]) * share + self.strength = 0.4 + 0.6 * share + elif blip: + self.window = max(self.window, BLIP_EXTEND_SECONDS) + self.length = max(self.length, self.window) + self.strength = max(self.strength, 0.7) + else: + self.window = max(self.window - dt, 0.0) + self.rpm, self.load = rpm, load + + def render(self, rpm: float, load: float, frames: int, volume: float) -> np.ndarray: + dt = frames / self.sample_rate + blip = self._blip(rpm, load, dt) + self._update(rpm, load, dt, blip) + out = np.zeros(frames + self.longest, dtype=np.float32) + out[:len(self.tail)] += self.tail + if self.window > 0.0 and self.intensity > 0.0 and volume > 0.0: + envelope = self.strength * (self.window / self.length) ** 0.7 + expected = RATE * envelope * (0.6 + 0.4 * self._rpm_share(rpm)) * dt + (0.8 if blip else 0.0) + for _ in range(self.rng.poisson(expected)): + kind = 'pop' if blip else KINDS[self.rng.choice(len(KINDS), p=KIND_SHARES)] + sample = self.samples[kind][self.rng.integers(LIBRARY_SIZE)] + start = int(self.rng.integers(frames)) + level = LEVEL * self.intensity * volume * envelope ** 0.5 * self.rng.uniform(0.35, 1.0) + out[start:start + len(sample)] += level * sample + blip = False + self.tail = out[frames:frames + self.longest].copy() + if not self.tail.any(): + self.tail = self.tail[:0] + return out[:frames] diff --git a/openpilot/starpilot/engine_sound/profiles.py b/openpilot/starpilot/engine_sound/profiles.py index 98c7d396ea..089349eed6 100644 --- a/openpilot/starpilot/engine_sound/profiles.py +++ b/openpilot/starpilot/engine_sound/profiles.py @@ -37,6 +37,7 @@ class Profile: pulse_partial: int = 8 # partial the pulses follow tremolo: tuple[float, float] = (0.0, 0.0) # rate in Hz, depth gain: tuple[float, float] = (0.35, 1.0) # loudness at no load and full load + pops: float = 0.0 # overrun pops and crackle, 0 none to 1 heavy def _engine_partials(firing: int, count: int, rough: float, bright: float) -> tuple[tuple[int, float, float], ...]: @@ -55,11 +56,11 @@ RACE_GEARS = (520.0, 340.0, 250.0, 198.0, 165.0, 142.0) RACE_REDLINE = 8600.0 -def _recorded(name: str, label: str, *, cylinders: int, idle: float, redline: float) -> Profile: - """A bundled loop bank of the same name, geared like the race car but scaled to its own rev range.""" +def _recorded(name: str, label: str, *, cylinders: int, idle: float, redline: float, loops: str = '', pops: float = 0.0) -> Profile: + """A bundled loop bank (of the same name unless given), geared like the race car but scaled to its own rev range.""" scale = redline / RACE_REDLINE return Profile( - name=name, label=label, loops=name, + name=name, label=label, loops=loops or name, pops=pops, idle_rpm=idle, redline_rpm=redline, gears=tuple(ratio * scale for ratio in RACE_GEARS), upshift_rpm=(0.38 * redline, 0.96 * redline), downshift_rpm=(0.2 * redline, 0.6 * redline), @@ -70,10 +71,14 @@ def _recorded(name: str, label: str, *, cylinders: int, idle: float, redline: fl PROFILES: dict[str, Profile] = {profile.name: profile for profile in ( + _recorded('bmw_m3', 'BMW M3', cylinders=6, idle=700.0, redline=7000.0, loops='bmw_m52', pops=1.0), _recorded('bmw_m52', 'BMW M52', cylinders=6, idle=700.0, redline=7000.0), _recorded('f1_car', 'F1 Car', cylinders=12, idle=2000.0, redline=17000.0), _recorded('ferrari_f136', 'Ferrari F136', cylinders=8, idle=1000.0, redline=9000.0), + # Banks from real recordings that end at 3000 and 4000 rpm; above about 1.5 times that the loops sound sped up. + _recorded('hellcat', 'Hellcat', cylinders=8, idle=700.0, redline=4500.0), _recorded('lfa', 'LFA', cylinders=10, idle=1000.0, redline=9000.0), + _recorded('mustang_gt', 'Mustang GT', cylinders=8, idle=750.0, redline=6000.0), )} diff --git a/openpilot/starpilot/engine_sound/synth.py b/openpilot/starpilot/engine_sound/synth.py index 3e71e70ebc..0fb051fcae 100644 --- a/openpilot/starpilot/engine_sound/synth.py +++ b/openpilot/starpilot/engine_sound/synth.py @@ -36,6 +36,8 @@ class Synth: self.frequency = profile.idle_rpm * profile.pitch self.load = 0.0 self.gain = 0.0 + from openpilot.starpilot.engine_sound.pops import Pops + self.pops = Pops(profile.pops, profile.idle_rpm, profile.redline_rpm, sample_rate) if profile.pops else None def _lookup(self, table: np.ndarray, phase: np.ndarray) -> np.ndarray: position = (phase % 1.0) * TABLE_SIZE @@ -81,7 +83,10 @@ class Synth: self.phase = float(phase[-1] % 1.0) self.frequency, self.load, self.gain = float(frequency[-1]), load, target_gain - return np.tanh(0.8 * out * gain).astype(np.float32) + out = 0.8 * out * gain + if self.pops is not None: + out = out + self.pops.render(rpm, load, frames, volume) + return np.tanh(out).astype(np.float32) def to_pcm(samples: np.ndarray) -> bytes: diff --git a/openpilot/starpilot/engine_sound/tests/test_bank_from_recording.py b/openpilot/starpilot/engine_sound/tests/test_bank_from_recording.py new file mode 100644 index 0000000000..fd6c2768b2 --- /dev/null +++ b/openpilot/starpilot/engine_sound/tests/test_bank_from_recording.py @@ -0,0 +1,40 @@ +import wave + +import numpy as np + +from openpilot.starpilot.engine_sound.tools.bank_from_recording import SAMPLE_RATE, read_recording, stretch, steady, track, usable + + +def v8_sweep(path, seconds=6.0, rate=44100): + """Idle at 1000 rpm for 1.5 s, then a steady climb to 3000, as whole engine orders with the firing order loudest.""" + t = np.arange(int(seconds * rate)) / rate + rpm = np.where(t < 1.5, 1000.0, 1000.0 + (t - 1.5) / (seconds - 1.5) * 2000.0) + cycles = np.cumsum(rpm / 120.0 / rate) + audio = sum((1.0 if order % 8 else 3.0) * np.sin(2 * np.pi * order * cycles) for order in range(2, 33, 2)) + audio = 0.5 * audio / np.abs(audio).max() + stereo = np.repeat((audio * 32767).astype(' 0.4) & (times < 5.6) + assert np.max(np.abs(rpm[inside] / expected[inside] - 1)) < 0.03 + + span = stretch(times, rpm, usable(times, rpm, [(1.5, 6.0)], 1), 2000.0) + assert span is not None + loop = steady(audio, times, rpm, span, 2000.0) + assert loop is not None and len(loop) >= 0.25 * SAMPLE_RATE + spectrum = np.abs(np.fft.rfft(loop * np.hanning(len(loop)), 1 << 20)) + peak = np.argmax(spectrum) * SAMPLE_RATE / (1 << 20) + assert abs(peak / (2000.0 * 8 / 120) - 1) < 0.02 + assert abs(loop[0] - loop[-1]) <= np.percentile(np.abs(np.diff(loop)), 99) * 1.5 diff --git a/openpilot/starpilot/engine_sound/tests/test_pops.py b/openpilot/starpilot/engine_sound/tests/test_pops.py new file mode 100644 index 0000000000..fa5138217a --- /dev/null +++ b/openpilot/starpilot/engine_sound/tests/test_pops.py @@ -0,0 +1,76 @@ +from dataclasses import replace + +import numpy as np + +from openpilot.starpilot.engine_sound.loops import LoopSynth, load_bank +from openpilot.starpilot.engine_sound.pops import Pops, library +from openpilot.starpilot.engine_sound.profiles import PROFILES +from openpilot.starpilot.engine_sound.tests.test_loops import make_bank + +FRAMES = 480 + + +def run(pops, steps): + return np.concatenate([pops.render(rpm, load, FRAMES, 1.0) for rpm, load in steps]) + + +def test_library_is_fixed_and_normalised(): + first, second = library(), library() + for kind, samples in first.items(): + for a, b in zip(samples, second[kind], strict=True): + assert np.array_equal(a, b) + assert np.abs(a).max() == np.float32(1.0) and a[-1] == 0.0 + + +def test_lifting_at_speed_pops_and_getting_back_on_the_throttle_stops_them(): + pops = Pops(1.0, 700.0, 7000.0) + assert not run(pops, [(5000.0, 0.9)] * 100).any() + after_lift = run(pops, [(5000.0 - 20 * i, 0.0) for i in range(150)]) + assert np.abs(after_lift).max() > 0.1 + run(pops, [(4000.0, 0.6)] * 30) + assert pops.window == 0.0 + assert not run(pops, [(4000.0, 0.6)] * 50).any() + + +def test_no_pops_at_low_revs_or_when_coasting_without_a_lift(): + pops = Pops(1.0, 700.0, 7000.0) + assert not run(pops, [(1000.0, 0.9)] * 50 + [(1000.0, 0.0)] * 200).any() + pops = Pops(1.0, 700.0, 7000.0) + assert not run(pops, [(4000.0, 0.0)] * 300).any() + + +def test_a_downshift_blip_on_overrun_pops_without_a_lift(): + pops = Pops(1.0, 700.0, 7000.0) + run(pops, [(1600.0, 0.0)] * 50) + assert np.abs(run(pops, [(1600.0 + 60 * i, 0.0) for i in range(10)] + [(2200.0, 0.0)] * 60)).max() > 0.1 + + +def test_a_pop_rings_on_into_the_next_block(): + pops = Pops(1.0, 700.0, 7000.0, seed=1) + run(pops, [(6000.0, 1.0)] * 50) + for _ in range(200): + pops.render(6000.0, 0.0, FRAMES, 1.0) + if pops.tail.any(): + break + carried = pops.tail.copy() + assert carried.any() + assert np.array_equal(pops.render(6000.0, 1.0, FRAMES, 1.0), carried[:FRAMES]) + + +def test_quiet_at_zero_volume_and_profiles_without_pops_are_unchanged(tmp_path): + pops = Pops(1.0, 700.0, 7000.0) + assert not np.concatenate([pops.render(6000.0, load, FRAMES, 0.0) for load in [1.0] * 50 + [0.0] * 100]).any() + bank = load_bank(make_bank(tmp_path)) + plain = LoopSynth(PROFILES['bmw_m52'], bank) + assert plain.pops is None + popping = LoopSynth(replace(PROFILES['bmw_m52'], pops=1.0), bank) + steps = [(5000.0, 1.0)] * 50 + [(5000.0 - 20 * i, 0.0) for i in range(150)] + quiet = np.concatenate([plain.render(rpm, load, FRAMES, 1.0) for rpm, load in steps]) + loud = np.concatenate([popping.render(rpm, load, FRAMES, 1.0) for rpm, load in steps]) + assert np.array_equal(quiet[:50 * FRAMES], loud[:50 * FRAMES]) + assert np.abs(loud - quiet).max() > 0.05 and np.abs(loud).max() <= 1.0 + + +def test_the_m3_pops_and_the_m52_does_not(): + assert PROFILES['bmw_m3'].pops > 0 and PROFILES['bmw_m3'].loops == 'bmw_m52' + assert PROFILES['bmw_m52'].pops == 0 diff --git a/openpilot/starpilot/engine_sound/tools/bank_from_recording.py b/openpilot/starpilot/engine_sound/tools/bank_from_recording.py new file mode 100644 index 0000000000..22bdbec1a9 --- /dev/null +++ b/openpilot/starpilot/engine_sound/tools/bank_from_recording.py @@ -0,0 +1,211 @@ +#!/usr/bin/env python3 +"""Build a loop bank from a recording of a real engine. + + python bank_from_recording.py hellcat.wav --cylinders 8 --anchor 14 700 \\ + --on 25-94 --off 94-119 --idle 10.5-17.5 --out banks/hellcat + +rpm is tracked through the recording from the anchor (a time and its known rpm, usually at idle), following the +engine's harmonics without jumps, so the anchor fixes the scale everywhere it can be followed continuously. +Each bank rpm takes the longest stretch near it from the --on (loaded, rpm not falling) or --off (overrun, rpm not +rising) ranges; the stretch is resampled against the engine's own cycle so it plays at one steady rpm, then made +into a seamless loop. --idle ranges are steady idle and feed both layers. +Check the track with --track-image before trusting a bank: a wrong anchor puts every loop an octave out. +""" +from __future__ import annotations + +import argparse +import json +import wave +from pathlib import Path + +import numpy as np + +SAMPLE_RATE = 48000 +HOP = SAMPLE_RATE // 20 +FFT = 1 << 14 +STEP = 1.008 # candidate rpm spacing as a ratio +MAX_STEP = 0.1 # largest rpm change between 50 ms frames, as a log ratio +NEAR = 0.12 # stretch may wander this share either side of the bank rpm; replay evens out the pitch +MIN_LOOP_SECONDS = 0.25 +LOOP_SECONDS = 1.5 +CROSSFADE_CYCLES = 2 +PEAK = 0.89 +IDLE_LEVEL = 0.5 +OFF_LEVEL = 0.6 + + +def read_recording(path: Path) -> np.ndarray: + with wave.open(str(path)) as source: + rate, channels, width = source.getframerate(), source.getnchannels(), source.getsampwidth() + raw = source.readframes(source.getnframes()) + if width != 2: + raise SystemExit(f'{path}: expected 16-bit PCM') + audio = np.frombuffer(raw, ' tuple[np.ndarray, np.ndarray]: + """(times, rpm) every 50 ms by dynamic programming over engine-order salience, pinned at the anchor.""" + freq = np.fft.rfftfreq(FFT, 1 / SAMPLE_RATE) + candidates = 400.0 * STEP ** np.arange(int(np.log(8000 / 400) / np.log(STEP)) + 1) + # Orders are multiples of rpm/120. Some engines carry only the whole engine orders (even ones) under load, and + # following the odd ones there would track half the true rpm; others carry every half order. The firing order leads. + orders = np.arange(1, 4 * cylinders + 1) if half_orders else np.arange(2, 4 * cylinders + 1, 2) + weights = np.where(orders % cylinders == 0, 3.0, 1.0) + rows = [] + for start in range(0, len(audio) - FFT, HOP): + level = np.log(np.abs(np.fft.rfft(audio[start:start + FFT] * np.hanning(FFT))) + 1e-9) + base = np.median(np.lib.stride_tricks.sliding_window_view(np.pad(level, 10, mode='edge'), 21), axis=1) + white = np.maximum(level - base, 0.0) + rows.append(sum(w * np.interp(candidates * order / 120, freq, white) for order, w in zip(orders, weights, strict=True)) / weights.sum()) + salience = np.array(rows) + times = np.arange(len(salience)) * HOP / SAMPLE_RATE + FFT / 2 / SAMPLE_RATE + pinned = int(np.argmin(np.abs(times - anchor[0]))) + salience[pinned] = np.where(np.abs(np.log(candidates / anchor[1])) < 0.03, salience[pinned].max() + 100.0, -1e9) + distance = np.abs(np.subtract.outer(np.arange(len(candidates)), np.arange(len(candidates)))) * np.log(STEP) + penalty = np.where(distance > MAX_STEP, 1e9, 6.0 * distance) + score, back = salience[0].copy(), np.zeros(salience.shape, dtype=np.int32) + for t in range(1, len(salience)): + total = score[:, None] - penalty + back[t] = np.argmax(total, axis=0) + score = total[back[t], np.arange(len(candidates))] + salience[t] + path = np.zeros(len(salience), dtype=np.int32) + path[-1] = int(np.argmax(score)) + for t in range(len(salience) - 1, 0, -1): + path[t - 1] = back[t, path[t]] + return times, candidates[path] + + +def ranges(text: list[str]) -> list[tuple[float, float]]: + return [tuple(float(value) for value in item.split('-')) for item in text] + + +def usable(times: np.ndarray, rpm: np.ndarray, spans, direction: int) -> np.ndarray: + """Frames inside the spans whose rpm is not moving against the layer (no falling under load, no rising on overrun).""" + inside = np.zeros(len(times), dtype=bool) + for start, end in spans: + inside |= (times >= start) & (times <= end) + slope = np.gradient(rpm, times) + return inside & (direction * slope >= -150.0) if direction else inside + + +def stretch(times: np.ndarray, rpm: np.ndarray, mask: np.ndarray, target: float) -> tuple[float, float] | None: + near = mask & (np.abs(np.log(rpm / target)) < NEAR) + best, run_start = None, None + for index, flag in enumerate(np.append(near, False)): + if flag and run_start is None: + run_start = index + elif not flag and run_start is not None: + span = (times[run_start], times[index - 1]) + if best is None or span[1] - span[0] > best[1] - best[0]: + best = span + run_start = None + return best + + +def steady(audio: np.ndarray, times: np.ndarray, rpm: np.ndarray, span: tuple[float, float], target: float) -> np.ndarray | None: + """The span replayed against the engine's own cycle so it runs at exactly the target rpm, as a seamless loop.""" + sample_times = np.arange(int(span[0] * SAMPLE_RATE), int(span[1] * SAMPLE_RATE)) / SAMPLE_RATE + cycles = np.cumsum(np.interp(sample_times, times, rpm)) / 120.0 / SAMPLE_RATE + per_sample = target / 120.0 / SAMPLE_RATE + out_cycles = np.arange(cycles[0], cycles[-1], per_sample) + source = np.interp(out_cycles, cycles, sample_times) * SAMPLE_RATE + whole = source.astype(np.int64) + fraction = source - whole + steady_audio = audio[whole] * (1 - fraction) + audio[np.minimum(whole + 1, len(audio) - 1)] * fraction + cycle = 120.0 / target * SAMPLE_RATE + fade = round(CROSSFADE_CYCLES * cycle) + count = int(min(LOOP_SECONDS * SAMPLE_RATE, len(steady_audio) - fade) // cycle) + length = round(count * cycle) + if length < MIN_LOOP_SECONDS * SAMPLE_RATE: + return None + start = (len(steady_audio) - length - fade) // 2 + segment = steady_audio[start:start + length + fade] + ramp = 0.5 - 0.5 * np.cos(np.pi * np.arange(fade) / fade) + loop = segment[:length].copy() + loop[:fade] = segment[:fade] * np.sqrt(ramp) + segment[length:] * np.sqrt(1 - ramp) + return loop - loop.mean() + + +def track_image(path: Path, audio: np.ndarray, times: np.ndarray, rpm: np.ndarray, cylinders: int) -> None: + from PIL import Image, ImageDraw + columns = [20 * np.log10(np.abs(np.fft.rfft(audio[i:i + 8192] * np.hanning(8192))) + 1e-9) + for i in range(0, len(audio) - 8192, SAMPLE_RATE // 20)] + top = 800.0 + image = np.array(columns).T[:int(top / (SAMPLE_RATE / 8192))][::-1] + image = np.clip((image - (image.max() - 60)) / 60, 0, 1) + picture = Image.fromarray((image * 200).astype(np.uint8)).convert('RGB').resize((1600, 400)) + draw = ImageDraw.Draw(picture) + seconds = len(audio) / SAMPLE_RATE + draw.line([(t / seconds * 1600, 400 - r * cylinders / 120 / top * 400) for t, r in zip(times, rpm, strict=True)], fill=(255, 60, 60)) + for second in range(0, int(seconds) + 1, 5): + draw.text((second / seconds * 1600 + 2, 2), f'{second}s', fill=(255, 255, 255)) + picture.save(path) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('recording', type=Path) + parser.add_argument('--cylinders', type=int, required=True) + parser.add_argument('--anchor', type=float, nargs=2, metavar=('SECONDS', 'RPM'), required=True) + parser.add_argument('--on', nargs='+', default=[], metavar='START-END') + parser.add_argument('--off', nargs='+', default=[], metavar='START-END') + parser.add_argument('--idle', nargs='+', default=[], metavar='START-END') + parser.add_argument('--half-orders', action='store_true', + help='track with every half order; use when the loaded spectrum has lines every rpm/120 Hz') + parser.add_argument('--step', type=float, default=250.0) + parser.add_argument('--out', type=Path, required=True) + parser.add_argument('--track-image', type=Path) + args = parser.parse_args() + + audio = read_recording(args.recording) + times, rpm = track(audio, args.cylinders, tuple(args.anchor), args.half_orders) + if args.track_image: + track_image(args.track_image, audio, times, rpm, args.cylinders) + masks = {'on': usable(times, rpm, ranges(args.on), 1), 'off': usable(times, rpm, ranges(args.off), -1)} + idle = usable(times, rpm, ranges(args.idle), 0) + low = min(rpm[idle | masks['on'] | masks['off']]) + high = max(rpm[masks['on'] | masks['off']]) + points = np.arange(np.ceil(low / args.step) * args.step, high + 1, args.step) + if idle.any(): + points = np.unique(np.append(points, round(float(np.median(rpm[idle]))))) + loops = {} + for layer, mask in masks.items(): + for target in points: + span = stretch(times, rpm, mask | idle, target) + loop = steady(audio, times, rpm, span, target) if span else None + if loop is not None: + loops[(layer, int(target))] = loop + if not any(layer == 'on' for layer, _ in loops): + raise SystemExit('no loaded stretch long enough for a loop') + + on_points = sorted(rpm for layer, rpm in loops if layer == 'on') + span = max(on_points[-1] - on_points[0], 1) + levelled = {} + for (layer, target), loop in loops.items(): + level = (IDLE_LEVEL + (1 - IDLE_LEVEL) * (target - on_points[0]) / span) * (OFF_LEVEL if layer == 'off' else 1.0) + levelled[(layer, target)] = loop * level / max(np.sqrt(np.mean(loop ** 2)), 1e-9) + scale = PEAK / max(np.abs(loop).max() for loop in levelled.values()) + args.out.mkdir(parents=True, exist_ok=True) + manifest = {'version': 1, 'source': f'recording {args.recording.name}', 'layers': {}} + for (layer, target), loop in sorted(levelled.items()): + name = f'{layer}_{target}.wav' + with wave.open(str(args.out / name), 'wb') as out: + out.setnchannels(1) + out.setsampwidth(2) + out.setframerate(SAMPLE_RATE) + out.writeframes(np.clip(np.round(loop * scale * 32767), -32768, 32767).astype('