diff --git a/config-mac.el b/config-mac.el index d01e729..4f1fd64 100644 --- a/config-mac.el +++ b/config-mac.el @@ -269,10 +269,14 @@ Returns answer with org-roam links to sources." whisper-translate nil ; whisper.cpp translates only via server --translate flag whisper-return-cursor 'end)) -;; live-dictate's avfoundation input needs an explicit `-i' of the form -;; ":"; ":0" means no video, default microphone. -;; First use will trigger the macOS microphone permission prompt. +;; live-dictate picks the microphone by name on darwin: avfoundation indices +;; shift as devices come and go, and index 0 here is "Microsoft Teams Audio", +;; a virtual driver that records nothing but silence. Leave the device nil to +;; auto-select the built-in microphone, or pin one by index or by regexp: +;; (setopt live-dictate-ffmpeg-input-device ":2") ; index +;; (setopt live-dictate-ffmpeg-input-device "melliw phone Microphone") ; name +;; First use will trigger the macOS microphone permission prompt for Emacs. (with-eval-after-load 'live-dictate - (setopt live-dictate-ffmpeg-input-device ":0")) + (setopt live-dictate-debug nil)) ;;; config-mac.el ends here diff --git a/lisp/live-dictate.el b/lisp/live-dictate.el index 3ef2dcc..aa3525a 100644 --- a/lisp/live-dictate.el +++ b/lisp/live-dictate.el @@ -22,6 +22,7 @@ (require 'json) (require 'cl-lib) +(require 'seq) (require 'subr-x) (defgroup live-dictate nil @@ -89,10 +90,28 @@ Above it the stream counts as speech; at or below it, as silence." (pcase system-type ('gnu/linux "default") (_ nil)) - "Value passed to FFmpeg's `-i' flag to record audio." + "Value passed to FFmpeg's `-i' flag to record audio. +On darwin, nil (the default) means: pick the device by name, using +`live-dictate-device-name-pattern'. A string is either a literal FFmpeg +device (e.g. \":2\") or a regexp matched against the device names." :type '(choice string (const nil)) :group 'live-dictate) +(defcustom live-dictate-device-name-pattern + (pcase system-type + ('darwin "MacBook.*Microphone\\|Built-in Microphone") + (_ nil)) + "Regexp matching the input device to prefer when the device is not pinned. +Only used on darwin, where avfoundation indices shift as devices come and go." + :type '(choice regexp (const nil)) + :group 'live-dictate) + +(defcustom live-dictate-ignore-device-name + "Teams Audio\\|Loopback\\|BlackHole\\|Aggregate\\|Soundflower" + "Regexp matching virtual/loopback devices that never carry microphone audio." + :type '(choice regexp (const nil)) + :group 'live-dictate) + (defcustom live-dictate-debug nil "Verbose logging to *Messages*." :type 'boolean @@ -112,6 +131,7 @@ Above it the stream counts as speech; at or below it, as silence." ;; `live-dictate--buf-start' up to `live-dictate--total' (both in samples). (defvar live-dictate--buf-start 0) (defvar live-dictate--total 0) +(defvar live-dictate--device nil) (defvar live-dictate--speech-start nil) (defvar live-dictate--silence 0) (defvar live-dictate--max-peak 0) @@ -134,6 +154,51 @@ Above it the stream counts as speech; at or below it, as silence." ;;; Audio capture +(defun live-dictate--avfoundation-audio-devices () + "Return an alist of (INDEX . NAME) for AVFoundation audio inputs." + (with-temp-buffer + (call-process "ffmpeg" nil t nil "-hide_banner" + "-f" "avfoundation" "-list_devices" "true" "-i" "") + (goto-char (point-min)) + (when (re-search-forward "AVFoundation audio devices:" nil t) + (let (devices) + (while (re-search-forward "\\[\\([0-9]+\\)\\] \\(.+?\\)[ \t]*$" nil t) + (push (cons (string-to-number (match-string 1)) (match-string 2)) + devices)) + (nreverse devices))))) + +(defun live-dictate--resolve-input-device () + "Work out the FFmpeg `-i' value for the configured input device." + (if (not (eq system-type 'darwin)) + live-dictate-ffmpeg-input-device + (let ((want live-dictate-ffmpeg-input-device)) + (if (and (stringp want) (string-match-p "\\`:[0-9]+\\'" want)) + want ; explicitly pinned index + (let* ((devices (live-dictate--avfoundation-audio-devices)) + (virtual-p + (lambda (dev) + (and live-dictate-ignore-device-name + (string-match-p live-dictate-ignore-device-name (cdr dev))))) + (named (and (stringp want) + (seq-find (lambda (dev) (string-match-p want (cdr dev))) + devices))) + (preferred (and live-dictate-device-name-pattern + (seq-find (lambda (dev) + (and (string-match-p + live-dictate-device-name-pattern + (cdr dev)) + (not (funcall virtual-p dev)))) + devices))) + (fallback (seq-find (lambda (dev) (not (funcall virtual-p dev))) devices)) + (chosen (or named preferred fallback (car devices)))) + (cond + ((null chosen) + (live-dictate--dbg "no avfoundation audio devices found") + nil) + (t + (live-dictate--dbg "audio device %d: %s" (car chosen) (cdr chosen)) + (concat ":" (number-to-string (car chosen)))))))))) + (defun live-dictate--peak (chunk) "Peak amplitude of raw PCM16 CHUNK, measured on the high byte." (let ((i 0) @@ -375,25 +440,29 @@ the OS microphone permission for Emacs and `live-dictate-ffmpeg-input-device'")) (live-dictate--mode-line nil)) (defun live-dictate--start-capture () - (setq live-dictate--ffmpeg - (make-process - :name "live-dictate-ffmpeg" - :command `("ffmpeg" "-nostdin" "-hide_banner" "-loglevel" "error" - "-f" ,live-dictate-ffmpeg-input-format - "-i" ,live-dictate-ffmpeg-input-device - "-ac" "1" "-ar" ,(number-to-string live-dictate--sample-rate) - "-f" "s16le" "pipe:1") - :connection-type 'pipe - :coding 'binary - :noquery t - :filter #'live-dictate--filter - :stderr (get-buffer-create live-dictate--stderr-buffer) - :sentinel (lambda (_proc event) - (when (and live-dictate--active - (not (string-prefix-p "finished" event))) - (message "live-dictate: FFmpeg stopped (%s)" - (string-trim event)) - (live-dictate--stop)))))) + (let ((device (live-dictate--resolve-input-device))) + (unless device + (user-error "live-dictate: no usable audio input device")) + (setq live-dictate--device device + live-dictate--ffmpeg + (make-process + :name "live-dictate-ffmpeg" + :command `("ffmpeg" "-nostdin" "-hide_banner" "-loglevel" "error" + "-f" ,live-dictate-ffmpeg-input-format + "-i" ,device + "-ac" "1" "-ar" ,(number-to-string live-dictate--sample-rate) + "-f" "s16le" "pipe:1") + :connection-type 'pipe + :coding 'binary + :noquery t + :filter #'live-dictate--filter + :stderr (get-buffer-create live-dictate--stderr-buffer) + :sentinel (lambda (_proc event) + (when (and live-dictate--active + (not (string-prefix-p "finished" event))) + (message "live-dictate: FFmpeg stopped (%s)" + (string-trim event)) + (live-dictate--stop))))))) (defun live-dictate--stop () "Stop dictation: send whatever is left, then clean up when it is done." @@ -409,15 +478,62 @@ the OS microphone permission for Emacs and `live-dictate-ffmpeg-input-device'")) (message "live-dictate: stopped"))) ;;;###autoload -(defun live-dictate () - "Toggle live dictation in the current buffer. -While active, speech is transcribed by a whisper.cpp server and the text is -inserted at point as each utterance completes. Run again to stop." +(defun live-dictate-stop () + "Stop live dictation; anything already spoken is still transcribed." (interactive) (if live-dictate--active (live-dictate--stop) - (unless (and live-dictate-ffmpeg-input-format live-dictate-ffmpeg-input-device) - (user-error "live-dictate: set live-dictate-ffmpeg-input-format/-device")) + (message "live-dictate: not running"))) + +(defun live-dictate--level (device) + "Record two seconds from DEVICE and return FFmpeg's max volume, or nil." + (with-temp-buffer + (call-process "ffmpeg" nil t nil "-hide_banner" "-loglevel" "info" + "-f" live-dictate-ffmpeg-input-format "-i" device + "-t" "2" "-ac" "1" "-ar" "16000" "-af" "volumedetect" + "-f" "null" "-") + (goto-char (point-min)) + (when (re-search-forward "max_volume: \\(-?[0-9.]+ dB\\)" nil t) + (match-string 1)))) + +;;;###autoload +(defun live-dictate-diagnose () + "Check the whisper.cpp server and the microphone, and say what is wrong." + (interactive) + (let ((devices (and (eq system-type 'darwin) + (live-dictate--avfoundation-audio-devices))) + (device (live-dictate--resolve-input-device))) + (message "live-dictate: server %s" live-dictate-server-url) + (when devices + (message "live-dictate: devices %s" + (mapconcat (lambda (d) (format "[%d] %s" (car d) (cdr d))) + devices ", "))) + (message "live-dictate: selected device %s" device) + (let ((level (and device (live-dictate--level device)))) + (cond + ((null level) + (message "live-dictate: could not record from %s" device)) + ((string-prefix-p "-91" level) + (message (concat "live-dictate: %s delivers digital silence -- grant " + "Microphone access to Emacs in System Settings > " + "Privacy & Security > Microphone, then retry") + device)) + (t + (message "live-dictate: %s is delivering audio (max volume %s)" + device level)))))) + +;;;###autoload +(defun live-dictate () + "Toggle live dictation in the current buffer. +While active, speech is transcribed by a whisper.cpp server and the text is +inserted at point as each utterance completes. Run the same command again +\(or `live-dictate-stop', SPC A d) to stop; the microphone indicator in the +mode line shows when it is listening." + (interactive) + (if live-dictate--active + (live-dictate--stop) + (unless live-dictate-ffmpeg-input-format + (user-error "live-dictate: set live-dictate-ffmpeg-input-format")) (unless (executable-find "ffmpeg") (user-error "live-dictate: FFmpeg not found in PATH")) (unless (executable-find "curl") @@ -440,7 +556,8 @@ inserted at point as each utterance completes. Run again to stop." (set-buffer-multibyte nil)) (live-dictate--mode-line t) (live-dictate--start-capture) - (message "live-dictate: listening (%s)" live-dictate-server-url))) + (message "live-dictate: listening (%s via device %s; SPC A d to stop)" + live-dictate-server-url live-dictate--device))) (provide 'live-dictate) ;;; live-dictate.el ends here